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