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