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