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