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