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