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