TargetLoweringObjectFileImpl.cpp 32 KB

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