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