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