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