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