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