TargetLoweringObjectFileImpl.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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/MCAsmInfo.h"
  27. #include "llvm/MC/MCContext.h"
  28. #include "llvm/MC/MCExpr.h"
  29. #include "llvm/MC/MCSectionCOFF.h"
  30. #include "llvm/MC/MCSectionELF.h"
  31. #include "llvm/MC/MCSectionMachO.h"
  32. #include "llvm/MC/MCStreamer.h"
  33. #include "llvm/MC/MCSymbolELF.h"
  34. #include "llvm/MC/MCValue.h"
  35. #include "llvm/ProfileData/InstrProf.h"
  36. #include "llvm/Support/COFF.h"
  37. #include "llvm/Support/Dwarf.h"
  38. #include "llvm/Support/ELF.h"
  39. #include "llvm/Support/ErrorHandling.h"
  40. #include "llvm/Support/raw_ostream.h"
  41. #include "llvm/Target/TargetLowering.h"
  42. #include "llvm/Target/TargetMachine.h"
  43. #include "llvm/Target/TargetSubtargetInfo.h"
  44. using namespace llvm;
  45. using namespace dwarf;
  46. //===----------------------------------------------------------------------===//
  47. // ELF
  48. //===----------------------------------------------------------------------===//
  49. MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
  50. const GlobalValue *GV, const TargetMachine &TM,
  51. MachineModuleInfo *MMI) const {
  52. unsigned Encoding = getPersonalityEncoding();
  53. if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
  54. return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
  55. TM.getSymbol(GV, getMangler())->getName());
  56. if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
  57. return TM.getSymbol(GV, getMangler());
  58. report_fatal_error("We do not support this DWARF encoding yet!");
  59. }
  60. void TargetLoweringObjectFileELF::emitPersonalityValue(
  61. MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
  62. SmallString<64> NameData("DW.ref.");
  63. NameData += Sym->getName();
  64. MCSymbolELF *Label =
  65. cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
  66. Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
  67. Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
  68. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
  69. MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
  70. ELF::SHT_PROGBITS, Flags, 0);
  71. unsigned Size = DL.getPointerSize();
  72. Streamer.SwitchSection(Sec);
  73. Streamer.EmitValueToAlignment(DL.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, const TargetMachine &TM,
  82. MachineModuleInfo *MMI, MCStreamer &Streamer) const {
  83. if (Encoding & dwarf::DW_EH_PE_indirect) {
  84. MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
  85. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
  86. // Add information about the stub reference to ELFMMI so that the stub
  87. // gets emitted by the asmprinter.
  88. MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
  89. if (!StubSym.getPointer()) {
  90. MCSymbol *Sym = TM.getSymbol(GV, getMangler());
  91. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  92. }
  93. return TargetLoweringObjectFile::
  94. getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
  95. Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
  96. }
  97. return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
  98. MMI, Streamer);
  99. }
  100. static SectionKind
  101. getELFKindForNamedSection(StringRef Name, SectionKind K) {
  102. // N.B.: The defaults used in here are no the same ones used in MC.
  103. // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
  104. // both gas and MC will produce a section with no flags. Given
  105. // section(".eh_frame") gcc will produce:
  106. //
  107. // .section .eh_frame,"a",@progbits
  108. if (Name == getInstrProfCoverageSectionName(false))
  109. return SectionKind::getMetadata();
  110. if (Name.empty() || Name[0] != '.') return K;
  111. // Some lame default implementation based on some magic section names.
  112. if (Name == ".bss" ||
  113. Name.startswith(".bss.") ||
  114. Name.startswith(".gnu.linkonce.b.") ||
  115. Name.startswith(".llvm.linkonce.b.") ||
  116. Name == ".sbss" ||
  117. Name.startswith(".sbss.") ||
  118. Name.startswith(".gnu.linkonce.sb.") ||
  119. Name.startswith(".llvm.linkonce.sb."))
  120. return SectionKind::getBSS();
  121. if (Name == ".tdata" ||
  122. Name.startswith(".tdata.") ||
  123. Name.startswith(".gnu.linkonce.td.") ||
  124. Name.startswith(".llvm.linkonce.td."))
  125. return SectionKind::getThreadData();
  126. if (Name == ".tbss" ||
  127. Name.startswith(".tbss.") ||
  128. Name.startswith(".gnu.linkonce.tb.") ||
  129. Name.startswith(".llvm.linkonce.tb."))
  130. return SectionKind::getThreadBSS();
  131. return K;
  132. }
  133. static unsigned getELFSectionType(StringRef Name, SectionKind K) {
  134. if (Name == ".init_array")
  135. return ELF::SHT_INIT_ARRAY;
  136. if (Name == ".fini_array")
  137. return ELF::SHT_FINI_ARRAY;
  138. if (Name == ".preinit_array")
  139. return ELF::SHT_PREINIT_ARRAY;
  140. if (K.isBSS() || K.isThreadBSS())
  141. return ELF::SHT_NOBITS;
  142. return ELF::SHT_PROGBITS;
  143. }
  144. static unsigned 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. MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
  170. const GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
  171. StringRef SectionName = GV->getSection();
  172. // Infer section flags from the section name if we can.
  173. Kind = getELFKindForNamedSection(SectionName, Kind);
  174. StringRef Group = "";
  175. unsigned Flags = getELFSectionFlags(Kind);
  176. if (const Comdat *C = getELFComdat(GV)) {
  177. Group = C->getName();
  178. Flags |= ELF::SHF_GROUP;
  179. }
  180. return getContext().getELFSection(SectionName,
  181. getELFSectionType(SectionName, Kind), Flags,
  182. /*EntrySize=*/0, Group);
  183. }
  184. /// Return the section prefix name used by options FunctionsSections and
  185. /// DataSections.
  186. static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
  187. if (Kind.isText())
  188. return ".text";
  189. if (Kind.isReadOnly())
  190. return ".rodata";
  191. if (Kind.isBSS())
  192. return ".bss";
  193. if (Kind.isThreadData())
  194. return ".tdata";
  195. if (Kind.isThreadBSS())
  196. return ".tbss";
  197. if (Kind.isData())
  198. return ".data";
  199. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  200. return ".data.rel.ro";
  201. }
  202. static MCSectionELF *
  203. selectELFSectionForGlobal(MCContext &Ctx, const GlobalValue *GV,
  204. SectionKind Kind, Mangler &Mang,
  205. const TargetMachine &TM, bool EmitUniqueSection,
  206. unsigned Flags, unsigned *NextUniqueID) {
  207. unsigned EntrySize = 0;
  208. if (Kind.isMergeableCString()) {
  209. if (Kind.isMergeable2ByteCString()) {
  210. EntrySize = 2;
  211. } else if (Kind.isMergeable4ByteCString()) {
  212. EntrySize = 4;
  213. } else {
  214. EntrySize = 1;
  215. assert(Kind.isMergeable1ByteCString() && "unknown string width");
  216. }
  217. } else if (Kind.isMergeableConst()) {
  218. if (Kind.isMergeableConst4()) {
  219. EntrySize = 4;
  220. } else if (Kind.isMergeableConst8()) {
  221. EntrySize = 8;
  222. } else if (Kind.isMergeableConst16()) {
  223. EntrySize = 16;
  224. } else {
  225. assert(Kind.isMergeableConst32() && "unknown data width");
  226. EntrySize = 32;
  227. }
  228. }
  229. StringRef Group = "";
  230. if (const Comdat *C = getELFComdat(GV)) {
  231. Flags |= ELF::SHF_GROUP;
  232. Group = C->getName();
  233. }
  234. bool UniqueSectionNames = TM.getUniqueSectionNames();
  235. SmallString<128> Name;
  236. if (Kind.isMergeableCString()) {
  237. // We also need alignment here.
  238. // FIXME: this is getting the alignment of the character, not the
  239. // alignment of the global!
  240. unsigned Align = GV->getParent()->getDataLayout().getPreferredAlignment(
  241. cast<GlobalVariable>(GV));
  242. std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
  243. Name = SizeSpec + utostr(Align);
  244. } else if (Kind.isMergeableConst()) {
  245. Name = ".rodata.cst";
  246. Name += utostr(EntrySize);
  247. } else {
  248. Name = getSectionPrefixForGlobal(Kind);
  249. }
  250. // FIXME: Extend the section prefix to include hotness catagories such as .hot
  251. // or .unlikely for functions.
  252. if (EmitUniqueSection && UniqueSectionNames) {
  253. Name.push_back('.');
  254. TM.getNameWithPrefix(Name, GV, Mang, true);
  255. }
  256. unsigned UniqueID = MCContext::GenericSectionID;
  257. if (EmitUniqueSection && !UniqueSectionNames) {
  258. UniqueID = *NextUniqueID;
  259. (*NextUniqueID)++;
  260. }
  261. return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
  262. EntrySize, Group, UniqueID);
  263. }
  264. MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
  265. const GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
  266. unsigned Flags = getELFSectionFlags(Kind);
  267. // If we have -ffunction-section or -fdata-section then we should emit the
  268. // global value to a uniqued section specifically for it.
  269. bool EmitUniqueSection = false;
  270. if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
  271. if (Kind.isText())
  272. EmitUniqueSection = TM.getFunctionSections();
  273. else
  274. EmitUniqueSection = TM.getDataSections();
  275. }
  276. EmitUniqueSection |= GV->hasComdat();
  277. return selectELFSectionForGlobal(getContext(), GV, Kind, getMangler(), TM,
  278. EmitUniqueSection, Flags, &NextUniqueID);
  279. }
  280. MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
  281. const Function &F, const TargetMachine &TM) const {
  282. // If the function can be removed, produce a unique section so that
  283. // the table doesn't prevent the removal.
  284. const Comdat *C = F.getComdat();
  285. bool EmitUniqueSection = TM.getFunctionSections() || C;
  286. if (!EmitUniqueSection)
  287. return ReadOnlySection;
  288. return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
  289. getMangler(), TM, EmitUniqueSection, ELF::SHF_ALLOC,
  290. &NextUniqueID);
  291. }
  292. bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
  293. bool UsesLabelDifference, const Function &F) const {
  294. // We can always create relative relocations, so use another section
  295. // that can be marked non-executable.
  296. return false;
  297. }
  298. /// Given a mergeable constant with the specified size and relocation
  299. /// information, return a section that it should be placed in.
  300. MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
  301. const DataLayout &DL, SectionKind Kind, const Constant *C,
  302. unsigned &Align) const {
  303. if (Kind.isMergeableConst4() && MergeableConst4Section)
  304. return MergeableConst4Section;
  305. if (Kind.isMergeableConst8() && MergeableConst8Section)
  306. return MergeableConst8Section;
  307. if (Kind.isMergeableConst16() && MergeableConst16Section)
  308. return MergeableConst16Section;
  309. if (Kind.isMergeableConst32() && MergeableConst32Section)
  310. return MergeableConst32Section;
  311. if (Kind.isReadOnly())
  312. return ReadOnlySection;
  313. assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
  314. return DataRelROSection;
  315. }
  316. static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
  317. bool IsCtor, unsigned Priority,
  318. const MCSymbol *KeySym) {
  319. std::string Name;
  320. unsigned Type;
  321. unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
  322. StringRef COMDAT = KeySym ? KeySym->getName() : "";
  323. if (KeySym)
  324. Flags |= ELF::SHF_GROUP;
  325. if (UseInitArray) {
  326. if (IsCtor) {
  327. Type = ELF::SHT_INIT_ARRAY;
  328. Name = ".init_array";
  329. } else {
  330. Type = ELF::SHT_FINI_ARRAY;
  331. Name = ".fini_array";
  332. }
  333. if (Priority != 65535) {
  334. Name += '.';
  335. Name += utostr(Priority);
  336. }
  337. } else {
  338. // The default scheme is .ctor / .dtor, so we have to invert the priority
  339. // numbering.
  340. if (IsCtor)
  341. Name = ".ctors";
  342. else
  343. Name = ".dtors";
  344. if (Priority != 65535) {
  345. Name += '.';
  346. Name += utostr(65535 - Priority);
  347. }
  348. Type = ELF::SHT_PROGBITS;
  349. }
  350. return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
  351. }
  352. MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
  353. unsigned Priority, const MCSymbol *KeySym) const {
  354. return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
  355. KeySym);
  356. }
  357. MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
  358. unsigned Priority, const MCSymbol *KeySym) const {
  359. return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
  360. KeySym);
  361. }
  362. const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
  363. const GlobalValue *LHS, const GlobalValue *RHS,
  364. const TargetMachine &TM) const {
  365. // We may only use a PLT-relative relocation to refer to unnamed_addr
  366. // functions.
  367. if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
  368. return nullptr;
  369. // Basic sanity checks.
  370. if (LHS->getType()->getPointerAddressSpace() != 0 ||
  371. RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
  372. RHS->isThreadLocal())
  373. return nullptr;
  374. return MCBinaryExpr::createSub(
  375. MCSymbolRefExpr::create(TM.getSymbol(LHS, getMangler()), PLTRelativeVariantKind,
  376. getContext()),
  377. MCSymbolRefExpr::create(TM.getSymbol(RHS, getMangler()), getContext()),
  378. getContext());
  379. }
  380. void
  381. TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
  382. UseInitArray = UseInitArray_;
  383. MCContext &Ctx = getContext();
  384. if (!UseInitArray) {
  385. StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
  386. ELF::SHF_ALLOC | ELF::SHF_WRITE);
  387. StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
  388. ELF::SHF_ALLOC | ELF::SHF_WRITE);
  389. return;
  390. }
  391. StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
  392. ELF::SHF_WRITE | ELF::SHF_ALLOC);
  393. StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
  394. ELF::SHF_WRITE | ELF::SHF_ALLOC);
  395. }
  396. //===----------------------------------------------------------------------===//
  397. // MachO
  398. //===----------------------------------------------------------------------===//
  399. TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
  400. : TargetLoweringObjectFile() {
  401. SupportIndirectSymViaGOTPCRel = true;
  402. }
  403. void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
  404. const TargetMachine &TM) {
  405. TargetLoweringObjectFile::Initialize(Ctx, TM);
  406. if (TM.getRelocationModel() == Reloc::Static) {
  407. StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
  408. SectionKind::getData());
  409. StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
  410. SectionKind::getData());
  411. } else {
  412. StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
  413. MachO::S_MOD_INIT_FUNC_POINTERS,
  414. SectionKind::getData());
  415. StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
  416. MachO::S_MOD_TERM_FUNC_POINTERS,
  417. SectionKind::getData());
  418. }
  419. }
  420. /// emitModuleFlags - Perform code emission for module flags.
  421. void TargetLoweringObjectFileMachO::emitModuleFlags(
  422. MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
  423. const TargetMachine &TM) const {
  424. unsigned VersionVal = 0;
  425. unsigned ImageInfoFlags = 0;
  426. MDNode *LinkerOptions = nullptr;
  427. StringRef SectionVal;
  428. for (const auto &MFE : ModuleFlags) {
  429. // Ignore flags with 'Require' behavior.
  430. if (MFE.Behavior == Module::Require)
  431. continue;
  432. StringRef Key = MFE.Key->getString();
  433. Metadata *Val = MFE.Val;
  434. if (Key == "Objective-C Image Info Version") {
  435. VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
  436. } else if (Key == "Objective-C Garbage Collection" ||
  437. Key == "Objective-C GC Only" ||
  438. Key == "Objective-C Is Simulated" ||
  439. Key == "Objective-C Class Properties" ||
  440. Key == "Objective-C Image Swift Version") {
  441. ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
  442. } else if (Key == "Objective-C Image Info Section") {
  443. SectionVal = cast<MDString>(Val)->getString();
  444. } else if (Key == "Linker Options") {
  445. LinkerOptions = cast<MDNode>(Val);
  446. }
  447. }
  448. // Emit the linker options if present.
  449. if (LinkerOptions) {
  450. for (const auto &Option : LinkerOptions->operands()) {
  451. SmallVector<std::string, 4> StrOptions;
  452. for (const auto &Piece : cast<MDNode>(Option)->operands())
  453. StrOptions.push_back(cast<MDString>(Piece)->getString());
  454. Streamer.EmitLinkerOptions(StrOptions);
  455. }
  456. }
  457. // The section is mandatory. If we don't have it, then we don't have GC info.
  458. if (SectionVal.empty()) return;
  459. StringRef Segment, Section;
  460. unsigned TAA = 0, StubSize = 0;
  461. bool TAAParsed;
  462. std::string ErrorCode =
  463. MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
  464. TAA, TAAParsed, StubSize);
  465. if (!ErrorCode.empty())
  466. // If invalid, report the error with report_fatal_error.
  467. report_fatal_error("Invalid section specifier '" + Section + "': " +
  468. ErrorCode + ".");
  469. // Get the section.
  470. MCSectionMachO *S = getContext().getMachOSection(
  471. Segment, Section, TAA, StubSize, SectionKind::getData());
  472. Streamer.SwitchSection(S);
  473. Streamer.EmitLabel(getContext().
  474. getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
  475. Streamer.EmitIntValue(VersionVal, 4);
  476. Streamer.EmitIntValue(ImageInfoFlags, 4);
  477. Streamer.AddBlankLine();
  478. }
  479. static void checkMachOComdat(const GlobalValue *GV) {
  480. const Comdat *C = GV->getComdat();
  481. if (!C)
  482. return;
  483. report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
  484. "' cannot be lowered.");
  485. }
  486. MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
  487. const GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
  488. // Parse the section specifier and create it if valid.
  489. StringRef Segment, Section;
  490. unsigned TAA = 0, StubSize = 0;
  491. bool TAAParsed;
  492. checkMachOComdat(GV);
  493. std::string ErrorCode =
  494. MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
  495. TAA, TAAParsed, StubSize);
  496. if (!ErrorCode.empty()) {
  497. // If invalid, report the error with report_fatal_error.
  498. report_fatal_error("Global variable '" + GV->getName() +
  499. "' has an invalid section specifier '" +
  500. GV->getSection() + "': " + ErrorCode + ".");
  501. }
  502. // Get the section.
  503. MCSectionMachO *S =
  504. getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
  505. // If TAA wasn't set by ParseSectionSpecifier() above,
  506. // use the value returned by getMachOSection() as a default.
  507. if (!TAAParsed)
  508. TAA = S->getTypeAndAttributes();
  509. // Okay, now that we got the section, verify that the TAA & StubSize agree.
  510. // If the user declared multiple globals with different section flags, we need
  511. // to reject it here.
  512. if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
  513. // If invalid, report the error with report_fatal_error.
  514. report_fatal_error("Global variable '" + GV->getName() +
  515. "' section type or attributes does not match previous"
  516. " section specifier");
  517. }
  518. return S;
  519. }
  520. MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
  521. const GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
  522. checkMachOComdat(GV);
  523. // Handle thread local data.
  524. if (Kind.isThreadBSS()) return TLSBSSSection;
  525. if (Kind.isThreadData()) return TLSDataSection;
  526. if (Kind.isText())
  527. return GV->isWeakForLinker() ? TextCoalSection : TextSection;
  528. // If this is weak/linkonce, put this in a coalescable section, either in text
  529. // or data depending on if it is writable.
  530. if (GV->isWeakForLinker()) {
  531. if (Kind.isReadOnly())
  532. return ConstTextCoalSection;
  533. return DataCoalSection;
  534. }
  535. // FIXME: Alignment check should be handled by section classifier.
  536. if (Kind.isMergeable1ByteCString() &&
  537. GV->getParent()->getDataLayout().getPreferredAlignment(
  538. cast<GlobalVariable>(GV)) < 32)
  539. return CStringSection;
  540. // Do not put 16-bit arrays in the UString section if they have an
  541. // externally visible label, this runs into issues with certain linker
  542. // versions.
  543. if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
  544. GV->getParent()->getDataLayout().getPreferredAlignment(
  545. cast<GlobalVariable>(GV)) < 32)
  546. return UStringSection;
  547. // With MachO only variables whose corresponding symbol starts with 'l' or
  548. // 'L' can be merged, so we only try merging GVs with private linkage.
  549. if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
  550. if (Kind.isMergeableConst4())
  551. return FourByteConstantSection;
  552. if (Kind.isMergeableConst8())
  553. return EightByteConstantSection;
  554. if (Kind.isMergeableConst16())
  555. return SixteenByteConstantSection;
  556. }
  557. // Otherwise, if it is readonly, but not something we can specially optimize,
  558. // just drop it in .const.
  559. if (Kind.isReadOnly())
  560. return ReadOnlySection;
  561. // If this is marked const, put it into a const section. But if the dynamic
  562. // linker needs to write to it, put it in the data segment.
  563. if (Kind.isReadOnlyWithRel())
  564. return ConstDataSection;
  565. // Put zero initialized globals with strong external linkage in the
  566. // DATA, __common section with the .zerofill directive.
  567. if (Kind.isBSSExtern())
  568. return DataCommonSection;
  569. // Put zero initialized globals with local linkage in __DATA,__bss directive
  570. // with the .zerofill directive (aka .lcomm).
  571. if (Kind.isBSSLocal())
  572. return DataBSSSection;
  573. // Otherwise, just drop the variable in the normal data section.
  574. return DataSection;
  575. }
  576. MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
  577. const DataLayout &DL, SectionKind Kind, const Constant *C,
  578. unsigned &Align) const {
  579. // If this constant requires a relocation, we have to put it in the data
  580. // segment, not in the text segment.
  581. if (Kind.isData() || Kind.isReadOnlyWithRel())
  582. return ConstDataSection;
  583. if (Kind.isMergeableConst4())
  584. return FourByteConstantSection;
  585. if (Kind.isMergeableConst8())
  586. return EightByteConstantSection;
  587. if (Kind.isMergeableConst16())
  588. return SixteenByteConstantSection;
  589. return ReadOnlySection; // .const
  590. }
  591. const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
  592. const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
  593. MachineModuleInfo *MMI, MCStreamer &Streamer) const {
  594. // The mach-o version of this method defaults to returning a stub reference.
  595. if (Encoding & DW_EH_PE_indirect) {
  596. MachineModuleInfoMachO &MachOMMI =
  597. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  598. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
  599. // Add information about the stub reference to MachOMMI so that the stub
  600. // gets emitted by the asmprinter.
  601. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
  602. if (!StubSym.getPointer()) {
  603. MCSymbol *Sym = TM.getSymbol(GV, getMangler());
  604. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  605. }
  606. return TargetLoweringObjectFile::
  607. getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
  608. Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
  609. }
  610. return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
  611. MMI, Streamer);
  612. }
  613. MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
  614. const GlobalValue *GV, const TargetMachine &TM,
  615. MachineModuleInfo *MMI) const {
  616. // The mach-o version of this method defaults to returning a stub reference.
  617. MachineModuleInfoMachO &MachOMMI =
  618. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  619. MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
  620. // Add information about the stub reference to MachOMMI so that the stub
  621. // gets emitted by the asmprinter.
  622. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
  623. if (!StubSym.getPointer()) {
  624. MCSymbol *Sym = TM.getSymbol(GV, getMangler());
  625. StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
  626. }
  627. return SSym;
  628. }
  629. const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
  630. const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
  631. MachineModuleInfo *MMI, MCStreamer &Streamer) const {
  632. // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
  633. // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
  634. // through a non_lazy_ptr stub instead. One advantage is that it allows the
  635. // computation of deltas to final external symbols. Example:
  636. //
  637. // _extgotequiv:
  638. // .long _extfoo
  639. //
  640. // _delta:
  641. // .long _extgotequiv-_delta
  642. //
  643. // is transformed to:
  644. //
  645. // _delta:
  646. // .long L_extfoo$non_lazy_ptr-(_delta+0)
  647. //
  648. // .section __IMPORT,__pointers,non_lazy_symbol_pointers
  649. // L_extfoo$non_lazy_ptr:
  650. // .indirect_symbol _extfoo
  651. // .long 0
  652. //
  653. MachineModuleInfoMachO &MachOMMI =
  654. MMI->getObjFileInfo<MachineModuleInfoMachO>();
  655. MCContext &Ctx = getContext();
  656. // The offset must consider the original displacement from the base symbol
  657. // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
  658. Offset = -MV.getConstant();
  659. const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
  660. // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
  661. // non_lazy_ptr stubs.
  662. SmallString<128> Name;
  663. StringRef Suffix = "$non_lazy_ptr";
  664. Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
  665. Name += Sym->getName();
  666. Name += Suffix;
  667. MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
  668. MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
  669. if (!StubSym.getPointer())
  670. StubSym = MachineModuleInfoImpl::
  671. StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
  672. const MCExpr *BSymExpr =
  673. MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
  674. const MCExpr *LHS =
  675. MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
  676. if (!Offset)
  677. return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
  678. const MCExpr *RHS =
  679. MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
  680. return MCBinaryExpr::createSub(LHS, RHS, Ctx);
  681. }
  682. static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
  683. const MCSection &Section) {
  684. if (!AsmInfo.isSectionAtomizableBySymbols(Section))
  685. return true;
  686. // If it is not dead stripped, it is safe to use private labels.
  687. const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
  688. if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
  689. return true;
  690. return false;
  691. }
  692. void TargetLoweringObjectFileMachO::getNameWithPrefix(
  693. SmallVectorImpl<char> &OutName, const GlobalValue *GV,
  694. const TargetMachine &TM) const {
  695. SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
  696. const MCSection *TheSection = SectionForGlobal(GV, GVKind, TM);
  697. bool CannotUsePrivateLabel =
  698. !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
  699. getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
  700. }
  701. //===----------------------------------------------------------------------===//
  702. // COFF
  703. //===----------------------------------------------------------------------===//
  704. static unsigned
  705. getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
  706. unsigned Flags = 0;
  707. bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
  708. if (K.isMetadata())
  709. Flags |=
  710. COFF::IMAGE_SCN_MEM_DISCARDABLE;
  711. else if (K.isText())
  712. Flags |=
  713. COFF::IMAGE_SCN_MEM_EXECUTE |
  714. COFF::IMAGE_SCN_MEM_READ |
  715. COFF::IMAGE_SCN_CNT_CODE |
  716. (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
  717. else if (K.isBSS())
  718. Flags |=
  719. COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
  720. COFF::IMAGE_SCN_MEM_READ |
  721. COFF::IMAGE_SCN_MEM_WRITE;
  722. else if (K.isThreadLocal())
  723. Flags |=
  724. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  725. COFF::IMAGE_SCN_MEM_READ |
  726. COFF::IMAGE_SCN_MEM_WRITE;
  727. else if (K.isReadOnly() || K.isReadOnlyWithRel())
  728. Flags |=
  729. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  730. COFF::IMAGE_SCN_MEM_READ;
  731. else if (K.isWriteable())
  732. Flags |=
  733. COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  734. COFF::IMAGE_SCN_MEM_READ |
  735. COFF::IMAGE_SCN_MEM_WRITE;
  736. return Flags;
  737. }
  738. static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
  739. const Comdat *C = GV->getComdat();
  740. assert(C && "expected GV to have a Comdat!");
  741. StringRef ComdatGVName = C->getName();
  742. const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
  743. if (!ComdatGV)
  744. report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
  745. "' does not exist.");
  746. if (ComdatGV->getComdat() != C)
  747. report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
  748. "' is not a key for its COMDAT.");
  749. return ComdatGV;
  750. }
  751. static int getSelectionForCOFF(const GlobalValue *GV) {
  752. if (const Comdat *C = GV->getComdat()) {
  753. const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
  754. if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
  755. ComdatKey = GA->getBaseObject();
  756. if (ComdatKey == GV) {
  757. switch (C->getSelectionKind()) {
  758. case Comdat::Any:
  759. return COFF::IMAGE_COMDAT_SELECT_ANY;
  760. case Comdat::ExactMatch:
  761. return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
  762. case Comdat::Largest:
  763. return COFF::IMAGE_COMDAT_SELECT_LARGEST;
  764. case Comdat::NoDuplicates:
  765. return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
  766. case Comdat::SameSize:
  767. return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
  768. }
  769. } else {
  770. return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
  771. }
  772. }
  773. return 0;
  774. }
  775. MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
  776. const GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
  777. int Selection = 0;
  778. unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
  779. StringRef Name = GV->getSection();
  780. StringRef COMDATSymName = "";
  781. if (GV->hasComdat()) {
  782. Selection = getSelectionForCOFF(GV);
  783. const GlobalValue *ComdatGV;
  784. if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
  785. ComdatGV = getComdatGVForCOFF(GV);
  786. else
  787. ComdatGV = GV;
  788. if (!ComdatGV->hasPrivateLinkage()) {
  789. MCSymbol *Sym = TM.getSymbol(ComdatGV, getMangler());
  790. COMDATSymName = Sym->getName();
  791. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  792. } else {
  793. Selection = 0;
  794. }
  795. }
  796. return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
  797. Selection);
  798. }
  799. static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
  800. if (Kind.isText())
  801. return ".text";
  802. if (Kind.isBSS())
  803. return ".bss";
  804. if (Kind.isThreadLocal())
  805. return ".tls$";
  806. if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
  807. return ".rdata";
  808. return ".data";
  809. }
  810. MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
  811. const GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
  812. // If we have -ffunction-sections then we should emit the global value to a
  813. // uniqued section specifically for it.
  814. bool EmitUniquedSection;
  815. if (Kind.isText())
  816. EmitUniquedSection = TM.getFunctionSections();
  817. else
  818. EmitUniquedSection = TM.getDataSections();
  819. if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
  820. const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
  821. unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
  822. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  823. int Selection = getSelectionForCOFF(GV);
  824. if (!Selection)
  825. Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
  826. const GlobalValue *ComdatGV;
  827. if (GV->hasComdat())
  828. ComdatGV = getComdatGVForCOFF(GV);
  829. else
  830. ComdatGV = GV;
  831. unsigned UniqueID = MCContext::GenericSectionID;
  832. if (EmitUniquedSection)
  833. UniqueID = NextUniqueID++;
  834. if (!ComdatGV->hasPrivateLinkage()) {
  835. MCSymbol *Sym = TM.getSymbol(ComdatGV, getMangler());
  836. StringRef COMDATSymName = Sym->getName();
  837. return getContext().getCOFFSection(Name, Characteristics, Kind,
  838. COMDATSymName, Selection, UniqueID);
  839. } else {
  840. SmallString<256> TmpData;
  841. getMangler().getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true);
  842. return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
  843. Selection, UniqueID);
  844. }
  845. }
  846. if (Kind.isText())
  847. return TextSection;
  848. if (Kind.isThreadLocal())
  849. return TLSDataSection;
  850. if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
  851. return ReadOnlySection;
  852. // Note: we claim that common symbols are put in BSSSection, but they are
  853. // really emitted with the magic .comm directive, which creates a symbol table
  854. // entry but not a section.
  855. if (Kind.isBSS() || Kind.isCommon())
  856. return BSSSection;
  857. return DataSection;
  858. }
  859. void TargetLoweringObjectFileCOFF::getNameWithPrefix(
  860. SmallVectorImpl<char> &OutName, const GlobalValue *GV,
  861. const TargetMachine &TM) const {
  862. bool CannotUsePrivateLabel = false;
  863. if (GV->hasPrivateLinkage() &&
  864. ((isa<Function>(GV) && TM.getFunctionSections()) ||
  865. (isa<GlobalVariable>(GV) && TM.getDataSections())))
  866. CannotUsePrivateLabel = true;
  867. getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
  868. }
  869. MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
  870. const Function &F, const TargetMachine &TM) const {
  871. // If the function can be removed, produce a unique section so that
  872. // the table doesn't prevent the removal.
  873. const Comdat *C = F.getComdat();
  874. bool EmitUniqueSection = TM.getFunctionSections() || C;
  875. if (!EmitUniqueSection)
  876. return ReadOnlySection;
  877. // FIXME: we should produce a symbol for F instead.
  878. if (F.hasPrivateLinkage())
  879. return ReadOnlySection;
  880. MCSymbol *Sym = TM.getSymbol(&F, getMangler());
  881. StringRef COMDATSymName = Sym->getName();
  882. SectionKind Kind = SectionKind::getReadOnly();
  883. const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
  884. unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
  885. Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
  886. unsigned UniqueID = NextUniqueID++;
  887. return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
  888. COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
  889. }
  890. void TargetLoweringObjectFileCOFF::emitModuleFlags(
  891. MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
  892. const TargetMachine &TM) const {
  893. MDNode *LinkerOptions = nullptr;
  894. for (const auto &MFE : ModuleFlags) {
  895. StringRef Key = MFE.Key->getString();
  896. if (Key == "Linker Options")
  897. LinkerOptions = cast<MDNode>(MFE.Val);
  898. }
  899. if (LinkerOptions) {
  900. // Emit the linker options to the linker .drectve section. According to the
  901. // spec, this section is a space-separated string containing flags for
  902. // linker.
  903. MCSection *Sec = getDrectveSection();
  904. Streamer.SwitchSection(Sec);
  905. for (const auto &Option : LinkerOptions->operands()) {
  906. for (const auto &Piece : cast<MDNode>(Option)->operands()) {
  907. // Lead with a space for consistency with our dllexport implementation.
  908. std::string Directive(" ");
  909. Directive.append(cast<MDString>(Piece)->getString());
  910. Streamer.EmitBytes(Directive);
  911. }
  912. }
  913. }
  914. }
  915. void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
  916. const TargetMachine &TM) {
  917. TargetLoweringObjectFile::Initialize(Ctx, TM);
  918. const Triple &T = TM.getTargetTriple();
  919. if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
  920. StaticCtorSection =
  921. Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  922. COFF::IMAGE_SCN_MEM_READ,
  923. SectionKind::getReadOnly());
  924. StaticDtorSection =
  925. Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  926. COFF::IMAGE_SCN_MEM_READ,
  927. SectionKind::getReadOnly());
  928. } else {
  929. StaticCtorSection = Ctx.getCOFFSection(
  930. ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  931. COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
  932. SectionKind::getData());
  933. StaticDtorSection = Ctx.getCOFFSection(
  934. ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
  935. COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
  936. SectionKind::getData());
  937. }
  938. }
  939. MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
  940. unsigned Priority, const MCSymbol *KeySym) const {
  941. return getContext().getAssociativeCOFFSection(
  942. cast<MCSectionCOFF>(StaticCtorSection), KeySym, 0);
  943. }
  944. MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
  945. unsigned Priority, const MCSymbol *KeySym) const {
  946. return getContext().getAssociativeCOFFSection(
  947. cast<MCSectionCOFF>(StaticDtorSection), KeySym, 0);
  948. }
  949. void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
  950. raw_ostream &OS, const GlobalValue *GV) const {
  951. if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
  952. return;
  953. const Triple &TT = getTargetTriple();
  954. if (TT.isKnownWindowsMSVCEnvironment())
  955. OS << " /EXPORT:";
  956. else
  957. OS << " -export:";
  958. if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
  959. std::string Flag;
  960. raw_string_ostream FlagOS(Flag);
  961. getMangler().getNameWithPrefix(FlagOS, GV, false);
  962. FlagOS.flush();
  963. if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
  964. OS << Flag.substr(1);
  965. else
  966. OS << Flag;
  967. } else {
  968. getMangler().getNameWithPrefix(OS, GV, false);
  969. }
  970. if (!GV->getValueType()->isFunctionTy()) {
  971. if (TT.isKnownWindowsMSVCEnvironment())
  972. OS << ",DATA";
  973. else
  974. OS << ",data";
  975. }
  976. }