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