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