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