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