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 we plan on emitting this inline builtin, we can't treat it as a builtin.
1912   if (FD->isInlineBuiltinDeclaration() && shouldEmitFunction(FD)) {
1913     F->addAttribute(llvm::AttributeList::FunctionIndex,
1914                     llvm::Attribute::NoBuiltin);
1915   }
1916 
1917   if (FD->isReplaceableGlobalAllocationFunction()) {
1918     // A replaceable global allocation function does not act like a builtin by
1919     // default, only if it is invoked by a new-expression or delete-expression.
1920     F->addAttribute(llvm::AttributeList::FunctionIndex,
1921                     llvm::Attribute::NoBuiltin);
1922   }
1923 
1924   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1925     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1926   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1927     if (MD->isVirtual())
1928       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1929 
1930   // Don't emit entries for function declarations in the cross-DSO mode. This
1931   // is handled with better precision by the receiving DSO. But if jump tables
1932   // are non-canonical then we need type metadata in order to produce the local
1933   // jump table.
1934   if (!CodeGenOpts.SanitizeCfiCrossDso ||
1935       !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
1936     CreateFunctionTypeMetadataForIcall(FD, F);
1937 
1938   if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1939     getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
1940 
1941   if (const auto *CB = FD->getAttr<CallbackAttr>()) {
1942     // Annotate the callback behavior as metadata:
1943     //  - The callback callee (as argument number).
1944     //  - The callback payloads (as argument numbers).
1945     llvm::LLVMContext &Ctx = F->getContext();
1946     llvm::MDBuilder MDB(Ctx);
1947 
1948     // The payload indices are all but the first one in the encoding. The first
1949     // identifies the callback callee.
1950     int CalleeIdx = *CB->encoding_begin();
1951     ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
1952     F->addMetadata(llvm::LLVMContext::MD_callback,
1953                    *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
1954                                                CalleeIdx, PayloadIndices,
1955                                                /* VarArgsArePassed */ false)}));
1956   }
1957 }
1958 
1959 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1960   assert(!GV->isDeclaration() &&
1961          "Only globals with definition can force usage.");
1962   LLVMUsed.emplace_back(GV);
1963 }
1964 
1965 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1966   assert(!GV->isDeclaration() &&
1967          "Only globals with definition can force usage.");
1968   LLVMCompilerUsed.emplace_back(GV);
1969 }
1970 
1971 static void emitUsed(CodeGenModule &CGM, StringRef Name,
1972                      std::vector<llvm::WeakTrackingVH> &List) {
1973   // Don't create llvm.used if there is no need.
1974   if (List.empty())
1975     return;
1976 
1977   // Convert List to what ConstantArray needs.
1978   SmallVector<llvm::Constant*, 8> UsedArray;
1979   UsedArray.resize(List.size());
1980   for (unsigned i = 0, e = List.size(); i != e; ++i) {
1981     UsedArray[i] =
1982         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1983             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1984   }
1985 
1986   if (UsedArray.empty())
1987     return;
1988   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1989 
1990   auto *GV = new llvm::GlobalVariable(
1991       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1992       llvm::ConstantArray::get(ATy, UsedArray), Name);
1993 
1994   GV->setSection("llvm.metadata");
1995 }
1996 
1997 void CodeGenModule::emitLLVMUsed() {
1998   emitUsed(*this, "llvm.used", LLVMUsed);
1999   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
2000 }
2001 
2002 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
2003   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
2004   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2005 }
2006 
2007 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
2008   llvm::SmallString<32> Opt;
2009   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2010   if (Opt.empty())
2011     return;
2012   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2013   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2014 }
2015 
2016 void CodeGenModule::AddDependentLib(StringRef Lib) {
2017   auto &C = getLLVMContext();
2018   if (getTarget().getTriple().isOSBinFormatELF()) {
2019       ELFDependentLibraries.push_back(
2020         llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
2021     return;
2022   }
2023 
2024   llvm::SmallString<24> Opt;
2025   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
2026   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2027   LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
2028 }
2029 
2030 /// Add link options implied by the given module, including modules
2031 /// it depends on, using a postorder walk.
2032 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
2033                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
2034                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
2035   // Import this module's parent.
2036   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
2037     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
2038   }
2039 
2040   // Import this module's dependencies.
2041   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
2042     if (Visited.insert(Mod->Imports[I - 1]).second)
2043       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
2044   }
2045 
2046   // Add linker options to link against the libraries/frameworks
2047   // described by this module.
2048   llvm::LLVMContext &Context = CGM.getLLVMContext();
2049   bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
2050 
2051   // For modules that use export_as for linking, use that module
2052   // name instead.
2053   if (Mod->UseExportAsModuleLinkName)
2054     return;
2055 
2056   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
2057     // Link against a framework.  Frameworks are currently Darwin only, so we
2058     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
2059     if (Mod->LinkLibraries[I-1].IsFramework) {
2060       llvm::Metadata *Args[2] = {
2061           llvm::MDString::get(Context, "-framework"),
2062           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
2063 
2064       Metadata.push_back(llvm::MDNode::get(Context, Args));
2065       continue;
2066     }
2067 
2068     // Link against a library.
2069     if (IsELF) {
2070       llvm::Metadata *Args[2] = {
2071           llvm::MDString::get(Context, "lib"),
2072           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
2073       };
2074       Metadata.push_back(llvm::MDNode::get(Context, Args));
2075     } else {
2076       llvm::SmallString<24> Opt;
2077       CGM.getTargetCodeGenInfo().getDependentLibraryOption(
2078           Mod->LinkLibraries[I - 1].Library, Opt);
2079       auto *OptString = llvm::MDString::get(Context, Opt);
2080       Metadata.push_back(llvm::MDNode::get(Context, OptString));
2081     }
2082   }
2083 }
2084 
2085 void CodeGenModule::EmitModuleLinkOptions() {
2086   // Collect the set of all of the modules we want to visit to emit link
2087   // options, which is essentially the imported modules and all of their
2088   // non-explicit child modules.
2089   llvm::SetVector<clang::Module *> LinkModules;
2090   llvm::SmallPtrSet<clang::Module *, 16> Visited;
2091   SmallVector<clang::Module *, 16> Stack;
2092 
2093   // Seed the stack with imported modules.
2094   for (Module *M : ImportedModules) {
2095     // Do not add any link flags when an implementation TU of a module imports
2096     // a header of that same module.
2097     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
2098         !getLangOpts().isCompilingModule())
2099       continue;
2100     if (Visited.insert(M).second)
2101       Stack.push_back(M);
2102   }
2103 
2104   // Find all of the modules to import, making a little effort to prune
2105   // non-leaf modules.
2106   while (!Stack.empty()) {
2107     clang::Module *Mod = Stack.pop_back_val();
2108 
2109     bool AnyChildren = false;
2110 
2111     // Visit the submodules of this module.
2112     for (const auto &SM : Mod->submodules()) {
2113       // Skip explicit children; they need to be explicitly imported to be
2114       // linked against.
2115       if (SM->IsExplicit)
2116         continue;
2117 
2118       if (Visited.insert(SM).second) {
2119         Stack.push_back(SM);
2120         AnyChildren = true;
2121       }
2122     }
2123 
2124     // We didn't find any children, so add this module to the list of
2125     // modules to link against.
2126     if (!AnyChildren) {
2127       LinkModules.insert(Mod);
2128     }
2129   }
2130 
2131   // Add link options for all of the imported modules in reverse topological
2132   // order.  We don't do anything to try to order import link flags with respect
2133   // to linker options inserted by things like #pragma comment().
2134   SmallVector<llvm::MDNode *, 16> MetadataArgs;
2135   Visited.clear();
2136   for (Module *M : LinkModules)
2137     if (Visited.insert(M).second)
2138       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
2139   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
2140   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
2141 
2142   // Add the linker options metadata flag.
2143   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
2144   for (auto *MD : LinkerOptionsMetadata)
2145     NMD->addOperand(MD);
2146 }
2147 
2148 void CodeGenModule::EmitDeferred() {
2149   // Emit deferred declare target declarations.
2150   if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
2151     getOpenMPRuntime().emitDeferredTargetDecls();
2152 
2153   // Emit code for any potentially referenced deferred decls.  Since a
2154   // previously unused static decl may become used during the generation of code
2155   // for a static function, iterate until no changes are made.
2156 
2157   if (!DeferredVTables.empty()) {
2158     EmitDeferredVTables();
2159 
2160     // Emitting a vtable doesn't directly cause more vtables to
2161     // become deferred, although it can cause functions to be
2162     // emitted that then need those vtables.
2163     assert(DeferredVTables.empty());
2164   }
2165 
2166   // Stop if we're out of both deferred vtables and deferred declarations.
2167   if (DeferredDeclsToEmit.empty())
2168     return;
2169 
2170   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
2171   // work, it will not interfere with this.
2172   std::vector<GlobalDecl> CurDeclsToEmit;
2173   CurDeclsToEmit.swap(DeferredDeclsToEmit);
2174 
2175   for (GlobalDecl &D : CurDeclsToEmit) {
2176     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
2177     // to get GlobalValue with exactly the type we need, not something that
2178     // might had been created for another decl with the same mangled name but
2179     // different type.
2180     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
2181         GetAddrOfGlobal(D, ForDefinition));
2182 
2183     // In case of different address spaces, we may still get a cast, even with
2184     // IsForDefinition equal to true. Query mangled names table to get
2185     // GlobalValue.
2186     if (!GV)
2187       GV = GetGlobalValue(getMangledName(D));
2188 
2189     // Make sure GetGlobalValue returned non-null.
2190     assert(GV);
2191 
2192     // Check to see if we've already emitted this.  This is necessary
2193     // for a couple of reasons: first, decls can end up in the
2194     // deferred-decls queue multiple times, and second, decls can end
2195     // up with definitions in unusual ways (e.g. by an extern inline
2196     // function acquiring a strong function redefinition).  Just
2197     // ignore these cases.
2198     if (!GV->isDeclaration())
2199       continue;
2200 
2201     // If this is OpenMP, check if it is legal to emit this global normally.
2202     if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
2203       continue;
2204 
2205     // Otherwise, emit the definition and move on to the next one.
2206     EmitGlobalDefinition(D, GV);
2207 
2208     // If we found out that we need to emit more decls, do that recursively.
2209     // This has the advantage that the decls are emitted in a DFS and related
2210     // ones are close together, which is convenient for testing.
2211     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
2212       EmitDeferred();
2213       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
2214     }
2215   }
2216 }
2217 
2218 void CodeGenModule::EmitVTablesOpportunistically() {
2219   // Try to emit external vtables as available_externally if they have emitted
2220   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
2221   // is not allowed to create new references to things that need to be emitted
2222   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
2223 
2224   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
2225          && "Only emit opportunistic vtables with optimizations");
2226 
2227   for (const CXXRecordDecl *RD : OpportunisticVTables) {
2228     assert(getVTables().isVTableExternal(RD) &&
2229            "This queue should only contain external vtables");
2230     if (getCXXABI().canSpeculativelyEmitVTable(RD))
2231       VTables.GenerateClassData(RD);
2232   }
2233   OpportunisticVTables.clear();
2234 }
2235 
2236 void CodeGenModule::EmitGlobalAnnotations() {
2237   if (Annotations.empty())
2238     return;
2239 
2240   // Create a new global variable for the ConstantStruct in the Module.
2241   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
2242     Annotations[0]->getType(), Annotations.size()), Annotations);
2243   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
2244                                       llvm::GlobalValue::AppendingLinkage,
2245                                       Array, "llvm.global.annotations");
2246   gv->setSection(AnnotationSection);
2247 }
2248 
2249 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
2250   llvm::Constant *&AStr = AnnotationStrings[Str];
2251   if (AStr)
2252     return AStr;
2253 
2254   // Not found yet, create a new global.
2255   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
2256   auto *gv =
2257       new llvm::GlobalVariable(getModule(), s->getType(), true,
2258                                llvm::GlobalValue::PrivateLinkage, s, ".str");
2259   gv->setSection(AnnotationSection);
2260   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2261   AStr = gv;
2262   return gv;
2263 }
2264 
2265 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
2266   SourceManager &SM = getContext().getSourceManager();
2267   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2268   if (PLoc.isValid())
2269     return EmitAnnotationString(PLoc.getFilename());
2270   return EmitAnnotationString(SM.getBufferName(Loc));
2271 }
2272 
2273 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
2274   SourceManager &SM = getContext().getSourceManager();
2275   PresumedLoc PLoc = SM.getPresumedLoc(L);
2276   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
2277     SM.getExpansionLineNumber(L);
2278   return llvm::ConstantInt::get(Int32Ty, LineNo);
2279 }
2280 
2281 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
2282                                                 const AnnotateAttr *AA,
2283                                                 SourceLocation L) {
2284   // Get the globals for file name, annotation, and the line number.
2285   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
2286                  *UnitGV = EmitAnnotationUnit(L),
2287                  *LineNoCst = EmitAnnotationLineNo(L);
2288 
2289   llvm::Constant *ASZeroGV = GV;
2290   if (GV->getAddressSpace() != 0) {
2291     ASZeroGV = llvm::ConstantExpr::getAddrSpaceCast(
2292                    GV, GV->getValueType()->getPointerTo(0));
2293   }
2294 
2295   // Create the ConstantStruct for the global annotation.
2296   llvm::Constant *Fields[4] = {
2297     llvm::ConstantExpr::getBitCast(ASZeroGV, Int8PtrTy),
2298     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
2299     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
2300     LineNoCst
2301   };
2302   return llvm::ConstantStruct::getAnon(Fields);
2303 }
2304 
2305 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
2306                                          llvm::GlobalValue *GV) {
2307   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2308   // Get the struct elements for these annotations.
2309   for (const auto *I : D->specific_attrs<AnnotateAttr>())
2310     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
2311 }
2312 
2313 bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
2314                                            llvm::Function *Fn,
2315                                            SourceLocation Loc) const {
2316   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
2317   // Blacklist by function name.
2318   if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
2319     return true;
2320   // Blacklist by location.
2321   if (Loc.isValid())
2322     return SanitizerBL.isBlacklistedLocation(Kind, Loc);
2323   // If location is unknown, this may be a compiler-generated function. Assume
2324   // it's located in the main file.
2325   auto &SM = Context.getSourceManager();
2326   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2327     return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
2328   }
2329   return false;
2330 }
2331 
2332 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
2333                                            SourceLocation Loc, QualType Ty,
2334                                            StringRef Category) const {
2335   // For now globals can be blacklisted only in ASan and KASan.
2336   const SanitizerMask EnabledAsanMask =
2337       LangOpts.Sanitize.Mask &
2338       (SanitizerKind::Address | SanitizerKind::KernelAddress |
2339        SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
2340        SanitizerKind::MemTag);
2341   if (!EnabledAsanMask)
2342     return false;
2343   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
2344   if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
2345     return true;
2346   if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
2347     return true;
2348   // Check global type.
2349   if (!Ty.isNull()) {
2350     // Drill down the array types: if global variable of a fixed type is
2351     // blacklisted, we also don't instrument arrays of them.
2352     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
2353       Ty = AT->getElementType();
2354     Ty = Ty.getCanonicalType().getUnqualifiedType();
2355     // We allow to blacklist only record types (classes, structs etc.)
2356     if (Ty->isRecordType()) {
2357       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
2358       if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
2359         return true;
2360     }
2361   }
2362   return false;
2363 }
2364 
2365 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
2366                                    StringRef Category) const {
2367   const auto &XRayFilter = getContext().getXRayFilter();
2368   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
2369   auto Attr = ImbueAttr::NONE;
2370   if (Loc.isValid())
2371     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
2372   if (Attr == ImbueAttr::NONE)
2373     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
2374   switch (Attr) {
2375   case ImbueAttr::NONE:
2376     return false;
2377   case ImbueAttr::ALWAYS:
2378     Fn->addFnAttr("function-instrument", "xray-always");
2379     break;
2380   case ImbueAttr::ALWAYS_ARG1:
2381     Fn->addFnAttr("function-instrument", "xray-always");
2382     Fn->addFnAttr("xray-log-args", "1");
2383     break;
2384   case ImbueAttr::NEVER:
2385     Fn->addFnAttr("function-instrument", "xray-never");
2386     break;
2387   }
2388   return true;
2389 }
2390 
2391 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
2392   // Never defer when EmitAllDecls is specified.
2393   if (LangOpts.EmitAllDecls)
2394     return true;
2395 
2396   if (CodeGenOpts.KeepStaticConsts) {
2397     const auto *VD = dyn_cast<VarDecl>(Global);
2398     if (VD && VD->getType().isConstQualified() &&
2399         VD->getStorageDuration() == SD_Static)
2400       return true;
2401   }
2402 
2403   return getContext().DeclMustBeEmitted(Global);
2404 }
2405 
2406 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2407   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2408     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2409       // Implicit template instantiations may change linkage if they are later
2410       // explicitly instantiated, so they should not be emitted eagerly.
2411       return false;
2412     // In OpenMP 5.0 function may be marked as device_type(nohost) and we should
2413     // not emit them eagerly unless we sure that the function must be emitted on
2414     // the host.
2415     if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd &&
2416         !LangOpts.OpenMPIsDevice &&
2417         !OMPDeclareTargetDeclAttr::getDeviceType(FD) &&
2418         !FD->isUsed(/*CheckUsedAttr=*/false) && !FD->isReferenced())
2419       return false;
2420   }
2421   if (const auto *VD = dyn_cast<VarDecl>(Global))
2422     if (Context.getInlineVariableDefinitionKind(VD) ==
2423         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
2424       // A definition of an inline constexpr static data member may change
2425       // linkage later if it's redeclared outside the class.
2426       return false;
2427   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2428   // codegen for global variables, because they may be marked as threadprivate.
2429   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
2430       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
2431       !isTypeConstant(Global->getType(), false) &&
2432       !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
2433     return false;
2434 
2435   return true;
2436 }
2437 
2438 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
2439   StringRef Name = getMangledName(GD);
2440 
2441   // The UUID descriptor should be pointer aligned.
2442   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
2443 
2444   // Look for an existing global.
2445   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2446     return ConstantAddress(GV, Alignment);
2447 
2448   ConstantEmitter Emitter(*this);
2449   llvm::Constant *Init;
2450 
2451   APValue &V = GD->getAsAPValue();
2452   if (!V.isAbsent()) {
2453     // If possible, emit the APValue version of the initializer. In particular,
2454     // this gets the type of the constant right.
2455     Init = Emitter.emitForInitializer(
2456         GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
2457   } else {
2458     // As a fallback, directly construct the constant.
2459     // FIXME: This may get padding wrong under esoteric struct layout rules.
2460     // MSVC appears to create a complete type 'struct __s_GUID' that it
2461     // presumably uses to represent these constants.
2462     MSGuidDecl::Parts Parts = GD->getParts();
2463     llvm::Constant *Fields[4] = {
2464         llvm::ConstantInt::get(Int32Ty, Parts.Part1),
2465         llvm::ConstantInt::get(Int16Ty, Parts.Part2),
2466         llvm::ConstantInt::get(Int16Ty, Parts.Part3),
2467         llvm::ConstantDataArray::getRaw(
2468             StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
2469             Int8Ty)};
2470     Init = llvm::ConstantStruct::getAnon(Fields);
2471   }
2472 
2473   auto *GV = new llvm::GlobalVariable(
2474       getModule(), Init->getType(),
2475       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2476   if (supportsCOMDAT())
2477     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2478   setDSOLocal(GV);
2479 
2480   llvm::Constant *Addr = GV;
2481   if (!V.isAbsent()) {
2482     Emitter.finalize(GV);
2483   } else {
2484     llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
2485     Addr = llvm::ConstantExpr::getBitCast(
2486         GV, Ty->getPointerTo(GV->getAddressSpace()));
2487   }
2488   return ConstantAddress(Addr, Alignment);
2489 }
2490 
2491 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
2492   const AliasAttr *AA = VD->getAttr<AliasAttr>();
2493   assert(AA && "No alias?");
2494 
2495   CharUnits Alignment = getContext().getDeclAlign(VD);
2496   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
2497 
2498   // See if there is already something with the target's name in the module.
2499   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
2500   if (Entry) {
2501     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
2502     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2503     return ConstantAddress(Ptr, Alignment);
2504   }
2505 
2506   llvm::Constant *Aliasee;
2507   if (isa<llvm::FunctionType>(DeclTy))
2508     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2509                                       GlobalDecl(cast<FunctionDecl>(VD)),
2510                                       /*ForVTable=*/false);
2511   else
2512     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2513                                     llvm::PointerType::getUnqual(DeclTy),
2514                                     nullptr);
2515 
2516   auto *F = cast<llvm::GlobalValue>(Aliasee);
2517   F->setLinkage(llvm::Function::ExternalWeakLinkage);
2518   WeakRefReferences.insert(F);
2519 
2520   return ConstantAddress(Aliasee, Alignment);
2521 }
2522 
2523 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
2524   const auto *Global = cast<ValueDecl>(GD.getDecl());
2525 
2526   // Weak references don't produce any output by themselves.
2527   if (Global->hasAttr<WeakRefAttr>())
2528     return;
2529 
2530   // If this is an alias definition (which otherwise looks like a declaration)
2531   // emit it now.
2532   if (Global->hasAttr<AliasAttr>())
2533     return EmitAliasDefinition(GD);
2534 
2535   // IFunc like an alias whose value is resolved at runtime by calling resolver.
2536   if (Global->hasAttr<IFuncAttr>())
2537     return emitIFuncDefinition(GD);
2538 
2539   // If this is a cpu_dispatch multiversion function, emit the resolver.
2540   if (Global->hasAttr<CPUDispatchAttr>())
2541     return emitCPUDispatchDefinition(GD);
2542 
2543   // If this is CUDA, be selective about which declarations we emit.
2544   if (LangOpts.CUDA) {
2545     if (LangOpts.CUDAIsDevice) {
2546       if (!Global->hasAttr<CUDADeviceAttr>() &&
2547           !Global->hasAttr<CUDAGlobalAttr>() &&
2548           !Global->hasAttr<CUDAConstantAttr>() &&
2549           !Global->hasAttr<CUDASharedAttr>() &&
2550           !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
2551           !Global->getType()->isCUDADeviceBuiltinTextureType())
2552         return;
2553     } else {
2554       // We need to emit host-side 'shadows' for all global
2555       // device-side variables because the CUDA runtime needs their
2556       // size and host-side address in order to provide access to
2557       // their device-side incarnations.
2558 
2559       // So device-only functions are the only things we skip.
2560       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2561           Global->hasAttr<CUDADeviceAttr>())
2562         return;
2563 
2564       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2565              "Expected Variable or Function");
2566     }
2567   }
2568 
2569   if (LangOpts.OpenMP) {
2570     // If this is OpenMP, check if it is legal to emit this global normally.
2571     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2572       return;
2573     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2574       if (MustBeEmitted(Global))
2575         EmitOMPDeclareReduction(DRD);
2576       return;
2577     } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
2578       if (MustBeEmitted(Global))
2579         EmitOMPDeclareMapper(DMD);
2580       return;
2581     }
2582   }
2583 
2584   // Ignore declarations, they will be emitted on their first use.
2585   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2586     // Forward declarations are emitted lazily on first use.
2587     if (!FD->doesThisDeclarationHaveABody()) {
2588       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2589         return;
2590 
2591       StringRef MangledName = getMangledName(GD);
2592 
2593       // Compute the function info and LLVM type.
2594       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2595       llvm::Type *Ty = getTypes().GetFunctionType(FI);
2596 
2597       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2598                               /*DontDefer=*/false);
2599       return;
2600     }
2601   } else {
2602     const auto *VD = cast<VarDecl>(Global);
2603     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
2604     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
2605         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2606       if (LangOpts.OpenMP) {
2607         // Emit declaration of the must-be-emitted declare target variable.
2608         if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2609                 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2610           bool UnifiedMemoryEnabled =
2611               getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
2612           if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2613               !UnifiedMemoryEnabled) {
2614             (void)GetAddrOfGlobalVar(VD);
2615           } else {
2616             assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2617                     (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2618                      UnifiedMemoryEnabled)) &&
2619                    "Link clause or to clause with unified memory expected.");
2620             (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
2621           }
2622 
2623           return;
2624         }
2625       }
2626       // If this declaration may have caused an inline variable definition to
2627       // change linkage, make sure that it's emitted.
2628       if (Context.getInlineVariableDefinitionKind(VD) ==
2629           ASTContext::InlineVariableDefinitionKind::Strong)
2630         GetAddrOfGlobalVar(VD);
2631       return;
2632     }
2633   }
2634 
2635   // Defer code generation to first use when possible, e.g. if this is an inline
2636   // function. If the global must always be emitted, do it eagerly if possible
2637   // to benefit from cache locality.
2638   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2639     // Emit the definition if it can't be deferred.
2640     EmitGlobalDefinition(GD);
2641     return;
2642   }
2643 
2644   // If we're deferring emission of a C++ variable with an
2645   // initializer, remember the order in which it appeared in the file.
2646   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
2647       cast<VarDecl>(Global)->hasInit()) {
2648     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2649     CXXGlobalInits.push_back(nullptr);
2650   }
2651 
2652   StringRef MangledName = getMangledName(GD);
2653   if (GetGlobalValue(MangledName) != nullptr) {
2654     // The value has already been used and should therefore be emitted.
2655     addDeferredDeclToEmit(GD);
2656   } else if (MustBeEmitted(Global)) {
2657     // The value must be emitted, but cannot be emitted eagerly.
2658     assert(!MayBeEmittedEagerly(Global));
2659     addDeferredDeclToEmit(GD);
2660   } else {
2661     // Otherwise, remember that we saw a deferred decl with this name.  The
2662     // first use of the mangled name will cause it to move into
2663     // DeferredDeclsToEmit.
2664     DeferredDecls[MangledName] = GD;
2665   }
2666 }
2667 
2668 // Check if T is a class type with a destructor that's not dllimport.
2669 static bool HasNonDllImportDtor(QualType T) {
2670   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2671     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2672       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2673         return true;
2674 
2675   return false;
2676 }
2677 
2678 namespace {
2679   struct FunctionIsDirectlyRecursive
2680       : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
2681     const StringRef Name;
2682     const Builtin::Context &BI;
2683     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
2684         : Name(N), BI(C) {}
2685 
2686     bool VisitCallExpr(const CallExpr *E) {
2687       const FunctionDecl *FD = E->getDirectCallee();
2688       if (!FD)
2689         return false;
2690       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2691       if (Attr && Name == Attr->getLabel())
2692         return true;
2693       unsigned BuiltinID = FD->getBuiltinID();
2694       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
2695         return false;
2696       StringRef BuiltinName = BI.getName(BuiltinID);
2697       if (BuiltinName.startswith("__builtin_") &&
2698           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
2699         return true;
2700       }
2701       return false;
2702     }
2703 
2704     bool VisitStmt(const Stmt *S) {
2705       for (const Stmt *Child : S->children())
2706         if (Child && this->Visit(Child))
2707           return true;
2708       return false;
2709     }
2710   };
2711 
2712   // Make sure we're not referencing non-imported vars or functions.
2713   struct DLLImportFunctionVisitor
2714       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2715     bool SafeToInline = true;
2716 
2717     bool shouldVisitImplicitCode() const { return true; }
2718 
2719     bool VisitVarDecl(VarDecl *VD) {
2720       if (VD->getTLSKind()) {
2721         // A thread-local variable cannot be imported.
2722         SafeToInline = false;
2723         return SafeToInline;
2724       }
2725 
2726       // A variable definition might imply a destructor call.
2727       if (VD->isThisDeclarationADefinition())
2728         SafeToInline = !HasNonDllImportDtor(VD->getType());
2729 
2730       return SafeToInline;
2731     }
2732 
2733     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2734       if (const auto *D = E->getTemporary()->getDestructor())
2735         SafeToInline = D->hasAttr<DLLImportAttr>();
2736       return SafeToInline;
2737     }
2738 
2739     bool VisitDeclRefExpr(DeclRefExpr *E) {
2740       ValueDecl *VD = E->getDecl();
2741       if (isa<FunctionDecl>(VD))
2742         SafeToInline = VD->hasAttr<DLLImportAttr>();
2743       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2744         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2745       return SafeToInline;
2746     }
2747 
2748     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2749       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2750       return SafeToInline;
2751     }
2752 
2753     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2754       CXXMethodDecl *M = E->getMethodDecl();
2755       if (!M) {
2756         // Call through a pointer to member function. This is safe to inline.
2757         SafeToInline = true;
2758       } else {
2759         SafeToInline = M->hasAttr<DLLImportAttr>();
2760       }
2761       return SafeToInline;
2762     }
2763 
2764     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2765       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2766       return SafeToInline;
2767     }
2768 
2769     bool VisitCXXNewExpr(CXXNewExpr *E) {
2770       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2771       return SafeToInline;
2772     }
2773   };
2774 }
2775 
2776 // isTriviallyRecursive - Check if this function calls another
2777 // decl that, because of the asm attribute or the other decl being a builtin,
2778 // ends up pointing to itself.
2779 bool
2780 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2781   StringRef Name;
2782   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
2783     // asm labels are a special kind of mangling we have to support.
2784     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2785     if (!Attr)
2786       return false;
2787     Name = Attr->getLabel();
2788   } else {
2789     Name = FD->getName();
2790   }
2791 
2792   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
2793   const Stmt *Body = FD->getBody();
2794   return Body ? Walker.Visit(Body) : false;
2795 }
2796 
2797 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
2798   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
2799     return true;
2800   const auto *F = cast<FunctionDecl>(GD.getDecl());
2801   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
2802     return false;
2803 
2804   if (F->hasAttr<DLLImportAttr>()) {
2805     // Check whether it would be safe to inline this dllimport function.
2806     DLLImportFunctionVisitor Visitor;
2807     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2808     if (!Visitor.SafeToInline)
2809       return false;
2810 
2811     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2812       // Implicit destructor invocations aren't captured in the AST, so the
2813       // check above can't see them. Check for them manually here.
2814       for (const Decl *Member : Dtor->getParent()->decls())
2815         if (isa<FieldDecl>(Member))
2816           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2817             return false;
2818       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2819         if (HasNonDllImportDtor(B.getType()))
2820           return false;
2821     }
2822   }
2823 
2824   // PR9614. Avoid cases where the source code is lying to us. An available
2825   // externally function should have an equivalent function somewhere else,
2826   // but a function that calls itself through asm label/`__builtin_` trickery is
2827   // clearly not equivalent to the real implementation.
2828   // This happens in glibc's btowc and in some configure checks.
2829   return !isTriviallyRecursive(F);
2830 }
2831 
2832 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2833   return CodeGenOpts.OptimizationLevel > 0;
2834 }
2835 
2836 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
2837                                                        llvm::GlobalValue *GV) {
2838   const auto *FD = cast<FunctionDecl>(GD.getDecl());
2839 
2840   if (FD->isCPUSpecificMultiVersion()) {
2841     auto *Spec = FD->getAttr<CPUSpecificAttr>();
2842     for (unsigned I = 0; I < Spec->cpus_size(); ++I)
2843       EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
2844     // Requires multiple emits.
2845   } else
2846     EmitGlobalFunctionDefinition(GD, GV);
2847 }
2848 
2849 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
2850   const auto *D = cast<ValueDecl>(GD.getDecl());
2851 
2852   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
2853                                  Context.getSourceManager(),
2854                                  "Generating code for declaration");
2855 
2856   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2857     // At -O0, don't generate IR for functions with available_externally
2858     // linkage.
2859     if (!shouldEmitFunction(GD))
2860       return;
2861 
2862     llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
2863       std::string Name;
2864       llvm::raw_string_ostream OS(Name);
2865       FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
2866                                /*Qualified=*/true);
2867       return Name;
2868     });
2869 
2870     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2871       // Make sure to emit the definition(s) before we emit the thunks.
2872       // This is necessary for the generation of certain thunks.
2873       if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
2874         ABI->emitCXXStructor(GD);
2875       else if (FD->isMultiVersion())
2876         EmitMultiVersionFunctionDefinition(GD, GV);
2877       else
2878         EmitGlobalFunctionDefinition(GD, GV);
2879 
2880       if (Method->isVirtual())
2881         getVTables().EmitThunks(GD);
2882 
2883       return;
2884     }
2885 
2886     if (FD->isMultiVersion())
2887       return EmitMultiVersionFunctionDefinition(GD, GV);
2888     return EmitGlobalFunctionDefinition(GD, GV);
2889   }
2890 
2891   if (const auto *VD = dyn_cast<VarDecl>(D))
2892     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2893 
2894   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
2895 }
2896 
2897 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2898                                                       llvm::Function *NewFn);
2899 
2900 static unsigned
2901 TargetMVPriority(const TargetInfo &TI,
2902                  const CodeGenFunction::MultiVersionResolverOption &RO) {
2903   unsigned Priority = 0;
2904   for (StringRef Feat : RO.Conditions.Features)
2905     Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
2906 
2907   if (!RO.Conditions.Architecture.empty())
2908     Priority = std::max(
2909         Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
2910   return Priority;
2911 }
2912 
2913 void CodeGenModule::emitMultiVersionFunctions() {
2914   for (GlobalDecl GD : MultiVersionFuncs) {
2915     SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
2916     const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2917     getContext().forEachMultiversionedFunctionVersion(
2918         FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2919           GlobalDecl CurGD{
2920               (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2921           StringRef MangledName = getMangledName(CurGD);
2922           llvm::Constant *Func = GetGlobalValue(MangledName);
2923           if (!Func) {
2924             if (CurFD->isDefined()) {
2925               EmitGlobalFunctionDefinition(CurGD, nullptr);
2926               Func = GetGlobalValue(MangledName);
2927             } else {
2928               const CGFunctionInfo &FI =
2929                   getTypes().arrangeGlobalDeclaration(GD);
2930               llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2931               Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2932                                        /*DontDefer=*/false, ForDefinition);
2933             }
2934             assert(Func && "This should have just been created");
2935           }
2936 
2937           const auto *TA = CurFD->getAttr<TargetAttr>();
2938           llvm::SmallVector<StringRef, 8> Feats;
2939           TA->getAddedFeatures(Feats);
2940 
2941           Options.emplace_back(cast<llvm::Function>(Func),
2942                                TA->getArchitecture(), Feats);
2943         });
2944 
2945     llvm::Function *ResolverFunc;
2946     const TargetInfo &TI = getTarget();
2947 
2948     if (TI.supportsIFunc() || FD->isTargetMultiVersion()) {
2949       ResolverFunc = cast<llvm::Function>(
2950           GetGlobalValue((getMangledName(GD) + ".resolver").str()));
2951       ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
2952     } else {
2953       ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
2954     }
2955 
2956     if (supportsCOMDAT())
2957       ResolverFunc->setComdat(
2958           getModule().getOrInsertComdat(ResolverFunc->getName()));
2959 
2960     llvm::stable_sort(
2961         Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
2962                        const CodeGenFunction::MultiVersionResolverOption &RHS) {
2963           return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
2964         });
2965     CodeGenFunction CGF(*this);
2966     CGF.EmitMultiVersionResolver(ResolverFunc, Options);
2967   }
2968 }
2969 
2970 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
2971   const auto *FD = cast<FunctionDecl>(GD.getDecl());
2972   assert(FD && "Not a FunctionDecl?");
2973   const auto *DD = FD->getAttr<CPUDispatchAttr>();
2974   assert(DD && "Not a cpu_dispatch Function?");
2975   llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
2976 
2977   if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
2978     const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
2979     DeclTy = getTypes().GetFunctionType(FInfo);
2980   }
2981 
2982   StringRef ResolverName = getMangledName(GD);
2983 
2984   llvm::Type *ResolverType;
2985   GlobalDecl ResolverGD;
2986   if (getTarget().supportsIFunc())
2987     ResolverType = llvm::FunctionType::get(
2988         llvm::PointerType::get(DeclTy,
2989                                Context.getTargetAddressSpace(FD->getType())),
2990         false);
2991   else {
2992     ResolverType = DeclTy;
2993     ResolverGD = GD;
2994   }
2995 
2996   auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
2997       ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
2998   ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
2999   if (supportsCOMDAT())
3000     ResolverFunc->setComdat(
3001         getModule().getOrInsertComdat(ResolverFunc->getName()));
3002 
3003   SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3004   const TargetInfo &Target = getTarget();
3005   unsigned Index = 0;
3006   for (const IdentifierInfo *II : DD->cpus()) {
3007     // Get the name of the target function so we can look it up/create it.
3008     std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
3009                               getCPUSpecificMangling(*this, II->getName());
3010 
3011     llvm::Constant *Func = GetGlobalValue(MangledName);
3012 
3013     if (!Func) {
3014       GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
3015       if (ExistingDecl.getDecl() &&
3016           ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
3017         EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
3018         Func = GetGlobalValue(MangledName);
3019       } else {
3020         if (!ExistingDecl.getDecl())
3021           ExistingDecl = GD.getWithMultiVersionIndex(Index);
3022 
3023       Func = GetOrCreateLLVMFunction(
3024           MangledName, DeclTy, ExistingDecl,
3025           /*ForVTable=*/false, /*DontDefer=*/true,
3026           /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
3027       }
3028     }
3029 
3030     llvm::SmallVector<StringRef, 32> Features;
3031     Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
3032     llvm::transform(Features, Features.begin(),
3033                     [](StringRef Str) { return Str.substr(1); });
3034     Features.erase(std::remove_if(
3035         Features.begin(), Features.end(), [&Target](StringRef Feat) {
3036           return !Target.validateCpuSupports(Feat);
3037         }), Features.end());
3038     Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
3039     ++Index;
3040   }
3041 
3042   llvm::sort(
3043       Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
3044                   const CodeGenFunction::MultiVersionResolverOption &RHS) {
3045         return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
3046                CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
3047       });
3048 
3049   // If the list contains multiple 'default' versions, such as when it contains
3050   // 'pentium' and 'generic', don't emit the call to the generic one (since we
3051   // always run on at least a 'pentium'). We do this by deleting the 'least
3052   // advanced' (read, lowest mangling letter).
3053   while (Options.size() > 1 &&
3054          CodeGenFunction::GetX86CpuSupportsMask(
3055              (Options.end() - 2)->Conditions.Features) == 0) {
3056     StringRef LHSName = (Options.end() - 2)->Function->getName();
3057     StringRef RHSName = (Options.end() - 1)->Function->getName();
3058     if (LHSName.compare(RHSName) < 0)
3059       Options.erase(Options.end() - 2);
3060     else
3061       Options.erase(Options.end() - 1);
3062   }
3063 
3064   CodeGenFunction CGF(*this);
3065   CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3066 
3067   if (getTarget().supportsIFunc()) {
3068     std::string AliasName = getMangledNameImpl(
3069         *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3070     llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3071     if (!AliasFunc) {
3072       auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
3073           AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
3074           /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
3075       auto *GA = llvm::GlobalAlias::create(
3076          DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule());
3077       GA->setLinkage(llvm::Function::WeakODRLinkage);
3078       SetCommonAttributes(GD, GA);
3079     }
3080   }
3081 }
3082 
3083 /// If a dispatcher for the specified mangled name is not in the module, create
3084 /// and return an llvm Function with the specified type.
3085 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
3086     GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
3087   std::string MangledName =
3088       getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
3089 
3090   // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
3091   // a separate resolver).
3092   std::string ResolverName = MangledName;
3093   if (getTarget().supportsIFunc())
3094     ResolverName += ".ifunc";
3095   else if (FD->isTargetMultiVersion())
3096     ResolverName += ".resolver";
3097 
3098   // If this already exists, just return that one.
3099   if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
3100     return ResolverGV;
3101 
3102   // Since this is the first time we've created this IFunc, make sure
3103   // that we put this multiversioned function into the list to be
3104   // replaced later if necessary (target multiversioning only).
3105   if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
3106     MultiVersionFuncs.push_back(GD);
3107 
3108   if (getTarget().supportsIFunc()) {
3109     llvm::Type *ResolverType = llvm::FunctionType::get(
3110         llvm::PointerType::get(
3111             DeclTy, getContext().getTargetAddressSpace(FD->getType())),
3112         false);
3113     llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3114         MangledName + ".resolver", ResolverType, GlobalDecl{},
3115         /*ForVTable=*/false);
3116     llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
3117         DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule());
3118     GIF->setName(ResolverName);
3119     SetCommonAttributes(FD, GIF);
3120 
3121     return GIF;
3122   }
3123 
3124   llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3125       ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
3126   assert(isa<llvm::GlobalValue>(Resolver) &&
3127          "Resolver should be created for the first time");
3128   SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
3129   return Resolver;
3130 }
3131 
3132 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
3133 /// module, create and return an llvm Function with the specified type. If there
3134 /// is something in the module with the specified name, return it potentially
3135 /// bitcasted to the right type.
3136 ///
3137 /// If D is non-null, it specifies a decl that correspond to this.  This is used
3138 /// to set the attributes on the function when it is first created.
3139 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
3140     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
3141     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
3142     ForDefinition_t IsForDefinition) {
3143   const Decl *D = GD.getDecl();
3144 
3145   // Any attempts to use a MultiVersion function should result in retrieving
3146   // the iFunc instead. Name Mangling will handle the rest of the changes.
3147   if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
3148     // For the device mark the function as one that should be emitted.
3149     if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
3150         !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
3151         !DontDefer && !IsForDefinition) {
3152       if (const FunctionDecl *FDDef = FD->getDefinition()) {
3153         GlobalDecl GDDef;
3154         if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
3155           GDDef = GlobalDecl(CD, GD.getCtorType());
3156         else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
3157           GDDef = GlobalDecl(DD, GD.getDtorType());
3158         else
3159           GDDef = GlobalDecl(FDDef);
3160         EmitGlobal(GDDef);
3161       }
3162     }
3163 
3164     if (FD->isMultiVersion()) {
3165       if (FD->hasAttr<TargetAttr>())
3166         UpdateMultiVersionNames(GD, FD);
3167       if (!IsForDefinition)
3168         return GetOrCreateMultiVersionResolver(GD, Ty, FD);
3169     }
3170   }
3171 
3172   // Lookup the entry, lazily creating it if necessary.
3173   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3174   if (Entry) {
3175     if (WeakRefReferences.erase(Entry)) {
3176       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
3177       if (FD && !FD->hasAttr<WeakAttr>())
3178         Entry->setLinkage(llvm::Function::ExternalLinkage);
3179     }
3180 
3181     // Handle dropped DLL attributes.
3182     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
3183       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3184       setDSOLocal(Entry);
3185     }
3186 
3187     // If there are two attempts to define the same mangled name, issue an
3188     // error.
3189     if (IsForDefinition && !Entry->isDeclaration()) {
3190       GlobalDecl OtherGD;
3191       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
3192       // to make sure that we issue an error only once.
3193       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3194           (GD.getCanonicalDecl().getDecl() !=
3195            OtherGD.getCanonicalDecl().getDecl()) &&
3196           DiagnosedConflictingDefinitions.insert(GD).second) {
3197         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3198             << MangledName;
3199         getDiags().Report(OtherGD.getDecl()->getLocation(),
3200                           diag::note_previous_definition);
3201       }
3202     }
3203 
3204     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
3205         (Entry->getValueType() == Ty)) {
3206       return Entry;
3207     }
3208 
3209     // Make sure the result is of the correct type.
3210     // (If function is requested for a definition, we always need to create a new
3211     // function, not just return a bitcast.)
3212     if (!IsForDefinition)
3213       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
3214   }
3215 
3216   // This function doesn't have a complete type (for example, the return
3217   // type is an incomplete struct). Use a fake type instead, and make
3218   // sure not to try to set attributes.
3219   bool IsIncompleteFunction = false;
3220 
3221   llvm::FunctionType *FTy;
3222   if (isa<llvm::FunctionType>(Ty)) {
3223     FTy = cast<llvm::FunctionType>(Ty);
3224   } else {
3225     FTy = llvm::FunctionType::get(VoidTy, false);
3226     IsIncompleteFunction = true;
3227   }
3228 
3229   llvm::Function *F =
3230       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
3231                              Entry ? StringRef() : MangledName, &getModule());
3232 
3233   // If we already created a function with the same mangled name (but different
3234   // type) before, take its name and add it to the list of functions to be
3235   // replaced with F at the end of CodeGen.
3236   //
3237   // This happens if there is a prototype for a function (e.g. "int f()") and
3238   // then a definition of a different type (e.g. "int f(int x)").
3239   if (Entry) {
3240     F->takeName(Entry);
3241 
3242     // This might be an implementation of a function without a prototype, in
3243     // which case, try to do special replacement of calls which match the new
3244     // prototype.  The really key thing here is that we also potentially drop
3245     // arguments from the call site so as to make a direct call, which makes the
3246     // inliner happier and suppresses a number of optimizer warnings (!) about
3247     // dropping arguments.
3248     if (!Entry->use_empty()) {
3249       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
3250       Entry->removeDeadConstantUsers();
3251     }
3252 
3253     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
3254         F, Entry->getValueType()->getPointerTo());
3255     addGlobalValReplacement(Entry, BC);
3256   }
3257 
3258   assert(F->getName() == MangledName && "name was uniqued!");
3259   if (D)
3260     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
3261   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
3262     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
3263     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
3264   }
3265 
3266   if (!DontDefer) {
3267     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
3268     // each other bottoming out with the base dtor.  Therefore we emit non-base
3269     // dtors on usage, even if there is no dtor definition in the TU.
3270     if (D && isa<CXXDestructorDecl>(D) &&
3271         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
3272                                            GD.getDtorType()))
3273       addDeferredDeclToEmit(GD);
3274 
3275     // This is the first use or definition of a mangled name.  If there is a
3276     // deferred decl with this name, remember that we need to emit it at the end
3277     // of the file.
3278     auto DDI = DeferredDecls.find(MangledName);
3279     if (DDI != DeferredDecls.end()) {
3280       // Move the potentially referenced deferred decl to the
3281       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
3282       // don't need it anymore).
3283       addDeferredDeclToEmit(DDI->second);
3284       DeferredDecls.erase(DDI);
3285 
3286       // Otherwise, there are cases we have to worry about where we're
3287       // using a declaration for which we must emit a definition but where
3288       // we might not find a top-level definition:
3289       //   - member functions defined inline in their classes
3290       //   - friend functions defined inline in some class
3291       //   - special member functions with implicit definitions
3292       // If we ever change our AST traversal to walk into class methods,
3293       // this will be unnecessary.
3294       //
3295       // We also don't emit a definition for a function if it's going to be an
3296       // entry in a vtable, unless it's already marked as used.
3297     } else if (getLangOpts().CPlusPlus && D) {
3298       // Look for a declaration that's lexically in a record.
3299       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
3300            FD = FD->getPreviousDecl()) {
3301         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
3302           if (FD->doesThisDeclarationHaveABody()) {
3303             addDeferredDeclToEmit(GD.getWithDecl(FD));
3304             break;
3305           }
3306         }
3307       }
3308     }
3309   }
3310 
3311   // Make sure the result is of the requested type.
3312   if (!IsIncompleteFunction) {
3313     assert(F->getFunctionType() == Ty);
3314     return F;
3315   }
3316 
3317   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3318   return llvm::ConstantExpr::getBitCast(F, PTy);
3319 }
3320 
3321 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
3322 /// non-null, then this function will use the specified type if it has to
3323 /// create it (this occurs when we see a definition of the function).
3324 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
3325                                                  llvm::Type *Ty,
3326                                                  bool ForVTable,
3327                                                  bool DontDefer,
3328                                               ForDefinition_t IsForDefinition) {
3329   // If there was no specific requested type, just convert it now.
3330   if (!Ty) {
3331     const auto *FD = cast<FunctionDecl>(GD.getDecl());
3332     Ty = getTypes().ConvertType(FD->getType());
3333   }
3334 
3335   // Devirtualized destructor calls may come through here instead of via
3336   // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
3337   // of the complete destructor when necessary.
3338   if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
3339     if (getTarget().getCXXABI().isMicrosoft() &&
3340         GD.getDtorType() == Dtor_Complete &&
3341         DD->getParent()->getNumVBases() == 0)
3342       GD = GlobalDecl(DD, Dtor_Base);
3343   }
3344 
3345   StringRef MangledName = getMangledName(GD);
3346   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
3347                                  /*IsThunk=*/false, llvm::AttributeList(),
3348                                  IsForDefinition);
3349 }
3350 
3351 static const FunctionDecl *
3352 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
3353   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
3354   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3355 
3356   IdentifierInfo &CII = C.Idents.get(Name);
3357   for (const auto &Result : DC->lookup(&CII))
3358     if (const auto FD = dyn_cast<FunctionDecl>(Result))
3359       return FD;
3360 
3361   if (!C.getLangOpts().CPlusPlus)
3362     return nullptr;
3363 
3364   // Demangle the premangled name from getTerminateFn()
3365   IdentifierInfo &CXXII =
3366       (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
3367           ? C.Idents.get("terminate")
3368           : C.Idents.get(Name);
3369 
3370   for (const auto &N : {"__cxxabiv1", "std"}) {
3371     IdentifierInfo &NS = C.Idents.get(N);
3372     for (const auto &Result : DC->lookup(&NS)) {
3373       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
3374       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
3375         for (const auto &Result : LSD->lookup(&NS))
3376           if ((ND = dyn_cast<NamespaceDecl>(Result)))
3377             break;
3378 
3379       if (ND)
3380         for (const auto &Result : ND->lookup(&CXXII))
3381           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3382             return FD;
3383     }
3384   }
3385 
3386   return nullptr;
3387 }
3388 
3389 /// CreateRuntimeFunction - Create a new runtime function with the specified
3390 /// type and name.
3391 llvm::FunctionCallee
3392 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
3393                                      llvm::AttributeList ExtraAttrs, bool Local,
3394                                      bool AssumeConvergent) {
3395   if (AssumeConvergent) {
3396     ExtraAttrs =
3397         ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex,
3398                                 llvm::Attribute::Convergent);
3399   }
3400 
3401   llvm::Constant *C =
3402       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
3403                               /*DontDefer=*/false, /*IsThunk=*/false,
3404                               ExtraAttrs);
3405 
3406   if (auto *F = dyn_cast<llvm::Function>(C)) {
3407     if (F->empty()) {
3408       F->setCallingConv(getRuntimeCC());
3409 
3410       // In Windows Itanium environments, try to mark runtime functions
3411       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
3412       // will link their standard library statically or dynamically. Marking
3413       // functions imported when they are not imported can cause linker errors
3414       // and warnings.
3415       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
3416           !getCodeGenOpts().LTOVisibilityPublicStd) {
3417         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
3418         if (!FD || FD->hasAttr<DLLImportAttr>()) {
3419           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3420           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
3421         }
3422       }
3423       setDSOLocal(F);
3424     }
3425   }
3426 
3427   return {FTy, C};
3428 }
3429 
3430 /// isTypeConstant - Determine whether an object of this type can be emitted
3431 /// as a constant.
3432 ///
3433 /// If ExcludeCtor is true, the duration when the object's constructor runs
3434 /// will not be considered. The caller will need to verify that the object is
3435 /// not written to during its construction.
3436 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
3437   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
3438     return false;
3439 
3440   if (Context.getLangOpts().CPlusPlus) {
3441     if (const CXXRecordDecl *Record
3442           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
3443       return ExcludeCtor && !Record->hasMutableFields() &&
3444              Record->hasTrivialDestructor();
3445   }
3446 
3447   return true;
3448 }
3449 
3450 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
3451 /// create and return an llvm GlobalVariable with the specified type.  If there
3452 /// is something in the module with the specified name, return it potentially
3453 /// bitcasted to the right type.
3454 ///
3455 /// If D is non-null, it specifies a decl that correspond to this.  This is used
3456 /// to set the attributes on the global when it is first created.
3457 ///
3458 /// If IsForDefinition is true, it is guaranteed that an actual global with
3459 /// type Ty will be returned, not conversion of a variable with the same
3460 /// mangled name but some other type.
3461 llvm::Constant *
3462 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
3463                                      llvm::PointerType *Ty,
3464                                      const VarDecl *D,
3465                                      ForDefinition_t IsForDefinition) {
3466   // Lookup the entry, lazily creating it if necessary.
3467   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3468   if (Entry) {
3469     if (WeakRefReferences.erase(Entry)) {
3470       if (D && !D->hasAttr<WeakAttr>())
3471         Entry->setLinkage(llvm::Function::ExternalLinkage);
3472     }
3473 
3474     // Handle dropped DLL attributes.
3475     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
3476       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3477 
3478     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
3479       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
3480 
3481     if (Entry->getType() == Ty)
3482       return Entry;
3483 
3484     // If there are two attempts to define the same mangled name, issue an
3485     // error.
3486     if (IsForDefinition && !Entry->isDeclaration()) {
3487       GlobalDecl OtherGD;
3488       const VarDecl *OtherD;
3489 
3490       // Check that D is not yet in DiagnosedConflictingDefinitions is required
3491       // to make sure that we issue an error only once.
3492       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
3493           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3494           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
3495           OtherD->hasInit() &&
3496           DiagnosedConflictingDefinitions.insert(D).second) {
3497         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3498             << MangledName;
3499         getDiags().Report(OtherGD.getDecl()->getLocation(),
3500                           diag::note_previous_definition);
3501       }
3502     }
3503 
3504     // Make sure the result is of the correct type.
3505     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
3506       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
3507 
3508     // (If global is requested for a definition, we always need to create a new
3509     // global, not just return a bitcast.)
3510     if (!IsForDefinition)
3511       return llvm::ConstantExpr::getBitCast(Entry, Ty);
3512   }
3513 
3514   auto AddrSpace = GetGlobalVarAddressSpace(D);
3515   auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
3516 
3517   auto *GV = new llvm::GlobalVariable(
3518       getModule(), Ty->getElementType(), false,
3519       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
3520       llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
3521 
3522   // If we already created a global with the same mangled name (but different
3523   // type) before, take its name and remove it from its parent.
3524   if (Entry) {
3525     GV->takeName(Entry);
3526 
3527     if (!Entry->use_empty()) {
3528       llvm::Constant *NewPtrForOldDecl =
3529           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3530       Entry->replaceAllUsesWith(NewPtrForOldDecl);
3531     }
3532 
3533     Entry->eraseFromParent();
3534   }
3535 
3536   // This is the first use or definition of a mangled name.  If there is a
3537   // deferred decl with this name, remember that we need to emit it at the end
3538   // of the file.
3539   auto DDI = DeferredDecls.find(MangledName);
3540   if (DDI != DeferredDecls.end()) {
3541     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3542     // list, and remove it from DeferredDecls (since we don't need it anymore).
3543     addDeferredDeclToEmit(DDI->second);
3544     DeferredDecls.erase(DDI);
3545   }
3546 
3547   // Handle things which are present even on external declarations.
3548   if (D) {
3549     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3550       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3551 
3552     // FIXME: This code is overly simple and should be merged with other global
3553     // handling.
3554     GV->setConstant(isTypeConstant(D->getType(), false));
3555 
3556     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
3557 
3558     setLinkageForGV(GV, D);
3559 
3560     if (D->getTLSKind()) {
3561       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3562         CXXThreadLocals.push_back(D);
3563       setTLSMode(GV, *D);
3564     }
3565 
3566     setGVProperties(GV, D);
3567 
3568     // If required by the ABI, treat declarations of static data members with
3569     // inline initializers as definitions.
3570     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
3571       EmitGlobalVarDefinition(D);
3572     }
3573 
3574     // Emit section information for extern variables.
3575     if (D->hasExternalStorage()) {
3576       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3577         GV->setSection(SA->getName());
3578     }
3579 
3580     // Handle XCore specific ABI requirements.
3581     if (getTriple().getArch() == llvm::Triple::xcore &&
3582         D->getLanguageLinkage() == CLanguageLinkage &&
3583         D->getType().isConstant(Context) &&
3584         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3585       GV->setSection(".cp.rodata");
3586 
3587     // Check if we a have a const declaration with an initializer, we may be
3588     // able to emit it as available_externally to expose it's value to the
3589     // optimizer.
3590     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3591         D->getType().isConstQualified() && !GV->hasInitializer() &&
3592         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3593       const auto *Record =
3594           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3595       bool HasMutableFields = Record && Record->hasMutableFields();
3596       if (!HasMutableFields) {
3597         const VarDecl *InitDecl;
3598         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3599         if (InitExpr) {
3600           ConstantEmitter emitter(*this);
3601           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3602           if (Init) {
3603             auto *InitType = Init->getType();
3604             if (GV->getValueType() != InitType) {
3605               // The type of the initializer does not match the definition.
3606               // This happens when an initializer has a different type from
3607               // the type of the global (because of padding at the end of a
3608               // structure for instance).
3609               GV->setName(StringRef());
3610               // Make a new global with the correct type, this is now guaranteed
3611               // to work.
3612               auto *NewGV = cast<llvm::GlobalVariable>(
3613                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
3614                       ->stripPointerCasts());
3615 
3616               // Erase the old global, since it is no longer used.
3617               GV->eraseFromParent();
3618               GV = NewGV;
3619             } else {
3620               GV->setInitializer(Init);
3621               GV->setConstant(true);
3622               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3623             }
3624             emitter.finalize(GV);
3625           }
3626         }
3627       }
3628     }
3629   }
3630 
3631   if (GV->isDeclaration())
3632     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
3633 
3634   LangAS ExpectedAS =
3635       D ? D->getType().getAddressSpace()
3636         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
3637   assert(getContext().getTargetAddressSpace(ExpectedAS) ==
3638          Ty->getPointerAddressSpace());
3639   if (AddrSpace != ExpectedAS)
3640     return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3641                                                        ExpectedAS, Ty);
3642 
3643   return GV;
3644 }
3645 
3646 llvm::Constant *
3647 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
3648                                ForDefinition_t IsForDefinition) {
3649   const Decl *D = GD.getDecl();
3650   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
3651     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3652                                 /*DontDefer=*/false, IsForDefinition);
3653   else if (isa<CXXMethodDecl>(D)) {
3654     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
3655         cast<CXXMethodDecl>(D));
3656     auto Ty = getTypes().GetFunctionType(*FInfo);
3657     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3658                              IsForDefinition);
3659   } else if (isa<FunctionDecl>(D)) {
3660     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3661     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3662     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3663                              IsForDefinition);
3664   } else
3665     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
3666                               IsForDefinition);
3667 }
3668 
3669 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
3670     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
3671     unsigned Alignment) {
3672   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
3673   llvm::GlobalVariable *OldGV = nullptr;
3674 
3675   if (GV) {
3676     // Check if the variable has the right type.
3677     if (GV->getValueType() == Ty)
3678       return GV;
3679 
3680     // Because C++ name mangling, the only way we can end up with an already
3681     // existing global with the same name is if it has been declared extern "C".
3682     assert(GV->isDeclaration() && "Declaration has wrong type!");
3683     OldGV = GV;
3684   }
3685 
3686   // Create a new variable.
3687   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
3688                                 Linkage, nullptr, Name);
3689 
3690   if (OldGV) {
3691     // Replace occurrences of the old variable if needed.
3692     GV->takeName(OldGV);
3693 
3694     if (!OldGV->use_empty()) {
3695       llvm::Constant *NewPtrForOldDecl =
3696       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3697       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3698     }
3699 
3700     OldGV->eraseFromParent();
3701   }
3702 
3703   if (supportsCOMDAT() && GV->isWeakForLinker() &&
3704       !GV->hasAvailableExternallyLinkage())
3705     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3706 
3707   GV->setAlignment(llvm::MaybeAlign(Alignment));
3708 
3709   return GV;
3710 }
3711 
3712 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3713 /// given global variable.  If Ty is non-null and if the global doesn't exist,
3714 /// then it will be created with the specified type instead of whatever the
3715 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
3716 /// that an actual global with type Ty will be returned, not conversion of a
3717 /// variable with the same mangled name but some other type.
3718 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
3719                                                   llvm::Type *Ty,
3720                                            ForDefinition_t IsForDefinition) {
3721   assert(D->hasGlobalStorage() && "Not a global variable");
3722   QualType ASTTy = D->getType();
3723   if (!Ty)
3724     Ty = getTypes().ConvertTypeForMem(ASTTy);
3725 
3726   llvm::PointerType *PTy =
3727     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
3728 
3729   StringRef MangledName = getMangledName(D);
3730   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
3731 }
3732 
3733 /// CreateRuntimeVariable - Create a new runtime global variable with the
3734 /// specified type and name.
3735 llvm::Constant *
3736 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
3737                                      StringRef Name) {
3738   auto PtrTy =
3739       getContext().getLangOpts().OpenCL
3740           ? llvm::PointerType::get(
3741                 Ty, getContext().getTargetAddressSpace(LangAS::opencl_global))
3742           : llvm::PointerType::getUnqual(Ty);
3743   auto *Ret = GetOrCreateLLVMGlobal(Name, PtrTy, nullptr);
3744   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3745   return Ret;
3746 }
3747 
3748 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
3749   assert(!D->getInit() && "Cannot emit definite definitions here!");
3750 
3751   StringRef MangledName = getMangledName(D);
3752   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3753 
3754   // We already have a definition, not declaration, with the same mangled name.
3755   // Emitting of declaration is not required (and actually overwrites emitted
3756   // definition).
3757   if (GV && !GV->isDeclaration())
3758     return;
3759 
3760   // If we have not seen a reference to this variable yet, place it into the
3761   // deferred declarations table to be emitted if needed later.
3762   if (!MustBeEmitted(D) && !GV) {
3763       DeferredDecls[MangledName] = D;
3764       return;
3765   }
3766 
3767   // The tentative definition is the only definition.
3768   EmitGlobalVarDefinition(D);
3769 }
3770 
3771 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
3772   EmitExternalVarDeclaration(D);
3773 }
3774 
3775 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
3776   return Context.toCharUnitsFromBits(
3777       getDataLayout().getTypeStoreSizeInBits(Ty));
3778 }
3779 
3780 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
3781   LangAS AddrSpace = LangAS::Default;
3782   if (LangOpts.OpenCL) {
3783     AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
3784     assert(AddrSpace == LangAS::opencl_global ||
3785            AddrSpace == LangAS::opencl_constant ||
3786            AddrSpace == LangAS::opencl_local ||
3787            AddrSpace >= LangAS::FirstTargetAddressSpace);
3788     return AddrSpace;
3789   }
3790 
3791   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3792     if (D && D->hasAttr<CUDAConstantAttr>())
3793       return LangAS::cuda_constant;
3794     else if (D && D->hasAttr<CUDASharedAttr>())
3795       return LangAS::cuda_shared;
3796     else if (D && D->hasAttr<CUDADeviceAttr>())
3797       return LangAS::cuda_device;
3798     else if (D && D->getType().isConstQualified())
3799       return LangAS::cuda_constant;
3800     else
3801       return LangAS::cuda_device;
3802   }
3803 
3804   if (LangOpts.OpenMP) {
3805     LangAS AS;
3806     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
3807       return AS;
3808   }
3809   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
3810 }
3811 
3812 LangAS CodeGenModule::getStringLiteralAddressSpace() const {
3813   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3814   if (LangOpts.OpenCL)
3815     return LangAS::opencl_constant;
3816   if (auto AS = getTarget().getConstantAddressSpace())
3817     return AS.getValue();
3818   return LangAS::Default;
3819 }
3820 
3821 // In address space agnostic languages, string literals are in default address
3822 // space in AST. However, certain targets (e.g. amdgcn) request them to be
3823 // emitted in constant address space in LLVM IR. To be consistent with other
3824 // parts of AST, string literal global variables in constant address space
3825 // need to be casted to default address space before being put into address
3826 // map and referenced by other part of CodeGen.
3827 // In OpenCL, string literals are in constant address space in AST, therefore
3828 // they should not be casted to default address space.
3829 static llvm::Constant *
3830 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
3831                                        llvm::GlobalVariable *GV) {
3832   llvm::Constant *Cast = GV;
3833   if (!CGM.getLangOpts().OpenCL) {
3834     if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3835       if (AS != LangAS::Default)
3836         Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
3837             CGM, GV, AS.getValue(), LangAS::Default,
3838             GV->getValueType()->getPointerTo(
3839                 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
3840     }
3841   }
3842   return Cast;
3843 }
3844 
3845 template<typename SomeDecl>
3846 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3847                                                llvm::GlobalValue *GV) {
3848   if (!getLangOpts().CPlusPlus)
3849     return;
3850 
3851   // Must have 'used' attribute, or else inline assembly can't rely on
3852   // the name existing.
3853   if (!D->template hasAttr<UsedAttr>())
3854     return;
3855 
3856   // Must have internal linkage and an ordinary name.
3857   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
3858     return;
3859 
3860   // Must be in an extern "C" context. Entities declared directly within
3861   // a record are not extern "C" even if the record is in such a context.
3862   const SomeDecl *First = D->getFirstDecl();
3863   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
3864     return;
3865 
3866   // OK, this is an internal linkage entity inside an extern "C" linkage
3867   // specification. Make a note of that so we can give it the "expected"
3868   // mangled name if nothing else is using that name.
3869   std::pair<StaticExternCMap::iterator, bool> R =
3870       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
3871 
3872   // If we have multiple internal linkage entities with the same name
3873   // in extern "C" regions, none of them gets that name.
3874   if (!R.second)
3875     R.first->second = nullptr;
3876 }
3877 
3878 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3879   if (!CGM.supportsCOMDAT())
3880     return false;
3881 
3882   // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
3883   // them being "merged" by the COMDAT Folding linker optimization.
3884   if (D.hasAttr<CUDAGlobalAttr>())
3885     return false;
3886 
3887   if (D.hasAttr<SelectAnyAttr>())
3888     return true;
3889 
3890   GVALinkage Linkage;
3891   if (auto *VD = dyn_cast<VarDecl>(&D))
3892     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3893   else
3894     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3895 
3896   switch (Linkage) {
3897   case GVA_Internal:
3898   case GVA_AvailableExternally:
3899   case GVA_StrongExternal:
3900     return false;
3901   case GVA_DiscardableODR:
3902   case GVA_StrongODR:
3903     return true;
3904   }
3905   llvm_unreachable("No such linkage");
3906 }
3907 
3908 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3909                                           llvm::GlobalObject &GO) {
3910   if (!shouldBeInCOMDAT(*this, D))
3911     return;
3912   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3913 }
3914 
3915 /// Pass IsTentative as true if you want to create a tentative definition.
3916 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3917                                             bool IsTentative) {
3918   // OpenCL global variables of sampler type are translated to function calls,
3919   // therefore no need to be translated.
3920   QualType ASTTy = D->getType();
3921   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3922     return;
3923 
3924   // If this is OpenMP device, check if it is legal to emit this global
3925   // normally.
3926   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3927       OpenMPRuntime->emitTargetGlobalVariable(D))
3928     return;
3929 
3930   llvm::Constant *Init = nullptr;
3931   bool NeedsGlobalCtor = false;
3932   bool NeedsGlobalDtor =
3933       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
3934 
3935   const VarDecl *InitDecl;
3936   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3937 
3938   Optional<ConstantEmitter> emitter;
3939 
3940   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3941   // as part of their declaration."  Sema has already checked for
3942   // error cases, so we just need to set Init to UndefValue.
3943   bool IsCUDASharedVar =
3944       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
3945   // Shadows of initialized device-side global variables are also left
3946   // undefined.
3947   bool IsCUDAShadowVar =
3948       !getLangOpts().CUDAIsDevice &&
3949       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3950        D->hasAttr<CUDASharedAttr>());
3951   bool IsCUDADeviceShadowVar =
3952       getLangOpts().CUDAIsDevice &&
3953       (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
3954        D->getType()->isCUDADeviceBuiltinTextureType());
3955   // HIP pinned shadow of initialized host-side global variables are also
3956   // left undefined.
3957   if (getLangOpts().CUDA &&
3958       (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
3959     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
3960   else if (D->hasAttr<LoaderUninitializedAttr>())
3961     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
3962   else if (!InitExpr) {
3963     // This is a tentative definition; tentative definitions are
3964     // implicitly initialized with { 0 }.
3965     //
3966     // Note that tentative definitions are only emitted at the end of
3967     // a translation unit, so they should never have incomplete
3968     // type. In addition, EmitTentativeDefinition makes sure that we
3969     // never attempt to emit a tentative definition if a real one
3970     // exists. A use may still exists, however, so we still may need
3971     // to do a RAUW.
3972     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
3973     Init = EmitNullConstant(D->getType());
3974   } else {
3975     initializedGlobalDecl = GlobalDecl(D);
3976     emitter.emplace(*this);
3977     Init = emitter->tryEmitForInitializer(*InitDecl);
3978 
3979     if (!Init) {
3980       QualType T = InitExpr->getType();
3981       if (D->getType()->isReferenceType())
3982         T = D->getType();
3983 
3984       if (getLangOpts().CPlusPlus) {
3985         Init = EmitNullConstant(T);
3986         NeedsGlobalCtor = true;
3987       } else {
3988         ErrorUnsupported(D, "static initializer");
3989         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3990       }
3991     } else {
3992       // We don't need an initializer, so remove the entry for the delayed
3993       // initializer position (just in case this entry was delayed) if we
3994       // also don't need to register a destructor.
3995       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
3996         DelayedCXXInitPosition.erase(D);
3997     }
3998   }
3999 
4000   llvm::Type* InitType = Init->getType();
4001   llvm::Constant *Entry =
4002       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
4003 
4004   // Strip off pointer casts if we got them.
4005   Entry = Entry->stripPointerCasts();
4006 
4007   // Entry is now either a Function or GlobalVariable.
4008   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
4009 
4010   // We have a definition after a declaration with the wrong type.
4011   // We must make a new GlobalVariable* and update everything that used OldGV
4012   // (a declaration or tentative definition) with the new GlobalVariable*
4013   // (which will be a definition).
4014   //
4015   // This happens if there is a prototype for a global (e.g.
4016   // "extern int x[];") and then a definition of a different type (e.g.
4017   // "int x[10];"). This also happens when an initializer has a different type
4018   // from the type of the global (this happens with unions).
4019   if (!GV || GV->getValueType() != InitType ||
4020       GV->getType()->getAddressSpace() !=
4021           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
4022 
4023     // Move the old entry aside so that we'll create a new one.
4024     Entry->setName(StringRef());
4025 
4026     // Make a new global with the correct type, this is now guaranteed to work.
4027     GV = cast<llvm::GlobalVariable>(
4028         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
4029             ->stripPointerCasts());
4030 
4031     // Replace all uses of the old global with the new global
4032     llvm::Constant *NewPtrForOldDecl =
4033         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
4034     Entry->replaceAllUsesWith(NewPtrForOldDecl);
4035 
4036     // Erase the old global, since it is no longer used.
4037     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
4038   }
4039 
4040   MaybeHandleStaticInExternC(D, GV);
4041 
4042   if (D->hasAttr<AnnotateAttr>())
4043     AddGlobalAnnotations(D, GV);
4044 
4045   // Set the llvm linkage type as appropriate.
4046   llvm::GlobalValue::LinkageTypes Linkage =
4047       getLLVMLinkageVarDefinition(D, GV->isConstant());
4048 
4049   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
4050   // the device. [...]"
4051   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
4052   // __device__, declares a variable that: [...]
4053   // Is accessible from all the threads within the grid and from the host
4054   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
4055   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
4056   if (GV && LangOpts.CUDA) {
4057     if (LangOpts.CUDAIsDevice) {
4058       if (Linkage != llvm::GlobalValue::InternalLinkage &&
4059           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()))
4060         GV->setExternallyInitialized(true);
4061     } else {
4062       // Host-side shadows of external declarations of device-side
4063       // global variables become internal definitions. These have to
4064       // be internal in order to prevent name conflicts with global
4065       // host variables with the same name in a different TUs.
4066       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
4067         Linkage = llvm::GlobalValue::InternalLinkage;
4068         // Shadow variables and their properties must be registered with CUDA
4069         // runtime. Skip Extern global variables, which will be registered in
4070         // the TU where they are defined.
4071         if (!D->hasExternalStorage())
4072           getCUDARuntime().registerDeviceVar(D, *GV, !D->hasDefinition(),
4073                                              D->hasAttr<CUDAConstantAttr>());
4074       } else if (D->hasAttr<CUDASharedAttr>()) {
4075         // __shared__ variables are odd. Shadows do get created, but
4076         // they are not registered with the CUDA runtime, so they
4077         // can't really be used to access their device-side
4078         // counterparts. It's not clear yet whether it's nvcc's bug or
4079         // a feature, but we've got to do the same for compatibility.
4080         Linkage = llvm::GlobalValue::InternalLinkage;
4081       } else if (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4082                  D->getType()->isCUDADeviceBuiltinTextureType()) {
4083         // Builtin surfaces and textures and their template arguments are
4084         // also registered with CUDA runtime.
4085         Linkage = llvm::GlobalValue::InternalLinkage;
4086         const ClassTemplateSpecializationDecl *TD =
4087             cast<ClassTemplateSpecializationDecl>(
4088                 D->getType()->getAs<RecordType>()->getDecl());
4089         const TemplateArgumentList &Args = TD->getTemplateArgs();
4090         if (TD->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) {
4091           assert(Args.size() == 2 &&
4092                  "Unexpected number of template arguments of CUDA device "
4093                  "builtin surface type.");
4094           auto SurfType = Args[1].getAsIntegral();
4095           if (!D->hasExternalStorage())
4096             getCUDARuntime().registerDeviceSurf(D, *GV, !D->hasDefinition(),
4097                                                 SurfType.getSExtValue());
4098         } else {
4099           assert(Args.size() == 3 &&
4100                  "Unexpected number of template arguments of CUDA device "
4101                  "builtin texture type.");
4102           auto TexType = Args[1].getAsIntegral();
4103           auto Normalized = Args[2].getAsIntegral();
4104           if (!D->hasExternalStorage())
4105             getCUDARuntime().registerDeviceTex(D, *GV, !D->hasDefinition(),
4106                                                TexType.getSExtValue(),
4107                                                Normalized.getZExtValue());
4108         }
4109       }
4110     }
4111   }
4112 
4113   GV->setInitializer(Init);
4114   if (emitter)
4115     emitter->finalize(GV);
4116 
4117   // If it is safe to mark the global 'constant', do so now.
4118   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
4119                   isTypeConstant(D->getType(), true));
4120 
4121   // If it is in a read-only section, mark it 'constant'.
4122   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
4123     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
4124     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
4125       GV->setConstant(true);
4126   }
4127 
4128   GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4129 
4130   // On Darwin, if the normal linkage of a C++ thread_local variable is
4131   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
4132   // copies within a linkage unit; otherwise, the backing variable has
4133   // internal linkage and all accesses should just be calls to the
4134   // Itanium-specified entry point, which has the normal linkage of the
4135   // variable. This is to preserve the ability to change the implementation
4136   // behind the scenes.
4137   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
4138       Context.getTargetInfo().getTriple().isOSDarwin() &&
4139       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
4140       !llvm::GlobalVariable::isWeakLinkage(Linkage))
4141     Linkage = llvm::GlobalValue::InternalLinkage;
4142 
4143   GV->setLinkage(Linkage);
4144   if (D->hasAttr<DLLImportAttr>())
4145     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
4146   else if (D->hasAttr<DLLExportAttr>())
4147     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
4148   else
4149     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
4150 
4151   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
4152     // common vars aren't constant even if declared const.
4153     GV->setConstant(false);
4154     // Tentative definition of global variables may be initialized with
4155     // non-zero null pointers. In this case they should have weak linkage
4156     // since common linkage must have zero initializer and must not have
4157     // explicit section therefore cannot have non-zero initial value.
4158     if (!GV->getInitializer()->isNullValue())
4159       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
4160   }
4161 
4162   setNonAliasAttributes(D, GV);
4163 
4164   if (D->getTLSKind() && !GV->isThreadLocal()) {
4165     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4166       CXXThreadLocals.push_back(D);
4167     setTLSMode(GV, *D);
4168   }
4169 
4170   maybeSetTrivialComdat(*D, *GV);
4171 
4172   // Emit the initializer function if necessary.
4173   if (NeedsGlobalCtor || NeedsGlobalDtor)
4174     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
4175 
4176   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
4177 
4178   // Emit global variable debug information.
4179   if (CGDebugInfo *DI = getModuleDebugInfo())
4180     if (getCodeGenOpts().hasReducedDebugInfo())
4181       DI->EmitGlobalVariable(GV, D);
4182 }
4183 
4184 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
4185   if (CGDebugInfo *DI = getModuleDebugInfo())
4186     if (getCodeGenOpts().hasReducedDebugInfo()) {
4187       QualType ASTTy = D->getType();
4188       llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
4189       llvm::PointerType *PTy =
4190           llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
4191       llvm::Constant *GV = GetOrCreateLLVMGlobal(D->getName(), PTy, D);
4192       DI->EmitExternalVariable(
4193           cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
4194     }
4195 }
4196 
4197 static bool isVarDeclStrongDefinition(const ASTContext &Context,
4198                                       CodeGenModule &CGM, const VarDecl *D,
4199                                       bool NoCommon) {
4200   // Don't give variables common linkage if -fno-common was specified unless it
4201   // was overridden by a NoCommon attribute.
4202   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
4203     return true;
4204 
4205   // C11 6.9.2/2:
4206   //   A declaration of an identifier for an object that has file scope without
4207   //   an initializer, and without a storage-class specifier or with the
4208   //   storage-class specifier static, constitutes a tentative definition.
4209   if (D->getInit() || D->hasExternalStorage())
4210     return true;
4211 
4212   // A variable cannot be both common and exist in a section.
4213   if (D->hasAttr<SectionAttr>())
4214     return true;
4215 
4216   // A variable cannot be both common and exist in a section.
4217   // We don't try to determine which is the right section in the front-end.
4218   // If no specialized section name is applicable, it will resort to default.
4219   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
4220       D->hasAttr<PragmaClangDataSectionAttr>() ||
4221       D->hasAttr<PragmaClangRelroSectionAttr>() ||
4222       D->hasAttr<PragmaClangRodataSectionAttr>())
4223     return true;
4224 
4225   // Thread local vars aren't considered common linkage.
4226   if (D->getTLSKind())
4227     return true;
4228 
4229   // Tentative definitions marked with WeakImportAttr are true definitions.
4230   if (D->hasAttr<WeakImportAttr>())
4231     return true;
4232 
4233   // A variable cannot be both common and exist in a comdat.
4234   if (shouldBeInCOMDAT(CGM, *D))
4235     return true;
4236 
4237   // Declarations with a required alignment do not have common linkage in MSVC
4238   // mode.
4239   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4240     if (D->hasAttr<AlignedAttr>())
4241       return true;
4242     QualType VarType = D->getType();
4243     if (Context.isAlignmentRequired(VarType))
4244       return true;
4245 
4246     if (const auto *RT = VarType->getAs<RecordType>()) {
4247       const RecordDecl *RD = RT->getDecl();
4248       for (const FieldDecl *FD : RD->fields()) {
4249         if (FD->isBitField())
4250           continue;
4251         if (FD->hasAttr<AlignedAttr>())
4252           return true;
4253         if (Context.isAlignmentRequired(FD->getType()))
4254           return true;
4255       }
4256     }
4257   }
4258 
4259   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
4260   // common symbols, so symbols with greater alignment requirements cannot be
4261   // common.
4262   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
4263   // alignments for common symbols via the aligncomm directive, so this
4264   // restriction only applies to MSVC environments.
4265   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
4266       Context.getTypeAlignIfKnown(D->getType()) >
4267           Context.toBits(CharUnits::fromQuantity(32)))
4268     return true;
4269 
4270   return false;
4271 }
4272 
4273 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
4274     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
4275   if (Linkage == GVA_Internal)
4276     return llvm::Function::InternalLinkage;
4277 
4278   if (D->hasAttr<WeakAttr>()) {
4279     if (IsConstantVariable)
4280       return llvm::GlobalVariable::WeakODRLinkage;
4281     else
4282       return llvm::GlobalVariable::WeakAnyLinkage;
4283   }
4284 
4285   if (const auto *FD = D->getAsFunction())
4286     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
4287       return llvm::GlobalVariable::LinkOnceAnyLinkage;
4288 
4289   // We are guaranteed to have a strong definition somewhere else,
4290   // so we can use available_externally linkage.
4291   if (Linkage == GVA_AvailableExternally)
4292     return llvm::GlobalValue::AvailableExternallyLinkage;
4293 
4294   // Note that Apple's kernel linker doesn't support symbol
4295   // coalescing, so we need to avoid linkonce and weak linkages there.
4296   // Normally, this means we just map to internal, but for explicit
4297   // instantiations we'll map to external.
4298 
4299   // In C++, the compiler has to emit a definition in every translation unit
4300   // that references the function.  We should use linkonce_odr because
4301   // a) if all references in this translation unit are optimized away, we
4302   // don't need to codegen it.  b) if the function persists, it needs to be
4303   // merged with other definitions. c) C++ has the ODR, so we know the
4304   // definition is dependable.
4305   if (Linkage == GVA_DiscardableODR)
4306     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
4307                                             : llvm::Function::InternalLinkage;
4308 
4309   // An explicit instantiation of a template has weak linkage, since
4310   // explicit instantiations can occur in multiple translation units
4311   // and must all be equivalent. However, we are not allowed to
4312   // throw away these explicit instantiations.
4313   //
4314   // We don't currently support CUDA device code spread out across multiple TUs,
4315   // so say that CUDA templates are either external (for kernels) or internal.
4316   // This lets llvm perform aggressive inter-procedural optimizations.
4317   if (Linkage == GVA_StrongODR) {
4318     if (Context.getLangOpts().AppleKext)
4319       return llvm::Function::ExternalLinkage;
4320     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
4321       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
4322                                           : llvm::Function::InternalLinkage;
4323     return llvm::Function::WeakODRLinkage;
4324   }
4325 
4326   // C++ doesn't have tentative definitions and thus cannot have common
4327   // linkage.
4328   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
4329       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
4330                                  CodeGenOpts.NoCommon))
4331     return llvm::GlobalVariable::CommonLinkage;
4332 
4333   // selectany symbols are externally visible, so use weak instead of
4334   // linkonce.  MSVC optimizes away references to const selectany globals, so
4335   // all definitions should be the same and ODR linkage should be used.
4336   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
4337   if (D->hasAttr<SelectAnyAttr>())
4338     return llvm::GlobalVariable::WeakODRLinkage;
4339 
4340   // Otherwise, we have strong external linkage.
4341   assert(Linkage == GVA_StrongExternal);
4342   return llvm::GlobalVariable::ExternalLinkage;
4343 }
4344 
4345 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
4346     const VarDecl *VD, bool IsConstant) {
4347   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
4348   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
4349 }
4350 
4351 /// Replace the uses of a function that was declared with a non-proto type.
4352 /// We want to silently drop extra arguments from call sites
4353 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
4354                                           llvm::Function *newFn) {
4355   // Fast path.
4356   if (old->use_empty()) return;
4357 
4358   llvm::Type *newRetTy = newFn->getReturnType();
4359   SmallVector<llvm::Value*, 4> newArgs;
4360   SmallVector<llvm::OperandBundleDef, 1> newBundles;
4361 
4362   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
4363          ui != ue; ) {
4364     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
4365     llvm::User *user = use->getUser();
4366 
4367     // Recognize and replace uses of bitcasts.  Most calls to
4368     // unprototyped functions will use bitcasts.
4369     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
4370       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
4371         replaceUsesOfNonProtoConstant(bitcast, newFn);
4372       continue;
4373     }
4374 
4375     // Recognize calls to the function.
4376     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
4377     if (!callSite) continue;
4378     if (!callSite->isCallee(&*use))
4379       continue;
4380 
4381     // If the return types don't match exactly, then we can't
4382     // transform this call unless it's dead.
4383     if (callSite->getType() != newRetTy && !callSite->use_empty())
4384       continue;
4385 
4386     // Get the call site's attribute list.
4387     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
4388     llvm::AttributeList oldAttrs = callSite->getAttributes();
4389 
4390     // If the function was passed too few arguments, don't transform.
4391     unsigned newNumArgs = newFn->arg_size();
4392     if (callSite->arg_size() < newNumArgs)
4393       continue;
4394 
4395     // If extra arguments were passed, we silently drop them.
4396     // If any of the types mismatch, we don't transform.
4397     unsigned argNo = 0;
4398     bool dontTransform = false;
4399     for (llvm::Argument &A : newFn->args()) {
4400       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
4401         dontTransform = true;
4402         break;
4403       }
4404 
4405       // Add any parameter attributes.
4406       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
4407       argNo++;
4408     }
4409     if (dontTransform)
4410       continue;
4411 
4412     // Okay, we can transform this.  Create the new call instruction and copy
4413     // over the required information.
4414     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
4415 
4416     // Copy over any operand bundles.
4417     callSite->getOperandBundlesAsDefs(newBundles);
4418 
4419     llvm::CallBase *newCall;
4420     if (dyn_cast<llvm::CallInst>(callSite)) {
4421       newCall =
4422           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
4423     } else {
4424       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
4425       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
4426                                          oldInvoke->getUnwindDest(), newArgs,
4427                                          newBundles, "", callSite);
4428     }
4429     newArgs.clear(); // for the next iteration
4430 
4431     if (!newCall->getType()->isVoidTy())
4432       newCall->takeName(callSite);
4433     newCall->setAttributes(llvm::AttributeList::get(
4434         newFn->getContext(), oldAttrs.getFnAttributes(),
4435         oldAttrs.getRetAttributes(), newArgAttrs));
4436     newCall->setCallingConv(callSite->getCallingConv());
4437 
4438     // Finally, remove the old call, replacing any uses with the new one.
4439     if (!callSite->use_empty())
4440       callSite->replaceAllUsesWith(newCall);
4441 
4442     // Copy debug location attached to CI.
4443     if (callSite->getDebugLoc())
4444       newCall->setDebugLoc(callSite->getDebugLoc());
4445 
4446     callSite->eraseFromParent();
4447   }
4448 }
4449 
4450 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
4451 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
4452 /// existing call uses of the old function in the module, this adjusts them to
4453 /// call the new function directly.
4454 ///
4455 /// This is not just a cleanup: the always_inline pass requires direct calls to
4456 /// functions to be able to inline them.  If there is a bitcast in the way, it
4457 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
4458 /// run at -O0.
4459 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4460                                                       llvm::Function *NewFn) {
4461   // If we're redefining a global as a function, don't transform it.
4462   if (!isa<llvm::Function>(Old)) return;
4463 
4464   replaceUsesOfNonProtoConstant(Old, NewFn);
4465 }
4466 
4467 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
4468   auto DK = VD->isThisDeclarationADefinition();
4469   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
4470     return;
4471 
4472   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
4473   // If we have a definition, this might be a deferred decl. If the
4474   // instantiation is explicit, make sure we emit it at the end.
4475   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
4476     GetAddrOfGlobalVar(VD);
4477 
4478   EmitTopLevelDecl(VD);
4479 }
4480 
4481 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
4482                                                  llvm::GlobalValue *GV) {
4483   const auto *D = cast<FunctionDecl>(GD.getDecl());
4484 
4485   // Compute the function info and LLVM type.
4486   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4487   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4488 
4489   // Get or create the prototype for the function.
4490   if (!GV || (GV->getValueType() != Ty))
4491     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
4492                                                    /*DontDefer=*/true,
4493                                                    ForDefinition));
4494 
4495   // Already emitted.
4496   if (!GV->isDeclaration())
4497     return;
4498 
4499   // We need to set linkage and visibility on the function before
4500   // generating code for it because various parts of IR generation
4501   // want to propagate this information down (e.g. to local static
4502   // declarations).
4503   auto *Fn = cast<llvm::Function>(GV);
4504   setFunctionLinkage(GD, Fn);
4505 
4506   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
4507   setGVProperties(Fn, GD);
4508 
4509   MaybeHandleStaticInExternC(D, Fn);
4510 
4511 
4512   maybeSetTrivialComdat(*D, *Fn);
4513 
4514   CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
4515 
4516   setNonAliasAttributes(GD, Fn);
4517   SetLLVMFunctionAttributesForDefinition(D, Fn);
4518 
4519   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
4520     AddGlobalCtor(Fn, CA->getPriority());
4521   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
4522     AddGlobalDtor(Fn, DA->getPriority());
4523   if (D->hasAttr<AnnotateAttr>())
4524     AddGlobalAnnotations(D, Fn);
4525 }
4526 
4527 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
4528   const auto *D = cast<ValueDecl>(GD.getDecl());
4529   const AliasAttr *AA = D->getAttr<AliasAttr>();
4530   assert(AA && "Not an alias?");
4531 
4532   StringRef MangledName = getMangledName(GD);
4533 
4534   if (AA->getAliasee() == MangledName) {
4535     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4536     return;
4537   }
4538 
4539   // If there is a definition in the module, then it wins over the alias.
4540   // This is dubious, but allow it to be safe.  Just ignore the alias.
4541   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4542   if (Entry && !Entry->isDeclaration())
4543     return;
4544 
4545   Aliases.push_back(GD);
4546 
4547   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4548 
4549   // Create a reference to the named value.  This ensures that it is emitted
4550   // if a deferred decl.
4551   llvm::Constant *Aliasee;
4552   llvm::GlobalValue::LinkageTypes LT;
4553   if (isa<llvm::FunctionType>(DeclTy)) {
4554     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
4555                                       /*ForVTable=*/false);
4556     LT = getFunctionLinkage(GD);
4557   } else {
4558     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
4559                                     llvm::PointerType::getUnqual(DeclTy),
4560                                     /*D=*/nullptr);
4561     LT = getLLVMLinkageVarDefinition(cast<VarDecl>(GD.getDecl()),
4562                                      D->getType().isConstQualified());
4563   }
4564 
4565   // Create the new alias itself, but don't set a name yet.
4566   unsigned AS = Aliasee->getType()->getPointerAddressSpace();
4567   auto *GA =
4568       llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
4569 
4570   if (Entry) {
4571     if (GA->getAliasee() == Entry) {
4572       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4573       return;
4574     }
4575 
4576     assert(Entry->isDeclaration());
4577 
4578     // If there is a declaration in the module, then we had an extern followed
4579     // by the alias, as in:
4580     //   extern int test6();
4581     //   ...
4582     //   int test6() __attribute__((alias("test7")));
4583     //
4584     // Remove it and replace uses of it with the alias.
4585     GA->takeName(Entry);
4586 
4587     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
4588                                                           Entry->getType()));
4589     Entry->eraseFromParent();
4590   } else {
4591     GA->setName(MangledName);
4592   }
4593 
4594   // Set attributes which are particular to an alias; this is a
4595   // specialization of the attributes which may be set on a global
4596   // variable/function.
4597   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
4598       D->isWeakImported()) {
4599     GA->setLinkage(llvm::Function::WeakAnyLinkage);
4600   }
4601 
4602   if (const auto *VD = dyn_cast<VarDecl>(D))
4603     if (VD->getTLSKind())
4604       setTLSMode(GA, *VD);
4605 
4606   SetCommonAttributes(GD, GA);
4607 }
4608 
4609 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4610   const auto *D = cast<ValueDecl>(GD.getDecl());
4611   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4612   assert(IFA && "Not an ifunc?");
4613 
4614   StringRef MangledName = getMangledName(GD);
4615 
4616   if (IFA->getResolver() == MangledName) {
4617     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4618     return;
4619   }
4620 
4621   // Report an error if some definition overrides ifunc.
4622   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4623   if (Entry && !Entry->isDeclaration()) {
4624     GlobalDecl OtherGD;
4625     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4626         DiagnosedConflictingDefinitions.insert(GD).second) {
4627       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4628           << MangledName;
4629       Diags.Report(OtherGD.getDecl()->getLocation(),
4630                    diag::note_previous_definition);
4631     }
4632     return;
4633   }
4634 
4635   Aliases.push_back(GD);
4636 
4637   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4638   llvm::Constant *Resolver =
4639       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4640                               /*ForVTable=*/false);
4641   llvm::GlobalIFunc *GIF =
4642       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4643                                 "", Resolver, &getModule());
4644   if (Entry) {
4645     if (GIF->getResolver() == Entry) {
4646       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4647       return;
4648     }
4649     assert(Entry->isDeclaration());
4650 
4651     // If there is a declaration in the module, then we had an extern followed
4652     // by the ifunc, as in:
4653     //   extern int test();
4654     //   ...
4655     //   int test() __attribute__((ifunc("resolver")));
4656     //
4657     // Remove it and replace uses of it with the ifunc.
4658     GIF->takeName(Entry);
4659 
4660     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4661                                                           Entry->getType()));
4662     Entry->eraseFromParent();
4663   } else
4664     GIF->setName(MangledName);
4665 
4666   SetCommonAttributes(GD, GIF);
4667 }
4668 
4669 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
4670                                             ArrayRef<llvm::Type*> Tys) {
4671   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
4672                                          Tys);
4673 }
4674 
4675 static llvm::StringMapEntry<llvm::GlobalVariable *> &
4676 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
4677                          const StringLiteral *Literal, bool TargetIsLSB,
4678                          bool &IsUTF16, unsigned &StringLength) {
4679   StringRef String = Literal->getString();
4680   unsigned NumBytes = String.size();
4681 
4682   // Check for simple case.
4683   if (!Literal->containsNonAsciiOrNull()) {
4684     StringLength = NumBytes;
4685     return *Map.insert(std::make_pair(String, nullptr)).first;
4686   }
4687 
4688   // Otherwise, convert the UTF8 literals into a string of shorts.
4689   IsUTF16 = true;
4690 
4691   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
4692   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4693   llvm::UTF16 *ToPtr = &ToBuf[0];
4694 
4695   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4696                                  ToPtr + NumBytes, llvm::strictConversion);
4697 
4698   // ConvertUTF8toUTF16 returns the length in ToPtr.
4699   StringLength = ToPtr - &ToBuf[0];
4700 
4701   // Add an explicit null.
4702   *ToPtr = 0;
4703   return *Map.insert(std::make_pair(
4704                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4705                                    (StringLength + 1) * 2),
4706                          nullptr)).first;
4707 }
4708 
4709 ConstantAddress
4710 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
4711   unsigned StringLength = 0;
4712   bool isUTF16 = false;
4713   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4714       GetConstantCFStringEntry(CFConstantStringMap, Literal,
4715                                getDataLayout().isLittleEndian(), isUTF16,
4716                                StringLength);
4717 
4718   if (auto *C = Entry.second)
4719     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
4720 
4721   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
4722   llvm::Constant *Zeros[] = { Zero, Zero };
4723 
4724   const ASTContext &Context = getContext();
4725   const llvm::Triple &Triple = getTriple();
4726 
4727   const auto CFRuntime = getLangOpts().CFRuntime;
4728   const bool IsSwiftABI =
4729       static_cast<unsigned>(CFRuntime) >=
4730       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
4731   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
4732 
4733   // If we don't already have it, get __CFConstantStringClassReference.
4734   if (!CFConstantStringClassRef) {
4735     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
4736     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
4737     Ty = llvm::ArrayType::get(Ty, 0);
4738 
4739     switch (CFRuntime) {
4740     default: break;
4741     case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
4742     case LangOptions::CoreFoundationABI::Swift5_0:
4743       CFConstantStringClassName =
4744           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
4745                               : "$s10Foundation19_NSCFConstantStringCN";
4746       Ty = IntPtrTy;
4747       break;
4748     case LangOptions::CoreFoundationABI::Swift4_2:
4749       CFConstantStringClassName =
4750           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
4751                               : "$S10Foundation19_NSCFConstantStringCN";
4752       Ty = IntPtrTy;
4753       break;
4754     case LangOptions::CoreFoundationABI::Swift4_1:
4755       CFConstantStringClassName =
4756           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
4757                               : "__T010Foundation19_NSCFConstantStringCN";
4758       Ty = IntPtrTy;
4759       break;
4760     }
4761 
4762     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
4763 
4764     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
4765       llvm::GlobalValue *GV = nullptr;
4766 
4767       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
4768         IdentifierInfo &II = Context.Idents.get(GV->getName());
4769         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
4770         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4771 
4772         const VarDecl *VD = nullptr;
4773         for (const auto &Result : DC->lookup(&II))
4774           if ((VD = dyn_cast<VarDecl>(Result)))
4775             break;
4776 
4777         if (Triple.isOSBinFormatELF()) {
4778           if (!VD)
4779             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4780         } else {
4781           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4782           if (!VD || !VD->hasAttr<DLLExportAttr>())
4783             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4784           else
4785             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
4786         }
4787 
4788         setDSOLocal(GV);
4789       }
4790     }
4791 
4792     // Decay array -> ptr
4793     CFConstantStringClassRef =
4794         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
4795                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
4796   }
4797 
4798   QualType CFTy = Context.getCFConstantStringType();
4799 
4800   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
4801 
4802   ConstantInitBuilder Builder(*this);
4803   auto Fields = Builder.beginStruct(STy);
4804 
4805   // Class pointer.
4806   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
4807 
4808   // Flags.
4809   if (IsSwiftABI) {
4810     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
4811     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
4812   } else {
4813     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4814   }
4815 
4816   // String pointer.
4817   llvm::Constant *C = nullptr;
4818   if (isUTF16) {
4819     auto Arr = llvm::makeArrayRef(
4820         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4821         Entry.first().size() / 2);
4822     C = llvm::ConstantDataArray::get(VMContext, Arr);
4823   } else {
4824     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
4825   }
4826 
4827   // Note: -fwritable-strings doesn't make the backing store strings of
4828   // CFStrings writable. (See <rdar://problem/10657500>)
4829   auto *GV =
4830       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
4831                                llvm::GlobalValue::PrivateLinkage, C, ".str");
4832   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4833   // Don't enforce the target's minimum global alignment, since the only use
4834   // of the string is via this class initializer.
4835   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
4836                             : Context.getTypeAlignInChars(Context.CharTy);
4837   GV->setAlignment(Align.getAsAlign());
4838 
4839   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
4840   // Without it LLVM can merge the string with a non unnamed_addr one during
4841   // LTO.  Doing that changes the section it ends in, which surprises ld64.
4842   if (Triple.isOSBinFormatMachO())
4843     GV->setSection(isUTF16 ? "__TEXT,__ustring"
4844                            : "__TEXT,__cstring,cstring_literals");
4845   // Make sure the literal ends up in .rodata to allow for safe ICF and for
4846   // the static linker to adjust permissions to read-only later on.
4847   else if (Triple.isOSBinFormatELF())
4848     GV->setSection(".rodata");
4849 
4850   // String.
4851   llvm::Constant *Str =
4852       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
4853 
4854   if (isUTF16)
4855     // Cast the UTF16 string to the correct type.
4856     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
4857   Fields.add(Str);
4858 
4859   // String length.
4860   llvm::IntegerType *LengthTy =
4861       llvm::IntegerType::get(getModule().getContext(),
4862                              Context.getTargetInfo().getLongWidth());
4863   if (IsSwiftABI) {
4864     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
4865         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
4866       LengthTy = Int32Ty;
4867     else
4868       LengthTy = IntPtrTy;
4869   }
4870   Fields.addInt(LengthTy, StringLength);
4871 
4872   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
4873   // properly aligned on 32-bit platforms.
4874   CharUnits Alignment =
4875       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
4876 
4877   // The struct.
4878   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
4879                                     /*isConstant=*/false,
4880                                     llvm::GlobalVariable::PrivateLinkage);
4881   GV->addAttribute("objc_arc_inert");
4882   switch (Triple.getObjectFormat()) {
4883   case llvm::Triple::UnknownObjectFormat:
4884     llvm_unreachable("unknown file format");
4885   case llvm::Triple::XCOFF:
4886     llvm_unreachable("XCOFF is not yet implemented");
4887   case llvm::Triple::COFF:
4888   case llvm::Triple::ELF:
4889   case llvm::Triple::Wasm:
4890     GV->setSection("cfstring");
4891     break;
4892   case llvm::Triple::MachO:
4893     GV->setSection("__DATA,__cfstring");
4894     break;
4895   }
4896   Entry.second = GV;
4897 
4898   return ConstantAddress(GV, Alignment);
4899 }
4900 
4901 bool CodeGenModule::getExpressionLocationsEnabled() const {
4902   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4903 }
4904 
4905 QualType CodeGenModule::getObjCFastEnumerationStateType() {
4906   if (ObjCFastEnumerationStateType.isNull()) {
4907     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
4908     D->startDefinition();
4909 
4910     QualType FieldTypes[] = {
4911       Context.UnsignedLongTy,
4912       Context.getPointerType(Context.getObjCIdType()),
4913       Context.getPointerType(Context.UnsignedLongTy),
4914       Context.getConstantArrayType(Context.UnsignedLongTy,
4915                            llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
4916     };
4917 
4918     for (size_t i = 0; i < 4; ++i) {
4919       FieldDecl *Field = FieldDecl::Create(Context,
4920                                            D,
4921                                            SourceLocation(),
4922                                            SourceLocation(), nullptr,
4923                                            FieldTypes[i], /*TInfo=*/nullptr,
4924                                            /*BitWidth=*/nullptr,
4925                                            /*Mutable=*/false,
4926                                            ICIS_NoInit);
4927       Field->setAccess(AS_public);
4928       D->addDecl(Field);
4929     }
4930 
4931     D->completeDefinition();
4932     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
4933   }
4934 
4935   return ObjCFastEnumerationStateType;
4936 }
4937 
4938 llvm::Constant *
4939 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
4940   assert(!E->getType()->isPointerType() && "Strings are always arrays");
4941 
4942   // Don't emit it as the address of the string, emit the string data itself
4943   // as an inline array.
4944   if (E->getCharByteWidth() == 1) {
4945     SmallString<64> Str(E->getString());
4946 
4947     // Resize the string to the right size, which is indicated by its type.
4948     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
4949     Str.resize(CAT->getSize().getZExtValue());
4950     return llvm::ConstantDataArray::getString(VMContext, Str, false);
4951   }
4952 
4953   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
4954   llvm::Type *ElemTy = AType->getElementType();
4955   unsigned NumElements = AType->getNumElements();
4956 
4957   // Wide strings have either 2-byte or 4-byte elements.
4958   if (ElemTy->getPrimitiveSizeInBits() == 16) {
4959     SmallVector<uint16_t, 32> Elements;
4960     Elements.reserve(NumElements);
4961 
4962     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4963       Elements.push_back(E->getCodeUnit(i));
4964     Elements.resize(NumElements);
4965     return llvm::ConstantDataArray::get(VMContext, Elements);
4966   }
4967 
4968   assert(ElemTy->getPrimitiveSizeInBits() == 32);
4969   SmallVector<uint32_t, 32> Elements;
4970   Elements.reserve(NumElements);
4971 
4972   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4973     Elements.push_back(E->getCodeUnit(i));
4974   Elements.resize(NumElements);
4975   return llvm::ConstantDataArray::get(VMContext, Elements);
4976 }
4977 
4978 static llvm::GlobalVariable *
4979 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4980                       CodeGenModule &CGM, StringRef GlobalName,
4981                       CharUnits Alignment) {
4982   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
4983       CGM.getStringLiteralAddressSpace());
4984 
4985   llvm::Module &M = CGM.getModule();
4986   // Create a global variable for this string
4987   auto *GV = new llvm::GlobalVariable(
4988       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
4989       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
4990   GV->setAlignment(Alignment.getAsAlign());
4991   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4992   if (GV->isWeakForLinker()) {
4993     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
4994     GV->setComdat(M.getOrInsertComdat(GV->getName()));
4995   }
4996   CGM.setDSOLocal(GV);
4997 
4998   return GV;
4999 }
5000 
5001 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
5002 /// constant array for the given string literal.
5003 ConstantAddress
5004 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
5005                                                   StringRef Name) {
5006   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
5007 
5008   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
5009   llvm::GlobalVariable **Entry = nullptr;
5010   if (!LangOpts.WritableStrings) {
5011     Entry = &ConstantStringMap[C];
5012     if (auto GV = *Entry) {
5013       if (Alignment.getQuantity() > GV->getAlignment())
5014         GV->setAlignment(Alignment.getAsAlign());
5015       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5016                              Alignment);
5017     }
5018   }
5019 
5020   SmallString<256> MangledNameBuffer;
5021   StringRef GlobalVariableName;
5022   llvm::GlobalValue::LinkageTypes LT;
5023 
5024   // Mangle the string literal if that's how the ABI merges duplicate strings.
5025   // Don't do it if they are writable, since we don't want writes in one TU to
5026   // affect strings in another.
5027   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
5028       !LangOpts.WritableStrings) {
5029     llvm::raw_svector_ostream Out(MangledNameBuffer);
5030     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
5031     LT = llvm::GlobalValue::LinkOnceODRLinkage;
5032     GlobalVariableName = MangledNameBuffer;
5033   } else {
5034     LT = llvm::GlobalValue::PrivateLinkage;
5035     GlobalVariableName = Name;
5036   }
5037 
5038   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
5039   if (Entry)
5040     *Entry = GV;
5041 
5042   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
5043                                   QualType());
5044 
5045   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5046                          Alignment);
5047 }
5048 
5049 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
5050 /// array for the given ObjCEncodeExpr node.
5051 ConstantAddress
5052 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
5053   std::string Str;
5054   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
5055 
5056   return GetAddrOfConstantCString(Str);
5057 }
5058 
5059 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
5060 /// the literal and a terminating '\0' character.
5061 /// The result has pointer to array type.
5062 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
5063     const std::string &Str, const char *GlobalName) {
5064   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
5065   CharUnits Alignment =
5066     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
5067 
5068   llvm::Constant *C =
5069       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
5070 
5071   // Don't share any string literals if strings aren't constant.
5072   llvm::GlobalVariable **Entry = nullptr;
5073   if (!LangOpts.WritableStrings) {
5074     Entry = &ConstantStringMap[C];
5075     if (auto GV = *Entry) {
5076       if (Alignment.getQuantity() > GV->getAlignment())
5077         GV->setAlignment(Alignment.getAsAlign());
5078       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5079                              Alignment);
5080     }
5081   }
5082 
5083   // Get the default prefix if a name wasn't specified.
5084   if (!GlobalName)
5085     GlobalName = ".str";
5086   // Create a global variable for this.
5087   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
5088                                   GlobalName, Alignment);
5089   if (Entry)
5090     *Entry = GV;
5091 
5092   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5093                          Alignment);
5094 }
5095 
5096 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
5097     const MaterializeTemporaryExpr *E, const Expr *Init) {
5098   assert((E->getStorageDuration() == SD_Static ||
5099           E->getStorageDuration() == SD_Thread) && "not a global temporary");
5100   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
5101 
5102   // If we're not materializing a subobject of the temporary, keep the
5103   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
5104   QualType MaterializedType = Init->getType();
5105   if (Init == E->getSubExpr())
5106     MaterializedType = E->getType();
5107 
5108   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
5109 
5110   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
5111     return ConstantAddress(Slot, Align);
5112 
5113   // FIXME: If an externally-visible declaration extends multiple temporaries,
5114   // we need to give each temporary the same name in every translation unit (and
5115   // we also need to make the temporaries externally-visible).
5116   SmallString<256> Name;
5117   llvm::raw_svector_ostream Out(Name);
5118   getCXXABI().getMangleContext().mangleReferenceTemporary(
5119       VD, E->getManglingNumber(), Out);
5120 
5121   APValue *Value = nullptr;
5122   if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
5123     // If the initializer of the extending declaration is a constant
5124     // initializer, we should have a cached constant initializer for this
5125     // temporary. Note that this might have a different value from the value
5126     // computed by evaluating the initializer if the surrounding constant
5127     // expression modifies the temporary.
5128     Value = E->getOrCreateValue(false);
5129   }
5130 
5131   // Try evaluating it now, it might have a constant initializer.
5132   Expr::EvalResult EvalResult;
5133   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
5134       !EvalResult.hasSideEffects())
5135     Value = &EvalResult.Val;
5136 
5137   LangAS AddrSpace =
5138       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
5139 
5140   Optional<ConstantEmitter> emitter;
5141   llvm::Constant *InitialValue = nullptr;
5142   bool Constant = false;
5143   llvm::Type *Type;
5144   if (Value) {
5145     // The temporary has a constant initializer, use it.
5146     emitter.emplace(*this);
5147     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
5148                                                MaterializedType);
5149     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
5150     Type = InitialValue->getType();
5151   } else {
5152     // No initializer, the initialization will be provided when we
5153     // initialize the declaration which performed lifetime extension.
5154     Type = getTypes().ConvertTypeForMem(MaterializedType);
5155   }
5156 
5157   // Create a global variable for this lifetime-extended temporary.
5158   llvm::GlobalValue::LinkageTypes Linkage =
5159       getLLVMLinkageVarDefinition(VD, Constant);
5160   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
5161     const VarDecl *InitVD;
5162     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
5163         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
5164       // Temporaries defined inside a class get linkonce_odr linkage because the
5165       // class can be defined in multiple translation units.
5166       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
5167     } else {
5168       // There is no need for this temporary to have external linkage if the
5169       // VarDecl has external linkage.
5170       Linkage = llvm::GlobalVariable::InternalLinkage;
5171     }
5172   }
5173   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
5174   auto *GV = new llvm::GlobalVariable(
5175       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
5176       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
5177   if (emitter) emitter->finalize(GV);
5178   setGVProperties(GV, VD);
5179   GV->setAlignment(Align.getAsAlign());
5180   if (supportsCOMDAT() && GV->isWeakForLinker())
5181     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5182   if (VD->getTLSKind())
5183     setTLSMode(GV, *VD);
5184   llvm::Constant *CV = GV;
5185   if (AddrSpace != LangAS::Default)
5186     CV = getTargetCodeGenInfo().performAddrSpaceCast(
5187         *this, GV, AddrSpace, LangAS::Default,
5188         Type->getPointerTo(
5189             getContext().getTargetAddressSpace(LangAS::Default)));
5190   MaterializedGlobalTemporaryMap[E] = CV;
5191   return ConstantAddress(CV, Align);
5192 }
5193 
5194 /// EmitObjCPropertyImplementations - Emit information for synthesized
5195 /// properties for an implementation.
5196 void CodeGenModule::EmitObjCPropertyImplementations(const
5197                                                     ObjCImplementationDecl *D) {
5198   for (const auto *PID : D->property_impls()) {
5199     // Dynamic is just for type-checking.
5200     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
5201       ObjCPropertyDecl *PD = PID->getPropertyDecl();
5202 
5203       // Determine which methods need to be implemented, some may have
5204       // been overridden. Note that ::isPropertyAccessor is not the method
5205       // we want, that just indicates if the decl came from a
5206       // property. What we want to know is if the method is defined in
5207       // this implementation.
5208       auto *Getter = PID->getGetterMethodDecl();
5209       if (!Getter || Getter->isSynthesizedAccessorStub())
5210         CodeGenFunction(*this).GenerateObjCGetter(
5211             const_cast<ObjCImplementationDecl *>(D), PID);
5212       auto *Setter = PID->getSetterMethodDecl();
5213       if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
5214         CodeGenFunction(*this).GenerateObjCSetter(
5215                                  const_cast<ObjCImplementationDecl *>(D), PID);
5216     }
5217   }
5218 }
5219 
5220 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
5221   const ObjCInterfaceDecl *iface = impl->getClassInterface();
5222   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
5223        ivar; ivar = ivar->getNextIvar())
5224     if (ivar->getType().isDestructedType())
5225       return true;
5226 
5227   return false;
5228 }
5229 
5230 static bool AllTrivialInitializers(CodeGenModule &CGM,
5231                                    ObjCImplementationDecl *D) {
5232   CodeGenFunction CGF(CGM);
5233   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
5234        E = D->init_end(); B != E; ++B) {
5235     CXXCtorInitializer *CtorInitExp = *B;
5236     Expr *Init = CtorInitExp->getInit();
5237     if (!CGF.isTrivialInitializer(Init))
5238       return false;
5239   }
5240   return true;
5241 }
5242 
5243 /// EmitObjCIvarInitializations - Emit information for ivar initialization
5244 /// for an implementation.
5245 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
5246   // We might need a .cxx_destruct even if we don't have any ivar initializers.
5247   if (needsDestructMethod(D)) {
5248     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
5249     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5250     ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
5251         getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5252         getContext().VoidTy, nullptr, D,
5253         /*isInstance=*/true, /*isVariadic=*/false,
5254         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5255         /*isImplicitlyDeclared=*/true,
5256         /*isDefined=*/false, ObjCMethodDecl::Required);
5257     D->addInstanceMethod(DTORMethod);
5258     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
5259     D->setHasDestructors(true);
5260   }
5261 
5262   // If the implementation doesn't have any ivar initializers, we don't need
5263   // a .cxx_construct.
5264   if (D->getNumIvarInitializers() == 0 ||
5265       AllTrivialInitializers(*this, D))
5266     return;
5267 
5268   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
5269   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5270   // The constructor returns 'self'.
5271   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
5272       getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5273       getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
5274       /*isVariadic=*/false,
5275       /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5276       /*isImplicitlyDeclared=*/true,
5277       /*isDefined=*/false, ObjCMethodDecl::Required);
5278   D->addInstanceMethod(CTORMethod);
5279   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
5280   D->setHasNonZeroConstructors(true);
5281 }
5282 
5283 // EmitLinkageSpec - Emit all declarations in a linkage spec.
5284 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
5285   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5286       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
5287     ErrorUnsupported(LSD, "linkage spec");
5288     return;
5289   }
5290 
5291   EmitDeclContext(LSD);
5292 }
5293 
5294 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
5295   for (auto *I : DC->decls()) {
5296     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
5297     // are themselves considered "top-level", so EmitTopLevelDecl on an
5298     // ObjCImplDecl does not recursively visit them. We need to do that in
5299     // case they're nested inside another construct (LinkageSpecDecl /
5300     // ExportDecl) that does stop them from being considered "top-level".
5301     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
5302       for (auto *M : OID->methods())
5303         EmitTopLevelDecl(M);
5304     }
5305 
5306     EmitTopLevelDecl(I);
5307   }
5308 }
5309 
5310 /// EmitTopLevelDecl - Emit code for a single top level declaration.
5311 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
5312   // Ignore dependent declarations.
5313   if (D->isTemplated())
5314     return;
5315 
5316   switch (D->getKind()) {
5317   case Decl::CXXConversion:
5318   case Decl::CXXMethod:
5319   case Decl::Function:
5320     EmitGlobal(cast<FunctionDecl>(D));
5321     // Always provide some coverage mapping
5322     // even for the functions that aren't emitted.
5323     AddDeferredUnusedCoverageMapping(D);
5324     break;
5325 
5326   case Decl::CXXDeductionGuide:
5327     // Function-like, but does not result in code emission.
5328     break;
5329 
5330   case Decl::Var:
5331   case Decl::Decomposition:
5332   case Decl::VarTemplateSpecialization:
5333     EmitGlobal(cast<VarDecl>(D));
5334     if (auto *DD = dyn_cast<DecompositionDecl>(D))
5335       for (auto *B : DD->bindings())
5336         if (auto *HD = B->getHoldingVar())
5337           EmitGlobal(HD);
5338     break;
5339 
5340   // Indirect fields from global anonymous structs and unions can be
5341   // ignored; only the actual variable requires IR gen support.
5342   case Decl::IndirectField:
5343     break;
5344 
5345   // C++ Decls
5346   case Decl::Namespace:
5347     EmitDeclContext(cast<NamespaceDecl>(D));
5348     break;
5349   case Decl::ClassTemplateSpecialization: {
5350     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
5351     if (DebugInfo &&
5352         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
5353         Spec->hasDefinition())
5354       DebugInfo->completeTemplateDefinition(*Spec);
5355   } LLVM_FALLTHROUGH;
5356   case Decl::CXXRecord:
5357     if (DebugInfo) {
5358       if (auto *ES = D->getASTContext().getExternalSource())
5359         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
5360           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
5361     }
5362     // Emit any static data members, they may be definitions.
5363     for (auto *I : cast<CXXRecordDecl>(D)->decls())
5364       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
5365         EmitTopLevelDecl(I);
5366     break;
5367     // No code generation needed.
5368   case Decl::UsingShadow:
5369   case Decl::ClassTemplate:
5370   case Decl::VarTemplate:
5371   case Decl::Concept:
5372   case Decl::VarTemplatePartialSpecialization:
5373   case Decl::FunctionTemplate:
5374   case Decl::TypeAliasTemplate:
5375   case Decl::Block:
5376   case Decl::Empty:
5377   case Decl::Binding:
5378     break;
5379   case Decl::Using:          // using X; [C++]
5380     if (CGDebugInfo *DI = getModuleDebugInfo())
5381         DI->EmitUsingDecl(cast<UsingDecl>(*D));
5382     return;
5383   case Decl::NamespaceAlias:
5384     if (CGDebugInfo *DI = getModuleDebugInfo())
5385         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
5386     return;
5387   case Decl::UsingDirective: // using namespace X; [C++]
5388     if (CGDebugInfo *DI = getModuleDebugInfo())
5389       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
5390     return;
5391   case Decl::CXXConstructor:
5392     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
5393     break;
5394   case Decl::CXXDestructor:
5395     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
5396     break;
5397 
5398   case Decl::StaticAssert:
5399     // Nothing to do.
5400     break;
5401 
5402   // Objective-C Decls
5403 
5404   // Forward declarations, no (immediate) code generation.
5405   case Decl::ObjCInterface:
5406   case Decl::ObjCCategory:
5407     break;
5408 
5409   case Decl::ObjCProtocol: {
5410     auto *Proto = cast<ObjCProtocolDecl>(D);
5411     if (Proto->isThisDeclarationADefinition())
5412       ObjCRuntime->GenerateProtocol(Proto);
5413     break;
5414   }
5415 
5416   case Decl::ObjCCategoryImpl:
5417     // Categories have properties but don't support synthesize so we
5418     // can ignore them here.
5419     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
5420     break;
5421 
5422   case Decl::ObjCImplementation: {
5423     auto *OMD = cast<ObjCImplementationDecl>(D);
5424     EmitObjCPropertyImplementations(OMD);
5425     EmitObjCIvarInitializations(OMD);
5426     ObjCRuntime->GenerateClass(OMD);
5427     // Emit global variable debug information.
5428     if (CGDebugInfo *DI = getModuleDebugInfo())
5429       if (getCodeGenOpts().hasReducedDebugInfo())
5430         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
5431             OMD->getClassInterface()), OMD->getLocation());
5432     break;
5433   }
5434   case Decl::ObjCMethod: {
5435     auto *OMD = cast<ObjCMethodDecl>(D);
5436     // If this is not a prototype, emit the body.
5437     if (OMD->getBody())
5438       CodeGenFunction(*this).GenerateObjCMethod(OMD);
5439     break;
5440   }
5441   case Decl::ObjCCompatibleAlias:
5442     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
5443     break;
5444 
5445   case Decl::PragmaComment: {
5446     const auto *PCD = cast<PragmaCommentDecl>(D);
5447     switch (PCD->getCommentKind()) {
5448     case PCK_Unknown:
5449       llvm_unreachable("unexpected pragma comment kind");
5450     case PCK_Linker:
5451       AppendLinkerOptions(PCD->getArg());
5452       break;
5453     case PCK_Lib:
5454         AddDependentLib(PCD->getArg());
5455       break;
5456     case PCK_Compiler:
5457     case PCK_ExeStr:
5458     case PCK_User:
5459       break; // We ignore all of these.
5460     }
5461     break;
5462   }
5463 
5464   case Decl::PragmaDetectMismatch: {
5465     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
5466     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
5467     break;
5468   }
5469 
5470   case Decl::LinkageSpec:
5471     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
5472     break;
5473 
5474   case Decl::FileScopeAsm: {
5475     // File-scope asm is ignored during device-side CUDA compilation.
5476     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
5477       break;
5478     // File-scope asm is ignored during device-side OpenMP compilation.
5479     if (LangOpts.OpenMPIsDevice)
5480       break;
5481     auto *AD = cast<FileScopeAsmDecl>(D);
5482     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
5483     break;
5484   }
5485 
5486   case Decl::Import: {
5487     auto *Import = cast<ImportDecl>(D);
5488 
5489     // If we've already imported this module, we're done.
5490     if (!ImportedModules.insert(Import->getImportedModule()))
5491       break;
5492 
5493     // Emit debug information for direct imports.
5494     if (!Import->getImportedOwningModule()) {
5495       if (CGDebugInfo *DI = getModuleDebugInfo())
5496         DI->EmitImportDecl(*Import);
5497     }
5498 
5499     // Find all of the submodules and emit the module initializers.
5500     llvm::SmallPtrSet<clang::Module *, 16> Visited;
5501     SmallVector<clang::Module *, 16> Stack;
5502     Visited.insert(Import->getImportedModule());
5503     Stack.push_back(Import->getImportedModule());
5504 
5505     while (!Stack.empty()) {
5506       clang::Module *Mod = Stack.pop_back_val();
5507       if (!EmittedModuleInitializers.insert(Mod).second)
5508         continue;
5509 
5510       for (auto *D : Context.getModuleInitializers(Mod))
5511         EmitTopLevelDecl(D);
5512 
5513       // Visit the submodules of this module.
5514       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
5515                                              SubEnd = Mod->submodule_end();
5516            Sub != SubEnd; ++Sub) {
5517         // Skip explicit children; they need to be explicitly imported to emit
5518         // the initializers.
5519         if ((*Sub)->IsExplicit)
5520           continue;
5521 
5522         if (Visited.insert(*Sub).second)
5523           Stack.push_back(*Sub);
5524       }
5525     }
5526     break;
5527   }
5528 
5529   case Decl::Export:
5530     EmitDeclContext(cast<ExportDecl>(D));
5531     break;
5532 
5533   case Decl::OMPThreadPrivate:
5534     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
5535     break;
5536 
5537   case Decl::OMPAllocate:
5538     break;
5539 
5540   case Decl::OMPDeclareReduction:
5541     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
5542     break;
5543 
5544   case Decl::OMPDeclareMapper:
5545     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
5546     break;
5547 
5548   case Decl::OMPRequires:
5549     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
5550     break;
5551 
5552   default:
5553     // Make sure we handled everything we should, every other kind is a
5554     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
5555     // function. Need to recode Decl::Kind to do that easily.
5556     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
5557     break;
5558   }
5559 }
5560 
5561 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
5562   // Do we need to generate coverage mapping?
5563   if (!CodeGenOpts.CoverageMapping)
5564     return;
5565   switch (D->getKind()) {
5566   case Decl::CXXConversion:
5567   case Decl::CXXMethod:
5568   case Decl::Function:
5569   case Decl::ObjCMethod:
5570   case Decl::CXXConstructor:
5571   case Decl::CXXDestructor: {
5572     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
5573       return;
5574     SourceManager &SM = getContext().getSourceManager();
5575     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
5576       return;
5577     auto I = DeferredEmptyCoverageMappingDecls.find(D);
5578     if (I == DeferredEmptyCoverageMappingDecls.end())
5579       DeferredEmptyCoverageMappingDecls[D] = true;
5580     break;
5581   }
5582   default:
5583     break;
5584   };
5585 }
5586 
5587 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
5588   // Do we need to generate coverage mapping?
5589   if (!CodeGenOpts.CoverageMapping)
5590     return;
5591   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
5592     if (Fn->isTemplateInstantiation())
5593       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
5594   }
5595   auto I = DeferredEmptyCoverageMappingDecls.find(D);
5596   if (I == DeferredEmptyCoverageMappingDecls.end())
5597     DeferredEmptyCoverageMappingDecls[D] = false;
5598   else
5599     I->second = false;
5600 }
5601 
5602 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
5603   // We call takeVector() here to avoid use-after-free.
5604   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
5605   // we deserialize function bodies to emit coverage info for them, and that
5606   // deserializes more declarations. How should we handle that case?
5607   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
5608     if (!Entry.second)
5609       continue;
5610     const Decl *D = Entry.first;
5611     switch (D->getKind()) {
5612     case Decl::CXXConversion:
5613     case Decl::CXXMethod:
5614     case Decl::Function:
5615     case Decl::ObjCMethod: {
5616       CodeGenPGO PGO(*this);
5617       GlobalDecl GD(cast<FunctionDecl>(D));
5618       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5619                                   getFunctionLinkage(GD));
5620       break;
5621     }
5622     case Decl::CXXConstructor: {
5623       CodeGenPGO PGO(*this);
5624       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
5625       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5626                                   getFunctionLinkage(GD));
5627       break;
5628     }
5629     case Decl::CXXDestructor: {
5630       CodeGenPGO PGO(*this);
5631       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
5632       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5633                                   getFunctionLinkage(GD));
5634       break;
5635     }
5636     default:
5637       break;
5638     };
5639   }
5640 }
5641 
5642 void CodeGenModule::EmitMainVoidAlias() {
5643   // In order to transition away from "__original_main" gracefully, emit an
5644   // alias for "main" in the no-argument case so that libc can detect when
5645   // new-style no-argument main is in used.
5646   if (llvm::Function *F = getModule().getFunction("main")) {
5647     if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
5648         F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth()))
5649       addUsedGlobal(llvm::GlobalAlias::create("__main_void", F));
5650   }
5651 }
5652 
5653 /// Turns the given pointer into a constant.
5654 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
5655                                           const void *Ptr) {
5656   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
5657   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
5658   return llvm::ConstantInt::get(i64, PtrInt);
5659 }
5660 
5661 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
5662                                    llvm::NamedMDNode *&GlobalMetadata,
5663                                    GlobalDecl D,
5664                                    llvm::GlobalValue *Addr) {
5665   if (!GlobalMetadata)
5666     GlobalMetadata =
5667       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
5668 
5669   // TODO: should we report variant information for ctors/dtors?
5670   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
5671                            llvm::ConstantAsMetadata::get(GetPointerConstant(
5672                                CGM.getLLVMContext(), D.getDecl()))};
5673   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
5674 }
5675 
5676 /// For each function which is declared within an extern "C" region and marked
5677 /// as 'used', but has internal linkage, create an alias from the unmangled
5678 /// name to the mangled name if possible. People expect to be able to refer
5679 /// to such functions with an unmangled name from inline assembly within the
5680 /// same translation unit.
5681 void CodeGenModule::EmitStaticExternCAliases() {
5682   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
5683     return;
5684   for (auto &I : StaticExternCValues) {
5685     IdentifierInfo *Name = I.first;
5686     llvm::GlobalValue *Val = I.second;
5687     if (Val && !getModule().getNamedValue(Name->getName()))
5688       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
5689   }
5690 }
5691 
5692 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
5693                                              GlobalDecl &Result) const {
5694   auto Res = Manglings.find(MangledName);
5695   if (Res == Manglings.end())
5696     return false;
5697   Result = Res->getValue();
5698   return true;
5699 }
5700 
5701 /// Emits metadata nodes associating all the global values in the
5702 /// current module with the Decls they came from.  This is useful for
5703 /// projects using IR gen as a subroutine.
5704 ///
5705 /// Since there's currently no way to associate an MDNode directly
5706 /// with an llvm::GlobalValue, we create a global named metadata
5707 /// with the name 'clang.global.decl.ptrs'.
5708 void CodeGenModule::EmitDeclMetadata() {
5709   llvm::NamedMDNode *GlobalMetadata = nullptr;
5710 
5711   for (auto &I : MangledDeclNames) {
5712     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
5713     // Some mangled names don't necessarily have an associated GlobalValue
5714     // in this module, e.g. if we mangled it for DebugInfo.
5715     if (Addr)
5716       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
5717   }
5718 }
5719 
5720 /// Emits metadata nodes for all the local variables in the current
5721 /// function.
5722 void CodeGenFunction::EmitDeclMetadata() {
5723   if (LocalDeclMap.empty()) return;
5724 
5725   llvm::LLVMContext &Context = getLLVMContext();
5726 
5727   // Find the unique metadata ID for this name.
5728   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
5729 
5730   llvm::NamedMDNode *GlobalMetadata = nullptr;
5731 
5732   for (auto &I : LocalDeclMap) {
5733     const Decl *D = I.first;
5734     llvm::Value *Addr = I.second.getPointer();
5735     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
5736       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
5737       Alloca->setMetadata(
5738           DeclPtrKind, llvm::MDNode::get(
5739                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
5740     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
5741       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
5742       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
5743     }
5744   }
5745 }
5746 
5747 void CodeGenModule::EmitVersionIdentMetadata() {
5748   llvm::NamedMDNode *IdentMetadata =
5749     TheModule.getOrInsertNamedMetadata("llvm.ident");
5750   std::string Version = getClangFullVersion();
5751   llvm::LLVMContext &Ctx = TheModule.getContext();
5752 
5753   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
5754   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
5755 }
5756 
5757 void CodeGenModule::EmitCommandLineMetadata() {
5758   llvm::NamedMDNode *CommandLineMetadata =
5759     TheModule.getOrInsertNamedMetadata("llvm.commandline");
5760   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
5761   llvm::LLVMContext &Ctx = TheModule.getContext();
5762 
5763   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
5764   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
5765 }
5766 
5767 void CodeGenModule::EmitTargetMetadata() {
5768   // Warning, new MangledDeclNames may be appended within this loop.
5769   // We rely on MapVector insertions adding new elements to the end
5770   // of the container.
5771   // FIXME: Move this loop into the one target that needs it, and only
5772   // loop over those declarations for which we couldn't emit the target
5773   // metadata when we emitted the declaration.
5774   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
5775     auto Val = *(MangledDeclNames.begin() + I);
5776     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
5777     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
5778     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
5779   }
5780 }
5781 
5782 void CodeGenModule::EmitCoverageFile() {
5783   if (getCodeGenOpts().CoverageDataFile.empty() &&
5784       getCodeGenOpts().CoverageNotesFile.empty())
5785     return;
5786 
5787   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
5788   if (!CUNode)
5789     return;
5790 
5791   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
5792   llvm::LLVMContext &Ctx = TheModule.getContext();
5793   auto *CoverageDataFile =
5794       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
5795   auto *CoverageNotesFile =
5796       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
5797   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5798     llvm::MDNode *CU = CUNode->getOperand(i);
5799     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5800     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
5801   }
5802 }
5803 
5804 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
5805                                                        bool ForEH) {
5806   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
5807   // FIXME: should we even be calling this method if RTTI is disabled
5808   // and it's not for EH?
5809   if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice ||
5810       (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
5811        getTriple().isNVPTX()))
5812     return llvm::Constant::getNullValue(Int8PtrTy);
5813 
5814   if (ForEH && Ty->isObjCObjectPointerType() &&
5815       LangOpts.ObjCRuntime.isGNUFamily())
5816     return ObjCRuntime->GetEHType(Ty);
5817 
5818   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
5819 }
5820 
5821 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
5822   // Do not emit threadprivates in simd-only mode.
5823   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5824     return;
5825   for (auto RefExpr : D->varlists()) {
5826     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5827     bool PerformInit =
5828         VD->getAnyInitializer() &&
5829         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
5830                                                         /*ForRef=*/false);
5831 
5832     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
5833     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
5834             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
5835       CXXGlobalInits.push_back(InitFunction);
5836   }
5837 }
5838 
5839 llvm::Metadata *
5840 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
5841                                             StringRef Suffix) {
5842   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
5843   if (InternalId)
5844     return InternalId;
5845 
5846   if (isExternallyVisible(T->getLinkage())) {
5847     std::string OutName;
5848     llvm::raw_string_ostream Out(OutName);
5849     getCXXABI().getMangleContext().mangleTypeName(T, Out);
5850     Out << Suffix;
5851 
5852     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
5853   } else {
5854     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
5855                                            llvm::ArrayRef<llvm::Metadata *>());
5856   }
5857 
5858   return InternalId;
5859 }
5860 
5861 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
5862   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
5863 }
5864 
5865 llvm::Metadata *
5866 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
5867   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
5868 }
5869 
5870 // Generalize pointer types to a void pointer with the qualifiers of the
5871 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
5872 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
5873 // 'void *'.
5874 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
5875   if (!Ty->isPointerType())
5876     return Ty;
5877 
5878   return Ctx.getPointerType(
5879       QualType(Ctx.VoidTy).withCVRQualifiers(
5880           Ty->getPointeeType().getCVRQualifiers()));
5881 }
5882 
5883 // Apply type generalization to a FunctionType's return and argument types
5884 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
5885   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
5886     SmallVector<QualType, 8> GeneralizedParams;
5887     for (auto &Param : FnType->param_types())
5888       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
5889 
5890     return Ctx.getFunctionType(
5891         GeneralizeType(Ctx, FnType->getReturnType()),
5892         GeneralizedParams, FnType->getExtProtoInfo());
5893   }
5894 
5895   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
5896     return Ctx.getFunctionNoProtoType(
5897         GeneralizeType(Ctx, FnType->getReturnType()));
5898 
5899   llvm_unreachable("Encountered unknown FunctionType");
5900 }
5901 
5902 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
5903   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
5904                                       GeneralizedMetadataIdMap, ".generalized");
5905 }
5906 
5907 /// Returns whether this module needs the "all-vtables" type identifier.
5908 bool CodeGenModule::NeedAllVtablesTypeId() const {
5909   // Returns true if at least one of vtable-based CFI checkers is enabled and
5910   // is not in the trapping mode.
5911   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5912            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5913           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5914            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5915           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5916            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5917           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5918            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5919 }
5920 
5921 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
5922                                           CharUnits Offset,
5923                                           const CXXRecordDecl *RD) {
5924   llvm::Metadata *MD =
5925       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
5926   VTable->addTypeMetadata(Offset.getQuantity(), MD);
5927 
5928   if (CodeGenOpts.SanitizeCfiCrossDso)
5929     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
5930       VTable->addTypeMetadata(Offset.getQuantity(),
5931                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
5932 
5933   if (NeedAllVtablesTypeId()) {
5934     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
5935     VTable->addTypeMetadata(Offset.getQuantity(), MD);
5936   }
5937 }
5938 
5939 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5940   if (!SanStats)
5941     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
5942 
5943   return *SanStats;
5944 }
5945 llvm::Value *
5946 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
5947                                                   CodeGenFunction &CGF) {
5948   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
5949   auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
5950   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5951   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5952                                 "__translate_sampler_initializer"),
5953                                 {C});
5954 }
5955