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