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