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