xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision a624cec56d4bf61c1f3cb7daf2d27dac59c56fa4)
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(),
2812                                     llvm::PointerType::getUnqual(DeclTy),
2813                                     nullptr);
2814 
2815   auto *F = cast<llvm::GlobalValue>(Aliasee);
2816   F->setLinkage(llvm::Function::ExternalWeakLinkage);
2817   WeakRefReferences.insert(F);
2818 
2819   return ConstantAddress(Aliasee, Alignment);
2820 }
2821 
2822 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
2823   const auto *Global = cast<ValueDecl>(GD.getDecl());
2824 
2825   // Weak references don't produce any output by themselves.
2826   if (Global->hasAttr<WeakRefAttr>())
2827     return;
2828 
2829   // If this is an alias definition (which otherwise looks like a declaration)
2830   // emit it now.
2831   if (Global->hasAttr<AliasAttr>())
2832     return EmitAliasDefinition(GD);
2833 
2834   // IFunc like an alias whose value is resolved at runtime by calling resolver.
2835   if (Global->hasAttr<IFuncAttr>())
2836     return emitIFuncDefinition(GD);
2837 
2838   // If this is a cpu_dispatch multiversion function, emit the resolver.
2839   if (Global->hasAttr<CPUDispatchAttr>())
2840     return emitCPUDispatchDefinition(GD);
2841 
2842   // If this is CUDA, be selective about which declarations we emit.
2843   if (LangOpts.CUDA) {
2844     if (LangOpts.CUDAIsDevice) {
2845       if (!Global->hasAttr<CUDADeviceAttr>() &&
2846           !Global->hasAttr<CUDAGlobalAttr>() &&
2847           !Global->hasAttr<CUDAConstantAttr>() &&
2848           !Global->hasAttr<CUDASharedAttr>() &&
2849           !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
2850           !Global->getType()->isCUDADeviceBuiltinTextureType())
2851         return;
2852     } else {
2853       // We need to emit host-side 'shadows' for all global
2854       // device-side variables because the CUDA runtime needs their
2855       // size and host-side address in order to provide access to
2856       // their device-side incarnations.
2857 
2858       // So device-only functions are the only things we skip.
2859       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2860           Global->hasAttr<CUDADeviceAttr>())
2861         return;
2862 
2863       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2864              "Expected Variable or Function");
2865     }
2866   }
2867 
2868   if (LangOpts.OpenMP) {
2869     // If this is OpenMP, check if it is legal to emit this global normally.
2870     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2871       return;
2872     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2873       if (MustBeEmitted(Global))
2874         EmitOMPDeclareReduction(DRD);
2875       return;
2876     } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
2877       if (MustBeEmitted(Global))
2878         EmitOMPDeclareMapper(DMD);
2879       return;
2880     }
2881   }
2882 
2883   // Ignore declarations, they will be emitted on their first use.
2884   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2885     // Forward declarations are emitted lazily on first use.
2886     if (!FD->doesThisDeclarationHaveABody()) {
2887       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2888         return;
2889 
2890       StringRef MangledName = getMangledName(GD);
2891 
2892       // Compute the function info and LLVM type.
2893       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2894       llvm::Type *Ty = getTypes().GetFunctionType(FI);
2895 
2896       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2897                               /*DontDefer=*/false);
2898       return;
2899     }
2900   } else {
2901     const auto *VD = cast<VarDecl>(Global);
2902     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
2903     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
2904         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2905       if (LangOpts.OpenMP) {
2906         // Emit declaration of the must-be-emitted declare target variable.
2907         if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2908                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2909           bool UnifiedMemoryEnabled =
2910               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
2911           if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2912               !UnifiedMemoryEnabled) {
2913             (void)GetAddrOfGlobalVar(VD);
2914           } else {
2915             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2916                     (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2917                      UnifiedMemoryEnabled)) &&
2918                    "Link clause or to clause with unified memory expected.");
2919             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
2920           }
2921 
2922           return;
2923         }
2924       }
2925       // If this declaration may have caused an inline variable definition to
2926       // change linkage, make sure that it's emitted.
2927       if (Context.getInlineVariableDefinitionKind(VD) ==
2928           ASTContext::InlineVariableDefinitionKind::Strong)
2929         GetAddrOfGlobalVar(VD);
2930       return;
2931     }
2932   }
2933 
2934   // Defer code generation to first use when possible, e.g. if this is an inline
2935   // function. If the global must always be emitted, do it eagerly if possible
2936   // to benefit from cache locality.
2937   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2938     // Emit the definition if it can't be deferred.
2939     EmitGlobalDefinition(GD);
2940     return;
2941   }
2942 
2943   // If we're deferring emission of a C++ variable with an
2944   // initializer, remember the order in which it appeared in the file.
2945   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
2946       cast<VarDecl>(Global)->hasInit()) {
2947     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2948     CXXGlobalInits.push_back(nullptr);
2949   }
2950 
2951   StringRef MangledName = getMangledName(GD);
2952   if (GetGlobalValue(MangledName) != nullptr) {
2953     // The value has already been used and should therefore be emitted.
2954     addDeferredDeclToEmit(GD);
2955   } else if (MustBeEmitted(Global)) {
2956     // The value must be emitted, but cannot be emitted eagerly.
2957     assert(!MayBeEmittedEagerly(Global));
2958     addDeferredDeclToEmit(GD);
2959   } else {
2960     // Otherwise, remember that we saw a deferred decl with this name.  The
2961     // first use of the mangled name will cause it to move into
2962     // DeferredDeclsToEmit.
2963     DeferredDecls[MangledName] = GD;
2964   }
2965 }
2966 
2967 // Check if T is a class type with a destructor that's not dllimport.
2968 static bool HasNonDllImportDtor(QualType T) {
2969   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2970     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2971       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2972         return true;
2973 
2974   return false;
2975 }
2976 
2977 namespace {
2978   struct FunctionIsDirectlyRecursive
2979       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
2980     const StringRef Name;
2981     const Builtin::Context &BI;
2982     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
2983         : Name(N), BI(C) {}
2984 
2985     bool VisitCallExpr(const CallExpr *E) {
2986       const FunctionDecl *FD = E->getDirectCallee();
2987       if (!FD)
2988         return false;
2989       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2990       if (Attr && Name == Attr->getLabel())
2991         return true;
2992       unsigned BuiltinID = FD->getBuiltinID();
2993       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
2994         return false;
2995       StringRef BuiltinName = BI.getName(BuiltinID);
2996       if (BuiltinName.startswith("__builtin_") &&
2997           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
2998         return true;
2999       }
3000       return false;
3001     }
3002 
3003     bool VisitStmt(const Stmt *S) {
3004       for (const Stmt *Child : S->children())
3005         if (Child && this->Visit(Child))
3006           return true;
3007       return false;
3008     }
3009   };
3010 
3011   // Make sure we're not referencing non-imported vars or functions.
3012   struct DLLImportFunctionVisitor
3013       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
3014     bool SafeToInline = true;
3015 
3016     bool shouldVisitImplicitCode() const { return true; }
3017 
3018     bool VisitVarDecl(VarDecl *VD) {
3019       if (VD->getTLSKind()) {
3020         // A thread-local variable cannot be imported.
3021         SafeToInline = false;
3022         return SafeToInline;
3023       }
3024 
3025       // A variable definition might imply a destructor call.
3026       if (VD->isThisDeclarationADefinition())
3027         SafeToInline = !HasNonDllImportDtor(VD->getType());
3028 
3029       return SafeToInline;
3030     }
3031 
3032     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
3033       if (const auto *D = E->getTemporary()->getDestructor())
3034         SafeToInline = D->hasAttr<DLLImportAttr>();
3035       return SafeToInline;
3036     }
3037 
3038     bool VisitDeclRefExpr(DeclRefExpr *E) {
3039       ValueDecl *VD = E->getDecl();
3040       if (isa<FunctionDecl>(VD))
3041         SafeToInline = VD->hasAttr<DLLImportAttr>();
3042       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
3043         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
3044       return SafeToInline;
3045     }
3046 
3047     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
3048       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
3049       return SafeToInline;
3050     }
3051 
3052     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3053       CXXMethodDecl *M = E->getMethodDecl();
3054       if (!M) {
3055         // Call through a pointer to member function. This is safe to inline.
3056         SafeToInline = true;
3057       } else {
3058         SafeToInline = M->hasAttr<DLLImportAttr>();
3059       }
3060       return SafeToInline;
3061     }
3062 
3063     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
3064       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
3065       return SafeToInline;
3066     }
3067 
3068     bool VisitCXXNewExpr(CXXNewExpr *E) {
3069       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
3070       return SafeToInline;
3071     }
3072   };
3073 }
3074 
3075 // isTriviallyRecursive - Check if this function calls another
3076 // decl that, because of the asm attribute or the other decl being a builtin,
3077 // ends up pointing to itself.
3078 bool
3079 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
3080   StringRef Name;
3081   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
3082     // asm labels are a special kind of mangling we have to support.
3083     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3084     if (!Attr)
3085       return false;
3086     Name = Attr->getLabel();
3087   } else {
3088     Name = FD->getName();
3089   }
3090 
3091   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
3092   const Stmt *Body = FD->getBody();
3093   return Body ? Walker.Visit(Body) : false;
3094 }
3095 
3096 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
3097   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
3098     return true;
3099   const auto *F = cast<FunctionDecl>(GD.getDecl());
3100   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
3101     return false;
3102 
3103   if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) {
3104     // Check whether it would be safe to inline this dllimport function.
3105     DLLImportFunctionVisitor Visitor;
3106     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
3107     if (!Visitor.SafeToInline)
3108       return false;
3109 
3110     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
3111       // Implicit destructor invocations aren't captured in the AST, so the
3112       // check above can't see them. Check for them manually here.
3113       for (const Decl *Member : Dtor->getParent()->decls())
3114         if (isa<FieldDecl>(Member))
3115           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
3116             return false;
3117       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
3118         if (HasNonDllImportDtor(B.getType()))
3119           return false;
3120     }
3121   }
3122 
3123   // PR9614. Avoid cases where the source code is lying to us. An available
3124   // externally function should have an equivalent function somewhere else,
3125   // but a function that calls itself through asm label/`__builtin_` trickery is
3126   // clearly not equivalent to the real implementation.
3127   // This happens in glibc's btowc and in some configure checks.
3128   return !isTriviallyRecursive(F);
3129 }
3130 
3131 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
3132   return CodeGenOpts.OptimizationLevel > 0;
3133 }
3134 
3135 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
3136                                                        llvm::GlobalValue *GV) {
3137   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3138 
3139   if (FD->isCPUSpecificMultiVersion()) {
3140     auto *Spec = FD->getAttr<CPUSpecificAttr>();
3141     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
3142       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
3143     // Requires multiple emits.
3144   } else
3145     EmitGlobalFunctionDefinition(GD, GV);
3146 }
3147 
3148 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
3149   const auto *D = cast<ValueDecl>(GD.getDecl());
3150 
3151   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
3152                                  Context.getSourceManager(),
3153                                  "Generating code for declaration");
3154 
3155   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3156     // At -O0, don't generate IR for functions with available_externally
3157     // linkage.
3158     if (!shouldEmitFunction(GD))
3159       return;
3160 
3161     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
3162       std::string Name;
3163       llvm::raw_string_ostream OS(Name);
3164       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
3165                                /*Qualified=*/true);
3166       return Name;
3167     });
3168 
3169     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3170       // Make sure to emit the definition(s) before we emit the thunks.
3171       // This is necessary for the generation of certain thunks.
3172       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
3173         ABI->emitCXXStructor(GD);
3174       else if (FD->isMultiVersion())
3175         EmitMultiVersionFunctionDefinition(GD, GV);
3176       else
3177         EmitGlobalFunctionDefinition(GD, GV);
3178 
3179       if (Method->isVirtual())
3180         getVTables().EmitThunks(GD);
3181 
3182       return;
3183     }
3184 
3185     if (FD->isMultiVersion())
3186       return EmitMultiVersionFunctionDefinition(GD, GV);
3187     return EmitGlobalFunctionDefinition(GD, GV);
3188   }
3189 
3190   if (const auto *VD = dyn_cast<VarDecl>(D))
3191     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
3192 
3193   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
3194 }
3195 
3196 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3197                                                       llvm::Function *NewFn);
3198 
3199 static unsigned
3200 TargetMVPriority(const TargetInfo &TI,
3201                  const CodeGenFunction::MultiVersionResolverOption &RO) {
3202   unsigned Priority = 0;
3203   for (StringRef Feat : RO.Conditions.Features)
3204     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
3205 
3206   if (!RO.Conditions.Architecture.empty())
3207     Priority = std::max(
3208         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
3209   return Priority;
3210 }
3211 
3212 void CodeGenModule::emitMultiVersionFunctions() {
3213   std::vector<GlobalDecl> MVFuncsToEmit;
3214   MultiVersionFuncs.swap(MVFuncsToEmit);
3215   for (GlobalDecl GD : MVFuncsToEmit) {
3216     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3217     const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3218     getContext().forEachMultiversionedFunctionVersion(
3219         FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
3220           GlobalDecl CurGD{
3221               (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
3222           StringRef MangledName = getMangledName(CurGD);
3223           llvm::Constant *Func = GetGlobalValue(MangledName);
3224           if (!Func) {
3225             if (CurFD->isDefined()) {
3226               EmitGlobalFunctionDefinition(CurGD, nullptr);
3227               Func = GetGlobalValue(MangledName);
3228             } else {
3229               const CGFunctionInfo &FI =
3230                   getTypes().arrangeGlobalDeclaration(GD);
3231               llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3232               Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
3233                                        /*DontDefer=*/false, ForDefinition);
3234             }
3235             assert(Func && "This should have just been created");
3236           }
3237 
3238           const auto *TA = CurFD->getAttr<TargetAttr>();
3239           llvm::SmallVector<StringRef, 8> Feats;
3240           TA->getAddedFeatures(Feats);
3241 
3242           Options.emplace_back(cast<llvm::Function>(Func),
3243                                TA->getArchitecture(), Feats);
3244         });
3245 
3246     llvm::Function *ResolverFunc;
3247     const TargetInfo &TI = getTarget();
3248 
3249     if (TI.supportsIFunc() || FD->isTargetMultiVersion()) {
3250       ResolverFunc = cast<llvm::Function>(
3251           GetGlobalValue((getMangledName(GD) + ".resolver").str()));
3252       ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3253     } else {
3254       ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
3255     }
3256 
3257     if (supportsCOMDAT())
3258       ResolverFunc->setComdat(
3259           getModule().getOrInsertComdat(ResolverFunc->getName()));
3260 
3261     llvm::stable_sort(
3262         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
3263                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
3264           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
3265         });
3266     CodeGenFunction CGF(*this);
3267     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3268   }
3269 
3270   // Ensure that any additions to the deferred decls list caused by emitting a
3271   // variant are emitted.  This can happen when the variant itself is inline and
3272   // calls a function without linkage.
3273   if (!MVFuncsToEmit.empty())
3274     EmitDeferred();
3275 
3276   // Ensure that any additions to the multiversion funcs list from either the
3277   // deferred decls or the multiversion functions themselves are emitted.
3278   if (!MultiVersionFuncs.empty())
3279     emitMultiVersionFunctions();
3280 }
3281 
3282 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
3283   const auto *FD = cast<FunctionDecl>(GD.getDecl());
3284   assert(FD && "Not a FunctionDecl?");
3285   const auto *DD = FD->getAttr<CPUDispatchAttr>();
3286   assert(DD && "Not a cpu_dispatch Function?");
3287   llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
3288 
3289   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
3290     const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
3291     DeclTy = getTypes().GetFunctionType(FInfo);
3292   }
3293 
3294   StringRef ResolverName = getMangledName(GD);
3295 
3296   llvm::Type *ResolverType;
3297   GlobalDecl ResolverGD;
3298   if (getTarget().supportsIFunc())
3299     ResolverType = llvm::FunctionType::get(
3300         llvm::PointerType::get(DeclTy,
3301                                Context.getTargetAddressSpace(FD->getType())),
3302         false);
3303   else {
3304     ResolverType = DeclTy;
3305     ResolverGD = GD;
3306   }
3307 
3308   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
3309       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
3310   ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3311   if (supportsCOMDAT())
3312     ResolverFunc->setComdat(
3313         getModule().getOrInsertComdat(ResolverFunc->getName()));
3314 
3315   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3316   const TargetInfo &Target = getTarget();
3317   unsigned Index = 0;
3318   for (const IdentifierInfo *II : DD->cpus()) {
3319     // Get the name of the target function so we can look it up/create it.
3320     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
3321                               getCPUSpecificMangling(*this, II->getName());
3322 
3323     llvm::Constant *Func = GetGlobalValue(MangledName);
3324 
3325     if (!Func) {
3326       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
3327       if (ExistingDecl.getDecl() &&
3328           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
3329         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
3330         Func = GetGlobalValue(MangledName);
3331       } else {
3332         if (!ExistingDecl.getDecl())
3333           ExistingDecl = GD.getWithMultiVersionIndex(Index);
3334 
3335       Func = GetOrCreateLLVMFunction(
3336           MangledName, DeclTy, ExistingDecl,
3337           /*ForVTable=*/false, /*DontDefer=*/true,
3338           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
3339       }
3340     }
3341 
3342     llvm::SmallVector<StringRef, 32> Features;
3343     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
3344     llvm::transform(Features, Features.begin(),
3345                     [](StringRef Str) { return Str.substr(1); });
3346     Features.erase(std::remove_if(
3347         Features.begin(), Features.end(), [&Target](StringRef Feat) {
3348           return !Target.validateCpuSupports(Feat);
3349         }), Features.end());
3350     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
3351     ++Index;
3352   }
3353 
3354   llvm::stable_sort(
3355       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
3356                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
3357         return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
3358                CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
3359       });
3360 
3361   // If the list contains multiple 'default' versions, such as when it contains
3362   // 'pentium' and 'generic', don't emit the call to the generic one (since we
3363   // always run on at least a 'pentium'). We do this by deleting the 'least
3364   // advanced' (read, lowest mangling letter).
3365   while (Options.size() > 1 &&
3366          CodeGenFunction::GetX86CpuSupportsMask(
3367              (Options.end() - 2)->Conditions.Features) == 0) {
3368     StringRef LHSName = (Options.end() - 2)->Function->getName();
3369     StringRef RHSName = (Options.end() - 1)->Function->getName();
3370     if (LHSName.compare(RHSName) < 0)
3371       Options.erase(Options.end() - 2);
3372     else
3373       Options.erase(Options.end() - 1);
3374   }
3375 
3376   CodeGenFunction CGF(*this);
3377   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3378 
3379   if (getTarget().supportsIFunc()) {
3380     std::string AliasName = getMangledNameImpl(
3381         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3382     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3383     if (!AliasFunc) {
3384       auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
3385           AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
3386           /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
3387       auto *GA = llvm::GlobalAlias::create(
3388          DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule());
3389       GA->setLinkage(llvm::Function::WeakODRLinkage);
3390       SetCommonAttributes(GD, GA);
3391     }
3392   }
3393 }
3394 
3395 /// If a dispatcher for the specified mangled name is not in the module, create
3396 /// and return an llvm Function with the specified type.
3397 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
3398     GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
3399   std::string MangledName =
3400       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
3401 
3402   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
3403   // a separate resolver).
3404   std::string ResolverName = MangledName;
3405   if (getTarget().supportsIFunc())
3406     ResolverName += ".ifunc";
3407   else if (FD->isTargetMultiVersion())
3408     ResolverName += ".resolver";
3409 
3410   // If this already exists, just return that one.
3411   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
3412     return ResolverGV;
3413 
3414   // Since this is the first time we've created this IFunc, make sure
3415   // that we put this multiversioned function into the list to be
3416   // replaced later if necessary (target multiversioning only).
3417   if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
3418     MultiVersionFuncs.push_back(GD);
3419 
3420   if (getTarget().supportsIFunc()) {
3421     llvm::Type *ResolverType = llvm::FunctionType::get(
3422         llvm::PointerType::get(
3423             DeclTy, getContext().getTargetAddressSpace(FD->getType())),
3424         false);
3425     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3426         MangledName + ".resolver", ResolverType, GlobalDecl{},
3427         /*ForVTable=*/false);
3428     llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
3429         DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule());
3430     GIF->setName(ResolverName);
3431     SetCommonAttributes(FD, GIF);
3432 
3433     return GIF;
3434   }
3435 
3436   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3437       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
3438   assert(isa<llvm::GlobalValue>(Resolver) &&
3439          "Resolver should be created for the first time");
3440   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
3441   return Resolver;
3442 }
3443 
3444 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
3445 /// module, create and return an llvm Function with the specified type. If there
3446 /// is something in the module with the specified name, return it potentially
3447 /// bitcasted to the right type.
3448 ///
3449 /// If D is non-null, it specifies a decl that correspond to this.  This is used
3450 /// to set the attributes on the function when it is first created.
3451 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
3452     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
3453     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
3454     ForDefinition_t IsForDefinition) {
3455   const Decl *D = GD.getDecl();
3456 
3457   // Any attempts to use a MultiVersion function should result in retrieving
3458   // the iFunc instead. Name Mangling will handle the rest of the changes.
3459   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
3460     // For the device mark the function as one that should be emitted.
3461     if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
3462         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
3463         !DontDefer && !IsForDefinition) {
3464       if (const FunctionDecl *FDDef = FD->getDefinition()) {
3465         GlobalDecl GDDef;
3466         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
3467           GDDef = GlobalDecl(CD, GD.getCtorType());
3468         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
3469           GDDef = GlobalDecl(DD, GD.getDtorType());
3470         else
3471           GDDef = GlobalDecl(FDDef);
3472         EmitGlobal(GDDef);
3473       }
3474     }
3475 
3476     if (FD->isMultiVersion()) {
3477       if (FD->hasAttr<TargetAttr>())
3478         UpdateMultiVersionNames(GD, FD);
3479       if (!IsForDefinition)
3480         return GetOrCreateMultiVersionResolver(GD, Ty, FD);
3481     }
3482   }
3483 
3484   // Lookup the entry, lazily creating it if necessary.
3485   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3486   if (Entry) {
3487     if (WeakRefReferences.erase(Entry)) {
3488       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
3489       if (FD && !FD->hasAttr<WeakAttr>())
3490         Entry->setLinkage(llvm::Function::ExternalLinkage);
3491     }
3492 
3493     // Handle dropped DLL attributes.
3494     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
3495       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3496       setDSOLocal(Entry);
3497     }
3498 
3499     // If there are two attempts to define the same mangled name, issue an
3500     // error.
3501     if (IsForDefinition && !Entry->isDeclaration()) {
3502       GlobalDecl OtherGD;
3503       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
3504       // to make sure that we issue an error only once.
3505       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3506           (GD.getCanonicalDecl().getDecl() !=
3507            OtherGD.getCanonicalDecl().getDecl()) &&
3508           DiagnosedConflictingDefinitions.insert(GD).second) {
3509         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3510             << MangledName;
3511         getDiags().Report(OtherGD.getDecl()->getLocation(),
3512                           diag::note_previous_definition);
3513       }
3514     }
3515 
3516     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
3517         (Entry->getValueType() == Ty)) {
3518       return Entry;
3519     }
3520 
3521     // Make sure the result is of the correct type.
3522     // (If function is requested for a definition, we always need to create a new
3523     // function, not just return a bitcast.)
3524     if (!IsForDefinition)
3525       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
3526   }
3527 
3528   // This function doesn't have a complete type (for example, the return
3529   // type is an incomplete struct). Use a fake type instead, and make
3530   // sure not to try to set attributes.
3531   bool IsIncompleteFunction = false;
3532 
3533   llvm::FunctionType *FTy;
3534   if (isa<llvm::FunctionType>(Ty)) {
3535     FTy = cast<llvm::FunctionType>(Ty);
3536   } else {
3537     FTy = llvm::FunctionType::get(VoidTy, false);
3538     IsIncompleteFunction = true;
3539   }
3540 
3541   llvm::Function *F =
3542       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
3543                              Entry ? StringRef() : MangledName, &getModule());
3544 
3545   // If we already created a function with the same mangled name (but different
3546   // type) before, take its name and add it to the list of functions to be
3547   // replaced with F at the end of CodeGen.
3548   //
3549   // This happens if there is a prototype for a function (e.g. "int f()") and
3550   // then a definition of a different type (e.g. "int f(int x)").
3551   if (Entry) {
3552     F->takeName(Entry);
3553 
3554     // This might be an implementation of a function without a prototype, in
3555     // which case, try to do special replacement of calls which match the new
3556     // prototype.  The really key thing here is that we also potentially drop
3557     // arguments from the call site so as to make a direct call, which makes the
3558     // inliner happier and suppresses a number of optimizer warnings (!) about
3559     // dropping arguments.
3560     if (!Entry->use_empty()) {
3561       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
3562       Entry->removeDeadConstantUsers();
3563     }
3564 
3565     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
3566         F, Entry->getValueType()->getPointerTo());
3567     addGlobalValReplacement(Entry, BC);
3568   }
3569 
3570   assert(F->getName() == MangledName && "name was uniqued!");
3571   if (D)
3572     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
3573   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
3574     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
3575     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
3576   }
3577 
3578   if (!DontDefer) {
3579     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
3580     // each other bottoming out with the base dtor.  Therefore we emit non-base
3581     // dtors on usage, even if there is no dtor definition in the TU.
3582     if (D && isa<CXXDestructorDecl>(D) &&
3583         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
3584                                            GD.getDtorType()))
3585       addDeferredDeclToEmit(GD);
3586 
3587     // This is the first use or definition of a mangled name.  If there is a
3588     // deferred decl with this name, remember that we need to emit it at the end
3589     // of the file.
3590     auto DDI = DeferredDecls.find(MangledName);
3591     if (DDI != DeferredDecls.end()) {
3592       // Move the potentially referenced deferred decl to the
3593       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
3594       // don't need it anymore).
3595       addDeferredDeclToEmit(DDI->second);
3596       DeferredDecls.erase(DDI);
3597 
3598       // Otherwise, there are cases we have to worry about where we're
3599       // using a declaration for which we must emit a definition but where
3600       // we might not find a top-level definition:
3601       //   - member functions defined inline in their classes
3602       //   - friend functions defined inline in some class
3603       //   - special member functions with implicit definitions
3604       // If we ever change our AST traversal to walk into class methods,
3605       // this will be unnecessary.
3606       //
3607       // We also don't emit a definition for a function if it's going to be an
3608       // entry in a vtable, unless it's already marked as used.
3609     } else if (getLangOpts().CPlusPlus && D) {
3610       // Look for a declaration that's lexically in a record.
3611       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
3612            FD = FD->getPreviousDecl()) {
3613         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
3614           if (FD->doesThisDeclarationHaveABody()) {
3615             addDeferredDeclToEmit(GD.getWithDecl(FD));
3616             break;
3617           }
3618         }
3619       }
3620     }
3621   }
3622 
3623   // Make sure the result is of the requested type.
3624   if (!IsIncompleteFunction) {
3625     assert(F->getFunctionType() == Ty);
3626     return F;
3627   }
3628 
3629   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3630   return llvm::ConstantExpr::getBitCast(F, PTy);
3631 }
3632 
3633 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
3634 /// non-null, then this function will use the specified type if it has to
3635 /// create it (this occurs when we see a definition of the function).
3636 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
3637                                                  llvm::Type *Ty,
3638                                                  bool ForVTable,
3639                                                  bool DontDefer,
3640                                               ForDefinition_t IsForDefinition) {
3641   assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&
3642          "consteval function should never be emitted");
3643   // If there was no specific requested type, just convert it now.
3644   if (!Ty) {
3645     const auto *FD = cast<FunctionDecl>(GD.getDecl());
3646     Ty = getTypes().ConvertType(FD->getType());
3647   }
3648 
3649   // Devirtualized destructor calls may come through here instead of via
3650   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
3651   // of the complete destructor when necessary.
3652   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
3653     if (getTarget().getCXXABI().isMicrosoft() &&
3654         GD.getDtorType() == Dtor_Complete &&
3655         DD->getParent()->getNumVBases() == 0)
3656       GD = GlobalDecl(DD, Dtor_Base);
3657   }
3658 
3659   StringRef MangledName = getMangledName(GD);
3660   auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
3661                                     /*IsThunk=*/false, llvm::AttributeList(),
3662                                     IsForDefinition);
3663   // Returns kernel handle for HIP kernel stub function.
3664   if (LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
3665       cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) {
3666     auto *Handle = getCUDARuntime().getKernelHandle(
3667         cast<llvm::Function>(F->stripPointerCasts()), GD);
3668     if (IsForDefinition)
3669       return F;
3670     return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo());
3671   }
3672   return F;
3673 }
3674 
3675 static const FunctionDecl *
3676 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
3677   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
3678   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3679 
3680   IdentifierInfo &CII = C.Idents.get(Name);
3681   for (const auto *Result : DC->lookup(&CII))
3682     if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3683       return FD;
3684 
3685   if (!C.getLangOpts().CPlusPlus)
3686     return nullptr;
3687 
3688   // Demangle the premangled name from getTerminateFn()
3689   IdentifierInfo &CXXII =
3690       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
3691           ? C.Idents.get("terminate")
3692           : C.Idents.get(Name);
3693 
3694   for (const auto &N : {"__cxxabiv1", "std"}) {
3695     IdentifierInfo &NS = C.Idents.get(N);
3696     for (const auto *Result : DC->lookup(&NS)) {
3697       const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
3698       if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
3699         for (const auto *Result : LSD->lookup(&NS))
3700           if ((ND = dyn_cast<NamespaceDecl>(Result)))
3701             break;
3702 
3703       if (ND)
3704         for (const auto *Result : ND->lookup(&CXXII))
3705           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3706             return FD;
3707     }
3708   }
3709 
3710   return nullptr;
3711 }
3712 
3713 /// CreateRuntimeFunction - Create a new runtime function with the specified
3714 /// type and name.
3715 llvm::FunctionCallee
3716 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
3717                                      llvm::AttributeList ExtraAttrs, bool Local,
3718                                      bool AssumeConvergent) {
3719   if (AssumeConvergent) {
3720     ExtraAttrs =
3721         ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex,
3722                                 llvm::Attribute::Convergent);
3723   }
3724 
3725   llvm::Constant *C =
3726       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
3727                               /*DontDefer=*/false, /*IsThunk=*/false,
3728                               ExtraAttrs);
3729 
3730   if (auto *F = dyn_cast<llvm::Function>(C)) {
3731     if (F->empty()) {
3732       F->setCallingConv(getRuntimeCC());
3733 
3734       // In Windows Itanium environments, try to mark runtime functions
3735       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
3736       // will link their standard library statically or dynamically. Marking
3737       // functions imported when they are not imported can cause linker errors
3738       // and warnings.
3739       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
3740           !getCodeGenOpts().LTOVisibilityPublicStd) {
3741         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
3742         if (!FD || FD->hasAttr<DLLImportAttr>()) {
3743           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3744           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
3745         }
3746       }
3747       setDSOLocal(F);
3748     }
3749   }
3750 
3751   return {FTy, C};
3752 }
3753 
3754 /// isTypeConstant - Determine whether an object of this type can be emitted
3755 /// as a constant.
3756 ///
3757 /// If ExcludeCtor is true, the duration when the object's constructor runs
3758 /// will not be considered. The caller will need to verify that the object is
3759 /// not written to during its construction.
3760 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
3761   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
3762     return false;
3763 
3764   if (Context.getLangOpts().CPlusPlus) {
3765     if (const CXXRecordDecl *Record
3766           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
3767       return ExcludeCtor && !Record->hasMutableFields() &&
3768              Record->hasTrivialDestructor();
3769   }
3770 
3771   return true;
3772 }
3773 
3774 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
3775 /// create and return an llvm GlobalVariable with the specified type.  If there
3776 /// is something in the module with the specified name, return it potentially
3777 /// bitcasted to the right type.
3778 ///
3779 /// If D is non-null, it specifies a decl that correspond to this.  This is used
3780 /// to set the attributes on the global when it is first created.
3781 ///
3782 /// If IsForDefinition is true, it is guaranteed that an actual global with
3783 /// type Ty will be returned, not conversion of a variable with the same
3784 /// mangled name but some other type.
3785 llvm::Constant *
3786 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
3787                                      llvm::PointerType *Ty,
3788                                      const VarDecl *D,
3789                                      ForDefinition_t IsForDefinition) {
3790   // Lookup the entry, lazily creating it if necessary.
3791   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3792   if (Entry) {
3793     if (WeakRefReferences.erase(Entry)) {
3794       if (D && !D->hasAttr<WeakAttr>())
3795         Entry->setLinkage(llvm::Function::ExternalLinkage);
3796     }
3797 
3798     // Handle dropped DLL attributes.
3799     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
3800       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3801 
3802     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
3803       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
3804 
3805     if (Entry->getType() == Ty)
3806       return Entry;
3807 
3808     // If there are two attempts to define the same mangled name, issue an
3809     // error.
3810     if (IsForDefinition && !Entry->isDeclaration()) {
3811       GlobalDecl OtherGD;
3812       const VarDecl *OtherD;
3813 
3814       // Check that D is not yet in DiagnosedConflictingDefinitions is required
3815       // to make sure that we issue an error only once.
3816       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
3817           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3818           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
3819           OtherD->hasInit() &&
3820           DiagnosedConflictingDefinitions.insert(D).second) {
3821         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3822             << MangledName;
3823         getDiags().Report(OtherGD.getDecl()->getLocation(),
3824                           diag::note_previous_definition);
3825       }
3826     }
3827 
3828     // Make sure the result is of the correct type.
3829     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
3830       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
3831 
3832     // (If global is requested for a definition, we always need to create a new
3833     // global, not just return a bitcast.)
3834     if (!IsForDefinition)
3835       return llvm::ConstantExpr::getBitCast(Entry, Ty);
3836   }
3837 
3838   auto AddrSpace = GetGlobalVarAddressSpace(D);
3839   auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
3840 
3841   auto *GV = new llvm::GlobalVariable(
3842       getModule(), Ty->getElementType(), false,
3843       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
3844       llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
3845 
3846   // If we already created a global with the same mangled name (but different
3847   // type) before, take its name and remove it from its parent.
3848   if (Entry) {
3849     GV->takeName(Entry);
3850 
3851     if (!Entry->use_empty()) {
3852       llvm::Constant *NewPtrForOldDecl =
3853           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3854       Entry->replaceAllUsesWith(NewPtrForOldDecl);
3855     }
3856 
3857     Entry->eraseFromParent();
3858   }
3859 
3860   // This is the first use or definition of a mangled name.  If there is a
3861   // deferred decl with this name, remember that we need to emit it at the end
3862   // of the file.
3863   auto DDI = DeferredDecls.find(MangledName);
3864   if (DDI != DeferredDecls.end()) {
3865     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3866     // list, and remove it from DeferredDecls (since we don't need it anymore).
3867     addDeferredDeclToEmit(DDI->second);
3868     DeferredDecls.erase(DDI);
3869   }
3870 
3871   // Handle things which are present even on external declarations.
3872   if (D) {
3873     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3874       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3875 
3876     // FIXME: This code is overly simple and should be merged with other global
3877     // handling.
3878     GV->setConstant(isTypeConstant(D->getType(), false));
3879 
3880     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
3881 
3882     setLinkageForGV(GV, D);
3883 
3884     if (D->getTLSKind()) {
3885       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3886         CXXThreadLocals.push_back(D);
3887       setTLSMode(GV, *D);
3888     }
3889 
3890     setGVProperties(GV, D);
3891 
3892     // If required by the ABI, treat declarations of static data members with
3893     // inline initializers as definitions.
3894     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
3895       EmitGlobalVarDefinition(D);
3896     }
3897 
3898     // Emit section information for extern variables.
3899     if (D->hasExternalStorage()) {
3900       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3901         GV->setSection(SA->getName());
3902     }
3903 
3904     // Handle XCore specific ABI requirements.
3905     if (getTriple().getArch() == llvm::Triple::xcore &&
3906         D->getLanguageLinkage() == CLanguageLinkage &&
3907         D->getType().isConstant(Context) &&
3908         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3909       GV->setSection(".cp.rodata");
3910 
3911     // Check if we a have a const declaration with an initializer, we may be
3912     // able to emit it as available_externally to expose it's value to the
3913     // optimizer.
3914     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3915         D->getType().isConstQualified() && !GV->hasInitializer() &&
3916         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3917       const auto *Record =
3918           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3919       bool HasMutableFields = Record && Record->hasMutableFields();
3920       if (!HasMutableFields) {
3921         const VarDecl *InitDecl;
3922         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3923         if (InitExpr) {
3924           ConstantEmitter emitter(*this);
3925           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3926           if (Init) {
3927             auto *InitType = Init->getType();
3928             if (GV->getValueType() != InitType) {
3929               // The type of the initializer does not match the definition.
3930               // This happens when an initializer has a different type from
3931               // the type of the global (because of padding at the end of a
3932               // structure for instance).
3933               GV->setName(StringRef());
3934               // Make a new global with the correct type, this is now guaranteed
3935               // to work.
3936               auto *NewGV = cast<llvm::GlobalVariable>(
3937                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
3938                       ->stripPointerCasts());
3939 
3940               // Erase the old global, since it is no longer used.
3941               GV->eraseFromParent();
3942               GV = NewGV;
3943             } else {
3944               GV->setInitializer(Init);
3945               GV->setConstant(true);
3946               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3947             }
3948             emitter.finalize(GV);
3949           }
3950         }
3951       }
3952     }
3953   }
3954 
3955   if (GV->isDeclaration()) {
3956     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
3957     // External HIP managed variables needed to be recorded for transformation
3958     // in both device and host compilations.
3959     if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() &&
3960         D->hasExternalStorage())
3961       getCUDARuntime().handleVarRegistration(D, *GV);
3962   }
3963 
3964   LangAS ExpectedAS =
3965       D ? D->getType().getAddressSpace()
3966         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
3967   assert(getContext().getTargetAddressSpace(ExpectedAS) ==
3968          Ty->getPointerAddressSpace());
3969   if (AddrSpace != ExpectedAS)
3970     return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3971                                                        ExpectedAS, Ty);
3972 
3973   return GV;
3974 }
3975 
3976 llvm::Constant *
3977 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
3978   const Decl *D = GD.getDecl();
3979 
3980   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
3981     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3982                                 /*DontDefer=*/false, IsForDefinition);
3983 
3984   if (isa<CXXMethodDecl>(D)) {
3985     auto FInfo =
3986         &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
3987     auto Ty = getTypes().GetFunctionType(*FInfo);
3988     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3989                              IsForDefinition);
3990   }
3991 
3992   if (isa<FunctionDecl>(D)) {
3993     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3994     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3995     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3996                              IsForDefinition);
3997   }
3998 
3999   return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
4000 }
4001 
4002 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
4003     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
4004     unsigned Alignment) {
4005   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
4006   llvm::GlobalVariable *OldGV = nullptr;
4007 
4008   if (GV) {
4009     // Check if the variable has the right type.
4010     if (GV->getValueType() == Ty)
4011       return GV;
4012 
4013     // Because C++ name mangling, the only way we can end up with an already
4014     // existing global with the same name is if it has been declared extern "C".
4015     assert(GV->isDeclaration() && "Declaration has wrong type!");
4016     OldGV = GV;
4017   }
4018 
4019   // Create a new variable.
4020   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
4021                                 Linkage, nullptr, Name);
4022 
4023   if (OldGV) {
4024     // Replace occurrences of the old variable if needed.
4025     GV->takeName(OldGV);
4026 
4027     if (!OldGV->use_empty()) {
4028       llvm::Constant *NewPtrForOldDecl =
4029       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
4030       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
4031     }
4032 
4033     OldGV->eraseFromParent();
4034   }
4035 
4036   if (supportsCOMDAT() && GV->isWeakForLinker() &&
4037       !GV->hasAvailableExternallyLinkage())
4038     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4039 
4040   GV->setAlignment(llvm::MaybeAlign(Alignment));
4041 
4042   return GV;
4043 }
4044 
4045 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
4046 /// given global variable.  If Ty is non-null and if the global doesn't exist,
4047 /// then it will be created with the specified type instead of whatever the
4048 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
4049 /// that an actual global with type Ty will be returned, not conversion of a
4050 /// variable with the same mangled name but some other type.
4051 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
4052                                                   llvm::Type *Ty,
4053                                            ForDefinition_t IsForDefinition) {
4054   assert(D->hasGlobalStorage() && "Not a global variable");
4055   QualType ASTTy = D->getType();
4056   if (!Ty)
4057     Ty = getTypes().ConvertTypeForMem(ASTTy);
4058 
4059   llvm::PointerType *PTy =
4060     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
4061 
4062   StringRef MangledName = getMangledName(D);
4063   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
4064 }
4065 
4066 /// CreateRuntimeVariable - Create a new runtime global variable with the
4067 /// specified type and name.
4068 llvm::Constant *
4069 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
4070                                      StringRef Name) {
4071   auto PtrTy =
4072       getContext().getLangOpts().OpenCL
4073           ? llvm::PointerType::get(
4074                 Ty, getContext().getTargetAddressSpace(LangAS::opencl_global))
4075           : llvm::PointerType::getUnqual(Ty);
4076   auto *Ret = GetOrCreateLLVMGlobal(Name, PtrTy, nullptr);
4077   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
4078   return Ret;
4079 }
4080 
4081 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
4082   assert(!D->getInit() && "Cannot emit definite definitions here!");
4083 
4084   StringRef MangledName = getMangledName(D);
4085   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
4086 
4087   // We already have a definition, not declaration, with the same mangled name.
4088   // Emitting of declaration is not required (and actually overwrites emitted
4089   // definition).
4090   if (GV && !GV->isDeclaration())
4091     return;
4092 
4093   // If we have not seen a reference to this variable yet, place it into the
4094   // deferred declarations table to be emitted if needed later.
4095   if (!MustBeEmitted(D) && !GV) {
4096       DeferredDecls[MangledName] = D;
4097       return;
4098   }
4099 
4100   // The tentative definition is the only definition.
4101   EmitGlobalVarDefinition(D);
4102 }
4103 
4104 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
4105   EmitExternalVarDeclaration(D);
4106 }
4107 
4108 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
4109   return Context.toCharUnitsFromBits(
4110       getDataLayout().getTypeStoreSizeInBits(Ty));
4111 }
4112 
4113 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
4114   LangAS AddrSpace = LangAS::Default;
4115   if (LangOpts.OpenCL) {
4116     AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
4117     assert(AddrSpace == LangAS::opencl_global ||
4118            AddrSpace == LangAS::opencl_global_device ||
4119            AddrSpace == LangAS::opencl_global_host ||
4120            AddrSpace == LangAS::opencl_constant ||
4121            AddrSpace == LangAS::opencl_local ||
4122            AddrSpace >= LangAS::FirstTargetAddressSpace);
4123     return AddrSpace;
4124   }
4125 
4126   if (LangOpts.SYCLIsDevice &&
4127       (!D || D->getType().getAddressSpace() == LangAS::Default))
4128     return LangAS::sycl_global;
4129 
4130   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
4131     if (D && D->hasAttr<CUDAConstantAttr>())
4132       return LangAS::cuda_constant;
4133     else if (D && D->hasAttr<CUDASharedAttr>())
4134       return LangAS::cuda_shared;
4135     else if (D && D->hasAttr<CUDADeviceAttr>())
4136       return LangAS::cuda_device;
4137     else if (D && D->getType().isConstQualified())
4138       return LangAS::cuda_constant;
4139     else
4140       return LangAS::cuda_device;
4141   }
4142 
4143   if (LangOpts.OpenMP) {
4144     LangAS AS;
4145     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
4146       return AS;
4147   }
4148   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
4149 }
4150 
4151 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
4152   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
4153   if (LangOpts.OpenCL)
4154     return LangAS::opencl_constant;
4155   if (LangOpts.SYCLIsDevice)
4156     return LangAS::sycl_global;
4157   if (auto AS = getTarget().getConstantAddressSpace())
4158     return AS.getValue();
4159   return LangAS::Default;
4160 }
4161 
4162 // In address space agnostic languages, string literals are in default address
4163 // space in AST. However, certain targets (e.g. amdgcn) request them to be
4164 // emitted in constant address space in LLVM IR. To be consistent with other
4165 // parts of AST, string literal global variables in constant address space
4166 // need to be casted to default address space before being put into address
4167 // map and referenced by other part of CodeGen.
4168 // In OpenCL, string literals are in constant address space in AST, therefore
4169 // they should not be casted to default address space.
4170 static llvm::Constant *
4171 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
4172                                        llvm::GlobalVariable *GV) {
4173   llvm::Constant *Cast = GV;
4174   if (!CGM.getLangOpts().OpenCL) {
4175     auto AS = CGM.GetGlobalConstantAddressSpace();
4176     if (AS != LangAS::Default)
4177       Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
4178           CGM, GV, AS, LangAS::Default,
4179           GV->getValueType()->getPointerTo(
4180               CGM.getContext().getTargetAddressSpace(LangAS::Default)));
4181   }
4182   return Cast;
4183 }
4184 
4185 template<typename SomeDecl>
4186 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
4187                                                llvm::GlobalValue *GV) {
4188   if (!getLangOpts().CPlusPlus)
4189     return;
4190 
4191   // Must have 'used' attribute, or else inline assembly can't rely on
4192   // the name existing.
4193   if (!D->template hasAttr<UsedAttr>())
4194     return;
4195 
4196   // Must have internal linkage and an ordinary name.
4197   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
4198     return;
4199 
4200   // Must be in an extern "C" context. Entities declared directly within
4201   // a record are not extern "C" even if the record is in such a context.
4202   const SomeDecl *First = D->getFirstDecl();
4203   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
4204     return;
4205 
4206   // OK, this is an internal linkage entity inside an extern "C" linkage
4207   // specification. Make a note of that so we can give it the "expected"
4208   // mangled name if nothing else is using that name.
4209   std::pair<StaticExternCMap::iterator, bool> R =
4210       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
4211 
4212   // If we have multiple internal linkage entities with the same name
4213   // in extern "C" regions, none of them gets that name.
4214   if (!R.second)
4215     R.first->second = nullptr;
4216 }
4217 
4218 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
4219   if (!CGM.supportsCOMDAT())
4220     return false;
4221 
4222   // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
4223   // them being "merged" by the COMDAT Folding linker optimization.
4224   if (D.hasAttr<CUDAGlobalAttr>())
4225     return false;
4226 
4227   if (D.hasAttr<SelectAnyAttr>())
4228     return true;
4229 
4230   GVALinkage Linkage;
4231   if (auto *VD = dyn_cast<VarDecl>(&D))
4232     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
4233   else
4234     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
4235 
4236   switch (Linkage) {
4237   case GVA_Internal:
4238   case GVA_AvailableExternally:
4239   case GVA_StrongExternal:
4240     return false;
4241   case GVA_DiscardableODR:
4242   case GVA_StrongODR:
4243     return true;
4244   }
4245   llvm_unreachable("No such linkage");
4246 }
4247 
4248 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
4249                                           llvm::GlobalObject &GO) {
4250   if (!shouldBeInCOMDAT(*this, D))
4251     return;
4252   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
4253 }
4254 
4255 /// Pass IsTentative as true if you want to create a tentative definition.
4256 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
4257                                             bool IsTentative) {
4258   // OpenCL global variables of sampler type are translated to function calls,
4259   // therefore no need to be translated.
4260   QualType ASTTy = D->getType();
4261   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
4262     return;
4263 
4264   // If this is OpenMP device, check if it is legal to emit this global
4265   // normally.
4266   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
4267       OpenMPRuntime->emitTargetGlobalVariable(D))
4268     return;
4269 
4270   llvm::Constant *Init = nullptr;
4271   bool NeedsGlobalCtor = false;
4272   bool NeedsGlobalDtor =
4273       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
4274 
4275   const VarDecl *InitDecl;
4276   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
4277 
4278   Optional<ConstantEmitter> emitter;
4279 
4280   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
4281   // as part of their declaration."  Sema has already checked for
4282   // error cases, so we just need to set Init to UndefValue.
4283   bool IsCUDASharedVar =
4284       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
4285   // Shadows of initialized device-side global variables are also left
4286   // undefined.
4287   // Managed Variables should be initialized on both host side and device side.
4288   bool IsCUDAShadowVar =
4289       !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
4290       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4291        D->hasAttr<CUDASharedAttr>());
4292   bool IsCUDADeviceShadowVar =
4293       getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() &&
4294       (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4295        D->getType()->isCUDADeviceBuiltinTextureType());
4296   if (getLangOpts().CUDA &&
4297       (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
4298     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4299   else if (D->hasAttr<LoaderUninitializedAttr>())
4300     Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4301   else if (!InitExpr) {
4302     // This is a tentative definition; tentative definitions are
4303     // implicitly initialized with { 0 }.
4304     //
4305     // Note that tentative definitions are only emitted at the end of
4306     // a translation unit, so they should never have incomplete
4307     // type. In addition, EmitTentativeDefinition makes sure that we
4308     // never attempt to emit a tentative definition if a real one
4309     // exists. A use may still exists, however, so we still may need
4310     // to do a RAUW.
4311     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
4312     Init = EmitNullConstant(D->getType());
4313   } else {
4314     initializedGlobalDecl = GlobalDecl(D);
4315     emitter.emplace(*this);
4316     Init = emitter->tryEmitForInitializer(*InitDecl);
4317 
4318     if (!Init) {
4319       QualType T = InitExpr->getType();
4320       if (D->getType()->isReferenceType())
4321         T = D->getType();
4322 
4323       if (getLangOpts().CPlusPlus) {
4324         Init = EmitNullConstant(T);
4325         NeedsGlobalCtor = true;
4326       } else {
4327         ErrorUnsupported(D, "static initializer");
4328         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
4329       }
4330     } else {
4331       // We don't need an initializer, so remove the entry for the delayed
4332       // initializer position (just in case this entry was delayed) if we
4333       // also don't need to register a destructor.
4334       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
4335         DelayedCXXInitPosition.erase(D);
4336     }
4337   }
4338 
4339   llvm::Type* InitType = Init->getType();
4340   llvm::Constant *Entry =
4341       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
4342 
4343   // Strip off pointer casts if we got them.
4344   Entry = Entry->stripPointerCasts();
4345 
4346   // Entry is now either a Function or GlobalVariable.
4347   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
4348 
4349   // We have a definition after a declaration with the wrong type.
4350   // We must make a new GlobalVariable* and update everything that used OldGV
4351   // (a declaration or tentative definition) with the new GlobalVariable*
4352   // (which will be a definition).
4353   //
4354   // This happens if there is a prototype for a global (e.g.
4355   // "extern int x[];") and then a definition of a different type (e.g.
4356   // "int x[10];"). This also happens when an initializer has a different type
4357   // from the type of the global (this happens with unions).
4358   if (!GV || GV->getValueType() != InitType ||
4359       GV->getType()->getAddressSpace() !=
4360           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
4361 
4362     // Move the old entry aside so that we'll create a new one.
4363     Entry->setName(StringRef());
4364 
4365     // Make a new global with the correct type, this is now guaranteed to work.
4366     GV = cast<llvm::GlobalVariable>(
4367         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
4368             ->stripPointerCasts());
4369 
4370     // Replace all uses of the old global with the new global
4371     llvm::Constant *NewPtrForOldDecl =
4372         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
4373                                                              Entry->getType());
4374     Entry->replaceAllUsesWith(NewPtrForOldDecl);
4375 
4376     // Erase the old global, since it is no longer used.
4377     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
4378   }
4379 
4380   MaybeHandleStaticInExternC(D, GV);
4381 
4382   if (D->hasAttr<AnnotateAttr>())
4383     AddGlobalAnnotations(D, GV);
4384 
4385   // Set the llvm linkage type as appropriate.
4386   llvm::GlobalValue::LinkageTypes Linkage =
4387       getLLVMLinkageVarDefinition(D, GV->isConstant());
4388 
4389   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
4390   // the device. [...]"
4391   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
4392   // __device__, declares a variable that: [...]
4393   // Is accessible from all the threads within the grid and from the host
4394   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
4395   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
4396   if (GV && LangOpts.CUDA) {
4397     if (LangOpts.CUDAIsDevice) {
4398       if (Linkage != llvm::GlobalValue::InternalLinkage &&
4399           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()))
4400         GV->setExternallyInitialized(true);
4401     } else {
4402       getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
4403     }
4404     getCUDARuntime().handleVarRegistration(D, *GV);
4405   }
4406 
4407   GV->setInitializer(Init);
4408   if (emitter)
4409     emitter->finalize(GV);
4410 
4411   // If it is safe to mark the global 'constant', do so now.
4412   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
4413                   isTypeConstant(D->getType(), true));
4414 
4415   // If it is in a read-only section, mark it 'constant'.
4416   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
4417     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
4418     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
4419       GV->setConstant(true);
4420   }
4421 
4422   GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4423 
4424   // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
4425   // function is only defined alongside the variable, not also alongside
4426   // callers. Normally, all accesses to a thread_local go through the
4427   // thread-wrapper in order to ensure initialization has occurred, underlying
4428   // variable will never be used other than the thread-wrapper, so it can be
4429   // converted to internal linkage.
4430   //
4431   // However, if the variable has the 'constinit' attribute, it _can_ be
4432   // referenced directly, without calling the thread-wrapper, so the linkage
4433   // must not be changed.
4434   //
4435   // Additionally, if the variable isn't plain external linkage, e.g. if it's
4436   // weak or linkonce, the de-duplication semantics are important to preserve,
4437   // so we don't change the linkage.
4438   if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
4439       Linkage == llvm::GlobalValue::ExternalLinkage &&
4440       Context.getTargetInfo().getTriple().isOSDarwin() &&
4441       !D->hasAttr<ConstInitAttr>())
4442     Linkage = llvm::GlobalValue::InternalLinkage;
4443 
4444   GV->setLinkage(Linkage);
4445   if (D->hasAttr<DLLImportAttr>())
4446     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
4447   else if (D->hasAttr<DLLExportAttr>())
4448     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
4449   else
4450     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
4451 
4452   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
4453     // common vars aren't constant even if declared const.
4454     GV->setConstant(false);
4455     // Tentative definition of global variables may be initialized with
4456     // non-zero null pointers. In this case they should have weak linkage
4457     // since common linkage must have zero initializer and must not have
4458     // explicit section therefore cannot have non-zero initial value.
4459     if (!GV->getInitializer()->isNullValue())
4460       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
4461   }
4462 
4463   setNonAliasAttributes(D, GV);
4464 
4465   if (D->getTLSKind() && !GV->isThreadLocal()) {
4466     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4467       CXXThreadLocals.push_back(D);
4468     setTLSMode(GV, *D);
4469   }
4470 
4471   maybeSetTrivialComdat(*D, *GV);
4472 
4473   // Emit the initializer function if necessary.
4474   if (NeedsGlobalCtor || NeedsGlobalDtor)
4475     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
4476 
4477   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
4478 
4479   // Emit global variable debug information.
4480   if (CGDebugInfo *DI = getModuleDebugInfo())
4481     if (getCodeGenOpts().hasReducedDebugInfo())
4482       DI->EmitGlobalVariable(GV, D);
4483 }
4484 
4485 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
4486   if (CGDebugInfo *DI = getModuleDebugInfo())
4487     if (getCodeGenOpts().hasReducedDebugInfo()) {
4488       QualType ASTTy = D->getType();
4489       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
4490       llvm::PointerType *PTy =
4491           llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
4492       llvm::Constant *GV = GetOrCreateLLVMGlobal(D->getName(), PTy, D);
4493       DI->EmitExternalVariable(
4494           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
4495     }
4496 }
4497 
4498 static bool isVarDeclStrongDefinition(const ASTContext &Context,
4499                                       CodeGenModule &CGM, const VarDecl *D,
4500                                       bool NoCommon) {
4501   // Don't give variables common linkage if -fno-common was specified unless it
4502   // was overridden by a NoCommon attribute.
4503   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
4504     return true;
4505 
4506   // C11 6.9.2/2:
4507   //   A declaration of an identifier for an object that has file scope without
4508   //   an initializer, and without a storage-class specifier or with the
4509   //   storage-class specifier static, constitutes a tentative definition.
4510   if (D->getInit() || D->hasExternalStorage())
4511     return true;
4512 
4513   // A variable cannot be both common and exist in a section.
4514   if (D->hasAttr<SectionAttr>())
4515     return true;
4516 
4517   // A variable cannot be both common and exist in a section.
4518   // We don't try to determine which is the right section in the front-end.
4519   // If no specialized section name is applicable, it will resort to default.
4520   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
4521       D->hasAttr<PragmaClangDataSectionAttr>() ||
4522       D->hasAttr<PragmaClangRelroSectionAttr>() ||
4523       D->hasAttr<PragmaClangRodataSectionAttr>())
4524     return true;
4525 
4526   // Thread local vars aren't considered common linkage.
4527   if (D->getTLSKind())
4528     return true;
4529 
4530   // Tentative definitions marked with WeakImportAttr are true definitions.
4531   if (D->hasAttr<WeakImportAttr>())
4532     return true;
4533 
4534   // A variable cannot be both common and exist in a comdat.
4535   if (shouldBeInCOMDAT(CGM, *D))
4536     return true;
4537 
4538   // Declarations with a required alignment do not have common linkage in MSVC
4539   // mode.
4540   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4541     if (D->hasAttr<AlignedAttr>())
4542       return true;
4543     QualType VarType = D->getType();
4544     if (Context.isAlignmentRequired(VarType))
4545       return true;
4546 
4547     if (const auto *RT = VarType->getAs<RecordType>()) {
4548       const RecordDecl *RD = RT->getDecl();
4549       for (const FieldDecl *FD : RD->fields()) {
4550         if (FD->isBitField())
4551           continue;
4552         if (FD->hasAttr<AlignedAttr>())
4553           return true;
4554         if (Context.isAlignmentRequired(FD->getType()))
4555           return true;
4556       }
4557     }
4558   }
4559 
4560   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
4561   // common symbols, so symbols with greater alignment requirements cannot be
4562   // common.
4563   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
4564   // alignments for common symbols via the aligncomm directive, so this
4565   // restriction only applies to MSVC environments.
4566   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
4567       Context.getTypeAlignIfKnown(D->getType()) >
4568           Context.toBits(CharUnits::fromQuantity(32)))
4569     return true;
4570 
4571   return false;
4572 }
4573 
4574 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
4575     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
4576   if (Linkage == GVA_Internal)
4577     return llvm::Function::InternalLinkage;
4578 
4579   if (D->hasAttr<WeakAttr>()) {
4580     if (IsConstantVariable)
4581       return llvm::GlobalVariable::WeakODRLinkage;
4582     else
4583       return llvm::GlobalVariable::WeakAnyLinkage;
4584   }
4585 
4586   if (const auto *FD = D->getAsFunction())
4587     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
4588       return llvm::GlobalVariable::LinkOnceAnyLinkage;
4589 
4590   // We are guaranteed to have a strong definition somewhere else,
4591   // so we can use available_externally linkage.
4592   if (Linkage == GVA_AvailableExternally)
4593     return llvm::GlobalValue::AvailableExternallyLinkage;
4594 
4595   // Note that Apple's kernel linker doesn't support symbol
4596   // coalescing, so we need to avoid linkonce and weak linkages there.
4597   // Normally, this means we just map to internal, but for explicit
4598   // instantiations we'll map to external.
4599 
4600   // In C++, the compiler has to emit a definition in every translation unit
4601   // that references the function.  We should use linkonce_odr because
4602   // a) if all references in this translation unit are optimized away, we
4603   // don't need to codegen it.  b) if the function persists, it needs to be
4604   // merged with other definitions. c) C++ has the ODR, so we know the
4605   // definition is dependable.
4606   if (Linkage == GVA_DiscardableODR)
4607     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
4608                                             : llvm::Function::InternalLinkage;
4609 
4610   // An explicit instantiation of a template has weak linkage, since
4611   // explicit instantiations can occur in multiple translation units
4612   // and must all be equivalent. However, we are not allowed to
4613   // throw away these explicit instantiations.
4614   //
4615   // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
4616   // so say that CUDA templates are either external (for kernels) or internal.
4617   // This lets llvm perform aggressive inter-procedural optimizations. For
4618   // -fgpu-rdc case, device function calls across multiple TU's are allowed,
4619   // therefore we need to follow the normal linkage paradigm.
4620   if (Linkage == GVA_StrongODR) {
4621     if (getLangOpts().AppleKext)
4622       return llvm::Function::ExternalLinkage;
4623     if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
4624         !getLangOpts().GPURelocatableDeviceCode)
4625       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
4626                                           : llvm::Function::InternalLinkage;
4627     return llvm::Function::WeakODRLinkage;
4628   }
4629 
4630   // C++ doesn't have tentative definitions and thus cannot have common
4631   // linkage.
4632   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
4633       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
4634                                  CodeGenOpts.NoCommon))
4635     return llvm::GlobalVariable::CommonLinkage;
4636 
4637   // selectany symbols are externally visible, so use weak instead of
4638   // linkonce.  MSVC optimizes away references to const selectany globals, so
4639   // all definitions should be the same and ODR linkage should be used.
4640   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
4641   if (D->hasAttr<SelectAnyAttr>())
4642     return llvm::GlobalVariable::WeakODRLinkage;
4643 
4644   // Otherwise, we have strong external linkage.
4645   assert(Linkage == GVA_StrongExternal);
4646   return llvm::GlobalVariable::ExternalLinkage;
4647 }
4648 
4649 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
4650     const VarDecl *VD, bool IsConstant) {
4651   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
4652   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
4653 }
4654 
4655 /// Replace the uses of a function that was declared with a non-proto type.
4656 /// We want to silently drop extra arguments from call sites
4657 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
4658                                           llvm::Function *newFn) {
4659   // Fast path.
4660   if (old->use_empty()) return;
4661 
4662   llvm::Type *newRetTy = newFn->getReturnType();
4663   SmallVector<llvm::Value*, 4> newArgs;
4664 
4665   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
4666          ui != ue; ) {
4667     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
4668     llvm::User *user = use->getUser();
4669 
4670     // Recognize and replace uses of bitcasts.  Most calls to
4671     // unprototyped functions will use bitcasts.
4672     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
4673       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
4674         replaceUsesOfNonProtoConstant(bitcast, newFn);
4675       continue;
4676     }
4677 
4678     // Recognize calls to the function.
4679     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
4680     if (!callSite) continue;
4681     if (!callSite->isCallee(&*use))
4682       continue;
4683 
4684     // If the return types don't match exactly, then we can't
4685     // transform this call unless it's dead.
4686     if (callSite->getType() != newRetTy && !callSite->use_empty())
4687       continue;
4688 
4689     // Get the call site's attribute list.
4690     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
4691     llvm::AttributeList oldAttrs = callSite->getAttributes();
4692 
4693     // If the function was passed too few arguments, don't transform.
4694     unsigned newNumArgs = newFn->arg_size();
4695     if (callSite->arg_size() < newNumArgs)
4696       continue;
4697 
4698     // If extra arguments were passed, we silently drop them.
4699     // If any of the types mismatch, we don't transform.
4700     unsigned argNo = 0;
4701     bool dontTransform = false;
4702     for (llvm::Argument &A : newFn->args()) {
4703       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
4704         dontTransform = true;
4705         break;
4706       }
4707 
4708       // Add any parameter attributes.
4709       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
4710       argNo++;
4711     }
4712     if (dontTransform)
4713       continue;
4714 
4715     // Okay, we can transform this.  Create the new call instruction and copy
4716     // over the required information.
4717     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
4718 
4719     // Copy over any operand bundles.
4720     SmallVector<llvm::OperandBundleDef, 1> newBundles;
4721     callSite->getOperandBundlesAsDefs(newBundles);
4722 
4723     llvm::CallBase *newCall;
4724     if (dyn_cast<llvm::CallInst>(callSite)) {
4725       newCall =
4726           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
4727     } else {
4728       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
4729       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
4730                                          oldInvoke->getUnwindDest(), newArgs,
4731                                          newBundles, "", callSite);
4732     }
4733     newArgs.clear(); // for the next iteration
4734 
4735     if (!newCall->getType()->isVoidTy())
4736       newCall->takeName(callSite);
4737     newCall->setAttributes(llvm::AttributeList::get(
4738         newFn->getContext(), oldAttrs.getFnAttributes(),
4739         oldAttrs.getRetAttributes(), newArgAttrs));
4740     newCall->setCallingConv(callSite->getCallingConv());
4741 
4742     // Finally, remove the old call, replacing any uses with the new one.
4743     if (!callSite->use_empty())
4744       callSite->replaceAllUsesWith(newCall);
4745 
4746     // Copy debug location attached to CI.
4747     if (callSite->getDebugLoc())
4748       newCall->setDebugLoc(callSite->getDebugLoc());
4749 
4750     callSite->eraseFromParent();
4751   }
4752 }
4753 
4754 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
4755 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
4756 /// existing call uses of the old function in the module, this adjusts them to
4757 /// call the new function directly.
4758 ///
4759 /// This is not just a cleanup: the always_inline pass requires direct calls to
4760 /// functions to be able to inline them.  If there is a bitcast in the way, it
4761 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
4762 /// run at -O0.
4763 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4764                                                       llvm::Function *NewFn) {
4765   // If we're redefining a global as a function, don't transform it.
4766   if (!isa<llvm::Function>(Old)) return;
4767 
4768   replaceUsesOfNonProtoConstant(Old, NewFn);
4769 }
4770 
4771 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
4772   auto DK = VD->isThisDeclarationADefinition();
4773   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
4774     return;
4775 
4776   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
4777   // If we have a definition, this might be a deferred decl. If the
4778   // instantiation is explicit, make sure we emit it at the end.
4779   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
4780     GetAddrOfGlobalVar(VD);
4781 
4782   EmitTopLevelDecl(VD);
4783 }
4784 
4785 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
4786                                                  llvm::GlobalValue *GV) {
4787   const auto *D = cast<FunctionDecl>(GD.getDecl());
4788 
4789   // Compute the function info and LLVM type.
4790   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4791   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4792 
4793   // Get or create the prototype for the function.
4794   if (!GV || (GV->getValueType() != Ty))
4795     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
4796                                                    /*DontDefer=*/true,
4797                                                    ForDefinition));
4798 
4799   // Already emitted.
4800   if (!GV->isDeclaration())
4801     return;
4802 
4803   // We need to set linkage and visibility on the function before
4804   // generating code for it because various parts of IR generation
4805   // want to propagate this information down (e.g. to local static
4806   // declarations).
4807   auto *Fn = cast<llvm::Function>(GV);
4808   setFunctionLinkage(GD, Fn);
4809 
4810   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
4811   setGVProperties(Fn, GD);
4812 
4813   MaybeHandleStaticInExternC(D, Fn);
4814 
4815   maybeSetTrivialComdat(*D, *Fn);
4816 
4817   // Set CodeGen attributes that represent floating point environment.
4818   setLLVMFunctionFEnvAttributes(D, Fn);
4819 
4820   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
4821 
4822   setNonAliasAttributes(GD, Fn);
4823   SetLLVMFunctionAttributesForDefinition(D, Fn);
4824 
4825   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
4826     AddGlobalCtor(Fn, CA->getPriority());
4827   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
4828     AddGlobalDtor(Fn, DA->getPriority(), true);
4829   if (D->hasAttr<AnnotateAttr>())
4830     AddGlobalAnnotations(D, Fn);
4831 }
4832 
4833 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
4834   const auto *D = cast<ValueDecl>(GD.getDecl());
4835   const AliasAttr *AA = D->getAttr<AliasAttr>();
4836   assert(AA && "Not an alias?");
4837 
4838   StringRef MangledName = getMangledName(GD);
4839 
4840   if (AA->getAliasee() == MangledName) {
4841     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4842     return;
4843   }
4844 
4845   // If there is a definition in the module, then it wins over the alias.
4846   // This is dubious, but allow it to be safe.  Just ignore the alias.
4847   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4848   if (Entry && !Entry->isDeclaration())
4849     return;
4850 
4851   Aliases.push_back(GD);
4852 
4853   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4854 
4855   // Create a reference to the named value.  This ensures that it is emitted
4856   // if a deferred decl.
4857   llvm::Constant *Aliasee;
4858   llvm::GlobalValue::LinkageTypes LT;
4859   if (isa<llvm::FunctionType>(DeclTy)) {
4860     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
4861                                       /*ForVTable=*/false);
4862     LT = getFunctionLinkage(GD);
4863   } else {
4864     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
4865                                     llvm::PointerType::getUnqual(DeclTy),
4866                                     /*D=*/nullptr);
4867     if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
4868       LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified());
4869     else
4870       LT = getFunctionLinkage(GD);
4871   }
4872 
4873   // Create the new alias itself, but don't set a name yet.
4874   unsigned AS = Aliasee->getType()->getPointerAddressSpace();
4875   auto *GA =
4876       llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
4877 
4878   if (Entry) {
4879     if (GA->getAliasee() == Entry) {
4880       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4881       return;
4882     }
4883 
4884     assert(Entry->isDeclaration());
4885 
4886     // If there is a declaration in the module, then we had an extern followed
4887     // by the alias, as in:
4888     //   extern int test6();
4889     //   ...
4890     //   int test6() __attribute__((alias("test7")));
4891     //
4892     // Remove it and replace uses of it with the alias.
4893     GA->takeName(Entry);
4894 
4895     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
4896                                                           Entry->getType()));
4897     Entry->eraseFromParent();
4898   } else {
4899     GA->setName(MangledName);
4900   }
4901 
4902   // Set attributes which are particular to an alias; this is a
4903   // specialization of the attributes which may be set on a global
4904   // variable/function.
4905   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
4906       D->isWeakImported()) {
4907     GA->setLinkage(llvm::Function::WeakAnyLinkage);
4908   }
4909 
4910   if (const auto *VD = dyn_cast<VarDecl>(D))
4911     if (VD->getTLSKind())
4912       setTLSMode(GA, *VD);
4913 
4914   SetCommonAttributes(GD, GA);
4915 }
4916 
4917 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4918   const auto *D = cast<ValueDecl>(GD.getDecl());
4919   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4920   assert(IFA && "Not an ifunc?");
4921 
4922   StringRef MangledName = getMangledName(GD);
4923 
4924   if (IFA->getResolver() == MangledName) {
4925     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4926     return;
4927   }
4928 
4929   // Report an error if some definition overrides ifunc.
4930   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4931   if (Entry && !Entry->isDeclaration()) {
4932     GlobalDecl OtherGD;
4933     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4934         DiagnosedConflictingDefinitions.insert(GD).second) {
4935       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4936           << MangledName;
4937       Diags.Report(OtherGD.getDecl()->getLocation(),
4938                    diag::note_previous_definition);
4939     }
4940     return;
4941   }
4942 
4943   Aliases.push_back(GD);
4944 
4945   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4946   llvm::Constant *Resolver =
4947       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4948                               /*ForVTable=*/false);
4949   llvm::GlobalIFunc *GIF =
4950       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4951                                 "", Resolver, &getModule());
4952   if (Entry) {
4953     if (GIF->getResolver() == Entry) {
4954       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4955       return;
4956     }
4957     assert(Entry->isDeclaration());
4958 
4959     // If there is a declaration in the module, then we had an extern followed
4960     // by the ifunc, as in:
4961     //   extern int test();
4962     //   ...
4963     //   int test() __attribute__((ifunc("resolver")));
4964     //
4965     // Remove it and replace uses of it with the ifunc.
4966     GIF->takeName(Entry);
4967 
4968     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4969                                                           Entry->getType()));
4970     Entry->eraseFromParent();
4971   } else
4972     GIF->setName(MangledName);
4973 
4974   SetCommonAttributes(GD, GIF);
4975 }
4976 
4977 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
4978                                             ArrayRef<llvm::Type*> Tys) {
4979   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
4980                                          Tys);
4981 }
4982 
4983 static llvm::StringMapEntry<llvm::GlobalVariable *> &
4984 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
4985                          const StringLiteral *Literal, bool TargetIsLSB,
4986                          bool &IsUTF16, unsigned &StringLength) {
4987   StringRef String = Literal->getString();
4988   unsigned NumBytes = String.size();
4989 
4990   // Check for simple case.
4991   if (!Literal->containsNonAsciiOrNull()) {
4992     StringLength = NumBytes;
4993     return *Map.insert(std::make_pair(String, nullptr)).first;
4994   }
4995 
4996   // Otherwise, convert the UTF8 literals into a string of shorts.
4997   IsUTF16 = true;
4998 
4999   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
5000   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5001   llvm::UTF16 *ToPtr = &ToBuf[0];
5002 
5003   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5004                                  ToPtr + NumBytes, llvm::strictConversion);
5005 
5006   // ConvertUTF8toUTF16 returns the length in ToPtr.
5007   StringLength = ToPtr - &ToBuf[0];
5008 
5009   // Add an explicit null.
5010   *ToPtr = 0;
5011   return *Map.insert(std::make_pair(
5012                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
5013                                    (StringLength + 1) * 2),
5014                          nullptr)).first;
5015 }
5016 
5017 ConstantAddress
5018 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
5019   unsigned StringLength = 0;
5020   bool isUTF16 = false;
5021   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
5022       GetConstantCFStringEntry(CFConstantStringMap, Literal,
5023                                getDataLayout().isLittleEndian(), isUTF16,
5024                                StringLength);
5025 
5026   if (auto *C = Entry.second)
5027     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
5028 
5029   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
5030   llvm::Constant *Zeros[] = { Zero, Zero };
5031 
5032   const ASTContext &Context = getContext();
5033   const llvm::Triple &Triple = getTriple();
5034 
5035   const auto CFRuntime = getLangOpts().CFRuntime;
5036   const bool IsSwiftABI =
5037       static_cast<unsigned>(CFRuntime) >=
5038       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
5039   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
5040 
5041   // If we don't already have it, get __CFConstantStringClassReference.
5042   if (!CFConstantStringClassRef) {
5043     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
5044     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
5045     Ty = llvm::ArrayType::get(Ty, 0);
5046 
5047     switch (CFRuntime) {
5048     default: break;
5049     case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
5050     case LangOptions::CoreFoundationABI::Swift5_0:
5051       CFConstantStringClassName =
5052           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
5053                               : "$s10Foundation19_NSCFConstantStringCN";
5054       Ty = IntPtrTy;
5055       break;
5056     case LangOptions::CoreFoundationABI::Swift4_2:
5057       CFConstantStringClassName =
5058           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
5059                               : "$S10Foundation19_NSCFConstantStringCN";
5060       Ty = IntPtrTy;
5061       break;
5062     case LangOptions::CoreFoundationABI::Swift4_1:
5063       CFConstantStringClassName =
5064           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
5065                               : "__T010Foundation19_NSCFConstantStringCN";
5066       Ty = IntPtrTy;
5067       break;
5068     }
5069 
5070     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
5071 
5072     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
5073       llvm::GlobalValue *GV = nullptr;
5074 
5075       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
5076         IdentifierInfo &II = Context.Idents.get(GV->getName());
5077         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
5078         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
5079 
5080         const VarDecl *VD = nullptr;
5081         for (const auto *Result : DC->lookup(&II))
5082           if ((VD = dyn_cast<VarDecl>(Result)))
5083             break;
5084 
5085         if (Triple.isOSBinFormatELF()) {
5086           if (!VD)
5087             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5088         } else {
5089           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
5090           if (!VD || !VD->hasAttr<DLLExportAttr>())
5091             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
5092           else
5093             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
5094         }
5095 
5096         setDSOLocal(GV);
5097       }
5098     }
5099 
5100     // Decay array -> ptr
5101     CFConstantStringClassRef =
5102         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
5103                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
5104   }
5105 
5106   QualType CFTy = Context.getCFConstantStringType();
5107 
5108   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
5109 
5110   ConstantInitBuilder Builder(*this);
5111   auto Fields = Builder.beginStruct(STy);
5112 
5113   // Class pointer.
5114   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
5115 
5116   // Flags.
5117   if (IsSwiftABI) {
5118     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
5119     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
5120   } else {
5121     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
5122   }
5123 
5124   // String pointer.
5125   llvm::Constant *C = nullptr;
5126   if (isUTF16) {
5127     auto Arr = llvm::makeArrayRef(
5128         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
5129         Entry.first().size() / 2);
5130     C = llvm::ConstantDataArray::get(VMContext, Arr);
5131   } else {
5132     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
5133   }
5134 
5135   // Note: -fwritable-strings doesn't make the backing store strings of
5136   // CFStrings writable. (See <rdar://problem/10657500>)
5137   auto *GV =
5138       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
5139                                llvm::GlobalValue::PrivateLinkage, C, ".str");
5140   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5141   // Don't enforce the target's minimum global alignment, since the only use
5142   // of the string is via this class initializer.
5143   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
5144                             : Context.getTypeAlignInChars(Context.CharTy);
5145   GV->setAlignment(Align.getAsAlign());
5146 
5147   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
5148   // Without it LLVM can merge the string with a non unnamed_addr one during
5149   // LTO.  Doing that changes the section it ends in, which surprises ld64.
5150   if (Triple.isOSBinFormatMachO())
5151     GV->setSection(isUTF16 ? "__TEXT,__ustring"
5152                            : "__TEXT,__cstring,cstring_literals");
5153   // Make sure the literal ends up in .rodata to allow for safe ICF and for
5154   // the static linker to adjust permissions to read-only later on.
5155   else if (Triple.isOSBinFormatELF())
5156     GV->setSection(".rodata");
5157 
5158   // String.
5159   llvm::Constant *Str =
5160       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
5161 
5162   if (isUTF16)
5163     // Cast the UTF16 string to the correct type.
5164     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
5165   Fields.add(Str);
5166 
5167   // String length.
5168   llvm::IntegerType *LengthTy =
5169       llvm::IntegerType::get(getModule().getContext(),
5170                              Context.getTargetInfo().getLongWidth());
5171   if (IsSwiftABI) {
5172     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5173         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5174       LengthTy = Int32Ty;
5175     else
5176       LengthTy = IntPtrTy;
5177   }
5178   Fields.addInt(LengthTy, StringLength);
5179 
5180   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
5181   // properly aligned on 32-bit platforms.
5182   CharUnits Alignment =
5183       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
5184 
5185   // The struct.
5186   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
5187                                     /*isConstant=*/false,
5188                                     llvm::GlobalVariable::PrivateLinkage);
5189   GV->addAttribute("objc_arc_inert");
5190   switch (Triple.getObjectFormat()) {
5191   case llvm::Triple::UnknownObjectFormat:
5192     llvm_unreachable("unknown file format");
5193   case llvm::Triple::GOFF:
5194     llvm_unreachable("GOFF is not yet implemented");
5195   case llvm::Triple::XCOFF:
5196     llvm_unreachable("XCOFF is not yet implemented");
5197   case llvm::Triple::COFF:
5198   case llvm::Triple::ELF:
5199   case llvm::Triple::Wasm:
5200     GV->setSection("cfstring");
5201     break;
5202   case llvm::Triple::MachO:
5203     GV->setSection("__DATA,__cfstring");
5204     break;
5205   }
5206   Entry.second = GV;
5207 
5208   return ConstantAddress(GV, Alignment);
5209 }
5210 
5211 bool CodeGenModule::getExpressionLocationsEnabled() const {
5212   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
5213 }
5214 
5215 QualType CodeGenModule::getObjCFastEnumerationStateType() {
5216   if (ObjCFastEnumerationStateType.isNull()) {
5217     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
5218     D->startDefinition();
5219 
5220     QualType FieldTypes[] = {
5221       Context.UnsignedLongTy,
5222       Context.getPointerType(Context.getObjCIdType()),
5223       Context.getPointerType(Context.UnsignedLongTy),
5224       Context.getConstantArrayType(Context.UnsignedLongTy,
5225                            llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
5226     };
5227 
5228     for (size_t i = 0; i < 4; ++i) {
5229       FieldDecl *Field = FieldDecl::Create(Context,
5230                                            D,
5231                                            SourceLocation(),
5232                                            SourceLocation(), nullptr,
5233                                            FieldTypes[i], /*TInfo=*/nullptr,
5234                                            /*BitWidth=*/nullptr,
5235                                            /*Mutable=*/false,
5236                                            ICIS_NoInit);
5237       Field->setAccess(AS_public);
5238       D->addDecl(Field);
5239     }
5240 
5241     D->completeDefinition();
5242     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
5243   }
5244 
5245   return ObjCFastEnumerationStateType;
5246 }
5247 
5248 llvm::Constant *
5249 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
5250   assert(!E->getType()->isPointerType() && "Strings are always arrays");
5251 
5252   // Don't emit it as the address of the string, emit the string data itself
5253   // as an inline array.
5254   if (E->getCharByteWidth() == 1) {
5255     SmallString<64> Str(E->getString());
5256 
5257     // Resize the string to the right size, which is indicated by its type.
5258     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
5259     Str.resize(CAT->getSize().getZExtValue());
5260     return llvm::ConstantDataArray::getString(VMContext, Str, false);
5261   }
5262 
5263   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
5264   llvm::Type *ElemTy = AType->getElementType();
5265   unsigned NumElements = AType->getNumElements();
5266 
5267   // Wide strings have either 2-byte or 4-byte elements.
5268   if (ElemTy->getPrimitiveSizeInBits() == 16) {
5269     SmallVector<uint16_t, 32> Elements;
5270     Elements.reserve(NumElements);
5271 
5272     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5273       Elements.push_back(E->getCodeUnit(i));
5274     Elements.resize(NumElements);
5275     return llvm::ConstantDataArray::get(VMContext, Elements);
5276   }
5277 
5278   assert(ElemTy->getPrimitiveSizeInBits() == 32);
5279   SmallVector<uint32_t, 32> Elements;
5280   Elements.reserve(NumElements);
5281 
5282   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5283     Elements.push_back(E->getCodeUnit(i));
5284   Elements.resize(NumElements);
5285   return llvm::ConstantDataArray::get(VMContext, Elements);
5286 }
5287 
5288 static llvm::GlobalVariable *
5289 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
5290                       CodeGenModule &CGM, StringRef GlobalName,
5291                       CharUnits Alignment) {
5292   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
5293       CGM.GetGlobalConstantAddressSpace());
5294 
5295   llvm::Module &M = CGM.getModule();
5296   // Create a global variable for this string
5297   auto *GV = new llvm::GlobalVariable(
5298       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
5299       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
5300   GV->setAlignment(Alignment.getAsAlign());
5301   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5302   if (GV->isWeakForLinker()) {
5303     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
5304     GV->setComdat(M.getOrInsertComdat(GV->getName()));
5305   }
5306   CGM.setDSOLocal(GV);
5307 
5308   return GV;
5309 }
5310 
5311 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
5312 /// constant array for the given string literal.
5313 ConstantAddress
5314 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
5315                                                   StringRef Name) {
5316   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
5317 
5318   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
5319   llvm::GlobalVariable **Entry = nullptr;
5320   if (!LangOpts.WritableStrings) {
5321     Entry = &ConstantStringMap[C];
5322     if (auto GV = *Entry) {
5323       if (Alignment.getQuantity() > GV->getAlignment())
5324         GV->setAlignment(Alignment.getAsAlign());
5325       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5326                              Alignment);
5327     }
5328   }
5329 
5330   SmallString<256> MangledNameBuffer;
5331   StringRef GlobalVariableName;
5332   llvm::GlobalValue::LinkageTypes LT;
5333 
5334   // Mangle the string literal if that's how the ABI merges duplicate strings.
5335   // Don't do it if they are writable, since we don't want writes in one TU to
5336   // affect strings in another.
5337   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
5338       !LangOpts.WritableStrings) {
5339     llvm::raw_svector_ostream Out(MangledNameBuffer);
5340     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
5341     LT = llvm::GlobalValue::LinkOnceODRLinkage;
5342     GlobalVariableName = MangledNameBuffer;
5343   } else {
5344     LT = llvm::GlobalValue::PrivateLinkage;
5345     GlobalVariableName = Name;
5346   }
5347 
5348   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
5349   if (Entry)
5350     *Entry = GV;
5351 
5352   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
5353                                   QualType());
5354 
5355   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5356                          Alignment);
5357 }
5358 
5359 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
5360 /// array for the given ObjCEncodeExpr node.
5361 ConstantAddress
5362 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
5363   std::string Str;
5364   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
5365 
5366   return GetAddrOfConstantCString(Str);
5367 }
5368 
5369 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
5370 /// the literal and a terminating '\0' character.
5371 /// The result has pointer to array type.
5372 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
5373     const std::string &Str, const char *GlobalName) {
5374   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
5375   CharUnits Alignment =
5376     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
5377 
5378   llvm::Constant *C =
5379       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
5380 
5381   // Don't share any string literals if strings aren't constant.
5382   llvm::GlobalVariable **Entry = nullptr;
5383   if (!LangOpts.WritableStrings) {
5384     Entry = &ConstantStringMap[C];
5385     if (auto GV = *Entry) {
5386       if (Alignment.getQuantity() > GV->getAlignment())
5387         GV->setAlignment(Alignment.getAsAlign());
5388       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5389                              Alignment);
5390     }
5391   }
5392 
5393   // Get the default prefix if a name wasn't specified.
5394   if (!GlobalName)
5395     GlobalName = ".str";
5396   // Create a global variable for this.
5397   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
5398                                   GlobalName, Alignment);
5399   if (Entry)
5400     *Entry = GV;
5401 
5402   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5403                          Alignment);
5404 }
5405 
5406 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
5407     const MaterializeTemporaryExpr *E, const Expr *Init) {
5408   assert((E->getStorageDuration() == SD_Static ||
5409           E->getStorageDuration() == SD_Thread) && "not a global temporary");
5410   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
5411 
5412   // If we're not materializing a subobject of the temporary, keep the
5413   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
5414   QualType MaterializedType = Init->getType();
5415   if (Init == E->getSubExpr())
5416     MaterializedType = E->getType();
5417 
5418   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
5419 
5420   auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr});
5421   if (!InsertResult.second) {
5422     // We've seen this before: either we already created it or we're in the
5423     // process of doing so.
5424     if (!InsertResult.first->second) {
5425       // We recursively re-entered this function, probably during emission of
5426       // the initializer. Create a placeholder. We'll clean this up in the
5427       // outer call, at the end of this function.
5428       llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType);
5429       InsertResult.first->second = new llvm::GlobalVariable(
5430           getModule(), Type, false, llvm::GlobalVariable::InternalLinkage,
5431           nullptr);
5432     }
5433     return ConstantAddress(InsertResult.first->second, Align);
5434   }
5435 
5436   // FIXME: If an externally-visible declaration extends multiple temporaries,
5437   // we need to give each temporary the same name in every translation unit (and
5438   // we also need to make the temporaries externally-visible).
5439   SmallString<256> Name;
5440   llvm::raw_svector_ostream Out(Name);
5441   getCXXABI().getMangleContext().mangleReferenceTemporary(
5442       VD, E->getManglingNumber(), Out);
5443 
5444   APValue *Value = nullptr;
5445   if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
5446     // If the initializer of the extending declaration is a constant
5447     // initializer, we should have a cached constant initializer for this
5448     // temporary. Note that this might have a different value from the value
5449     // computed by evaluating the initializer if the surrounding constant
5450     // expression modifies the temporary.
5451     Value = E->getOrCreateValue(false);
5452   }
5453 
5454   // Try evaluating it now, it might have a constant initializer.
5455   Expr::EvalResult EvalResult;
5456   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
5457       !EvalResult.hasSideEffects())
5458     Value = &EvalResult.Val;
5459 
5460   LangAS AddrSpace =
5461       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
5462 
5463   Optional<ConstantEmitter> emitter;
5464   llvm::Constant *InitialValue = nullptr;
5465   bool Constant = false;
5466   llvm::Type *Type;
5467   if (Value) {
5468     // The temporary has a constant initializer, use it.
5469     emitter.emplace(*this);
5470     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
5471                                                MaterializedType);
5472     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
5473     Type = InitialValue->getType();
5474   } else {
5475     // No initializer, the initialization will be provided when we
5476     // initialize the declaration which performed lifetime extension.
5477     Type = getTypes().ConvertTypeForMem(MaterializedType);
5478   }
5479 
5480   // Create a global variable for this lifetime-extended temporary.
5481   llvm::GlobalValue::LinkageTypes Linkage =
5482       getLLVMLinkageVarDefinition(VD, Constant);
5483   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
5484     const VarDecl *InitVD;
5485     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
5486         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
5487       // Temporaries defined inside a class get linkonce_odr linkage because the
5488       // class can be defined in multiple translation units.
5489       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
5490     } else {
5491       // There is no need for this temporary to have external linkage if the
5492       // VarDecl has external linkage.
5493       Linkage = llvm::GlobalVariable::InternalLinkage;
5494     }
5495   }
5496   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
5497   auto *GV = new llvm::GlobalVariable(
5498       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
5499       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
5500   if (emitter) emitter->finalize(GV);
5501   setGVProperties(GV, VD);
5502   GV->setAlignment(Align.getAsAlign());
5503   if (supportsCOMDAT() && GV->isWeakForLinker())
5504     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5505   if (VD->getTLSKind())
5506     setTLSMode(GV, *VD);
5507   llvm::Constant *CV = GV;
5508   if (AddrSpace != LangAS::Default)
5509     CV = getTargetCodeGenInfo().performAddrSpaceCast(
5510         *this, GV, AddrSpace, LangAS::Default,
5511         Type->getPointerTo(
5512             getContext().getTargetAddressSpace(LangAS::Default)));
5513 
5514   // Update the map with the new temporary. If we created a placeholder above,
5515   // replace it with the new global now.
5516   llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E];
5517   if (Entry) {
5518     Entry->replaceAllUsesWith(
5519         llvm::ConstantExpr::getBitCast(CV, Entry->getType()));
5520     llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent();
5521   }
5522   Entry = CV;
5523 
5524   return ConstantAddress(CV, Align);
5525 }
5526 
5527 /// EmitObjCPropertyImplementations - Emit information for synthesized
5528 /// properties for an implementation.
5529 void CodeGenModule::EmitObjCPropertyImplementations(const
5530                                                     ObjCImplementationDecl *D) {
5531   for (const auto *PID : D->property_impls()) {
5532     // Dynamic is just for type-checking.
5533     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
5534       ObjCPropertyDecl *PD = PID->getPropertyDecl();
5535 
5536       // Determine which methods need to be implemented, some may have
5537       // been overridden. Note that ::isPropertyAccessor is not the method
5538       // we want, that just indicates if the decl came from a
5539       // property. What we want to know is if the method is defined in
5540       // this implementation.
5541       auto *Getter = PID->getGetterMethodDecl();
5542       if (!Getter || Getter->isSynthesizedAccessorStub())
5543         CodeGenFunction(*this).GenerateObjCGetter(
5544             const_cast<ObjCImplementationDecl *>(D), PID);
5545       auto *Setter = PID->getSetterMethodDecl();
5546       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
5547         CodeGenFunction(*this).GenerateObjCSetter(
5548                                  const_cast<ObjCImplementationDecl *>(D), PID);
5549     }
5550   }
5551 }
5552 
5553 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
5554   const ObjCInterfaceDecl *iface = impl->getClassInterface();
5555   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
5556        ivar; ivar = ivar->getNextIvar())
5557     if (ivar->getType().isDestructedType())
5558       return true;
5559 
5560   return false;
5561 }
5562 
5563 static bool AllTrivialInitializers(CodeGenModule &CGM,
5564                                    ObjCImplementationDecl *D) {
5565   CodeGenFunction CGF(CGM);
5566   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
5567        E = D->init_end(); B != E; ++B) {
5568     CXXCtorInitializer *CtorInitExp = *B;
5569     Expr *Init = CtorInitExp->getInit();
5570     if (!CGF.isTrivialInitializer(Init))
5571       return false;
5572   }
5573   return true;
5574 }
5575 
5576 /// EmitObjCIvarInitializations - Emit information for ivar initialization
5577 /// for an implementation.
5578 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
5579   // We might need a .cxx_destruct even if we don't have any ivar initializers.
5580   if (needsDestructMethod(D)) {
5581     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
5582     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5583     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
5584         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5585         getContext().VoidTy, nullptr, D,
5586         /*isInstance=*/true, /*isVariadic=*/false,
5587         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5588         /*isImplicitlyDeclared=*/true,
5589         /*isDefined=*/false, ObjCMethodDecl::Required);
5590     D->addInstanceMethod(DTORMethod);
5591     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
5592     D->setHasDestructors(true);
5593   }
5594 
5595   // If the implementation doesn't have any ivar initializers, we don't need
5596   // a .cxx_construct.
5597   if (D->getNumIvarInitializers() == 0 ||
5598       AllTrivialInitializers(*this, D))
5599     return;
5600 
5601   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
5602   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5603   // The constructor returns 'self'.
5604   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
5605       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5606       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
5607       /*isVariadic=*/false,
5608       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5609       /*isImplicitlyDeclared=*/true,
5610       /*isDefined=*/false, ObjCMethodDecl::Required);
5611   D->addInstanceMethod(CTORMethod);
5612   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
5613   D->setHasNonZeroConstructors(true);
5614 }
5615 
5616 // EmitLinkageSpec - Emit all declarations in a linkage spec.
5617 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
5618   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5619       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
5620     ErrorUnsupported(LSD, "linkage spec");
5621     return;
5622   }
5623 
5624   EmitDeclContext(LSD);
5625 }
5626 
5627 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
5628   for (auto *I : DC->decls()) {
5629     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
5630     // are themselves considered "top-level", so EmitTopLevelDecl on an
5631     // ObjCImplDecl does not recursively visit them. We need to do that in
5632     // case they're nested inside another construct (LinkageSpecDecl /
5633     // ExportDecl) that does stop them from being considered "top-level".
5634     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
5635       for (auto *M : OID->methods())
5636         EmitTopLevelDecl(M);
5637     }
5638 
5639     EmitTopLevelDecl(I);
5640   }
5641 }
5642 
5643 /// EmitTopLevelDecl - Emit code for a single top level declaration.
5644 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
5645   // Ignore dependent declarations.
5646   if (D->isTemplated())
5647     return;
5648 
5649   // Consteval function shouldn't be emitted.
5650   if (auto *FD = dyn_cast<FunctionDecl>(D))
5651     if (FD->isConsteval())
5652       return;
5653 
5654   switch (D->getKind()) {
5655   case Decl::CXXConversion:
5656   case Decl::CXXMethod:
5657   case Decl::Function:
5658     EmitGlobal(cast<FunctionDecl>(D));
5659     // Always provide some coverage mapping
5660     // even for the functions that aren't emitted.
5661     AddDeferredUnusedCoverageMapping(D);
5662     break;
5663 
5664   case Decl::CXXDeductionGuide:
5665     // Function-like, but does not result in code emission.
5666     break;
5667 
5668   case Decl::Var:
5669   case Decl::Decomposition:
5670   case Decl::VarTemplateSpecialization:
5671     EmitGlobal(cast<VarDecl>(D));
5672     if (auto *DD = dyn_cast<DecompositionDecl>(D))
5673       for (auto *B : DD->bindings())
5674         if (auto *HD = B->getHoldingVar())
5675           EmitGlobal(HD);
5676     break;
5677 
5678   // Indirect fields from global anonymous structs and unions can be
5679   // ignored; only the actual variable requires IR gen support.
5680   case Decl::IndirectField:
5681     break;
5682 
5683   // C++ Decls
5684   case Decl::Namespace:
5685     EmitDeclContext(cast<NamespaceDecl>(D));
5686     break;
5687   case Decl::ClassTemplateSpecialization: {
5688     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
5689     if (CGDebugInfo *DI = getModuleDebugInfo())
5690       if (Spec->getSpecializationKind() ==
5691               TSK_ExplicitInstantiationDefinition &&
5692           Spec->hasDefinition())
5693         DI->completeTemplateDefinition(*Spec);
5694   } LLVM_FALLTHROUGH;
5695   case Decl::CXXRecord: {
5696     CXXRecordDecl *CRD = cast<CXXRecordDecl>(D);
5697     if (CGDebugInfo *DI = getModuleDebugInfo()) {
5698       if (CRD->hasDefinition())
5699         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
5700       if (auto *ES = D->getASTContext().getExternalSource())
5701         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
5702           DI->completeUnusedClass(*CRD);
5703     }
5704     // Emit any static data members, they may be definitions.
5705     for (auto *I : CRD->decls())
5706       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
5707         EmitTopLevelDecl(I);
5708     break;
5709   }
5710     // No code generation needed.
5711   case Decl::UsingShadow:
5712   case Decl::ClassTemplate:
5713   case Decl::VarTemplate:
5714   case Decl::Concept:
5715   case Decl::VarTemplatePartialSpecialization:
5716   case Decl::FunctionTemplate:
5717   case Decl::TypeAliasTemplate:
5718   case Decl::Block:
5719   case Decl::Empty:
5720   case Decl::Binding:
5721     break;
5722   case Decl::Using:          // using X; [C++]
5723     if (CGDebugInfo *DI = getModuleDebugInfo())
5724         DI->EmitUsingDecl(cast<UsingDecl>(*D));
5725     break;
5726   case Decl::NamespaceAlias:
5727     if (CGDebugInfo *DI = getModuleDebugInfo())
5728         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
5729     break;
5730   case Decl::UsingDirective: // using namespace X; [C++]
5731     if (CGDebugInfo *DI = getModuleDebugInfo())
5732       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
5733     break;
5734   case Decl::CXXConstructor:
5735     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
5736     break;
5737   case Decl::CXXDestructor:
5738     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
5739     break;
5740 
5741   case Decl::StaticAssert:
5742     // Nothing to do.
5743     break;
5744 
5745   // Objective-C Decls
5746 
5747   // Forward declarations, no (immediate) code generation.
5748   case Decl::ObjCInterface:
5749   case Decl::ObjCCategory:
5750     break;
5751 
5752   case Decl::ObjCProtocol: {
5753     auto *Proto = cast<ObjCProtocolDecl>(D);
5754     if (Proto->isThisDeclarationADefinition())
5755       ObjCRuntime->GenerateProtocol(Proto);
5756     break;
5757   }
5758 
5759   case Decl::ObjCCategoryImpl:
5760     // Categories have properties but don't support synthesize so we
5761     // can ignore them here.
5762     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
5763     break;
5764 
5765   case Decl::ObjCImplementation: {
5766     auto *OMD = cast<ObjCImplementationDecl>(D);
5767     EmitObjCPropertyImplementations(OMD);
5768     EmitObjCIvarInitializations(OMD);
5769     ObjCRuntime->GenerateClass(OMD);
5770     // Emit global variable debug information.
5771     if (CGDebugInfo *DI = getModuleDebugInfo())
5772       if (getCodeGenOpts().hasReducedDebugInfo())
5773         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
5774             OMD->getClassInterface()), OMD->getLocation());
5775     break;
5776   }
5777   case Decl::ObjCMethod: {
5778     auto *OMD = cast<ObjCMethodDecl>(D);
5779     // If this is not a prototype, emit the body.
5780     if (OMD->getBody())
5781       CodeGenFunction(*this).GenerateObjCMethod(OMD);
5782     break;
5783   }
5784   case Decl::ObjCCompatibleAlias:
5785     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
5786     break;
5787 
5788   case Decl::PragmaComment: {
5789     const auto *PCD = cast<PragmaCommentDecl>(D);
5790     switch (PCD->getCommentKind()) {
5791     case PCK_Unknown:
5792       llvm_unreachable("unexpected pragma comment kind");
5793     case PCK_Linker:
5794       AppendLinkerOptions(PCD->getArg());
5795       break;
5796     case PCK_Lib:
5797         AddDependentLib(PCD->getArg());
5798       break;
5799     case PCK_Compiler:
5800     case PCK_ExeStr:
5801     case PCK_User:
5802       break; // We ignore all of these.
5803     }
5804     break;
5805   }
5806 
5807   case Decl::PragmaDetectMismatch: {
5808     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
5809     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
5810     break;
5811   }
5812 
5813   case Decl::LinkageSpec:
5814     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
5815     break;
5816 
5817   case Decl::FileScopeAsm: {
5818     // File-scope asm is ignored during device-side CUDA compilation.
5819     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
5820       break;
5821     // File-scope asm is ignored during device-side OpenMP compilation.
5822     if (LangOpts.OpenMPIsDevice)
5823       break;
5824     // File-scope asm is ignored during device-side SYCL compilation.
5825     if (LangOpts.SYCLIsDevice)
5826       break;
5827     auto *AD = cast<FileScopeAsmDecl>(D);
5828     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
5829     break;
5830   }
5831 
5832   case Decl::Import: {
5833     auto *Import = cast<ImportDecl>(D);
5834 
5835     // If we've already imported this module, we're done.
5836     if (!ImportedModules.insert(Import->getImportedModule()))
5837       break;
5838 
5839     // Emit debug information for direct imports.
5840     if (!Import->getImportedOwningModule()) {
5841       if (CGDebugInfo *DI = getModuleDebugInfo())
5842         DI->EmitImportDecl(*Import);
5843     }
5844 
5845     // Find all of the submodules and emit the module initializers.
5846     llvm::SmallPtrSet<clang::Module *, 16> Visited;
5847     SmallVector<clang::Module *, 16> Stack;
5848     Visited.insert(Import->getImportedModule());
5849     Stack.push_back(Import->getImportedModule());
5850 
5851     while (!Stack.empty()) {
5852       clang::Module *Mod = Stack.pop_back_val();
5853       if (!EmittedModuleInitializers.insert(Mod).second)
5854         continue;
5855 
5856       for (auto *D : Context.getModuleInitializers(Mod))
5857         EmitTopLevelDecl(D);
5858 
5859       // Visit the submodules of this module.
5860       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
5861                                              SubEnd = Mod->submodule_end();
5862            Sub != SubEnd; ++Sub) {
5863         // Skip explicit children; they need to be explicitly imported to emit
5864         // the initializers.
5865         if ((*Sub)->IsExplicit)
5866           continue;
5867 
5868         if (Visited.insert(*Sub).second)
5869           Stack.push_back(*Sub);
5870       }
5871     }
5872     break;
5873   }
5874 
5875   case Decl::Export:
5876     EmitDeclContext(cast<ExportDecl>(D));
5877     break;
5878 
5879   case Decl::OMPThreadPrivate:
5880     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
5881     break;
5882 
5883   case Decl::OMPAllocate:
5884     EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D));
5885     break;
5886 
5887   case Decl::OMPDeclareReduction:
5888     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
5889     break;
5890 
5891   case Decl::OMPDeclareMapper:
5892     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
5893     break;
5894 
5895   case Decl::OMPRequires:
5896     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
5897     break;
5898 
5899   case Decl::Typedef:
5900   case Decl::TypeAlias: // using foo = bar; [C++11]
5901     if (CGDebugInfo *DI = getModuleDebugInfo())
5902       DI->EmitAndRetainType(
5903           getContext().getTypedefType(cast<TypedefNameDecl>(D)));
5904     break;
5905 
5906   case Decl::Record:
5907     if (CGDebugInfo *DI = getModuleDebugInfo())
5908       if (cast<RecordDecl>(D)->getDefinition())
5909         DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D)));
5910     break;
5911 
5912   case Decl::Enum:
5913     if (CGDebugInfo *DI = getModuleDebugInfo())
5914       if (cast<EnumDecl>(D)->getDefinition())
5915         DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D)));
5916     break;
5917 
5918   default:
5919     // Make sure we handled everything we should, every other kind is a
5920     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
5921     // function. Need to recode Decl::Kind to do that easily.
5922     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
5923     break;
5924   }
5925 }
5926 
5927 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
5928   // Do we need to generate coverage mapping?
5929   if (!CodeGenOpts.CoverageMapping)
5930     return;
5931   switch (D->getKind()) {
5932   case Decl::CXXConversion:
5933   case Decl::CXXMethod:
5934   case Decl::Function:
5935   case Decl::ObjCMethod:
5936   case Decl::CXXConstructor:
5937   case Decl::CXXDestructor: {
5938     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
5939       break;
5940     SourceManager &SM = getContext().getSourceManager();
5941     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
5942       break;
5943     auto I = DeferredEmptyCoverageMappingDecls.find(D);
5944     if (I == DeferredEmptyCoverageMappingDecls.end())
5945       DeferredEmptyCoverageMappingDecls[D] = true;
5946     break;
5947   }
5948   default:
5949     break;
5950   };
5951 }
5952 
5953 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
5954   // Do we need to generate coverage mapping?
5955   if (!CodeGenOpts.CoverageMapping)
5956     return;
5957   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
5958     if (Fn->isTemplateInstantiation())
5959       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
5960   }
5961   auto I = DeferredEmptyCoverageMappingDecls.find(D);
5962   if (I == DeferredEmptyCoverageMappingDecls.end())
5963     DeferredEmptyCoverageMappingDecls[D] = false;
5964   else
5965     I->second = false;
5966 }
5967 
5968 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
5969   // We call takeVector() here to avoid use-after-free.
5970   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
5971   // we deserialize function bodies to emit coverage info for them, and that
5972   // deserializes more declarations. How should we handle that case?
5973   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
5974     if (!Entry.second)
5975       continue;
5976     const Decl *D = Entry.first;
5977     switch (D->getKind()) {
5978     case Decl::CXXConversion:
5979     case Decl::CXXMethod:
5980     case Decl::Function:
5981     case Decl::ObjCMethod: {
5982       CodeGenPGO PGO(*this);
5983       GlobalDecl GD(cast<FunctionDecl>(D));
5984       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5985                                   getFunctionLinkage(GD));
5986       break;
5987     }
5988     case Decl::CXXConstructor: {
5989       CodeGenPGO PGO(*this);
5990       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
5991       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5992                                   getFunctionLinkage(GD));
5993       break;
5994     }
5995     case Decl::CXXDestructor: {
5996       CodeGenPGO PGO(*this);
5997       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
5998       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5999                                   getFunctionLinkage(GD));
6000       break;
6001     }
6002     default:
6003       break;
6004     };
6005   }
6006 }
6007 
6008 void CodeGenModule::EmitMainVoidAlias() {
6009   // In order to transition away from "__original_main" gracefully, emit an
6010   // alias for "main" in the no-argument case so that libc can detect when
6011   // new-style no-argument main is in used.
6012   if (llvm::Function *F = getModule().getFunction("main")) {
6013     if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
6014         F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth()))
6015       addUsedGlobal(llvm::GlobalAlias::create("__main_void", F));
6016   }
6017 }
6018 
6019 /// Turns the given pointer into a constant.
6020 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
6021                                           const void *Ptr) {
6022   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
6023   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
6024   return llvm::ConstantInt::get(i64, PtrInt);
6025 }
6026 
6027 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
6028                                    llvm::NamedMDNode *&GlobalMetadata,
6029                                    GlobalDecl D,
6030                                    llvm::GlobalValue *Addr) {
6031   if (!GlobalMetadata)
6032     GlobalMetadata =
6033       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
6034 
6035   // TODO: should we report variant information for ctors/dtors?
6036   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
6037                            llvm::ConstantAsMetadata::get(GetPointerConstant(
6038                                CGM.getLLVMContext(), D.getDecl()))};
6039   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
6040 }
6041 
6042 /// For each function which is declared within an extern "C" region and marked
6043 /// as 'used', but has internal linkage, create an alias from the unmangled
6044 /// name to the mangled name if possible. People expect to be able to refer
6045 /// to such functions with an unmangled name from inline assembly within the
6046 /// same translation unit.
6047 void CodeGenModule::EmitStaticExternCAliases() {
6048   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
6049     return;
6050   for (auto &I : StaticExternCValues) {
6051     IdentifierInfo *Name = I.first;
6052     llvm::GlobalValue *Val = I.second;
6053     if (Val && !getModule().getNamedValue(Name->getName()))
6054       addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
6055   }
6056 }
6057 
6058 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
6059                                              GlobalDecl &Result) const {
6060   auto Res = Manglings.find(MangledName);
6061   if (Res == Manglings.end())
6062     return false;
6063   Result = Res->getValue();
6064   return true;
6065 }
6066 
6067 /// Emits metadata nodes associating all the global values in the
6068 /// current module with the Decls they came from.  This is useful for
6069 /// projects using IR gen as a subroutine.
6070 ///
6071 /// Since there's currently no way to associate an MDNode directly
6072 /// with an llvm::GlobalValue, we create a global named metadata
6073 /// with the name 'clang.global.decl.ptrs'.
6074 void CodeGenModule::EmitDeclMetadata() {
6075   llvm::NamedMDNode *GlobalMetadata = nullptr;
6076 
6077   for (auto &I : MangledDeclNames) {
6078     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
6079     // Some mangled names don't necessarily have an associated GlobalValue
6080     // in this module, e.g. if we mangled it for DebugInfo.
6081     if (Addr)
6082       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
6083   }
6084 }
6085 
6086 /// Emits metadata nodes for all the local variables in the current
6087 /// function.
6088 void CodeGenFunction::EmitDeclMetadata() {
6089   if (LocalDeclMap.empty()) return;
6090 
6091   llvm::LLVMContext &Context = getLLVMContext();
6092 
6093   // Find the unique metadata ID for this name.
6094   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
6095 
6096   llvm::NamedMDNode *GlobalMetadata = nullptr;
6097 
6098   for (auto &I : LocalDeclMap) {
6099     const Decl *D = I.first;
6100     llvm::Value *Addr = I.second.getPointer();
6101     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
6102       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
6103       Alloca->setMetadata(
6104           DeclPtrKind, llvm::MDNode::get(
6105                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
6106     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
6107       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
6108       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
6109     }
6110   }
6111 }
6112 
6113 void CodeGenModule::EmitVersionIdentMetadata() {
6114   llvm::NamedMDNode *IdentMetadata =
6115     TheModule.getOrInsertNamedMetadata("llvm.ident");
6116   std::string Version = getClangFullVersion();
6117   llvm::LLVMContext &Ctx = TheModule.getContext();
6118 
6119   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
6120   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
6121 }
6122 
6123 void CodeGenModule::EmitCommandLineMetadata() {
6124   llvm::NamedMDNode *CommandLineMetadata =
6125     TheModule.getOrInsertNamedMetadata("llvm.commandline");
6126   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
6127   llvm::LLVMContext &Ctx = TheModule.getContext();
6128 
6129   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
6130   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
6131 }
6132 
6133 void CodeGenModule::EmitCoverageFile() {
6134   if (getCodeGenOpts().CoverageDataFile.empty() &&
6135       getCodeGenOpts().CoverageNotesFile.empty())
6136     return;
6137 
6138   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
6139   if (!CUNode)
6140     return;
6141 
6142   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
6143   llvm::LLVMContext &Ctx = TheModule.getContext();
6144   auto *CoverageDataFile =
6145       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
6146   auto *CoverageNotesFile =
6147       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
6148   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
6149     llvm::MDNode *CU = CUNode->getOperand(i);
6150     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
6151     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
6152   }
6153 }
6154 
6155 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
6156                                                        bool ForEH) {
6157   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
6158   // FIXME: should we even be calling this method if RTTI is disabled
6159   // and it's not for EH?
6160   if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice ||
6161       (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
6162        getTriple().isNVPTX()))
6163     return llvm::Constant::getNullValue(Int8PtrTy);
6164 
6165   if (ForEH && Ty->isObjCObjectPointerType() &&
6166       LangOpts.ObjCRuntime.isGNUFamily())
6167     return ObjCRuntime->GetEHType(Ty);
6168 
6169   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
6170 }
6171 
6172 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
6173   // Do not emit threadprivates in simd-only mode.
6174   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
6175     return;
6176   for (auto RefExpr : D->varlists()) {
6177     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
6178     bool PerformInit =
6179         VD->getAnyInitializer() &&
6180         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
6181                                                         /*ForRef=*/false);
6182 
6183     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
6184     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
6185             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
6186       CXXGlobalInits.push_back(InitFunction);
6187   }
6188 }
6189 
6190 llvm::Metadata *
6191 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
6192                                             StringRef Suffix) {
6193   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
6194   if (InternalId)
6195     return InternalId;
6196 
6197   if (isExternallyVisible(T->getLinkage())) {
6198     std::string OutName;
6199     llvm::raw_string_ostream Out(OutName);
6200     getCXXABI().getMangleContext().mangleTypeName(T, Out);
6201     Out << Suffix;
6202 
6203     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
6204   } else {
6205     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
6206                                            llvm::ArrayRef<llvm::Metadata *>());
6207   }
6208 
6209   return InternalId;
6210 }
6211 
6212 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
6213   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
6214 }
6215 
6216 llvm::Metadata *
6217 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
6218   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
6219 }
6220 
6221 // Generalize pointer types to a void pointer with the qualifiers of the
6222 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
6223 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
6224 // 'void *'.
6225 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
6226   if (!Ty->isPointerType())
6227     return Ty;
6228 
6229   return Ctx.getPointerType(
6230       QualType(Ctx.VoidTy).withCVRQualifiers(
6231           Ty->getPointeeType().getCVRQualifiers()));
6232 }
6233 
6234 // Apply type generalization to a FunctionType's return and argument types
6235 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
6236   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
6237     SmallVector<QualType, 8> GeneralizedParams;
6238     for (auto &Param : FnType->param_types())
6239       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
6240 
6241     return Ctx.getFunctionType(
6242         GeneralizeType(Ctx, FnType->getReturnType()),
6243         GeneralizedParams, FnType->getExtProtoInfo());
6244   }
6245 
6246   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
6247     return Ctx.getFunctionNoProtoType(
6248         GeneralizeType(Ctx, FnType->getReturnType()));
6249 
6250   llvm_unreachable("Encountered unknown FunctionType");
6251 }
6252 
6253 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
6254   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
6255                                       GeneralizedMetadataIdMap, ".generalized");
6256 }
6257 
6258 /// Returns whether this module needs the "all-vtables" type identifier.
6259 bool CodeGenModule::NeedAllVtablesTypeId() const {
6260   // Returns true if at least one of vtable-based CFI checkers is enabled and
6261   // is not in the trapping mode.
6262   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
6263            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
6264           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
6265            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
6266           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
6267            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
6268           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
6269            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
6270 }
6271 
6272 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
6273                                           CharUnits Offset,
6274                                           const CXXRecordDecl *RD) {
6275   llvm::Metadata *MD =
6276       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
6277   VTable->addTypeMetadata(Offset.getQuantity(), MD);
6278 
6279   if (CodeGenOpts.SanitizeCfiCrossDso)
6280     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
6281       VTable->addTypeMetadata(Offset.getQuantity(),
6282                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
6283 
6284   if (NeedAllVtablesTypeId()) {
6285     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
6286     VTable->addTypeMetadata(Offset.getQuantity(), MD);
6287   }
6288 }
6289 
6290 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
6291   if (!SanStats)
6292     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
6293 
6294   return *SanStats;
6295 }
6296 
6297 llvm::Value *
6298 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
6299                                                   CodeGenFunction &CGF) {
6300   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
6301   auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
6302   auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
6303   auto *Call = CGF.EmitRuntimeCall(
6304       CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C});
6305   return Call;
6306 }
6307 
6308 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
6309     QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
6310   return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
6311                                  /* forPointeeType= */ true);
6312 }
6313 
6314 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
6315                                                  LValueBaseInfo *BaseInfo,
6316                                                  TBAAAccessInfo *TBAAInfo,
6317                                                  bool forPointeeType) {
6318   if (TBAAInfo)
6319     *TBAAInfo = getTBAAAccessInfo(T);
6320 
6321   // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
6322   // that doesn't return the information we need to compute BaseInfo.
6323 
6324   // Honor alignment typedef attributes even on incomplete types.
6325   // We also honor them straight for C++ class types, even as pointees;
6326   // there's an expressivity gap here.
6327   if (auto TT = T->getAs<TypedefType>()) {
6328     if (auto Align = TT->getDecl()->getMaxAlignment()) {
6329       if (BaseInfo)
6330         *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
6331       return getContext().toCharUnitsFromBits(Align);
6332     }
6333   }
6334 
6335   bool AlignForArray = T->isArrayType();
6336 
6337   // Analyze the base element type, so we don't get confused by incomplete
6338   // array types.
6339   T = getContext().getBaseElementType(T);
6340 
6341   if (T->isIncompleteType()) {
6342     // We could try to replicate the logic from
6343     // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
6344     // type is incomplete, so it's impossible to test. We could try to reuse
6345     // getTypeAlignIfKnown, but that doesn't return the information we need
6346     // to set BaseInfo.  So just ignore the possibility that the alignment is
6347     // greater than one.
6348     if (BaseInfo)
6349       *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6350     return CharUnits::One();
6351   }
6352 
6353   if (BaseInfo)
6354     *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6355 
6356   CharUnits Alignment;
6357   const CXXRecordDecl *RD;
6358   if (T.getQualifiers().hasUnaligned()) {
6359     Alignment = CharUnits::One();
6360   } else if (forPointeeType && !AlignForArray &&
6361              (RD = T->getAsCXXRecordDecl())) {
6362     // For C++ class pointees, we don't know whether we're pointing at a
6363     // base or a complete object, so we generally need to use the
6364     // non-virtual alignment.
6365     Alignment = getClassPointerAlignment(RD);
6366   } else {
6367     Alignment = getContext().getTypeAlignInChars(T);
6368   }
6369 
6370   // Cap to the global maximum type alignment unless the alignment
6371   // was somehow explicit on the type.
6372   if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
6373     if (Alignment.getQuantity() > MaxAlign &&
6374         !getContext().isAlignmentRequired(T))
6375       Alignment = CharUnits::fromQuantity(MaxAlign);
6376   }
6377   return Alignment;
6378 }
6379 
6380 bool CodeGenModule::stopAutoInit() {
6381   unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
6382   if (StopAfter) {
6383     // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
6384     // used
6385     if (NumAutoVarInit >= StopAfter) {
6386       return true;
6387     }
6388     if (!NumAutoVarInit) {
6389       unsigned DiagID = getDiags().getCustomDiagID(
6390           DiagnosticsEngine::Warning,
6391           "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
6392           "number of times ftrivial-auto-var-init=%1 gets applied.");
6393       getDiags().Report(DiagID)
6394           << StopAfter
6395           << (getContext().getLangOpts().getTrivialAutoVarInit() ==
6396                       LangOptions::TrivialAutoVarInitKind::Zero
6397                   ? "zero"
6398                   : "pattern");
6399     }
6400     ++NumAutoVarInit;
6401   }
6402   return false;
6403 }
6404 
6405 void CodeGenModule::printPostfixForExternalizedStaticVar(
6406     llvm::raw_ostream &OS) const {
6407   OS << ".static." << getContext().getCUIDHash();
6408 }
6409