xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 40ab8ae9fb70f1550815bf0f867148b5101a4f66)
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, bool Local,
3336                                      bool AssumeConvergent) {
3337   if (AssumeConvergent) {
3338     ExtraAttrs =
3339         ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex,
3340                                 llvm::Attribute::Convergent);
3341   }
3342 
3343   llvm::Constant *C =
3344       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
3345                               /*DontDefer=*/false, /*IsThunk=*/false,
3346                               ExtraAttrs);
3347 
3348   if (auto *F = dyn_cast<llvm::Function>(C)) {
3349     if (F->empty()) {
3350       F->setCallingConv(getRuntimeCC());
3351 
3352       // In Windows Itanium environments, try to mark runtime functions
3353       // dllimport. For Mingw and MSVC, don't. We don't really know if the user
3354       // will link their standard library statically or dynamically. Marking
3355       // functions imported when they are not imported can cause linker errors
3356       // and warnings.
3357       if (!Local && getTriple().isWindowsItaniumEnvironment() &&
3358           !getCodeGenOpts().LTOVisibilityPublicStd) {
3359         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
3360         if (!FD || FD->hasAttr<DLLImportAttr>()) {
3361           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3362           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
3363         }
3364       }
3365       setDSOLocal(F);
3366     }
3367   }
3368 
3369   return {FTy, C};
3370 }
3371 
3372 /// isTypeConstant - Determine whether an object of this type can be emitted
3373 /// as a constant.
3374 ///
3375 /// If ExcludeCtor is true, the duration when the object's constructor runs
3376 /// will not be considered. The caller will need to verify that the object is
3377 /// not written to during its construction.
3378 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
3379   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
3380     return false;
3381 
3382   if (Context.getLangOpts().CPlusPlus) {
3383     if (const CXXRecordDecl *Record
3384           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
3385       return ExcludeCtor && !Record->hasMutableFields() &&
3386              Record->hasTrivialDestructor();
3387   }
3388 
3389   return true;
3390 }
3391 
3392 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
3393 /// create and return an llvm GlobalVariable with the specified type.  If there
3394 /// is something in the module with the specified name, return it potentially
3395 /// bitcasted to the right type.
3396 ///
3397 /// If D is non-null, it specifies a decl that correspond to this.  This is used
3398 /// to set the attributes on the global when it is first created.
3399 ///
3400 /// If IsForDefinition is true, it is guaranteed that an actual global with
3401 /// type Ty will be returned, not conversion of a variable with the same
3402 /// mangled name but some other type.
3403 llvm::Constant *
3404 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
3405                                      llvm::PointerType *Ty,
3406                                      const VarDecl *D,
3407                                      ForDefinition_t IsForDefinition) {
3408   // Lookup the entry, lazily creating it if necessary.
3409   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3410   if (Entry) {
3411     if (WeakRefReferences.erase(Entry)) {
3412       if (D && !D->hasAttr<WeakAttr>())
3413         Entry->setLinkage(llvm::Function::ExternalLinkage);
3414     }
3415 
3416     // Handle dropped DLL attributes.
3417     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
3418       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3419 
3420     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
3421       getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
3422 
3423     if (Entry->getType() == Ty)
3424       return Entry;
3425 
3426     // If there are two attempts to define the same mangled name, issue an
3427     // error.
3428     if (IsForDefinition && !Entry->isDeclaration()) {
3429       GlobalDecl OtherGD;
3430       const VarDecl *OtherD;
3431 
3432       // Check that D is not yet in DiagnosedConflictingDefinitions is required
3433       // to make sure that we issue an error only once.
3434       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
3435           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3436           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
3437           OtherD->hasInit() &&
3438           DiagnosedConflictingDefinitions.insert(D).second) {
3439         getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3440             << MangledName;
3441         getDiags().Report(OtherGD.getDecl()->getLocation(),
3442                           diag::note_previous_definition);
3443       }
3444     }
3445 
3446     // Make sure the result is of the correct type.
3447     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
3448       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
3449 
3450     // (If global is requested for a definition, we always need to create a new
3451     // global, not just return a bitcast.)
3452     if (!IsForDefinition)
3453       return llvm::ConstantExpr::getBitCast(Entry, Ty);
3454   }
3455 
3456   auto AddrSpace = GetGlobalVarAddressSpace(D);
3457   auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
3458 
3459   auto *GV = new llvm::GlobalVariable(
3460       getModule(), Ty->getElementType(), false,
3461       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
3462       llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
3463 
3464   // If we already created a global with the same mangled name (but different
3465   // type) before, take its name and remove it from its parent.
3466   if (Entry) {
3467     GV->takeName(Entry);
3468 
3469     if (!Entry->use_empty()) {
3470       llvm::Constant *NewPtrForOldDecl =
3471           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3472       Entry->replaceAllUsesWith(NewPtrForOldDecl);
3473     }
3474 
3475     Entry->eraseFromParent();
3476   }
3477 
3478   // This is the first use or definition of a mangled name.  If there is a
3479   // deferred decl with this name, remember that we need to emit it at the end
3480   // of the file.
3481   auto DDI = DeferredDecls.find(MangledName);
3482   if (DDI != DeferredDecls.end()) {
3483     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3484     // list, and remove it from DeferredDecls (since we don't need it anymore).
3485     addDeferredDeclToEmit(DDI->second);
3486     DeferredDecls.erase(DDI);
3487   }
3488 
3489   // Handle things which are present even on external declarations.
3490   if (D) {
3491     if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3492       getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3493 
3494     // FIXME: This code is overly simple and should be merged with other global
3495     // handling.
3496     GV->setConstant(isTypeConstant(D->getType(), false));
3497 
3498     GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
3499 
3500     setLinkageForGV(GV, D);
3501 
3502     if (D->getTLSKind()) {
3503       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3504         CXXThreadLocals.push_back(D);
3505       setTLSMode(GV, *D);
3506     }
3507 
3508     setGVProperties(GV, D);
3509 
3510     // If required by the ABI, treat declarations of static data members with
3511     // inline initializers as definitions.
3512     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
3513       EmitGlobalVarDefinition(D);
3514     }
3515 
3516     // Emit section information for extern variables.
3517     if (D->hasExternalStorage()) {
3518       if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3519         GV->setSection(SA->getName());
3520     }
3521 
3522     // Handle XCore specific ABI requirements.
3523     if (getTriple().getArch() == llvm::Triple::xcore &&
3524         D->getLanguageLinkage() == CLanguageLinkage &&
3525         D->getType().isConstant(Context) &&
3526         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3527       GV->setSection(".cp.rodata");
3528 
3529     // Check if we a have a const declaration with an initializer, we may be
3530     // able to emit it as available_externally to expose it's value to the
3531     // optimizer.
3532     if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3533         D->getType().isConstQualified() && !GV->hasInitializer() &&
3534         !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3535       const auto *Record =
3536           Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3537       bool HasMutableFields = Record && Record->hasMutableFields();
3538       if (!HasMutableFields) {
3539         const VarDecl *InitDecl;
3540         const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3541         if (InitExpr) {
3542           ConstantEmitter emitter(*this);
3543           llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3544           if (Init) {
3545             auto *InitType = Init->getType();
3546             if (GV->getType()->getElementType() != InitType) {
3547               // The type of the initializer does not match the definition.
3548               // This happens when an initializer has a different type from
3549               // the type of the global (because of padding at the end of a
3550               // structure for instance).
3551               GV->setName(StringRef());
3552               // Make a new global with the correct type, this is now guaranteed
3553               // to work.
3554               auto *NewGV = cast<llvm::GlobalVariable>(
3555                   GetAddrOfGlobalVar(D, InitType, IsForDefinition)
3556                       ->stripPointerCasts());
3557 
3558               // Erase the old global, since it is no longer used.
3559               GV->eraseFromParent();
3560               GV = NewGV;
3561             } else {
3562               GV->setInitializer(Init);
3563               GV->setConstant(true);
3564               GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3565             }
3566             emitter.finalize(GV);
3567           }
3568         }
3569       }
3570     }
3571   }
3572 
3573   LangAS ExpectedAS =
3574       D ? D->getType().getAddressSpace()
3575         : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
3576   assert(getContext().getTargetAddressSpace(ExpectedAS) ==
3577          Ty->getPointerAddressSpace());
3578   if (AddrSpace != ExpectedAS)
3579     return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3580                                                        ExpectedAS, Ty);
3581 
3582   if (GV->isDeclaration())
3583     getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
3584 
3585   return GV;
3586 }
3587 
3588 llvm::Constant *
3589 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
3590                                ForDefinition_t IsForDefinition) {
3591   const Decl *D = GD.getDecl();
3592   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
3593     return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3594                                 /*DontDefer=*/false, IsForDefinition);
3595   else if (isa<CXXMethodDecl>(D)) {
3596     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
3597         cast<CXXMethodDecl>(D));
3598     auto Ty = getTypes().GetFunctionType(*FInfo);
3599     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3600                              IsForDefinition);
3601   } else if (isa<FunctionDecl>(D)) {
3602     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3603     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3604     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3605                              IsForDefinition);
3606   } else
3607     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
3608                               IsForDefinition);
3609 }
3610 
3611 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
3612     StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
3613     unsigned Alignment) {
3614   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
3615   llvm::GlobalVariable *OldGV = nullptr;
3616 
3617   if (GV) {
3618     // Check if the variable has the right type.
3619     if (GV->getType()->getElementType() == Ty)
3620       return GV;
3621 
3622     // Because C++ name mangling, the only way we can end up with an already
3623     // existing global with the same name is if it has been declared extern "C".
3624     assert(GV->isDeclaration() && "Declaration has wrong type!");
3625     OldGV = GV;
3626   }
3627 
3628   // Create a new variable.
3629   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
3630                                 Linkage, nullptr, Name);
3631 
3632   if (OldGV) {
3633     // Replace occurrences of the old variable if needed.
3634     GV->takeName(OldGV);
3635 
3636     if (!OldGV->use_empty()) {
3637       llvm::Constant *NewPtrForOldDecl =
3638       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3639       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3640     }
3641 
3642     OldGV->eraseFromParent();
3643   }
3644 
3645   if (supportsCOMDAT() && GV->isWeakForLinker() &&
3646       !GV->hasAvailableExternallyLinkage())
3647     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3648 
3649   GV->setAlignment(llvm::MaybeAlign(Alignment));
3650 
3651   return GV;
3652 }
3653 
3654 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3655 /// given global variable.  If Ty is non-null and if the global doesn't exist,
3656 /// then it will be created with the specified type instead of whatever the
3657 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
3658 /// that an actual global with type Ty will be returned, not conversion of a
3659 /// variable with the same mangled name but some other type.
3660 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
3661                                                   llvm::Type *Ty,
3662                                            ForDefinition_t IsForDefinition) {
3663   assert(D->hasGlobalStorage() && "Not a global variable");
3664   QualType ASTTy = D->getType();
3665   if (!Ty)
3666     Ty = getTypes().ConvertTypeForMem(ASTTy);
3667 
3668   llvm::PointerType *PTy =
3669     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
3670 
3671   StringRef MangledName = getMangledName(D);
3672   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
3673 }
3674 
3675 /// CreateRuntimeVariable - Create a new runtime global variable with the
3676 /// specified type and name.
3677 llvm::Constant *
3678 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
3679                                      StringRef Name) {
3680   auto PtrTy =
3681       getContext().getLangOpts().OpenCL
3682           ? llvm::PointerType::get(
3683                 Ty, getContext().getTargetAddressSpace(LangAS::opencl_global))
3684           : llvm::PointerType::getUnqual(Ty);
3685   auto *Ret = GetOrCreateLLVMGlobal(Name, PtrTy, nullptr);
3686   setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3687   return Ret;
3688 }
3689 
3690 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
3691   assert(!D->getInit() && "Cannot emit definite definitions here!");
3692 
3693   StringRef MangledName = getMangledName(D);
3694   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3695 
3696   // We already have a definition, not declaration, with the same mangled name.
3697   // Emitting of declaration is not required (and actually overwrites emitted
3698   // definition).
3699   if (GV && !GV->isDeclaration())
3700     return;
3701 
3702   // If we have not seen a reference to this variable yet, place it into the
3703   // deferred declarations table to be emitted if needed later.
3704   if (!MustBeEmitted(D) && !GV) {
3705       DeferredDecls[MangledName] = D;
3706       return;
3707   }
3708 
3709   // The tentative definition is the only definition.
3710   EmitGlobalVarDefinition(D);
3711 }
3712 
3713 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
3714   return Context.toCharUnitsFromBits(
3715       getDataLayout().getTypeStoreSizeInBits(Ty));
3716 }
3717 
3718 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
3719   LangAS AddrSpace = LangAS::Default;
3720   if (LangOpts.OpenCL) {
3721     AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
3722     assert(AddrSpace == LangAS::opencl_global ||
3723            AddrSpace == LangAS::opencl_constant ||
3724            AddrSpace == LangAS::opencl_local ||
3725            AddrSpace >= LangAS::FirstTargetAddressSpace);
3726     return AddrSpace;
3727   }
3728 
3729   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3730     if (D && D->hasAttr<CUDAConstantAttr>())
3731       return LangAS::cuda_constant;
3732     else if (D && D->hasAttr<CUDASharedAttr>())
3733       return LangAS::cuda_shared;
3734     else if (D && D->hasAttr<CUDADeviceAttr>())
3735       return LangAS::cuda_device;
3736     else if (D && D->getType().isConstQualified())
3737       return LangAS::cuda_constant;
3738     else
3739       return LangAS::cuda_device;
3740   }
3741 
3742   if (LangOpts.OpenMP) {
3743     LangAS AS;
3744     if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
3745       return AS;
3746   }
3747   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
3748 }
3749 
3750 LangAS CodeGenModule::getStringLiteralAddressSpace() const {
3751   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3752   if (LangOpts.OpenCL)
3753     return LangAS::opencl_constant;
3754   if (auto AS = getTarget().getConstantAddressSpace())
3755     return AS.getValue();
3756   return LangAS::Default;
3757 }
3758 
3759 // In address space agnostic languages, string literals are in default address
3760 // space in AST. However, certain targets (e.g. amdgcn) request them to be
3761 // emitted in constant address space in LLVM IR. To be consistent with other
3762 // parts of AST, string literal global variables in constant address space
3763 // need to be casted to default address space before being put into address
3764 // map and referenced by other part of CodeGen.
3765 // In OpenCL, string literals are in constant address space in AST, therefore
3766 // they should not be casted to default address space.
3767 static llvm::Constant *
3768 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
3769                                        llvm::GlobalVariable *GV) {
3770   llvm::Constant *Cast = GV;
3771   if (!CGM.getLangOpts().OpenCL) {
3772     if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3773       if (AS != LangAS::Default)
3774         Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
3775             CGM, GV, AS.getValue(), LangAS::Default,
3776             GV->getValueType()->getPointerTo(
3777                 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
3778     }
3779   }
3780   return Cast;
3781 }
3782 
3783 template<typename SomeDecl>
3784 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3785                                                llvm::GlobalValue *GV) {
3786   if (!getLangOpts().CPlusPlus)
3787     return;
3788 
3789   // Must have 'used' attribute, or else inline assembly can't rely on
3790   // the name existing.
3791   if (!D->template hasAttr<UsedAttr>())
3792     return;
3793 
3794   // Must have internal linkage and an ordinary name.
3795   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
3796     return;
3797 
3798   // Must be in an extern "C" context. Entities declared directly within
3799   // a record are not extern "C" even if the record is in such a context.
3800   const SomeDecl *First = D->getFirstDecl();
3801   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
3802     return;
3803 
3804   // OK, this is an internal linkage entity inside an extern "C" linkage
3805   // specification. Make a note of that so we can give it the "expected"
3806   // mangled name if nothing else is using that name.
3807   std::pair<StaticExternCMap::iterator, bool> R =
3808       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
3809 
3810   // If we have multiple internal linkage entities with the same name
3811   // in extern "C" regions, none of them gets that name.
3812   if (!R.second)
3813     R.first->second = nullptr;
3814 }
3815 
3816 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3817   if (!CGM.supportsCOMDAT())
3818     return false;
3819 
3820   // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
3821   // them being "merged" by the COMDAT Folding linker optimization.
3822   if (D.hasAttr<CUDAGlobalAttr>())
3823     return false;
3824 
3825   if (D.hasAttr<SelectAnyAttr>())
3826     return true;
3827 
3828   GVALinkage Linkage;
3829   if (auto *VD = dyn_cast<VarDecl>(&D))
3830     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3831   else
3832     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3833 
3834   switch (Linkage) {
3835   case GVA_Internal:
3836   case GVA_AvailableExternally:
3837   case GVA_StrongExternal:
3838     return false;
3839   case GVA_DiscardableODR:
3840   case GVA_StrongODR:
3841     return true;
3842   }
3843   llvm_unreachable("No such linkage");
3844 }
3845 
3846 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3847                                           llvm::GlobalObject &GO) {
3848   if (!shouldBeInCOMDAT(*this, D))
3849     return;
3850   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3851 }
3852 
3853 /// Pass IsTentative as true if you want to create a tentative definition.
3854 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3855                                             bool IsTentative) {
3856   // OpenCL global variables of sampler type are translated to function calls,
3857   // therefore no need to be translated.
3858   QualType ASTTy = D->getType();
3859   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3860     return;
3861 
3862   // If this is OpenMP device, check if it is legal to emit this global
3863   // normally.
3864   if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3865       OpenMPRuntime->emitTargetGlobalVariable(D))
3866     return;
3867 
3868   llvm::Constant *Init = nullptr;
3869   bool NeedsGlobalCtor = false;
3870   bool NeedsGlobalDtor =
3871       D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
3872 
3873   const VarDecl *InitDecl;
3874   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3875 
3876   Optional<ConstantEmitter> emitter;
3877 
3878   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3879   // as part of their declaration."  Sema has already checked for
3880   // error cases, so we just need to set Init to UndefValue.
3881   bool IsCUDASharedVar =
3882       getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
3883   // Shadows of initialized device-side global variables are also left
3884   // undefined.
3885   bool IsCUDAShadowVar =
3886       !getLangOpts().CUDAIsDevice &&
3887       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3888        D->hasAttr<CUDASharedAttr>());
3889   // HIP pinned shadow of initialized host-side global variables are also
3890   // left undefined.
3891   bool IsHIPPinnedShadowVar =
3892       getLangOpts().CUDAIsDevice && D->hasAttr<HIPPinnedShadowAttr>();
3893   if (getLangOpts().CUDA &&
3894       (IsCUDASharedVar || IsCUDAShadowVar || IsHIPPinnedShadowVar))
3895     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
3896   else if (!InitExpr) {
3897     // This is a tentative definition; tentative definitions are
3898     // implicitly initialized with { 0 }.
3899     //
3900     // Note that tentative definitions are only emitted at the end of
3901     // a translation unit, so they should never have incomplete
3902     // type. In addition, EmitTentativeDefinition makes sure that we
3903     // never attempt to emit a tentative definition if a real one
3904     // exists. A use may still exists, however, so we still may need
3905     // to do a RAUW.
3906     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
3907     Init = EmitNullConstant(D->getType());
3908   } else {
3909     initializedGlobalDecl = GlobalDecl(D);
3910     emitter.emplace(*this);
3911     Init = emitter->tryEmitForInitializer(*InitDecl);
3912 
3913     if (!Init) {
3914       QualType T = InitExpr->getType();
3915       if (D->getType()->isReferenceType())
3916         T = D->getType();
3917 
3918       if (getLangOpts().CPlusPlus) {
3919         Init = EmitNullConstant(T);
3920         NeedsGlobalCtor = true;
3921       } else {
3922         ErrorUnsupported(D, "static initializer");
3923         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3924       }
3925     } else {
3926       // We don't need an initializer, so remove the entry for the delayed
3927       // initializer position (just in case this entry was delayed) if we
3928       // also don't need to register a destructor.
3929       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
3930         DelayedCXXInitPosition.erase(D);
3931     }
3932   }
3933 
3934   llvm::Type* InitType = Init->getType();
3935   llvm::Constant *Entry =
3936       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
3937 
3938   // Strip off pointer casts if we got them.
3939   Entry = Entry->stripPointerCasts();
3940 
3941   // Entry is now either a Function or GlobalVariable.
3942   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
3943 
3944   // We have a definition after a declaration with the wrong type.
3945   // We must make a new GlobalVariable* and update everything that used OldGV
3946   // (a declaration or tentative definition) with the new GlobalVariable*
3947   // (which will be a definition).
3948   //
3949   // This happens if there is a prototype for a global (e.g.
3950   // "extern int x[];") and then a definition of a different type (e.g.
3951   // "int x[10];"). This also happens when an initializer has a different type
3952   // from the type of the global (this happens with unions).
3953   if (!GV || GV->getType()->getElementType() != InitType ||
3954       GV->getType()->getAddressSpace() !=
3955           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
3956 
3957     // Move the old entry aside so that we'll create a new one.
3958     Entry->setName(StringRef());
3959 
3960     // Make a new global with the correct type, this is now guaranteed to work.
3961     GV = cast<llvm::GlobalVariable>(
3962         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
3963             ->stripPointerCasts());
3964 
3965     // Replace all uses of the old global with the new global
3966     llvm::Constant *NewPtrForOldDecl =
3967         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3968     Entry->replaceAllUsesWith(NewPtrForOldDecl);
3969 
3970     // Erase the old global, since it is no longer used.
3971     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
3972   }
3973 
3974   MaybeHandleStaticInExternC(D, GV);
3975 
3976   if (D->hasAttr<AnnotateAttr>())
3977     AddGlobalAnnotations(D, GV);
3978 
3979   // Set the llvm linkage type as appropriate.
3980   llvm::GlobalValue::LinkageTypes Linkage =
3981       getLLVMLinkageVarDefinition(D, GV->isConstant());
3982 
3983   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
3984   // the device. [...]"
3985   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
3986   // __device__, declares a variable that: [...]
3987   // Is accessible from all the threads within the grid and from the host
3988   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
3989   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
3990   if (GV && LangOpts.CUDA) {
3991     if (LangOpts.CUDAIsDevice) {
3992       if (Linkage != llvm::GlobalValue::InternalLinkage &&
3993           (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()))
3994         GV->setExternallyInitialized(true);
3995     } else {
3996       // Host-side shadows of external declarations of device-side
3997       // global variables become internal definitions. These have to
3998       // be internal in order to prevent name conflicts with global
3999       // host variables with the same name in a different TUs.
4000       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
4001           D->hasAttr<HIPPinnedShadowAttr>()) {
4002         Linkage = llvm::GlobalValue::InternalLinkage;
4003 
4004         // Shadow variables and their properties must be registered
4005         // with CUDA runtime.
4006         unsigned Flags = 0;
4007         if (!D->hasDefinition())
4008           Flags |= CGCUDARuntime::ExternDeviceVar;
4009         if (D->hasAttr<CUDAConstantAttr>())
4010           Flags |= CGCUDARuntime::ConstantDeviceVar;
4011         // Extern global variables will be registered in the TU where they are
4012         // defined.
4013         if (!D->hasExternalStorage())
4014           getCUDARuntime().registerDeviceVar(D, *GV, Flags);
4015       } else if (D->hasAttr<CUDASharedAttr>())
4016         // __shared__ variables are odd. Shadows do get created, but
4017         // they are not registered with the CUDA runtime, so they
4018         // can't really be used to access their device-side
4019         // counterparts. It's not clear yet whether it's nvcc's bug or
4020         // a feature, but we've got to do the same for compatibility.
4021         Linkage = llvm::GlobalValue::InternalLinkage;
4022     }
4023   }
4024 
4025   if (!IsHIPPinnedShadowVar)
4026     GV->setInitializer(Init);
4027   if (emitter) emitter->finalize(GV);
4028 
4029   // If it is safe to mark the global 'constant', do so now.
4030   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
4031                   isTypeConstant(D->getType(), true));
4032 
4033   // If it is in a read-only section, mark it 'constant'.
4034   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
4035     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
4036     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
4037       GV->setConstant(true);
4038   }
4039 
4040   GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4041 
4042   // On Darwin, if the normal linkage of a C++ thread_local variable is
4043   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
4044   // copies within a linkage unit; otherwise, the backing variable has
4045   // internal linkage and all accesses should just be calls to the
4046   // Itanium-specified entry point, which has the normal linkage of the
4047   // variable. This is to preserve the ability to change the implementation
4048   // behind the scenes.
4049   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
4050       Context.getTargetInfo().getTriple().isOSDarwin() &&
4051       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
4052       !llvm::GlobalVariable::isWeakLinkage(Linkage))
4053     Linkage = llvm::GlobalValue::InternalLinkage;
4054 
4055   GV->setLinkage(Linkage);
4056   if (D->hasAttr<DLLImportAttr>())
4057     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
4058   else if (D->hasAttr<DLLExportAttr>())
4059     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
4060   else
4061     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
4062 
4063   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
4064     // common vars aren't constant even if declared const.
4065     GV->setConstant(false);
4066     // Tentative definition of global variables may be initialized with
4067     // non-zero null pointers. In this case they should have weak linkage
4068     // since common linkage must have zero initializer and must not have
4069     // explicit section therefore cannot have non-zero initial value.
4070     if (!GV->getInitializer()->isNullValue())
4071       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
4072   }
4073 
4074   setNonAliasAttributes(D, GV);
4075 
4076   if (D->getTLSKind() && !GV->isThreadLocal()) {
4077     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4078       CXXThreadLocals.push_back(D);
4079     setTLSMode(GV, *D);
4080   }
4081 
4082   maybeSetTrivialComdat(*D, *GV);
4083 
4084   // Emit the initializer function if necessary.
4085   if (NeedsGlobalCtor || NeedsGlobalDtor)
4086     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
4087 
4088   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
4089 
4090   // Emit global variable debug information.
4091   if (CGDebugInfo *DI = getModuleDebugInfo())
4092     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
4093       DI->EmitGlobalVariable(GV, D);
4094 }
4095 
4096 static bool isVarDeclStrongDefinition(const ASTContext &Context,
4097                                       CodeGenModule &CGM, const VarDecl *D,
4098                                       bool NoCommon) {
4099   // Don't give variables common linkage if -fno-common was specified unless it
4100   // was overridden by a NoCommon attribute.
4101   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
4102     return true;
4103 
4104   // C11 6.9.2/2:
4105   //   A declaration of an identifier for an object that has file scope without
4106   //   an initializer, and without a storage-class specifier or with the
4107   //   storage-class specifier static, constitutes a tentative definition.
4108   if (D->getInit() || D->hasExternalStorage())
4109     return true;
4110 
4111   // A variable cannot be both common and exist in a section.
4112   if (D->hasAttr<SectionAttr>())
4113     return true;
4114 
4115   // A variable cannot be both common and exist in a section.
4116   // We don't try to determine which is the right section in the front-end.
4117   // If no specialized section name is applicable, it will resort to default.
4118   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
4119       D->hasAttr<PragmaClangDataSectionAttr>() ||
4120       D->hasAttr<PragmaClangRelroSectionAttr>() ||
4121       D->hasAttr<PragmaClangRodataSectionAttr>())
4122     return true;
4123 
4124   // Thread local vars aren't considered common linkage.
4125   if (D->getTLSKind())
4126     return true;
4127 
4128   // Tentative definitions marked with WeakImportAttr are true definitions.
4129   if (D->hasAttr<WeakImportAttr>())
4130     return true;
4131 
4132   // A variable cannot be both common and exist in a comdat.
4133   if (shouldBeInCOMDAT(CGM, *D))
4134     return true;
4135 
4136   // Declarations with a required alignment do not have common linkage in MSVC
4137   // mode.
4138   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4139     if (D->hasAttr<AlignedAttr>())
4140       return true;
4141     QualType VarType = D->getType();
4142     if (Context.isAlignmentRequired(VarType))
4143       return true;
4144 
4145     if (const auto *RT = VarType->getAs<RecordType>()) {
4146       const RecordDecl *RD = RT->getDecl();
4147       for (const FieldDecl *FD : RD->fields()) {
4148         if (FD->isBitField())
4149           continue;
4150         if (FD->hasAttr<AlignedAttr>())
4151           return true;
4152         if (Context.isAlignmentRequired(FD->getType()))
4153           return true;
4154       }
4155     }
4156   }
4157 
4158   // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
4159   // common symbols, so symbols with greater alignment requirements cannot be
4160   // common.
4161   // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
4162   // alignments for common symbols via the aligncomm directive, so this
4163   // restriction only applies to MSVC environments.
4164   if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
4165       Context.getTypeAlignIfKnown(D->getType()) >
4166           Context.toBits(CharUnits::fromQuantity(32)))
4167     return true;
4168 
4169   return false;
4170 }
4171 
4172 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
4173     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
4174   if (Linkage == GVA_Internal)
4175     return llvm::Function::InternalLinkage;
4176 
4177   if (D->hasAttr<WeakAttr>()) {
4178     if (IsConstantVariable)
4179       return llvm::GlobalVariable::WeakODRLinkage;
4180     else
4181       return llvm::GlobalVariable::WeakAnyLinkage;
4182   }
4183 
4184   if (const auto *FD = D->getAsFunction())
4185     if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
4186       return llvm::GlobalVariable::LinkOnceAnyLinkage;
4187 
4188   // We are guaranteed to have a strong definition somewhere else,
4189   // so we can use available_externally linkage.
4190   if (Linkage == GVA_AvailableExternally)
4191     return llvm::GlobalValue::AvailableExternallyLinkage;
4192 
4193   // Note that Apple's kernel linker doesn't support symbol
4194   // coalescing, so we need to avoid linkonce and weak linkages there.
4195   // Normally, this means we just map to internal, but for explicit
4196   // instantiations we'll map to external.
4197 
4198   // In C++, the compiler has to emit a definition in every translation unit
4199   // that references the function.  We should use linkonce_odr because
4200   // a) if all references in this translation unit are optimized away, we
4201   // don't need to codegen it.  b) if the function persists, it needs to be
4202   // merged with other definitions. c) C++ has the ODR, so we know the
4203   // definition is dependable.
4204   if (Linkage == GVA_DiscardableODR)
4205     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
4206                                             : llvm::Function::InternalLinkage;
4207 
4208   // An explicit instantiation of a template has weak linkage, since
4209   // explicit instantiations can occur in multiple translation units
4210   // and must all be equivalent. However, we are not allowed to
4211   // throw away these explicit instantiations.
4212   //
4213   // We don't currently support CUDA device code spread out across multiple TUs,
4214   // so say that CUDA templates are either external (for kernels) or internal.
4215   // This lets llvm perform aggressive inter-procedural optimizations.
4216   if (Linkage == GVA_StrongODR) {
4217     if (Context.getLangOpts().AppleKext)
4218       return llvm::Function::ExternalLinkage;
4219     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
4220       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
4221                                           : llvm::Function::InternalLinkage;
4222     return llvm::Function::WeakODRLinkage;
4223   }
4224 
4225   // C++ doesn't have tentative definitions and thus cannot have common
4226   // linkage.
4227   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
4228       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
4229                                  CodeGenOpts.NoCommon))
4230     return llvm::GlobalVariable::CommonLinkage;
4231 
4232   // selectany symbols are externally visible, so use weak instead of
4233   // linkonce.  MSVC optimizes away references to const selectany globals, so
4234   // all definitions should be the same and ODR linkage should be used.
4235   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
4236   if (D->hasAttr<SelectAnyAttr>())
4237     return llvm::GlobalVariable::WeakODRLinkage;
4238 
4239   // Otherwise, we have strong external linkage.
4240   assert(Linkage == GVA_StrongExternal);
4241   return llvm::GlobalVariable::ExternalLinkage;
4242 }
4243 
4244 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
4245     const VarDecl *VD, bool IsConstant) {
4246   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
4247   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
4248 }
4249 
4250 /// Replace the uses of a function that was declared with a non-proto type.
4251 /// We want to silently drop extra arguments from call sites
4252 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
4253                                           llvm::Function *newFn) {
4254   // Fast path.
4255   if (old->use_empty()) return;
4256 
4257   llvm::Type *newRetTy = newFn->getReturnType();
4258   SmallVector<llvm::Value*, 4> newArgs;
4259   SmallVector<llvm::OperandBundleDef, 1> newBundles;
4260 
4261   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
4262          ui != ue; ) {
4263     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
4264     llvm::User *user = use->getUser();
4265 
4266     // Recognize and replace uses of bitcasts.  Most calls to
4267     // unprototyped functions will use bitcasts.
4268     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
4269       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
4270         replaceUsesOfNonProtoConstant(bitcast, newFn);
4271       continue;
4272     }
4273 
4274     // Recognize calls to the function.
4275     llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
4276     if (!callSite) continue;
4277     if (!callSite->isCallee(&*use))
4278       continue;
4279 
4280     // If the return types don't match exactly, then we can't
4281     // transform this call unless it's dead.
4282     if (callSite->getType() != newRetTy && !callSite->use_empty())
4283       continue;
4284 
4285     // Get the call site's attribute list.
4286     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
4287     llvm::AttributeList oldAttrs = callSite->getAttributes();
4288 
4289     // If the function was passed too few arguments, don't transform.
4290     unsigned newNumArgs = newFn->arg_size();
4291     if (callSite->arg_size() < newNumArgs)
4292       continue;
4293 
4294     // If extra arguments were passed, we silently drop them.
4295     // If any of the types mismatch, we don't transform.
4296     unsigned argNo = 0;
4297     bool dontTransform = false;
4298     for (llvm::Argument &A : newFn->args()) {
4299       if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
4300         dontTransform = true;
4301         break;
4302       }
4303 
4304       // Add any parameter attributes.
4305       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
4306       argNo++;
4307     }
4308     if (dontTransform)
4309       continue;
4310 
4311     // Okay, we can transform this.  Create the new call instruction and copy
4312     // over the required information.
4313     newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
4314 
4315     // Copy over any operand bundles.
4316     callSite->getOperandBundlesAsDefs(newBundles);
4317 
4318     llvm::CallBase *newCall;
4319     if (dyn_cast<llvm::CallInst>(callSite)) {
4320       newCall =
4321           llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
4322     } else {
4323       auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
4324       newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
4325                                          oldInvoke->getUnwindDest(), newArgs,
4326                                          newBundles, "", callSite);
4327     }
4328     newArgs.clear(); // for the next iteration
4329 
4330     if (!newCall->getType()->isVoidTy())
4331       newCall->takeName(callSite);
4332     newCall->setAttributes(llvm::AttributeList::get(
4333         newFn->getContext(), oldAttrs.getFnAttributes(),
4334         oldAttrs.getRetAttributes(), newArgAttrs));
4335     newCall->setCallingConv(callSite->getCallingConv());
4336 
4337     // Finally, remove the old call, replacing any uses with the new one.
4338     if (!callSite->use_empty())
4339       callSite->replaceAllUsesWith(newCall);
4340 
4341     // Copy debug location attached to CI.
4342     if (callSite->getDebugLoc())
4343       newCall->setDebugLoc(callSite->getDebugLoc());
4344 
4345     callSite->eraseFromParent();
4346   }
4347 }
4348 
4349 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
4350 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
4351 /// existing call uses of the old function in the module, this adjusts them to
4352 /// call the new function directly.
4353 ///
4354 /// This is not just a cleanup: the always_inline pass requires direct calls to
4355 /// functions to be able to inline them.  If there is a bitcast in the way, it
4356 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
4357 /// run at -O0.
4358 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4359                                                       llvm::Function *NewFn) {
4360   // If we're redefining a global as a function, don't transform it.
4361   if (!isa<llvm::Function>(Old)) return;
4362 
4363   replaceUsesOfNonProtoConstant(Old, NewFn);
4364 }
4365 
4366 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
4367   auto DK = VD->isThisDeclarationADefinition();
4368   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
4369     return;
4370 
4371   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
4372   // If we have a definition, this might be a deferred decl. If the
4373   // instantiation is explicit, make sure we emit it at the end.
4374   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
4375     GetAddrOfGlobalVar(VD);
4376 
4377   EmitTopLevelDecl(VD);
4378 }
4379 
4380 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
4381                                                  llvm::GlobalValue *GV) {
4382   // Check if this must be emitted as declare variant.
4383   if (LangOpts.OpenMP && OpenMPRuntime &&
4384       OpenMPRuntime->emitDeclareVariant(GD, /*IsForDefinition=*/true))
4385     return;
4386 
4387   const auto *D = cast<FunctionDecl>(GD.getDecl());
4388 
4389   // Compute the function info and LLVM type.
4390   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4391   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4392 
4393   // Get or create the prototype for the function.
4394   if (!GV || (GV->getType()->getElementType() != Ty))
4395     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
4396                                                    /*DontDefer=*/true,
4397                                                    ForDefinition));
4398 
4399   // Already emitted.
4400   if (!GV->isDeclaration())
4401     return;
4402 
4403   // We need to set linkage and visibility on the function before
4404   // generating code for it because various parts of IR generation
4405   // want to propagate this information down (e.g. to local static
4406   // declarations).
4407   auto *Fn = cast<llvm::Function>(GV);
4408   setFunctionLinkage(GD, Fn);
4409 
4410   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
4411   setGVProperties(Fn, GD);
4412 
4413   MaybeHandleStaticInExternC(D, Fn);
4414 
4415 
4416   maybeSetTrivialComdat(*D, *Fn);
4417 
4418   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
4419 
4420   setNonAliasAttributes(GD, Fn);
4421   SetLLVMFunctionAttributesForDefinition(D, Fn);
4422 
4423   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
4424     AddGlobalCtor(Fn, CA->getPriority());
4425   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
4426     AddGlobalDtor(Fn, DA->getPriority());
4427   if (D->hasAttr<AnnotateAttr>())
4428     AddGlobalAnnotations(D, Fn);
4429 }
4430 
4431 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
4432   const auto *D = cast<ValueDecl>(GD.getDecl());
4433   const AliasAttr *AA = D->getAttr<AliasAttr>();
4434   assert(AA && "Not an alias?");
4435 
4436   StringRef MangledName = getMangledName(GD);
4437 
4438   if (AA->getAliasee() == MangledName) {
4439     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4440     return;
4441   }
4442 
4443   // If there is a definition in the module, then it wins over the alias.
4444   // This is dubious, but allow it to be safe.  Just ignore the alias.
4445   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4446   if (Entry && !Entry->isDeclaration())
4447     return;
4448 
4449   Aliases.push_back(GD);
4450 
4451   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4452 
4453   // Create a reference to the named value.  This ensures that it is emitted
4454   // if a deferred decl.
4455   llvm::Constant *Aliasee;
4456   llvm::GlobalValue::LinkageTypes LT;
4457   if (isa<llvm::FunctionType>(DeclTy)) {
4458     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
4459                                       /*ForVTable=*/false);
4460     LT = getFunctionLinkage(GD);
4461   } else {
4462     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
4463                                     llvm::PointerType::getUnqual(DeclTy),
4464                                     /*D=*/nullptr);
4465     LT = getLLVMLinkageVarDefinition(cast<VarDecl>(GD.getDecl()),
4466                                      D->getType().isConstQualified());
4467   }
4468 
4469   // Create the new alias itself, but don't set a name yet.
4470   auto *GA =
4471       llvm::GlobalAlias::create(DeclTy, 0, LT, "", Aliasee, &getModule());
4472 
4473   if (Entry) {
4474     if (GA->getAliasee() == Entry) {
4475       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4476       return;
4477     }
4478 
4479     assert(Entry->isDeclaration());
4480 
4481     // If there is a declaration in the module, then we had an extern followed
4482     // by the alias, as in:
4483     //   extern int test6();
4484     //   ...
4485     //   int test6() __attribute__((alias("test7")));
4486     //
4487     // Remove it and replace uses of it with the alias.
4488     GA->takeName(Entry);
4489 
4490     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
4491                                                           Entry->getType()));
4492     Entry->eraseFromParent();
4493   } else {
4494     GA->setName(MangledName);
4495   }
4496 
4497   // Set attributes which are particular to an alias; this is a
4498   // specialization of the attributes which may be set on a global
4499   // variable/function.
4500   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
4501       D->isWeakImported()) {
4502     GA->setLinkage(llvm::Function::WeakAnyLinkage);
4503   }
4504 
4505   if (const auto *VD = dyn_cast<VarDecl>(D))
4506     if (VD->getTLSKind())
4507       setTLSMode(GA, *VD);
4508 
4509   SetCommonAttributes(GD, GA);
4510 }
4511 
4512 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4513   const auto *D = cast<ValueDecl>(GD.getDecl());
4514   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4515   assert(IFA && "Not an ifunc?");
4516 
4517   StringRef MangledName = getMangledName(GD);
4518 
4519   if (IFA->getResolver() == MangledName) {
4520     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4521     return;
4522   }
4523 
4524   // Report an error if some definition overrides ifunc.
4525   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4526   if (Entry && !Entry->isDeclaration()) {
4527     GlobalDecl OtherGD;
4528     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4529         DiagnosedConflictingDefinitions.insert(GD).second) {
4530       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4531           << MangledName;
4532       Diags.Report(OtherGD.getDecl()->getLocation(),
4533                    diag::note_previous_definition);
4534     }
4535     return;
4536   }
4537 
4538   Aliases.push_back(GD);
4539 
4540   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4541   llvm::Constant *Resolver =
4542       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4543                               /*ForVTable=*/false);
4544   llvm::GlobalIFunc *GIF =
4545       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4546                                 "", Resolver, &getModule());
4547   if (Entry) {
4548     if (GIF->getResolver() == Entry) {
4549       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4550       return;
4551     }
4552     assert(Entry->isDeclaration());
4553 
4554     // If there is a declaration in the module, then we had an extern followed
4555     // by the ifunc, as in:
4556     //   extern int test();
4557     //   ...
4558     //   int test() __attribute__((ifunc("resolver")));
4559     //
4560     // Remove it and replace uses of it with the ifunc.
4561     GIF->takeName(Entry);
4562 
4563     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4564                                                           Entry->getType()));
4565     Entry->eraseFromParent();
4566   } else
4567     GIF->setName(MangledName);
4568 
4569   SetCommonAttributes(GD, GIF);
4570 }
4571 
4572 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
4573                                             ArrayRef<llvm::Type*> Tys) {
4574   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
4575                                          Tys);
4576 }
4577 
4578 static llvm::StringMapEntry<llvm::GlobalVariable *> &
4579 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
4580                          const StringLiteral *Literal, bool TargetIsLSB,
4581                          bool &IsUTF16, unsigned &StringLength) {
4582   StringRef String = Literal->getString();
4583   unsigned NumBytes = String.size();
4584 
4585   // Check for simple case.
4586   if (!Literal->containsNonAsciiOrNull()) {
4587     StringLength = NumBytes;
4588     return *Map.insert(std::make_pair(String, nullptr)).first;
4589   }
4590 
4591   // Otherwise, convert the UTF8 literals into a string of shorts.
4592   IsUTF16 = true;
4593 
4594   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
4595   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4596   llvm::UTF16 *ToPtr = &ToBuf[0];
4597 
4598   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4599                                  ToPtr + NumBytes, llvm::strictConversion);
4600 
4601   // ConvertUTF8toUTF16 returns the length in ToPtr.
4602   StringLength = ToPtr - &ToBuf[0];
4603 
4604   // Add an explicit null.
4605   *ToPtr = 0;
4606   return *Map.insert(std::make_pair(
4607                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4608                                    (StringLength + 1) * 2),
4609                          nullptr)).first;
4610 }
4611 
4612 ConstantAddress
4613 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
4614   unsigned StringLength = 0;
4615   bool isUTF16 = false;
4616   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4617       GetConstantCFStringEntry(CFConstantStringMap, Literal,
4618                                getDataLayout().isLittleEndian(), isUTF16,
4619                                StringLength);
4620 
4621   if (auto *C = Entry.second)
4622     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
4623 
4624   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
4625   llvm::Constant *Zeros[] = { Zero, Zero };
4626 
4627   const ASTContext &Context = getContext();
4628   const llvm::Triple &Triple = getTriple();
4629 
4630   const auto CFRuntime = getLangOpts().CFRuntime;
4631   const bool IsSwiftABI =
4632       static_cast<unsigned>(CFRuntime) >=
4633       static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
4634   const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
4635 
4636   // If we don't already have it, get __CFConstantStringClassReference.
4637   if (!CFConstantStringClassRef) {
4638     const char *CFConstantStringClassName = "__CFConstantStringClassReference";
4639     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
4640     Ty = llvm::ArrayType::get(Ty, 0);
4641 
4642     switch (CFRuntime) {
4643     default: break;
4644     case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
4645     case LangOptions::CoreFoundationABI::Swift5_0:
4646       CFConstantStringClassName =
4647           Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
4648                               : "$s10Foundation19_NSCFConstantStringCN";
4649       Ty = IntPtrTy;
4650       break;
4651     case LangOptions::CoreFoundationABI::Swift4_2:
4652       CFConstantStringClassName =
4653           Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
4654                               : "$S10Foundation19_NSCFConstantStringCN";
4655       Ty = IntPtrTy;
4656       break;
4657     case LangOptions::CoreFoundationABI::Swift4_1:
4658       CFConstantStringClassName =
4659           Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
4660                               : "__T010Foundation19_NSCFConstantStringCN";
4661       Ty = IntPtrTy;
4662       break;
4663     }
4664 
4665     llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
4666 
4667     if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
4668       llvm::GlobalValue *GV = nullptr;
4669 
4670       if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
4671         IdentifierInfo &II = Context.Idents.get(GV->getName());
4672         TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
4673         DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4674 
4675         const VarDecl *VD = nullptr;
4676         for (const auto &Result : DC->lookup(&II))
4677           if ((VD = dyn_cast<VarDecl>(Result)))
4678             break;
4679 
4680         if (Triple.isOSBinFormatELF()) {
4681           if (!VD)
4682             GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4683         } else {
4684           GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4685           if (!VD || !VD->hasAttr<DLLExportAttr>())
4686             GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4687           else
4688             GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
4689         }
4690 
4691         setDSOLocal(GV);
4692       }
4693     }
4694 
4695     // Decay array -> ptr
4696     CFConstantStringClassRef =
4697         IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
4698                    : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
4699   }
4700 
4701   QualType CFTy = Context.getCFConstantStringType();
4702 
4703   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
4704 
4705   ConstantInitBuilder Builder(*this);
4706   auto Fields = Builder.beginStruct(STy);
4707 
4708   // Class pointer.
4709   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
4710 
4711   // Flags.
4712   if (IsSwiftABI) {
4713     Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
4714     Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
4715   } else {
4716     Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4717   }
4718 
4719   // String pointer.
4720   llvm::Constant *C = nullptr;
4721   if (isUTF16) {
4722     auto Arr = llvm::makeArrayRef(
4723         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4724         Entry.first().size() / 2);
4725     C = llvm::ConstantDataArray::get(VMContext, Arr);
4726   } else {
4727     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
4728   }
4729 
4730   // Note: -fwritable-strings doesn't make the backing store strings of
4731   // CFStrings writable. (See <rdar://problem/10657500>)
4732   auto *GV =
4733       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
4734                                llvm::GlobalValue::PrivateLinkage, C, ".str");
4735   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4736   // Don't enforce the target's minimum global alignment, since the only use
4737   // of the string is via this class initializer.
4738   CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
4739                             : Context.getTypeAlignInChars(Context.CharTy);
4740   GV->setAlignment(Align.getAsAlign());
4741 
4742   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
4743   // Without it LLVM can merge the string with a non unnamed_addr one during
4744   // LTO.  Doing that changes the section it ends in, which surprises ld64.
4745   if (Triple.isOSBinFormatMachO())
4746     GV->setSection(isUTF16 ? "__TEXT,__ustring"
4747                            : "__TEXT,__cstring,cstring_literals");
4748   // Make sure the literal ends up in .rodata to allow for safe ICF and for
4749   // the static linker to adjust permissions to read-only later on.
4750   else if (Triple.isOSBinFormatELF())
4751     GV->setSection(".rodata");
4752 
4753   // String.
4754   llvm::Constant *Str =
4755       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
4756 
4757   if (isUTF16)
4758     // Cast the UTF16 string to the correct type.
4759     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
4760   Fields.add(Str);
4761 
4762   // String length.
4763   llvm::IntegerType *LengthTy =
4764       llvm::IntegerType::get(getModule().getContext(),
4765                              Context.getTargetInfo().getLongWidth());
4766   if (IsSwiftABI) {
4767     if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
4768         CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
4769       LengthTy = Int32Ty;
4770     else
4771       LengthTy = IntPtrTy;
4772   }
4773   Fields.addInt(LengthTy, StringLength);
4774 
4775   // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
4776   // properly aligned on 32-bit platforms.
4777   CharUnits Alignment =
4778       IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
4779 
4780   // The struct.
4781   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
4782                                     /*isConstant=*/false,
4783                                     llvm::GlobalVariable::PrivateLinkage);
4784   GV->addAttribute("objc_arc_inert");
4785   switch (Triple.getObjectFormat()) {
4786   case llvm::Triple::UnknownObjectFormat:
4787     llvm_unreachable("unknown file format");
4788   case llvm::Triple::XCOFF:
4789     llvm_unreachable("XCOFF is not yet implemented");
4790   case llvm::Triple::COFF:
4791   case llvm::Triple::ELF:
4792   case llvm::Triple::Wasm:
4793     GV->setSection("cfstring");
4794     break;
4795   case llvm::Triple::MachO:
4796     GV->setSection("__DATA,__cfstring");
4797     break;
4798   }
4799   Entry.second = GV;
4800 
4801   return ConstantAddress(GV, Alignment);
4802 }
4803 
4804 bool CodeGenModule::getExpressionLocationsEnabled() const {
4805   return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4806 }
4807 
4808 QualType CodeGenModule::getObjCFastEnumerationStateType() {
4809   if (ObjCFastEnumerationStateType.isNull()) {
4810     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
4811     D->startDefinition();
4812 
4813     QualType FieldTypes[] = {
4814       Context.UnsignedLongTy,
4815       Context.getPointerType(Context.getObjCIdType()),
4816       Context.getPointerType(Context.UnsignedLongTy),
4817       Context.getConstantArrayType(Context.UnsignedLongTy,
4818                            llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
4819     };
4820 
4821     for (size_t i = 0; i < 4; ++i) {
4822       FieldDecl *Field = FieldDecl::Create(Context,
4823                                            D,
4824                                            SourceLocation(),
4825                                            SourceLocation(), nullptr,
4826                                            FieldTypes[i], /*TInfo=*/nullptr,
4827                                            /*BitWidth=*/nullptr,
4828                                            /*Mutable=*/false,
4829                                            ICIS_NoInit);
4830       Field->setAccess(AS_public);
4831       D->addDecl(Field);
4832     }
4833 
4834     D->completeDefinition();
4835     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
4836   }
4837 
4838   return ObjCFastEnumerationStateType;
4839 }
4840 
4841 llvm::Constant *
4842 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
4843   assert(!E->getType()->isPointerType() && "Strings are always arrays");
4844 
4845   // Don't emit it as the address of the string, emit the string data itself
4846   // as an inline array.
4847   if (E->getCharByteWidth() == 1) {
4848     SmallString<64> Str(E->getString());
4849 
4850     // Resize the string to the right size, which is indicated by its type.
4851     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
4852     Str.resize(CAT->getSize().getZExtValue());
4853     return llvm::ConstantDataArray::getString(VMContext, Str, false);
4854   }
4855 
4856   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
4857   llvm::Type *ElemTy = AType->getElementType();
4858   unsigned NumElements = AType->getNumElements();
4859 
4860   // Wide strings have either 2-byte or 4-byte elements.
4861   if (ElemTy->getPrimitiveSizeInBits() == 16) {
4862     SmallVector<uint16_t, 32> Elements;
4863     Elements.reserve(NumElements);
4864 
4865     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4866       Elements.push_back(E->getCodeUnit(i));
4867     Elements.resize(NumElements);
4868     return llvm::ConstantDataArray::get(VMContext, Elements);
4869   }
4870 
4871   assert(ElemTy->getPrimitiveSizeInBits() == 32);
4872   SmallVector<uint32_t, 32> Elements;
4873   Elements.reserve(NumElements);
4874 
4875   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4876     Elements.push_back(E->getCodeUnit(i));
4877   Elements.resize(NumElements);
4878   return llvm::ConstantDataArray::get(VMContext, Elements);
4879 }
4880 
4881 static llvm::GlobalVariable *
4882 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4883                       CodeGenModule &CGM, StringRef GlobalName,
4884                       CharUnits Alignment) {
4885   unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
4886       CGM.getStringLiteralAddressSpace());
4887 
4888   llvm::Module &M = CGM.getModule();
4889   // Create a global variable for this string
4890   auto *GV = new llvm::GlobalVariable(
4891       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
4892       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
4893   GV->setAlignment(Alignment.getAsAlign());
4894   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4895   if (GV->isWeakForLinker()) {
4896     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
4897     GV->setComdat(M.getOrInsertComdat(GV->getName()));
4898   }
4899   CGM.setDSOLocal(GV);
4900 
4901   return GV;
4902 }
4903 
4904 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
4905 /// constant array for the given string literal.
4906 ConstantAddress
4907 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
4908                                                   StringRef Name) {
4909   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
4910 
4911   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
4912   llvm::GlobalVariable **Entry = nullptr;
4913   if (!LangOpts.WritableStrings) {
4914     Entry = &ConstantStringMap[C];
4915     if (auto GV = *Entry) {
4916       if (Alignment.getQuantity() > GV->getAlignment())
4917         GV->setAlignment(Alignment.getAsAlign());
4918       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4919                              Alignment);
4920     }
4921   }
4922 
4923   SmallString<256> MangledNameBuffer;
4924   StringRef GlobalVariableName;
4925   llvm::GlobalValue::LinkageTypes LT;
4926 
4927   // Mangle the string literal if that's how the ABI merges duplicate strings.
4928   // Don't do it if they are writable, since we don't want writes in one TU to
4929   // affect strings in another.
4930   if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
4931       !LangOpts.WritableStrings) {
4932     llvm::raw_svector_ostream Out(MangledNameBuffer);
4933     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
4934     LT = llvm::GlobalValue::LinkOnceODRLinkage;
4935     GlobalVariableName = MangledNameBuffer;
4936   } else {
4937     LT = llvm::GlobalValue::PrivateLinkage;
4938     GlobalVariableName = Name;
4939   }
4940 
4941   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
4942   if (Entry)
4943     *Entry = GV;
4944 
4945   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
4946                                   QualType());
4947 
4948   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4949                          Alignment);
4950 }
4951 
4952 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
4953 /// array for the given ObjCEncodeExpr node.
4954 ConstantAddress
4955 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
4956   std::string Str;
4957   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
4958 
4959   return GetAddrOfConstantCString(Str);
4960 }
4961 
4962 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
4963 /// the literal and a terminating '\0' character.
4964 /// The result has pointer to array type.
4965 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
4966     const std::string &Str, const char *GlobalName) {
4967   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
4968   CharUnits Alignment =
4969     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
4970 
4971   llvm::Constant *C =
4972       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
4973 
4974   // Don't share any string literals if strings aren't constant.
4975   llvm::GlobalVariable **Entry = nullptr;
4976   if (!LangOpts.WritableStrings) {
4977     Entry = &ConstantStringMap[C];
4978     if (auto GV = *Entry) {
4979       if (Alignment.getQuantity() > GV->getAlignment())
4980         GV->setAlignment(Alignment.getAsAlign());
4981       return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4982                              Alignment);
4983     }
4984   }
4985 
4986   // Get the default prefix if a name wasn't specified.
4987   if (!GlobalName)
4988     GlobalName = ".str";
4989   // Create a global variable for this.
4990   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
4991                                   GlobalName, Alignment);
4992   if (Entry)
4993     *Entry = GV;
4994 
4995   return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4996                          Alignment);
4997 }
4998 
4999 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
5000     const MaterializeTemporaryExpr *E, const Expr *Init) {
5001   assert((E->getStorageDuration() == SD_Static ||
5002           E->getStorageDuration() == SD_Thread) && "not a global temporary");
5003   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
5004 
5005   // If we're not materializing a subobject of the temporary, keep the
5006   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
5007   QualType MaterializedType = Init->getType();
5008   if (Init == E->GetTemporaryExpr())
5009     MaterializedType = E->getType();
5010 
5011   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
5012 
5013   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
5014     return ConstantAddress(Slot, Align);
5015 
5016   // FIXME: If an externally-visible declaration extends multiple temporaries,
5017   // we need to give each temporary the same name in every translation unit (and
5018   // we also need to make the temporaries externally-visible).
5019   SmallString<256> Name;
5020   llvm::raw_svector_ostream Out(Name);
5021   getCXXABI().getMangleContext().mangleReferenceTemporary(
5022       VD, E->getManglingNumber(), Out);
5023 
5024   APValue *Value = nullptr;
5025   if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
5026     // If the initializer of the extending declaration is a constant
5027     // initializer, we should have a cached constant initializer for this
5028     // temporary. Note that this might have a different value from the value
5029     // computed by evaluating the initializer if the surrounding constant
5030     // expression modifies the temporary.
5031     Value = getContext().getMaterializedTemporaryValue(E, false);
5032   }
5033 
5034   // Try evaluating it now, it might have a constant initializer.
5035   Expr::EvalResult EvalResult;
5036   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
5037       !EvalResult.hasSideEffects())
5038     Value = &EvalResult.Val;
5039 
5040   LangAS AddrSpace =
5041       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
5042 
5043   Optional<ConstantEmitter> emitter;
5044   llvm::Constant *InitialValue = nullptr;
5045   bool Constant = false;
5046   llvm::Type *Type;
5047   if (Value) {
5048     // The temporary has a constant initializer, use it.
5049     emitter.emplace(*this);
5050     InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
5051                                                MaterializedType);
5052     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
5053     Type = InitialValue->getType();
5054   } else {
5055     // No initializer, the initialization will be provided when we
5056     // initialize the declaration which performed lifetime extension.
5057     Type = getTypes().ConvertTypeForMem(MaterializedType);
5058   }
5059 
5060   // Create a global variable for this lifetime-extended temporary.
5061   llvm::GlobalValue::LinkageTypes Linkage =
5062       getLLVMLinkageVarDefinition(VD, Constant);
5063   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
5064     const VarDecl *InitVD;
5065     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
5066         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
5067       // Temporaries defined inside a class get linkonce_odr linkage because the
5068       // class can be defined in multiple translation units.
5069       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
5070     } else {
5071       // There is no need for this temporary to have external linkage if the
5072       // VarDecl has external linkage.
5073       Linkage = llvm::GlobalVariable::InternalLinkage;
5074     }
5075   }
5076   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
5077   auto *GV = new llvm::GlobalVariable(
5078       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
5079       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
5080   if (emitter) emitter->finalize(GV);
5081   setGVProperties(GV, VD);
5082   GV->setAlignment(Align.getAsAlign());
5083   if (supportsCOMDAT() && GV->isWeakForLinker())
5084     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5085   if (VD->getTLSKind())
5086     setTLSMode(GV, *VD);
5087   llvm::Constant *CV = GV;
5088   if (AddrSpace != LangAS::Default)
5089     CV = getTargetCodeGenInfo().performAddrSpaceCast(
5090         *this, GV, AddrSpace, LangAS::Default,
5091         Type->getPointerTo(
5092             getContext().getTargetAddressSpace(LangAS::Default)));
5093   MaterializedGlobalTemporaryMap[E] = CV;
5094   return ConstantAddress(CV, Align);
5095 }
5096 
5097 /// EmitObjCPropertyImplementations - Emit information for synthesized
5098 /// properties for an implementation.
5099 void CodeGenModule::EmitObjCPropertyImplementations(const
5100                                                     ObjCImplementationDecl *D) {
5101   for (const auto *PID : D->property_impls()) {
5102     // Dynamic is just for type-checking.
5103     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
5104       ObjCPropertyDecl *PD = PID->getPropertyDecl();
5105 
5106       // Determine which methods need to be implemented, some may have
5107       // been overridden. Note that ::isPropertyAccessor is not the method
5108       // we want, that just indicates if the decl came from a
5109       // property. What we want to know is if the method is defined in
5110       // this implementation.
5111       if (!D->getInstanceMethod(PD->getGetterName()))
5112         CodeGenFunction(*this).GenerateObjCGetter(
5113                                  const_cast<ObjCImplementationDecl *>(D), PID);
5114       if (!PD->isReadOnly() &&
5115           !D->getInstanceMethod(PD->getSetterName()))
5116         CodeGenFunction(*this).GenerateObjCSetter(
5117                                  const_cast<ObjCImplementationDecl *>(D), PID);
5118     }
5119   }
5120 }
5121 
5122 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
5123   const ObjCInterfaceDecl *iface = impl->getClassInterface();
5124   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
5125        ivar; ivar = ivar->getNextIvar())
5126     if (ivar->getType().isDestructedType())
5127       return true;
5128 
5129   return false;
5130 }
5131 
5132 static bool AllTrivialInitializers(CodeGenModule &CGM,
5133                                    ObjCImplementationDecl *D) {
5134   CodeGenFunction CGF(CGM);
5135   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
5136        E = D->init_end(); B != E; ++B) {
5137     CXXCtorInitializer *CtorInitExp = *B;
5138     Expr *Init = CtorInitExp->getInit();
5139     if (!CGF.isTrivialInitializer(Init))
5140       return false;
5141   }
5142   return true;
5143 }
5144 
5145 /// EmitObjCIvarInitializations - Emit information for ivar initialization
5146 /// for an implementation.
5147 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
5148   // We might need a .cxx_destruct even if we don't have any ivar initializers.
5149   if (needsDestructMethod(D)) {
5150     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
5151     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5152     ObjCMethodDecl *DTORMethod =
5153       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
5154                              cxxSelector, getContext().VoidTy, nullptr, D,
5155                              /*isInstance=*/true, /*isVariadic=*/false,
5156                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
5157                              /*isDefined=*/false, ObjCMethodDecl::Required);
5158     D->addInstanceMethod(DTORMethod);
5159     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
5160     D->setHasDestructors(true);
5161   }
5162 
5163   // If the implementation doesn't have any ivar initializers, we don't need
5164   // a .cxx_construct.
5165   if (D->getNumIvarInitializers() == 0 ||
5166       AllTrivialInitializers(*this, D))
5167     return;
5168 
5169   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
5170   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5171   // The constructor returns 'self'.
5172   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
5173                                                 D->getLocation(),
5174                                                 D->getLocation(),
5175                                                 cxxSelector,
5176                                                 getContext().getObjCIdType(),
5177                                                 nullptr, D, /*isInstance=*/true,
5178                                                 /*isVariadic=*/false,
5179                                                 /*isPropertyAccessor=*/true,
5180                                                 /*isImplicitlyDeclared=*/true,
5181                                                 /*isDefined=*/false,
5182                                                 ObjCMethodDecl::Required);
5183   D->addInstanceMethod(CTORMethod);
5184   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
5185   D->setHasNonZeroConstructors(true);
5186 }
5187 
5188 // EmitLinkageSpec - Emit all declarations in a linkage spec.
5189 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
5190   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5191       LSD->getLanguage() != LinkageSpecDecl::lang_cxx &&
5192       LSD->getLanguage() != LinkageSpecDecl::lang_cxx_11 &&
5193       LSD->getLanguage() != LinkageSpecDecl::lang_cxx_14) {
5194     ErrorUnsupported(LSD, "linkage spec");
5195     return;
5196   }
5197 
5198   EmitDeclContext(LSD);
5199 }
5200 
5201 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
5202   for (auto *I : DC->decls()) {
5203     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
5204     // are themselves considered "top-level", so EmitTopLevelDecl on an
5205     // ObjCImplDecl does not recursively visit them. We need to do that in
5206     // case they're nested inside another construct (LinkageSpecDecl /
5207     // ExportDecl) that does stop them from being considered "top-level".
5208     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
5209       for (auto *M : OID->methods())
5210         EmitTopLevelDecl(M);
5211     }
5212 
5213     EmitTopLevelDecl(I);
5214   }
5215 }
5216 
5217 /// EmitTopLevelDecl - Emit code for a single top level declaration.
5218 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
5219   // Ignore dependent declarations.
5220   if (D->isTemplated())
5221     return;
5222 
5223   switch (D->getKind()) {
5224   case Decl::CXXConversion:
5225   case Decl::CXXMethod:
5226   case Decl::Function:
5227     EmitGlobal(cast<FunctionDecl>(D));
5228     // Always provide some coverage mapping
5229     // even for the functions that aren't emitted.
5230     AddDeferredUnusedCoverageMapping(D);
5231     break;
5232 
5233   case Decl::CXXDeductionGuide:
5234     // Function-like, but does not result in code emission.
5235     break;
5236 
5237   case Decl::Var:
5238   case Decl::Decomposition:
5239   case Decl::VarTemplateSpecialization:
5240     EmitGlobal(cast<VarDecl>(D));
5241     if (auto *DD = dyn_cast<DecompositionDecl>(D))
5242       for (auto *B : DD->bindings())
5243         if (auto *HD = B->getHoldingVar())
5244           EmitGlobal(HD);
5245     break;
5246 
5247   // Indirect fields from global anonymous structs and unions can be
5248   // ignored; only the actual variable requires IR gen support.
5249   case Decl::IndirectField:
5250     break;
5251 
5252   // C++ Decls
5253   case Decl::Namespace:
5254     EmitDeclContext(cast<NamespaceDecl>(D));
5255     break;
5256   case Decl::ClassTemplateSpecialization: {
5257     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
5258     if (DebugInfo &&
5259         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
5260         Spec->hasDefinition())
5261       DebugInfo->completeTemplateDefinition(*Spec);
5262   } LLVM_FALLTHROUGH;
5263   case Decl::CXXRecord:
5264     if (DebugInfo) {
5265       if (auto *ES = D->getASTContext().getExternalSource())
5266         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
5267           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
5268     }
5269     // Emit any static data members, they may be definitions.
5270     for (auto *I : cast<CXXRecordDecl>(D)->decls())
5271       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
5272         EmitTopLevelDecl(I);
5273     break;
5274     // No code generation needed.
5275   case Decl::UsingShadow:
5276   case Decl::ClassTemplate:
5277   case Decl::VarTemplate:
5278   case Decl::Concept:
5279   case Decl::VarTemplatePartialSpecialization:
5280   case Decl::FunctionTemplate:
5281   case Decl::TypeAliasTemplate:
5282   case Decl::Block:
5283   case Decl::Empty:
5284   case Decl::Binding:
5285     break;
5286   case Decl::Using:          // using X; [C++]
5287     if (CGDebugInfo *DI = getModuleDebugInfo())
5288         DI->EmitUsingDecl(cast<UsingDecl>(*D));
5289     return;
5290   case Decl::NamespaceAlias:
5291     if (CGDebugInfo *DI = getModuleDebugInfo())
5292         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
5293     return;
5294   case Decl::UsingDirective: // using namespace X; [C++]
5295     if (CGDebugInfo *DI = getModuleDebugInfo())
5296       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
5297     return;
5298   case Decl::CXXConstructor:
5299     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
5300     break;
5301   case Decl::CXXDestructor:
5302     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
5303     break;
5304 
5305   case Decl::StaticAssert:
5306     // Nothing to do.
5307     break;
5308 
5309   // Objective-C Decls
5310 
5311   // Forward declarations, no (immediate) code generation.
5312   case Decl::ObjCInterface:
5313   case Decl::ObjCCategory:
5314     break;
5315 
5316   case Decl::ObjCProtocol: {
5317     auto *Proto = cast<ObjCProtocolDecl>(D);
5318     if (Proto->isThisDeclarationADefinition())
5319       ObjCRuntime->GenerateProtocol(Proto);
5320     break;
5321   }
5322 
5323   case Decl::ObjCCategoryImpl:
5324     // Categories have properties but don't support synthesize so we
5325     // can ignore them here.
5326     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
5327     break;
5328 
5329   case Decl::ObjCImplementation: {
5330     auto *OMD = cast<ObjCImplementationDecl>(D);
5331     EmitObjCPropertyImplementations(OMD);
5332     EmitObjCIvarInitializations(OMD);
5333     ObjCRuntime->GenerateClass(OMD);
5334     // Emit global variable debug information.
5335     if (CGDebugInfo *DI = getModuleDebugInfo())
5336       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
5337         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
5338             OMD->getClassInterface()), OMD->getLocation());
5339     break;
5340   }
5341   case Decl::ObjCMethod: {
5342     auto *OMD = cast<ObjCMethodDecl>(D);
5343     // If this is not a prototype, emit the body.
5344     if (OMD->getBody())
5345       CodeGenFunction(*this).GenerateObjCMethod(OMD);
5346     break;
5347   }
5348   case Decl::ObjCCompatibleAlias:
5349     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
5350     break;
5351 
5352   case Decl::PragmaComment: {
5353     const auto *PCD = cast<PragmaCommentDecl>(D);
5354     switch (PCD->getCommentKind()) {
5355     case PCK_Unknown:
5356       llvm_unreachable("unexpected pragma comment kind");
5357     case PCK_Linker:
5358       AppendLinkerOptions(PCD->getArg());
5359       break;
5360     case PCK_Lib:
5361         AddDependentLib(PCD->getArg());
5362       break;
5363     case PCK_Compiler:
5364     case PCK_ExeStr:
5365     case PCK_User:
5366       break; // We ignore all of these.
5367     }
5368     break;
5369   }
5370 
5371   case Decl::PragmaDetectMismatch: {
5372     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
5373     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
5374     break;
5375   }
5376 
5377   case Decl::LinkageSpec:
5378     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
5379     break;
5380 
5381   case Decl::FileScopeAsm: {
5382     // File-scope asm is ignored during device-side CUDA compilation.
5383     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
5384       break;
5385     // File-scope asm is ignored during device-side OpenMP compilation.
5386     if (LangOpts.OpenMPIsDevice)
5387       break;
5388     auto *AD = cast<FileScopeAsmDecl>(D);
5389     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
5390     break;
5391   }
5392 
5393   case Decl::Import: {
5394     auto *Import = cast<ImportDecl>(D);
5395 
5396     // If we've already imported this module, we're done.
5397     if (!ImportedModules.insert(Import->getImportedModule()))
5398       break;
5399 
5400     // Emit debug information for direct imports.
5401     if (!Import->getImportedOwningModule()) {
5402       if (CGDebugInfo *DI = getModuleDebugInfo())
5403         DI->EmitImportDecl(*Import);
5404     }
5405 
5406     // Find all of the submodules and emit the module initializers.
5407     llvm::SmallPtrSet<clang::Module *, 16> Visited;
5408     SmallVector<clang::Module *, 16> Stack;
5409     Visited.insert(Import->getImportedModule());
5410     Stack.push_back(Import->getImportedModule());
5411 
5412     while (!Stack.empty()) {
5413       clang::Module *Mod = Stack.pop_back_val();
5414       if (!EmittedModuleInitializers.insert(Mod).second)
5415         continue;
5416 
5417       for (auto *D : Context.getModuleInitializers(Mod))
5418         EmitTopLevelDecl(D);
5419 
5420       // Visit the submodules of this module.
5421       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
5422                                              SubEnd = Mod->submodule_end();
5423            Sub != SubEnd; ++Sub) {
5424         // Skip explicit children; they need to be explicitly imported to emit
5425         // the initializers.
5426         if ((*Sub)->IsExplicit)
5427           continue;
5428 
5429         if (Visited.insert(*Sub).second)
5430           Stack.push_back(*Sub);
5431       }
5432     }
5433     break;
5434   }
5435 
5436   case Decl::Export:
5437     EmitDeclContext(cast<ExportDecl>(D));
5438     break;
5439 
5440   case Decl::OMPThreadPrivate:
5441     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
5442     break;
5443 
5444   case Decl::OMPAllocate:
5445     break;
5446 
5447   case Decl::OMPDeclareReduction:
5448     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
5449     break;
5450 
5451   case Decl::OMPDeclareMapper:
5452     EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
5453     break;
5454 
5455   case Decl::OMPRequires:
5456     EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
5457     break;
5458 
5459   default:
5460     // Make sure we handled everything we should, every other kind is a
5461     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
5462     // function. Need to recode Decl::Kind to do that easily.
5463     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
5464     break;
5465   }
5466 }
5467 
5468 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
5469   // Do we need to generate coverage mapping?
5470   if (!CodeGenOpts.CoverageMapping)
5471     return;
5472   switch (D->getKind()) {
5473   case Decl::CXXConversion:
5474   case Decl::CXXMethod:
5475   case Decl::Function:
5476   case Decl::ObjCMethod:
5477   case Decl::CXXConstructor:
5478   case Decl::CXXDestructor: {
5479     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
5480       return;
5481     SourceManager &SM = getContext().getSourceManager();
5482     if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
5483       return;
5484     auto I = DeferredEmptyCoverageMappingDecls.find(D);
5485     if (I == DeferredEmptyCoverageMappingDecls.end())
5486       DeferredEmptyCoverageMappingDecls[D] = true;
5487     break;
5488   }
5489   default:
5490     break;
5491   };
5492 }
5493 
5494 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
5495   // Do we need to generate coverage mapping?
5496   if (!CodeGenOpts.CoverageMapping)
5497     return;
5498   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
5499     if (Fn->isTemplateInstantiation())
5500       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
5501   }
5502   auto I = DeferredEmptyCoverageMappingDecls.find(D);
5503   if (I == DeferredEmptyCoverageMappingDecls.end())
5504     DeferredEmptyCoverageMappingDecls[D] = false;
5505   else
5506     I->second = false;
5507 }
5508 
5509 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
5510   // We call takeVector() here to avoid use-after-free.
5511   // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
5512   // we deserialize function bodies to emit coverage info for them, and that
5513   // deserializes more declarations. How should we handle that case?
5514   for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
5515     if (!Entry.second)
5516       continue;
5517     const Decl *D = Entry.first;
5518     switch (D->getKind()) {
5519     case Decl::CXXConversion:
5520     case Decl::CXXMethod:
5521     case Decl::Function:
5522     case Decl::ObjCMethod: {
5523       CodeGenPGO PGO(*this);
5524       GlobalDecl GD(cast<FunctionDecl>(D));
5525       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5526                                   getFunctionLinkage(GD));
5527       break;
5528     }
5529     case Decl::CXXConstructor: {
5530       CodeGenPGO PGO(*this);
5531       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
5532       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5533                                   getFunctionLinkage(GD));
5534       break;
5535     }
5536     case Decl::CXXDestructor: {
5537       CodeGenPGO PGO(*this);
5538       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
5539       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5540                                   getFunctionLinkage(GD));
5541       break;
5542     }
5543     default:
5544       break;
5545     };
5546   }
5547 }
5548 
5549 /// Turns the given pointer into a constant.
5550 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
5551                                           const void *Ptr) {
5552   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
5553   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
5554   return llvm::ConstantInt::get(i64, PtrInt);
5555 }
5556 
5557 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
5558                                    llvm::NamedMDNode *&GlobalMetadata,
5559                                    GlobalDecl D,
5560                                    llvm::GlobalValue *Addr) {
5561   if (!GlobalMetadata)
5562     GlobalMetadata =
5563       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
5564 
5565   // TODO: should we report variant information for ctors/dtors?
5566   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
5567                            llvm::ConstantAsMetadata::get(GetPointerConstant(
5568                                CGM.getLLVMContext(), D.getDecl()))};
5569   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
5570 }
5571 
5572 /// For each function which is declared within an extern "C" region and marked
5573 /// as 'used', but has internal linkage, create an alias from the unmangled
5574 /// name to the mangled name if possible. People expect to be able to refer
5575 /// to such functions with an unmangled name from inline assembly within the
5576 /// same translation unit.
5577 void CodeGenModule::EmitStaticExternCAliases() {
5578   if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
5579     return;
5580   for (auto &I : StaticExternCValues) {
5581     IdentifierInfo *Name = I.first;
5582     llvm::GlobalValue *Val = I.second;
5583     if (Val && !getModule().getNamedValue(Name->getName()))
5584       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
5585   }
5586 }
5587 
5588 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
5589                                              GlobalDecl &Result) const {
5590   auto Res = Manglings.find(MangledName);
5591   if (Res == Manglings.end())
5592     return false;
5593   Result = Res->getValue();
5594   return true;
5595 }
5596 
5597 /// Emits metadata nodes associating all the global values in the
5598 /// current module with the Decls they came from.  This is useful for
5599 /// projects using IR gen as a subroutine.
5600 ///
5601 /// Since there's currently no way to associate an MDNode directly
5602 /// with an llvm::GlobalValue, we create a global named metadata
5603 /// with the name 'clang.global.decl.ptrs'.
5604 void CodeGenModule::EmitDeclMetadata() {
5605   llvm::NamedMDNode *GlobalMetadata = nullptr;
5606 
5607   for (auto &I : MangledDeclNames) {
5608     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
5609     // Some mangled names don't necessarily have an associated GlobalValue
5610     // in this module, e.g. if we mangled it for DebugInfo.
5611     if (Addr)
5612       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
5613   }
5614 }
5615 
5616 /// Emits metadata nodes for all the local variables in the current
5617 /// function.
5618 void CodeGenFunction::EmitDeclMetadata() {
5619   if (LocalDeclMap.empty()) return;
5620 
5621   llvm::LLVMContext &Context = getLLVMContext();
5622 
5623   // Find the unique metadata ID for this name.
5624   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
5625 
5626   llvm::NamedMDNode *GlobalMetadata = nullptr;
5627 
5628   for (auto &I : LocalDeclMap) {
5629     const Decl *D = I.first;
5630     llvm::Value *Addr = I.second.getPointer();
5631     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
5632       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
5633       Alloca->setMetadata(
5634           DeclPtrKind, llvm::MDNode::get(
5635                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
5636     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
5637       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
5638       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
5639     }
5640   }
5641 }
5642 
5643 void CodeGenModule::EmitVersionIdentMetadata() {
5644   llvm::NamedMDNode *IdentMetadata =
5645     TheModule.getOrInsertNamedMetadata("llvm.ident");
5646   std::string Version = getClangFullVersion();
5647   llvm::LLVMContext &Ctx = TheModule.getContext();
5648 
5649   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
5650   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
5651 }
5652 
5653 void CodeGenModule::EmitCommandLineMetadata() {
5654   llvm::NamedMDNode *CommandLineMetadata =
5655     TheModule.getOrInsertNamedMetadata("llvm.commandline");
5656   std::string CommandLine = getCodeGenOpts().RecordCommandLine;
5657   llvm::LLVMContext &Ctx = TheModule.getContext();
5658 
5659   llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
5660   CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
5661 }
5662 
5663 void CodeGenModule::EmitTargetMetadata() {
5664   // Warning, new MangledDeclNames may be appended within this loop.
5665   // We rely on MapVector insertions adding new elements to the end
5666   // of the container.
5667   // FIXME: Move this loop into the one target that needs it, and only
5668   // loop over those declarations for which we couldn't emit the target
5669   // metadata when we emitted the declaration.
5670   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
5671     auto Val = *(MangledDeclNames.begin() + I);
5672     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
5673     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
5674     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
5675   }
5676 }
5677 
5678 void CodeGenModule::EmitCoverageFile() {
5679   if (getCodeGenOpts().CoverageDataFile.empty() &&
5680       getCodeGenOpts().CoverageNotesFile.empty())
5681     return;
5682 
5683   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
5684   if (!CUNode)
5685     return;
5686 
5687   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
5688   llvm::LLVMContext &Ctx = TheModule.getContext();
5689   auto *CoverageDataFile =
5690       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
5691   auto *CoverageNotesFile =
5692       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
5693   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5694     llvm::MDNode *CU = CUNode->getOperand(i);
5695     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5696     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
5697   }
5698 }
5699 
5700 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
5701   // Sema has checked that all uuid strings are of the form
5702   // "12345678-1234-1234-1234-1234567890ab".
5703   assert(Uuid.size() == 36);
5704   for (unsigned i = 0; i < 36; ++i) {
5705     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
5706     else                                         assert(isHexDigit(Uuid[i]));
5707   }
5708 
5709   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
5710   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
5711 
5712   llvm::Constant *Field3[8];
5713   for (unsigned Idx = 0; Idx < 8; ++Idx)
5714     Field3[Idx] = llvm::ConstantInt::get(
5715         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
5716 
5717   llvm::Constant *Fields[4] = {
5718     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
5719     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
5720     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
5721     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
5722   };
5723 
5724   return llvm::ConstantStruct::getAnon(Fields);
5725 }
5726 
5727 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
5728                                                        bool ForEH) {
5729   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
5730   // FIXME: should we even be calling this method if RTTI is disabled
5731   // and it's not for EH?
5732   if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
5733     return llvm::Constant::getNullValue(Int8PtrTy);
5734 
5735   if (ForEH && Ty->isObjCObjectPointerType() &&
5736       LangOpts.ObjCRuntime.isGNUFamily())
5737     return ObjCRuntime->GetEHType(Ty);
5738 
5739   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
5740 }
5741 
5742 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
5743   // Do not emit threadprivates in simd-only mode.
5744   if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5745     return;
5746   for (auto RefExpr : D->varlists()) {
5747     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5748     bool PerformInit =
5749         VD->getAnyInitializer() &&
5750         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
5751                                                         /*ForRef=*/false);
5752 
5753     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
5754     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
5755             VD, Addr, RefExpr->getBeginLoc(), PerformInit))
5756       CXXGlobalInits.push_back(InitFunction);
5757   }
5758 }
5759 
5760 llvm::Metadata *
5761 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
5762                                             StringRef Suffix) {
5763   llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
5764   if (InternalId)
5765     return InternalId;
5766 
5767   if (isExternallyVisible(T->getLinkage())) {
5768     std::string OutName;
5769     llvm::raw_string_ostream Out(OutName);
5770     getCXXABI().getMangleContext().mangleTypeName(T, Out);
5771     Out << Suffix;
5772 
5773     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
5774   } else {
5775     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
5776                                            llvm::ArrayRef<llvm::Metadata *>());
5777   }
5778 
5779   return InternalId;
5780 }
5781 
5782 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
5783   return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
5784 }
5785 
5786 llvm::Metadata *
5787 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
5788   return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
5789 }
5790 
5791 // Generalize pointer types to a void pointer with the qualifiers of the
5792 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
5793 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
5794 // 'void *'.
5795 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
5796   if (!Ty->isPointerType())
5797     return Ty;
5798 
5799   return Ctx.getPointerType(
5800       QualType(Ctx.VoidTy).withCVRQualifiers(
5801           Ty->getPointeeType().getCVRQualifiers()));
5802 }
5803 
5804 // Apply type generalization to a FunctionType's return and argument types
5805 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
5806   if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
5807     SmallVector<QualType, 8> GeneralizedParams;
5808     for (auto &Param : FnType->param_types())
5809       GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
5810 
5811     return Ctx.getFunctionType(
5812         GeneralizeType(Ctx, FnType->getReturnType()),
5813         GeneralizedParams, FnType->getExtProtoInfo());
5814   }
5815 
5816   if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
5817     return Ctx.getFunctionNoProtoType(
5818         GeneralizeType(Ctx, FnType->getReturnType()));
5819 
5820   llvm_unreachable("Encountered unknown FunctionType");
5821 }
5822 
5823 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
5824   return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
5825                                       GeneralizedMetadataIdMap, ".generalized");
5826 }
5827 
5828 /// Returns whether this module needs the "all-vtables" type identifier.
5829 bool CodeGenModule::NeedAllVtablesTypeId() const {
5830   // Returns true if at least one of vtable-based CFI checkers is enabled and
5831   // is not in the trapping mode.
5832   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5833            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5834           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5835            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5836           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5837            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5838           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5839            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5840 }
5841 
5842 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
5843                                           CharUnits Offset,
5844                                           const CXXRecordDecl *RD) {
5845   llvm::Metadata *MD =
5846       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
5847   VTable->addTypeMetadata(Offset.getQuantity(), MD);
5848 
5849   if (CodeGenOpts.SanitizeCfiCrossDso)
5850     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
5851       VTable->addTypeMetadata(Offset.getQuantity(),
5852                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
5853 
5854   if (NeedAllVtablesTypeId()) {
5855     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
5856     VTable->addTypeMetadata(Offset.getQuantity(), MD);
5857   }
5858 }
5859 
5860 TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) {
5861   assert(TD != nullptr);
5862   TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
5863 
5864   ParsedAttr.Features.erase(
5865       llvm::remove_if(ParsedAttr.Features,
5866                       [&](const std::string &Feat) {
5867                         return !Target.isValidFeatureName(
5868                             StringRef{Feat}.substr(1));
5869                       }),
5870       ParsedAttr.Features.end());
5871   return ParsedAttr;
5872 }
5873 
5874 
5875 // Fills in the supplied string map with the set of target features for the
5876 // passed in function.
5877 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
5878                                           GlobalDecl GD) {
5879   StringRef TargetCPU = Target.getTargetOpts().CPU;
5880   const FunctionDecl *FD = GD.getDecl()->getAsFunction();
5881   if (const auto *TD = FD->getAttr<TargetAttr>()) {
5882     TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
5883 
5884     // Make a copy of the features as passed on the command line into the
5885     // beginning of the additional features from the function to override.
5886     ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
5887                             Target.getTargetOpts().FeaturesAsWritten.begin(),
5888                             Target.getTargetOpts().FeaturesAsWritten.end());
5889 
5890     if (ParsedAttr.Architecture != "" &&
5891         Target.isValidCPUName(ParsedAttr.Architecture))
5892       TargetCPU = ParsedAttr.Architecture;
5893 
5894     // Now populate the feature map, first with the TargetCPU which is either
5895     // the default or a new one from the target attribute string. Then we'll use
5896     // the passed in features (FeaturesAsWritten) along with the new ones from
5897     // the attribute.
5898     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5899                           ParsedAttr.Features);
5900   } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
5901     llvm::SmallVector<StringRef, 32> FeaturesTmp;
5902     Target.getCPUSpecificCPUDispatchFeatures(
5903         SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
5904     std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
5905     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features);
5906   } else {
5907     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5908                           Target.getTargetOpts().Features);
5909   }
5910 }
5911 
5912 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5913   if (!SanStats)
5914     SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
5915 
5916   return *SanStats;
5917 }
5918 llvm::Value *
5919 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
5920                                                   CodeGenFunction &CGF) {
5921   llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
5922   auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
5923   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5924   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5925                                 "__translate_sampler_initializer"),
5926                                 {C});
5927 }
5928