TargetLoweringObjectFileImpl.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. //===-- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info --===//
  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 file implements classes used to handle lowerings specific to common
  11. // object file formats.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/ADT/Triple.h"
  18. #include "llvm/CodeGen/MachineModuleInfoImpls.h"
  19. #include "llvm/IR/Constants.h"
  20. #include "llvm/IR/DataLayout.h"
  21. #include "llvm/IR/DerivedTypes.h"
  22. #include "llvm/IR/Function.h"
  23. #include "llvm/IR/GlobalVariable.h"
  24. #include "llvm/IR/Mangler.h"
  25. #include "llvm/IR/Module.h"
  26. #include "llvm/MC/MCContext.h"
  27. #include "llvm/MC/MCExpr.h"
  28. #include "llvm/MC/MCSectionCOFF.h"
  29. #include "llvm/MC/MCSectionELF.h"
  30. #include "llvm/MC/MCSectionMachO.h"
  31. #include "llvm/MC/MCStreamer.h"
  32. #include "llvm/MC/MCSymbol.h"
  33. #include "llvm/Support/Dwarf.h"
  34. #include "llvm/Support/ELF.h"
  35. #include "llvm/Support/ErrorHandling.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include "llvm/Target/TargetLowering.h"
  38. #include "llvm/Target/TargetMachine.h"
  39. #include "llvm/Target/TargetSubtargetInfo.h"
  40. using namespace llvm;
  41. using namespace dwarf;
  42. //===----------------------------------------------------------------------===//
  43. // ELF
  44. //===----------------------------------------------------------------------===//
  45. MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
  46. const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
  47. MachineModuleInfo *MMI) const {
  48. unsigned Encoding = getPersonalityEncoding();
  49. if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
  50. return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
  51. TM.getSymbol(GV, Mang)->getName());
  52. if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
  53. return TM.getSymbol(GV, Mang);
  54. report_fatal_error("We do not support this DWARF encoding yet!");
  55. }
  56. void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
  57. const TargetMachine &TM,
  58. const MCSymbol *Sym) const {
  59. SmallString<64> NameData("DW.ref.");
  60. NameData += Sym->getName();
  61. MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
  62. Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
  63. Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
  64. StringRef Prefix = ".data.";
  65. NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
  66. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
  67. const MCSection *Sec = getContext().getELFSection(NameData,
  68. ELF::SHT_PROGBITS,
  69. Flags,
  70. SectionKind::getDataRel(),
  71. 0, Label->getName());
  72. unsigned Size = TM.getSubtargetImpl()->getDataLayout()->getPointerSize();
  73. Streamer.SwitchSection(Sec);
  74. Streamer.EmitValueToAlignment(
  75. TM.getSubtargetImpl()->getDataLayout()->getPointerABIAlignment());
  76. Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
  77. const MCExpr *E = MCConstantExpr::Create(Size, getContext());
  78. Streamer.EmitELFSize(Label, E);
  79. Streamer.EmitLabel(Label);
  80. Streamer.EmitSymbolValue(Sym, Size);
  81. }
  82. const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
  83. const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
  84. const TargetMachine &TM, MachineModuleInfo *MMI,
  85. MCStreamer &Streamer) const {
  86. if (Encoding & dwarf::DW_EH_PE_indirect) {
  87. MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
  88. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
  89. // Add information about the stub reference to ELFMMI so that the stub
  90. // gets emitted by the asmprinter.
  91. MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
  92. if (!StubSym.getPointer()) {
  93. MCSymbol *Sym = TM.getSymbol(GV, Mang);
  94. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  95. }
  96. return TargetLoweringObjectFile::
  97. getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
  98. Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
  99. }
  100. return TargetLoweringObjectFile::
  101. getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
  102. }
  103. static SectionKind
  104. getELFKindForNamedSection(StringRef Name, SectionKind K) {
  105. // N.B.: The defaults used in here are no the same ones used in MC.
  106. // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
  107. // both gas and MC will produce a section with no flags. Given
  108. // section(".eh_frame") gcc will produce:
  109. //
  110. // .section .eh_frame,"a",@progbits
  111. if (Name.empty() || Name[0] != '.') return K;
  112. // Some lame default implementation based on some magic section names.
  113. if (Name == ".bss" ||
  114. Name.startswith(".bss.") ||
  115. Name.startswith(".gnu.linkonce.b.") ||
  116. Name.startswith(".llvm.linkonce.b.") ||
  117. Name == ".sbss" ||
  118. Name.startswith(".sbss.") ||
  119. Name.startswith(".gnu.linkonce.sb.") ||
  120. Name.startswith(".llvm.linkonce.sb."))
  121. return SectionKind::getBSS();
  122. if (Name == ".tdata" ||
  123. Name.startswith(".tdata.") ||
  124. Name.startswith(".gnu.linkonce.td.") ||
  125. Name.startswith(".llvm.linkonce.td."))
  126. return SectionKind::getThreadData();
  127. if (Name == ".tbss" ||
  128. Name.startswith(".tbss.") ||
  129. Name.startswith(".gnu.linkonce.tb.") ||
  130. Name.startswith(".llvm.linkonce.tb."))
  131. return SectionKind::getThreadBSS();
  132. return K;
  133. }
  134. static unsigned getELFSectionType(StringRef Name, SectionKind K) {
  135. if (Name == ".init_array")
  136. return ELF::SHT_INIT_ARRAY;
  137. if (Name == ".fini_array")
  138. return ELF::SHT_FINI_ARRAY;
  139. if (Name == ".preinit_array")
  140. return ELF::SHT_PREINIT_ARRAY;
  141. if (K.isBSS() || K.isThreadBSS())
  142. return ELF::SHT_NOBITS;
  143. return ELF::SHT_PROGBITS;
  144. }
  145. static unsigned
  146. getELFSectionFlags(SectionKind K) {
  147. unsigned Flags = 0;
  148. if (!K.isMetadata())
  149. Flags |= ELF::SHF_ALLOC;
  150. if (K.isText())
  151. Flags |= ELF::SHF_EXECINSTR;
  152. if (K.isWriteable())
  153. Flags |= ELF::SHF_WRITE;
  154. if (K.isThreadLocal())
  155. Flags |= ELF::SHF_TLS;
  156. // K.isMergeableConst() is left out to honour PR4650
  157. if (K.isMergeableCString() || K.isMergeableConst4() ||
  158. K.isMergeableConst8() || K.isMergeableConst16())
  159. Flags |= ELF::SHF_MERGE;
  160. if (K.isMergeableCString())
  161. Flags |= ELF::SHF_STRINGS;
  162. return Flags;
  163. }
  164. static const Comdat *getELFComdat(const GlobalValue *GV) {
  165. const Comdat *C = GV->getComdat();
  166. if (!C)
  167. return nullptr;
  168. if (C->getSelectionKind() != Comdat::Any)
  169. report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
  170. C->getName() + "' cannot be lowered.");
  171. return C;
  172. }
  173. const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
  174. const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
  175. const TargetMachine &TM) const {
  176. StringRef SectionName = GV->getSection();
  177. // Infer section flags from the section name if we can.
  178. Kind = getELFKindForNamedSection(SectionName, Kind);
  179. StringRef Group = "";
  180. unsigned Flags = getELFSectionFlags(Kind);
  181. if (const Comdat *C = getELFComdat(GV)) {
  182. Group = C->getName();
  183. Flags |= ELF::SHF_GROUP;
  184. }
  185. return getContext().getELFSection(SectionName,
  186. getELFSectionType(SectionName, Kind), Flags,
  187. Kind, /*EntrySize=*/0, Group);
  188. }
  189. /// getSectionPrefixForGlobal - Return the section prefix name used by options
  190. /// FunctionsSections and DataSections.
  191. static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
  192. if (Kind.isText()) return ".text.";
  193. if (Kind.isReadOnly()) return ".rodata.";
  194. if (Kind.isBSS()) return ".bss.";
  195. if (Kind.isThreadData()) return ".tdata.";
  196. if (Kind.isThreadBSS()) return ".tbss.";
  197. if (Kind.isDataNoRel()) return ".data.";
  198. if (Kind.isDataRelLocal()) return ".data.rel.local.";
  199. if (Kind.isDataRel()) return ".data.rel.";
  200. if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
  201. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  202. return ".data.rel.ro.";
  203. }
  204. const MCSection *TargetLoweringObjectFileELF::
  205. SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
  206. Mangler &Mang, const TargetMachine &TM) const {
  207. // If we have -ffunction-section or -fdata-section then we should emit the
  208. // global value to a uniqued section specifically for it.
  209. bool EmitUniquedSection;
  210. if (Kind.isText())
  211. EmitUniquedSection = TM.getFunctionSections();
  212. else
  213. EmitUniquedSection = TM.getDataSections();
  214. // If this global is linkonce/weak and the target handles this by emitting it
  215. // into a 'uniqued' section name, create and return the section now.
  216. if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
  217. !Kind.isCommon()) {
  218. StringRef Prefix = getSectionPrefixForGlobal(Kind);
  219. SmallString<128> Name(Prefix);
  220. TM.getNameWithPrefix(Name, GV, Mang, true);
  221. StringRef Group = "";
  222. unsigned Flags = getELFSectionFlags(Kind);
  223. if (GV->isWeakForLinker() || GV->hasComdat()) {
  224. if (const Comdat *C = getELFComdat(GV))
  225. Group = C->getName();
  226. else
  227. Group = Name.substr(Prefix.size());
  228. Flags |= ELF::SHF_GROUP;
  229. }
  230. return getContext().getELFSection(Name.str(),
  231. getELFSectionType(Name.str(), Kind),
  232. Flags, Kind, 0, Group);
  233. }
  234. if (Kind.isText()) return TextSection;
  235. if (Kind.isMergeable1ByteCString() ||
  236. Kind.isMergeable2ByteCString() ||
  237. Kind.isMergeable4ByteCString()) {
  238. // We also need alignment here.
  239. // FIXME: this is getting the alignment of the character, not the
  240. // alignment of the global!
  241. unsigned Align =
  242. TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
  243. cast<GlobalVariable>(GV));
  244. const char *SizeSpec = ".rodata.str1.";
  245. if (Kind.isMergeable2ByteCString())
  246. SizeSpec = ".rodata.str2.";
  247. else if (Kind.isMergeable4ByteCString())
  248. SizeSpec = ".rodata.str4.";
  249. else
  250. assert(Kind.isMergeable1ByteCString() && "unknown string width");
  251. std::string Name = SizeSpec + utostr(Align);
  252. return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
  253. ELF::SHF_ALLOC |
  254. ELF::SHF_MERGE |
  255. ELF::SHF_STRINGS,
  256. Kind);
  257. }
  258. if (Kind.isMergeableConst()) {
  259. if (Kind.isMergeableConst4() && MergeableConst4Section)
  260. return MergeableConst4Section;
  261. if (Kind.isMergeableConst8() && MergeableConst8Section)
  262. return MergeableConst8Section;
  263. if (Kind.isMergeableConst16() && MergeableConst16Section)
  264. return MergeableConst16Section;
  265. return ReadOnlySection; // .const
  266. }
  267. if (Kind.isReadOnly()) return ReadOnlySection;
  268. if (Kind.isThreadData()) return TLSDataSection;
  269. if (Kind.isThreadBSS()) return TLSBSSSection;
  270. // Note: we claim that common symbols are put in BSSSection, but they are
  271. // really emitted with the magic .comm directive, which creates a symbol table
  272. // entry but not a section.
  273. if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
  274. if (Kind.isDataNoRel()) return DataSection;
  275. if (Kind.isDataRelLocal()) return DataRelLocalSection;
  276. if (Kind.isDataRel()) return DataRelSection;
  277. if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
  278. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  279. return DataRelROSection;
  280. }
  281. /// getSectionForConstant - Given a mergeable constant with the
  282. /// specified size and relocation information, return a section that it
  283. /// should be placed in.
  284. const MCSection *
  285. TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
  286. const Constant *C) const {
  287. if (Kind.isMergeableConst4() && MergeableConst4Section)
  288. return MergeableConst4Section;
  289. if (Kind.isMergeableConst8() && MergeableConst8Section)
  290. return MergeableConst8Section;
  291. if (Kind.isMergeableConst16() && MergeableConst16Section)
  292. return MergeableConst16Section;
  293. if (Kind.isReadOnly())
  294. return ReadOnlySection;
  295. if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
  296. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  297. return DataRelROSection;
  298. }
  299. static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
  300. bool UseInitArray,
  301. bool IsCtor,
  302. unsigned Priority,
  303. const MCSymbol *KeySym) {
  304. std::string Name;
  305. unsigned Type;
  306. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
  307. SectionKind Kind = SectionKind::getDataRel();
  308. StringRef COMDAT = KeySym ? KeySym->getName() : "";
  309. if (KeySym)
  310. Flags |= ELF::SHF_GROUP;
  311. if (UseInitArray) {
  312. if (IsCtor) {
  313. Type = ELF::SHT_INIT_ARRAY;
  314. Name = ".init_array";
  315. } else {
  316. Type = ELF::SHT_FINI_ARRAY;
  317. Name = ".fini_array";
  318. }
  319. if (Priority != 65535) {
  320. Name += '.';
  321. Name += utostr(Priority);
  322. }
  323. } else {
  324. // The default scheme is .ctor / .dtor, so we have to invert the priority
  325. // numbering.
  326. if (IsCtor)
  327. Name = ".ctors";
  328. else
  329. Name = ".dtors";
  330. if (Priority != 65535) {
  331. Name += '.';
  332. Name += utostr(65535 - Priority);
  333. }
  334. Type = ELF::SHT_PROGBITS;
  335. }
  336. return Ctx.getELFSection(Name, Type, Flags, Kind, 0, COMDAT);
  337. }
  338. const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
  339. unsigned Priority, const MCSymbol *KeySym) const {
  340. return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
  341. KeySym);
  342. }
  343. const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
  344. unsigned Priority, const MCSymbol *KeySym) const {
  345. return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
  346. KeySym);
  347. }
  348. void
  349. TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
  350. UseInitArray = UseInitArray_;
  351. if (!UseInitArray)
  352. return;
  353. StaticCtorSection =
  354. getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
  355. ELF::SHF_WRITE |
  356. ELF::SHF_ALLOC,
  357. SectionKind::getDataRel());
  358. StaticDtorSection =
  359. getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
  360. ELF::SHF_WRITE |
  361. ELF::SHF_ALLOC,
  362. SectionKind::getDataRel());
  363. }
  364. //===----------------------------------------------------------------------===//
  365. // MachO
  366. //===----------------------------------------------------------------------===//
  367. /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
  368. /// option string. Returns StringRef() if the option does not specify a library.
  369. StringRef TargetLoweringObjectFileMachO::
  370. getDepLibFromLinkerOpt(StringRef LinkerOption) const {
  371. const char *LibCmd = "-l";
  372. if (LinkerOption.startswith(LibCmd))
  373. return LinkerOption.substr(strlen(LibCmd));
  374. return StringRef();
  375. }
  376. /// emitModuleFlags - Perform code emission for module flags.
  377. void TargetLoweringObjectFileMachO::
  378. emitModuleFlags(MCStreamer &Streamer,
  379. ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
  380. Mangler &Mang, const TargetMachine &TM) const {
  381. unsigned VersionVal = 0;
  382. unsigned ImageInfoFlags = 0;
  383. MDNode *LinkerOptions = nullptr;
  384. StringRef SectionVal;
  385. for (ArrayRef<Module::ModuleFlagEntry>::iterator
  386. i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
  387. const Module::ModuleFlagEntry &MFE = *i;
  388. // Ignore flags with 'Require' behavior.
  389. if (MFE.Behavior == Module::Require)
  390. continue;
  391. StringRef Key = MFE.Key->getString();
  392. Metadata *Val = MFE.Val;
  393. if (Key == "Objective-C Image Info Version") {
  394. VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
  395. } else if (Key == "Objective-C Garbage Collection" ||
  396. Key == "Objective-C GC Only" ||
  397. Key == "Objective-C Is Simulated" ||
  398. Key == "Objective-C Image Swift Version") {
  399. ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
  400. } else if (Key == "Objective-C Image Info Section") {
  401. SectionVal = cast<MDString>(Val)->getString();
  402. } else if (Key == "Linker Options") {
  403. LinkerOptions = cast<MDNode>(Val);
  404. }
  405. }
  406. // Emit the linker options if present.
  407. if (LinkerOptions) {
  408. for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
  409. MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
  410. SmallVector<std::string, 4> StrOptions;
  411. // Convert to strings.
  412. for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
  413. MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
  414. StrOptions.push_back(MDOption->getString());
  415. }
  416. Streamer.EmitLinkerOptions(StrOptions);
  417. }
  418. }
  419. // The section is mandatory. If we don't have it, then we don't have GC info.
  420. if (SectionVal.empty()) return;
  421. StringRef Segment, Section;
  422. unsigned TAA = 0, StubSize = 0;
  423. bool TAAParsed;
  424. std::string ErrorCode =
  425. MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
  426. TAA, TAAParsed, StubSize);
  427. if (!ErrorCode.empty())
  428. // If invalid, report the error with report_fatal_error.
  429. report_fatal_error("Invalid section specifier '" + Section + "': " +
  430. ErrorCode + ".");
  431. // Get the section.
  432. const MCSectionMachO *S =
  433. getContext().getMachOSection(Segment, Section, TAA, StubSize,
  434. SectionKind::getDataNoRel());
  435. Streamer.SwitchSection(S);
  436. Streamer.EmitLabel(getContext().
  437. GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
  438. Streamer.EmitIntValue(VersionVal, 4);
  439. Streamer.EmitIntValue(ImageInfoFlags, 4);
  440. Streamer.AddBlankLine();
  441. }
  442. static void checkMachOComdat(const GlobalValue *GV) {
  443. const Comdat *C = GV->getComdat();
  444. if (!C)
  445. return;
  446. report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
  447. "' cannot be lowered.");
  448. }
  449. const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
  450. const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
  451. const TargetMachine &TM) const {
  452. // Parse the section specifier and create it if valid.
  453. StringRef Segment, Section;
  454. unsigned TAA = 0, StubSize = 0;
  455. bool TAAParsed;
  456. checkMachOComdat(GV);
  457. std::string ErrorCode =
  458. MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
  459. TAA, TAAParsed, StubSize);
  460. if (!ErrorCode.empty()) {
  461. // If invalid, report the error with report_fatal_error.
  462. report_fatal_error("Global variable '" + GV->getName() +
  463. "' has an invalid section specifier '" +
  464. GV->getSection() + "': " + ErrorCode + ".");
  465. }
  466. // Get the section.
  467. const MCSectionMachO *S =
  468. getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
  469. // If TAA wasn't set by ParseSectionSpecifier() above,
  470. // use the value returned by getMachOSection() as a default.
  471. if (!TAAParsed)
  472. TAA = S->getTypeAndAttributes();
  473. // Okay, now that we got the section, verify that the TAA & StubSize agree.
  474. // If the user declared multiple globals with different section flags, we need
  475. // to reject it here.
  476. if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
  477. // If invalid, report the error with report_fatal_error.
  478. report_fatal_error("Global variable '" + GV->getName() +
  479. "' section type or attributes does not match previous"
  480. " section specifier");
  481. }
  482. return S;
  483. }
  484. bool TargetLoweringObjectFileMachO::isSectionAtomizableBySymbols(
  485. const MCSection &Section) const {
  486. const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
  487. // Sections holding 1 byte strings are atomized based on the data
  488. // they contain.
  489. // Sections holding 2 byte strings require symbols in order to be
  490. // atomized.
  491. // There is no dedicated section for 4 byte strings.
  492. if (SMO.getKind().isMergeable1ByteCString())
  493. return false;
  494. if (SMO.getSegmentName() == "__TEXT" &&
  495. SMO.getSectionName() == "__objc_classname" &&
  496. SMO.getType() == MachO::S_CSTRING_LITERALS)
  497. return false;
  498. if (SMO.getSegmentName() == "__TEXT" &&
  499. SMO.getSectionName() == "__objc_methname" &&
  500. SMO.getType() == MachO::S_CSTRING_LITERALS)
  501. return false;
  502. if (SMO.getSegmentName() == "__TEXT" &&
  503. SMO.getSectionName() == "__objc_methtype" &&
  504. SMO.getType() == MachO::S_CSTRING_LITERALS)
  505. return false;
  506. if (SMO.getSegmentName() == "__DATA" &&
  507. SMO.getSectionName() == "__cfstring")
  508. return false;
  509. // no_dead_strip sections are not atomized in practice.
  510. if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
  511. return false;
  512. switch (SMO.getType()) {
  513. default:
  514. return true;
  515. // These sections are atomized at the element boundaries without using
  516. // symbols.
  517. case MachO::S_4BYTE_LITERALS:
  518. case MachO::S_8BYTE_LITERALS:
  519. case MachO::S_16BYTE_LITERALS:
  520. case MachO::S_LITERAL_POINTERS:
  521. case MachO::S_NON_LAZY_SYMBOL_POINTERS:
  522. case MachO::S_LAZY_SYMBOL_POINTERS:
  523. case MachO::S_MOD_INIT_FUNC_POINTERS:
  524. case MachO::S_MOD_TERM_FUNC_POINTERS:
  525. case MachO::S_INTERPOSING:
  526. return false;
  527. }
  528. }
  529. const MCSection *TargetLoweringObjectFileMachO::
  530. SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
  531. Mangler &Mang, const TargetMachine &TM) const {
  532. checkMachOComdat(GV);
  533. // Handle thread local data.
  534. if (Kind.isThreadBSS()) return TLSBSSSection;
  535. if (Kind.isThreadData()) return TLSDataSection;
  536. if (Kind.isText())
  537. return GV->isWeakForLinker() ? TextCoalSection : TextSection;
  538. // If this is weak/linkonce, put this in a coalescable section, either in text
  539. // or data depending on if it is writable.
  540. if (GV->isWeakForLinker()) {
  541. if (Kind.isReadOnly())
  542. return ConstTextCoalSection;
  543. return DataCoalSection;
  544. }
  545. // FIXME: Alignment check should be handled by section classifier.
  546. if (Kind.isMergeable1ByteCString() &&
  547. TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
  548. cast<GlobalVariable>(GV)) < 32)
  549. return CStringSection;
  550. // Do not put 16-bit arrays in the UString section if they have an
  551. // externally visible label, this runs into issues with certain linker
  552. // versions.
  553. if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
  554. TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
  555. cast<GlobalVariable>(GV)) < 32)
  556. return UStringSection;
  557. // With MachO only variables whose corresponding symbol starts with 'l' or
  558. // 'L' can be merged, so we only try merging GVs with private linkage.
  559. if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
  560. if (Kind.isMergeableConst4())
  561. return FourByteConstantSection;
  562. if (Kind.isMergeableConst8())
  563. return EightByteConstantSection;
  564. if (Kind.isMergeableConst16())
  565. return SixteenByteConstantSection;
  566. }
  567. // Otherwise, if it is readonly, but not something we can specially optimize,
  568. // just drop it in .const.
  569. if (Kind.isReadOnly())
  570. return ReadOnlySection;
  571. // If this is marked const, put it into a const section. But if the dynamic
  572. // linker needs to write to it, put it in the data segment.
  573. if (Kind.isReadOnlyWithRel())
  574. return ConstDataSection;
  575. // Put zero initialized globals with strong external linkage in the
  576. // DATA, __common section with the .zerofill directive.
  577. if (Kind.isBSSExtern())
  578. return DataCommonSection;
  579. // Put zero initialized globals with local linkage in __DATA,__bss directive
  580. // with the .zerofill directive (aka .lcomm).
  581. if (Kind.isBSSLocal())
  582. return DataBSSSection;
  583. // Otherwise, just drop the variable in the normal data section.
  584. return DataSection;
  585. }
  586. const MCSection *
  587. TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
  588. const Constant *C) const {
  589. // If this constant requires a relocation, we have to put it in the data
  590. // segment, not in the text segment.
  591. if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
  592. return ConstDataSection;
  593. if (Kind.isMergeableConst4())
  594. return FourByteConstantSection;
  595. if (Kind.isMergeableConst8())
  596. return EightByteConstantSection;
  597. if (Kind.isMergeableConst16())
  598. return SixteenByteConstantSection;
  599. return ReadOnlySection; // .const
  600. }
  601. const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
  602. const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
  603. const TargetMachine &TM, MachineModuleInfo *MMI,
  604. MCStreamer &Streamer) const {
  605. // The mach-o version of this method defaults to returning a stub reference.
  606. if (Encoding & DW_EH_PE_indirect) {
  607. MachineModuleInfoMachO &MachOMMI =
  608. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  609. MCSymbol *SSym =
  610. getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
  611. // Add information about the stub reference to MachOMMI so that the stub
  612. // gets emitted by the asmprinter.
  613. MachineModuleInfoImpl::StubValueTy &StubSym =
  614. GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
  615. MachOMMI.getGVStubEntry(SSym);
  616. if (!StubSym.getPointer()) {
  617. MCSymbol *Sym = TM.getSymbol(GV, Mang);
  618. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  619. }
  620. return TargetLoweringObjectFile::
  621. getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
  622. Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
  623. }
  624. return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
  625. TM, MMI, Streamer);
  626. }
  627. MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
  628. const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
  629. MachineModuleInfo *MMI) const {
  630. // The mach-o version of this method defaults to returning a stub reference.
  631. MachineModuleInfoMachO &MachOMMI =
  632. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  633. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
  634. // Add information about the stub reference to MachOMMI so that the stub
  635. // gets emitted by the asmprinter.
  636. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
  637. if (!StubSym.getPointer()) {
  638. MCSymbol *Sym = TM.getSymbol(GV, Mang);
  639. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  640. }
  641. return SSym;
  642. }
  643. //===----------------------------------------------------------------------===//
  644. // COFF
  645. //===----------------------------------------------------------------------===//
  646. static unsigned
  647. getCOFFSectionFlags(SectionKind K) {
  648. unsigned Flags = 0;
  649. if (K.isMetadata())
  650. Flags |=
  651. COFF::IMAGE_SCN_MEM_DISCARDABLE;
  652. else if (K.isText())
  653. Flags |=
  654. COFF::IMAGE_SCN_MEM_EXECUTE |
  655. COFF::IMAGE_SCN_MEM_READ |
  656. COFF::IMAGE_SCN_CNT_CODE;
  657. else if (K.isBSS())
  658. Flags |=
  659. COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
  660. COFF::IMAGE_SCN_MEM_READ |
  661. COFF::IMAGE_SCN_MEM_WRITE;
  662. else if (K.isThreadLocal())
  663. Flags |=
  664. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  665. COFF::IMAGE_SCN_MEM_READ |
  666. COFF::IMAGE_SCN_MEM_WRITE;
  667. else if (K.isReadOnly() || K.isReadOnlyWithRel())
  668. Flags |=
  669. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  670. COFF::IMAGE_SCN_MEM_READ;
  671. else if (K.isWriteable())
  672. Flags |=
  673. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  674. COFF::IMAGE_SCN_MEM_READ |
  675. COFF::IMAGE_SCN_MEM_WRITE;
  676. return Flags;
  677. }
  678. static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
  679. const Comdat *C = GV->getComdat();
  680. assert(C && "expected GV to have a Comdat!");
  681. StringRef ComdatGVName = C->getName();
  682. const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
  683. if (!ComdatGV)
  684. report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
  685. "' does not exist.");
  686. if (ComdatGV->getComdat() != C)
  687. report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
  688. "' is not a key for its COMDAT.");
  689. return ComdatGV;
  690. }
  691. static int getSelectionForCOFF(const GlobalValue *GV) {
  692. if (const Comdat *C = GV->getComdat()) {
  693. const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
  694. if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
  695. ComdatKey = GA->getBaseObject();
  696. if (ComdatKey == GV) {
  697. switch (C->getSelectionKind()) {
  698. case Comdat::Any:
  699. return COFF::IMAGE_COMDAT_SELECT_ANY;
  700. case Comdat::ExactMatch:
  701. return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
  702. case Comdat::Largest:
  703. return COFF::IMAGE_COMDAT_SELECT_LARGEST;
  704. case Comdat::NoDuplicates:
  705. return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
  706. case Comdat::SameSize:
  707. return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
  708. }
  709. } else {
  710. return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
  711. }
  712. } else if (GV->isWeakForLinker()) {
  713. return COFF::IMAGE_COMDAT_SELECT_ANY;
  714. }
  715. return 0;
  716. }
  717. const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
  718. const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
  719. const TargetMachine &TM) const {
  720. int Selection = 0;
  721. unsigned Characteristics = getCOFFSectionFlags(Kind);
  722. StringRef Name = GV->getSection();
  723. StringRef COMDATSymName = "";
  724. if ((GV->isWeakForLinker() || GV->hasComdat()) && !Kind.isCommon()) {
  725. Selection = getSelectionForCOFF(GV);
  726. const GlobalValue *ComdatGV;
  727. if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
  728. ComdatGV = getComdatGVForCOFF(GV);
  729. else
  730. ComdatGV = GV;
  731. if (!ComdatGV->hasPrivateLinkage()) {
  732. MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
  733. COMDATSymName = Sym->getName();
  734. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  735. } else {
  736. Selection = 0;
  737. }
  738. }
  739. return getContext().getCOFFSection(Name,
  740. Characteristics,
  741. Kind,
  742. COMDATSymName,
  743. Selection);
  744. }
  745. static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
  746. if (Kind.isText())
  747. return ".text";
  748. if (Kind.isBSS())
  749. return ".bss";
  750. if (Kind.isThreadLocal())
  751. return ".tls$";
  752. if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
  753. return ".rdata";
  754. return ".data";
  755. }
  756. const MCSection *TargetLoweringObjectFileCOFF::
  757. SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
  758. Mangler &Mang, const TargetMachine &TM) const {
  759. // If we have -ffunction-sections then we should emit the global value to a
  760. // uniqued section specifically for it.
  761. bool EmitUniquedSection;
  762. if (Kind.isText())
  763. EmitUniquedSection = TM.getFunctionSections();
  764. else
  765. EmitUniquedSection = TM.getDataSections();
  766. // If this global is linkonce/weak and the target handles this by emitting it
  767. // into a 'uniqued' section name, create and return the section now.
  768. // Section names depend on the name of the symbol which is not feasible if the
  769. // symbol has private linkage.
  770. if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
  771. !Kind.isCommon()) {
  772. const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
  773. unsigned Characteristics = getCOFFSectionFlags(Kind);
  774. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  775. int Selection = getSelectionForCOFF(GV);
  776. if (!Selection)
  777. Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
  778. const GlobalValue *ComdatGV;
  779. if (GV->hasComdat())
  780. ComdatGV = getComdatGVForCOFF(GV);
  781. else
  782. ComdatGV = GV;
  783. if (!ComdatGV->hasPrivateLinkage()) {
  784. MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
  785. StringRef COMDATSymName = Sym->getName();
  786. return getContext().getCOFFSection(Name, Characteristics, Kind,
  787. COMDATSymName, Selection);
  788. }
  789. }
  790. if (Kind.isText())
  791. return TextSection;
  792. if (Kind.isThreadLocal())
  793. return TLSDataSection;
  794. if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
  795. return ReadOnlySection;
  796. // Note: we claim that common symbols are put in BSSSection, but they are
  797. // really emitted with the magic .comm directive, which creates a symbol table
  798. // entry but not a section.
  799. if (Kind.isBSS() || Kind.isCommon())
  800. return BSSSection;
  801. return DataSection;
  802. }
  803. StringRef TargetLoweringObjectFileCOFF::
  804. getDepLibFromLinkerOpt(StringRef LinkerOption) const {
  805. const char *LibCmd = "/DEFAULTLIB:";
  806. if (LinkerOption.startswith(LibCmd))
  807. return LinkerOption.substr(strlen(LibCmd));
  808. return StringRef();
  809. }
  810. void TargetLoweringObjectFileCOFF::
  811. emitModuleFlags(MCStreamer &Streamer,
  812. ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
  813. Mangler &Mang, const TargetMachine &TM) const {
  814. MDNode *LinkerOptions = nullptr;
  815. // Look for the "Linker Options" flag, since it's the only one we support.
  816. for (ArrayRef<Module::ModuleFlagEntry>::iterator
  817. i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
  818. const Module::ModuleFlagEntry &MFE = *i;
  819. StringRef Key = MFE.Key->getString();
  820. Metadata *Val = MFE.Val;
  821. if (Key == "Linker Options") {
  822. LinkerOptions = cast<MDNode>(Val);
  823. break;
  824. }
  825. }
  826. if (!LinkerOptions)
  827. return;
  828. // Emit the linker options to the linker .drectve section. According to the
  829. // spec, this section is a space-separated string containing flags for linker.
  830. const MCSection *Sec = getDrectveSection();
  831. Streamer.SwitchSection(Sec);
  832. for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
  833. MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
  834. for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
  835. MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
  836. StringRef Op = MDOption->getString();
  837. // Lead with a space for consistency with our dllexport implementation.
  838. std::string Escaped(" ");
  839. if (Op.find(" ") != StringRef::npos) {
  840. // The PE-COFF spec says args with spaces must be quoted. It doesn't say
  841. // how to escape quotes, but it probably uses this algorithm:
  842. // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
  843. // FIXME: Reuse escaping code from Support/Windows/Program.inc
  844. Escaped.push_back('\"');
  845. Escaped.append(Op);
  846. Escaped.push_back('\"');
  847. } else {
  848. Escaped.append(Op);
  849. }
  850. Streamer.EmitBytes(Escaped);
  851. }
  852. }
  853. }
  854. const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
  855. unsigned Priority, const MCSymbol *KeySym) const {
  856. return getContext().getAssociativeCOFFSection(
  857. cast<MCSectionCOFF>(StaticCtorSection), KeySym);
  858. }
  859. const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
  860. unsigned Priority, const MCSymbol *KeySym) const {
  861. return getContext().getAssociativeCOFFSection(
  862. cast<MCSectionCOFF>(StaticDtorSection), KeySym);
  863. }