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