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