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