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