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