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