MCELFStreamer.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. //===- lib/MC/MCELFStreamer.cpp - ELF Object Output -----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file assembles .s files and emits ELF .o object files.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/MC/MCELFStreamer.h"
  13. #include "llvm/ADT/SmallString.h"
  14. #include "llvm/ADT/SmallVector.h"
  15. #include "llvm/BinaryFormat/ELF.h"
  16. #include "llvm/MC/MCAsmBackend.h"
  17. #include "llvm/MC/MCAsmInfo.h"
  18. #include "llvm/MC/MCAssembler.h"
  19. #include "llvm/MC/MCCodeEmitter.h"
  20. #include "llvm/MC/MCContext.h"
  21. #include "llvm/MC/MCExpr.h"
  22. #include "llvm/MC/MCFixup.h"
  23. #include "llvm/MC/MCFragment.h"
  24. #include "llvm/MC/MCObjectFileInfo.h"
  25. #include "llvm/MC/MCObjectWriter.h"
  26. #include "llvm/MC/MCSection.h"
  27. #include "llvm/MC/MCSectionELF.h"
  28. #include "llvm/MC/MCStreamer.h"
  29. #include "llvm/MC/MCSymbol.h"
  30. #include "llvm/MC/MCSymbolELF.h"
  31. #include "llvm/Support/Casting.h"
  32. #include "llvm/Support/ErrorHandling.h"
  33. #include "llvm/Support/TargetRegistry.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include <cassert>
  36. #include <cstdint>
  37. using namespace llvm;
  38. MCELFStreamer::MCELFStreamer(MCContext &Context,
  39. std::unique_ptr<MCAsmBackend> TAB,
  40. std::unique_ptr<MCObjectWriter> OW,
  41. std::unique_ptr<MCCodeEmitter> Emitter)
  42. : MCObjectStreamer(Context, std::move(TAB), std::move(OW),
  43. std::move(Emitter)) {}
  44. bool MCELFStreamer::isBundleLocked() const {
  45. return getCurrentSectionOnly()->isBundleLocked();
  46. }
  47. void MCELFStreamer::mergeFragment(MCDataFragment *DF,
  48. MCDataFragment *EF) {
  49. MCAssembler &Assembler = getAssembler();
  50. if (Assembler.isBundlingEnabled() && Assembler.getRelaxAll()) {
  51. uint64_t FSize = EF->getContents().size();
  52. if (FSize > Assembler.getBundleAlignSize())
  53. report_fatal_error("Fragment can't be larger than a bundle size");
  54. uint64_t RequiredBundlePadding = computeBundlePadding(
  55. Assembler, EF, DF->getContents().size(), FSize);
  56. if (RequiredBundlePadding > UINT8_MAX)
  57. report_fatal_error("Padding cannot exceed 255 bytes");
  58. if (RequiredBundlePadding > 0) {
  59. SmallString<256> Code;
  60. raw_svector_ostream VecOS(Code);
  61. EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
  62. Assembler.writeFragmentPadding(VecOS, *EF, FSize);
  63. DF->getContents().append(Code.begin(), Code.end());
  64. }
  65. }
  66. flushPendingLabels(DF, DF->getContents().size());
  67. for (unsigned i = 0, e = EF->getFixups().size(); i != e; ++i) {
  68. EF->getFixups()[i].setOffset(EF->getFixups()[i].getOffset() +
  69. DF->getContents().size());
  70. DF->getFixups().push_back(EF->getFixups()[i]);
  71. }
  72. if (DF->getSubtargetInfo() == nullptr && EF->getSubtargetInfo())
  73. DF->setHasInstructions(*EF->getSubtargetInfo());
  74. DF->getContents().append(EF->getContents().begin(), EF->getContents().end());
  75. }
  76. void MCELFStreamer::InitSections(bool NoExecStack) {
  77. MCContext &Ctx = getContext();
  78. SwitchSection(Ctx.getObjectFileInfo()->getTextSection());
  79. emitCodeAlignment(4);
  80. if (NoExecStack)
  81. SwitchSection(Ctx.getAsmInfo()->getNonexecutableStackSection(Ctx));
  82. }
  83. void MCELFStreamer::emitLabel(MCSymbol *S, SMLoc Loc) {
  84. auto *Symbol = cast<MCSymbolELF>(S);
  85. MCObjectStreamer::emitLabel(Symbol, Loc);
  86. const MCSectionELF &Section =
  87. static_cast<const MCSectionELF &>(*getCurrentSectionOnly());
  88. if (Section.getFlags() & ELF::SHF_TLS)
  89. Symbol->setType(ELF::STT_TLS);
  90. }
  91. void MCELFStreamer::emitLabelAtPos(MCSymbol *S, SMLoc Loc, MCFragment *F,
  92. uint64_t Offset) {
  93. auto *Symbol = cast<MCSymbolELF>(S);
  94. MCObjectStreamer::emitLabelAtPos(Symbol, Loc, F, Offset);
  95. const MCSectionELF &Section =
  96. static_cast<const MCSectionELF &>(*getCurrentSectionOnly());
  97. if (Section.getFlags() & ELF::SHF_TLS)
  98. Symbol->setType(ELF::STT_TLS);
  99. }
  100. void MCELFStreamer::emitAssemblerFlag(MCAssemblerFlag Flag) {
  101. // Let the target do whatever target specific stuff it needs to do.
  102. getAssembler().getBackend().handleAssemblerFlag(Flag);
  103. // Do any generic stuff we need to do.
  104. switch (Flag) {
  105. case MCAF_SyntaxUnified: return; // no-op here.
  106. case MCAF_Code16: return; // Change parsing mode; no-op here.
  107. case MCAF_Code32: return; // Change parsing mode; no-op here.
  108. case MCAF_Code64: return; // Change parsing mode; no-op here.
  109. case MCAF_SubsectionsViaSymbols:
  110. getAssembler().setSubsectionsViaSymbols(true);
  111. return;
  112. }
  113. llvm_unreachable("invalid assembler flag!");
  114. }
  115. // If bundle alignment is used and there are any instructions in the section, it
  116. // needs to be aligned to at least the bundle size.
  117. static void setSectionAlignmentForBundling(const MCAssembler &Assembler,
  118. MCSection *Section) {
  119. if (Section && Assembler.isBundlingEnabled() && Section->hasInstructions() &&
  120. Section->getAlignment() < Assembler.getBundleAlignSize())
  121. Section->setAlignment(Align(Assembler.getBundleAlignSize()));
  122. }
  123. void MCELFStreamer::changeSection(MCSection *Section,
  124. const MCExpr *Subsection) {
  125. MCSection *CurSection = getCurrentSectionOnly();
  126. if (CurSection && isBundleLocked())
  127. report_fatal_error("Unterminated .bundle_lock when changing a section");
  128. MCAssembler &Asm = getAssembler();
  129. // Ensure the previous section gets aligned if necessary.
  130. setSectionAlignmentForBundling(Asm, CurSection);
  131. auto *SectionELF = static_cast<const MCSectionELF *>(Section);
  132. const MCSymbol *Grp = SectionELF->getGroup();
  133. if (Grp)
  134. Asm.registerSymbol(*Grp);
  135. changeSectionImpl(Section, Subsection);
  136. Asm.registerSymbol(*Section->getBeginSymbol());
  137. }
  138. void MCELFStreamer::emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
  139. getAssembler().registerSymbol(*Symbol);
  140. const MCExpr *Value = MCSymbolRefExpr::create(
  141. Symbol, MCSymbolRefExpr::VK_WEAKREF, getContext());
  142. Alias->setVariableValue(Value);
  143. }
  144. // When GNU as encounters more than one .type declaration for an object it seems
  145. // to use a mechanism similar to the one below to decide which type is actually
  146. // used in the object file. The greater of T1 and T2 is selected based on the
  147. // following ordering:
  148. // STT_NOTYPE < STT_OBJECT < STT_FUNC < STT_GNU_IFUNC < STT_TLS < anything else
  149. // If neither T1 < T2 nor T2 < T1 according to this ordering, use T2 (the user
  150. // provided type).
  151. static unsigned CombineSymbolTypes(unsigned T1, unsigned T2) {
  152. for (unsigned Type : {ELF::STT_NOTYPE, ELF::STT_OBJECT, ELF::STT_FUNC,
  153. ELF::STT_GNU_IFUNC, ELF::STT_TLS}) {
  154. if (T1 == Type)
  155. return T2;
  156. if (T2 == Type)
  157. return T1;
  158. }
  159. return T2;
  160. }
  161. bool MCELFStreamer::emitSymbolAttribute(MCSymbol *S, MCSymbolAttr Attribute) {
  162. auto *Symbol = cast<MCSymbolELF>(S);
  163. // Adding a symbol attribute always introduces the symbol, note that an
  164. // important side effect of calling registerSymbol here is to register
  165. // the symbol with the assembler.
  166. getAssembler().registerSymbol(*Symbol);
  167. // The implementation of symbol attributes is designed to match 'as', but it
  168. // leaves much to desired. It doesn't really make sense to arbitrarily add and
  169. // remove flags, but 'as' allows this (in particular, see .desc).
  170. //
  171. // In the future it might be worth trying to make these operations more well
  172. // defined.
  173. switch (Attribute) {
  174. case MCSA_Cold:
  175. case MCSA_Extern:
  176. case MCSA_LazyReference:
  177. case MCSA_Reference:
  178. case MCSA_SymbolResolver:
  179. case MCSA_PrivateExtern:
  180. case MCSA_WeakDefinition:
  181. case MCSA_WeakDefAutoPrivate:
  182. case MCSA_Invalid:
  183. case MCSA_IndirectSymbol:
  184. return false;
  185. case MCSA_NoDeadStrip:
  186. // Ignore for now.
  187. break;
  188. case MCSA_ELF_TypeGnuUniqueObject:
  189. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_OBJECT));
  190. Symbol->setBinding(ELF::STB_GNU_UNIQUE);
  191. break;
  192. case MCSA_Global:
  193. // For `.weak x; .global x`, GNU as sets the binding to STB_WEAK while we
  194. // traditionally set the binding to STB_GLOBAL. This is error-prone, so we
  195. // error on such cases. Note, we also disallow changed binding from .local.
  196. if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_GLOBAL)
  197. getContext().reportError(getStartTokLoc(),
  198. Symbol->getName() +
  199. " changed binding to STB_GLOBAL");
  200. Symbol->setBinding(ELF::STB_GLOBAL);
  201. break;
  202. case MCSA_WeakReference:
  203. case MCSA_Weak:
  204. // For `.global x; .weak x`, both MC and GNU as set the binding to STB_WEAK.
  205. // We emit a warning for now but may switch to an error in the future.
  206. if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_WEAK)
  207. getContext().reportWarning(
  208. getStartTokLoc(), Symbol->getName() + " changed binding to STB_WEAK");
  209. Symbol->setBinding(ELF::STB_WEAK);
  210. break;
  211. case MCSA_Local:
  212. if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_LOCAL)
  213. getContext().reportError(getStartTokLoc(),
  214. Symbol->getName() +
  215. " changed binding to STB_LOCAL");
  216. Symbol->setBinding(ELF::STB_LOCAL);
  217. break;
  218. case MCSA_ELF_TypeFunction:
  219. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_FUNC));
  220. break;
  221. case MCSA_ELF_TypeIndFunction:
  222. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_GNU_IFUNC));
  223. break;
  224. case MCSA_ELF_TypeObject:
  225. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_OBJECT));
  226. break;
  227. case MCSA_ELF_TypeTLS:
  228. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_TLS));
  229. break;
  230. case MCSA_ELF_TypeCommon:
  231. // TODO: Emit these as a common symbol.
  232. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_OBJECT));
  233. break;
  234. case MCSA_ELF_TypeNoType:
  235. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_NOTYPE));
  236. break;
  237. case MCSA_Protected:
  238. Symbol->setVisibility(ELF::STV_PROTECTED);
  239. break;
  240. case MCSA_Hidden:
  241. Symbol->setVisibility(ELF::STV_HIDDEN);
  242. break;
  243. case MCSA_Internal:
  244. Symbol->setVisibility(ELF::STV_INTERNAL);
  245. break;
  246. case MCSA_AltEntry:
  247. llvm_unreachable("ELF doesn't support the .alt_entry attribute");
  248. case MCSA_LGlobal:
  249. llvm_unreachable("ELF doesn't support the .lglobl attribute");
  250. }
  251. return true;
  252. }
  253. void MCELFStreamer::emitCommonSymbol(MCSymbol *S, uint64_t Size,
  254. unsigned ByteAlignment) {
  255. auto *Symbol = cast<MCSymbolELF>(S);
  256. getAssembler().registerSymbol(*Symbol);
  257. if (!Symbol->isBindingSet())
  258. Symbol->setBinding(ELF::STB_GLOBAL);
  259. Symbol->setType(ELF::STT_OBJECT);
  260. if (Symbol->getBinding() == ELF::STB_LOCAL) {
  261. MCSection &Section = *getAssembler().getContext().getELFSection(
  262. ".bss", ELF::SHT_NOBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
  263. MCSectionSubPair P = getCurrentSection();
  264. SwitchSection(&Section);
  265. emitValueToAlignment(ByteAlignment, 0, 1, 0);
  266. emitLabel(Symbol);
  267. emitZeros(Size);
  268. SwitchSection(P.first, P.second);
  269. } else {
  270. if(Symbol->declareCommon(Size, ByteAlignment))
  271. report_fatal_error("Symbol: " + Symbol->getName() +
  272. " redeclared as different type");
  273. }
  274. cast<MCSymbolELF>(Symbol)
  275. ->setSize(MCConstantExpr::create(Size, getContext()));
  276. }
  277. void MCELFStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
  278. cast<MCSymbolELF>(Symbol)->setSize(Value);
  279. }
  280. void MCELFStreamer::emitELFSymverDirective(StringRef AliasName,
  281. const MCSymbol *Aliasee) {
  282. getAssembler().Symvers.push_back(
  283. MCAssembler::Symver{AliasName, Aliasee, getStartTokLoc()});
  284. }
  285. void MCELFStreamer::emitLocalCommonSymbol(MCSymbol *S, uint64_t Size,
  286. unsigned ByteAlignment) {
  287. auto *Symbol = cast<MCSymbolELF>(S);
  288. // FIXME: Should this be caught and done earlier?
  289. getAssembler().registerSymbol(*Symbol);
  290. Symbol->setBinding(ELF::STB_LOCAL);
  291. emitCommonSymbol(Symbol, Size, ByteAlignment);
  292. }
  293. void MCELFStreamer::emitValueImpl(const MCExpr *Value, unsigned Size,
  294. SMLoc Loc) {
  295. if (isBundleLocked())
  296. report_fatal_error("Emitting values inside a locked bundle is forbidden");
  297. fixSymbolsInTLSFixups(Value);
  298. MCObjectStreamer::emitValueImpl(Value, Size, Loc);
  299. }
  300. void MCELFStreamer::emitValueToAlignment(unsigned ByteAlignment,
  301. int64_t Value,
  302. unsigned ValueSize,
  303. unsigned MaxBytesToEmit) {
  304. if (isBundleLocked())
  305. report_fatal_error("Emitting values inside a locked bundle is forbidden");
  306. MCObjectStreamer::emitValueToAlignment(ByteAlignment, Value,
  307. ValueSize, MaxBytesToEmit);
  308. }
  309. void MCELFStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
  310. const MCSymbolRefExpr *To,
  311. uint64_t Count) {
  312. getAssembler().CGProfile.push_back({From, To, Count});
  313. }
  314. void MCELFStreamer::emitIdent(StringRef IdentString) {
  315. MCSection *Comment = getAssembler().getContext().getELFSection(
  316. ".comment", ELF::SHT_PROGBITS, ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, "");
  317. PushSection();
  318. SwitchSection(Comment);
  319. if (!SeenIdent) {
  320. emitInt8(0);
  321. SeenIdent = true;
  322. }
  323. emitBytes(IdentString);
  324. emitInt8(0);
  325. PopSection();
  326. }
  327. void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
  328. switch (expr->getKind()) {
  329. case MCExpr::Target:
  330. cast<MCTargetExpr>(expr)->fixELFSymbolsInTLSFixups(getAssembler());
  331. break;
  332. case MCExpr::Constant:
  333. break;
  334. case MCExpr::Binary: {
  335. const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
  336. fixSymbolsInTLSFixups(be->getLHS());
  337. fixSymbolsInTLSFixups(be->getRHS());
  338. break;
  339. }
  340. case MCExpr::SymbolRef: {
  341. const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
  342. switch (symRef.getKind()) {
  343. default:
  344. return;
  345. case MCSymbolRefExpr::VK_GOTTPOFF:
  346. case MCSymbolRefExpr::VK_INDNTPOFF:
  347. case MCSymbolRefExpr::VK_NTPOFF:
  348. case MCSymbolRefExpr::VK_GOTNTPOFF:
  349. case MCSymbolRefExpr::VK_TLSCALL:
  350. case MCSymbolRefExpr::VK_TLSDESC:
  351. case MCSymbolRefExpr::VK_TLSGD:
  352. case MCSymbolRefExpr::VK_TLSLD:
  353. case MCSymbolRefExpr::VK_TLSLDM:
  354. case MCSymbolRefExpr::VK_TPOFF:
  355. case MCSymbolRefExpr::VK_TPREL:
  356. case MCSymbolRefExpr::VK_DTPOFF:
  357. case MCSymbolRefExpr::VK_DTPREL:
  358. case MCSymbolRefExpr::VK_PPC_DTPMOD:
  359. case MCSymbolRefExpr::VK_PPC_TPREL_LO:
  360. case MCSymbolRefExpr::VK_PPC_TPREL_HI:
  361. case MCSymbolRefExpr::VK_PPC_TPREL_HA:
  362. case MCSymbolRefExpr::VK_PPC_TPREL_HIGH:
  363. case MCSymbolRefExpr::VK_PPC_TPREL_HIGHA:
  364. case MCSymbolRefExpr::VK_PPC_TPREL_HIGHER:
  365. case MCSymbolRefExpr::VK_PPC_TPREL_HIGHERA:
  366. case MCSymbolRefExpr::VK_PPC_TPREL_HIGHEST:
  367. case MCSymbolRefExpr::VK_PPC_TPREL_HIGHESTA:
  368. case MCSymbolRefExpr::VK_PPC_DTPREL_LO:
  369. case MCSymbolRefExpr::VK_PPC_DTPREL_HI:
  370. case MCSymbolRefExpr::VK_PPC_DTPREL_HA:
  371. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGH:
  372. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHA:
  373. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHER:
  374. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHERA:
  375. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHEST:
  376. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHESTA:
  377. case MCSymbolRefExpr::VK_PPC_GOT_TPREL:
  378. case MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO:
  379. case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HI:
  380. case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA:
  381. case MCSymbolRefExpr::VK_PPC_GOT_TPREL_PCREL:
  382. case MCSymbolRefExpr::VK_PPC_GOT_DTPREL:
  383. case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_LO:
  384. case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HI:
  385. case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HA:
  386. case MCSymbolRefExpr::VK_PPC_TLS:
  387. case MCSymbolRefExpr::VK_PPC_TLS_PCREL:
  388. case MCSymbolRefExpr::VK_PPC_GOT_TLSGD:
  389. case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO:
  390. case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HI:
  391. case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA:
  392. case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_PCREL:
  393. case MCSymbolRefExpr::VK_PPC_TLSGD:
  394. case MCSymbolRefExpr::VK_PPC_GOT_TLSLD:
  395. case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO:
  396. case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HI:
  397. case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA:
  398. case MCSymbolRefExpr::VK_PPC_TLSLD:
  399. break;
  400. }
  401. getAssembler().registerSymbol(symRef.getSymbol());
  402. cast<MCSymbolELF>(symRef.getSymbol()).setType(ELF::STT_TLS);
  403. break;
  404. }
  405. case MCExpr::Unary:
  406. fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
  407. break;
  408. }
  409. }
  410. void MCELFStreamer::finalizeCGProfileEntry(const MCSymbolRefExpr *&SRE) {
  411. const MCSymbol *S = &SRE->getSymbol();
  412. if (S->isTemporary()) {
  413. if (!S->isInSection()) {
  414. getContext().reportError(
  415. SRE->getLoc(), Twine("Reference to undefined temporary symbol ") +
  416. "`" + S->getName() + "`");
  417. return;
  418. }
  419. S = S->getSection().getBeginSymbol();
  420. S->setUsedInReloc();
  421. SRE =
  422. MCSymbolRefExpr::create(S, SRE->getKind(), getContext(), SRE->getLoc());
  423. return;
  424. }
  425. // Not a temporary, referece it as a weak undefined.
  426. bool Created;
  427. getAssembler().registerSymbol(*S, &Created);
  428. if (Created)
  429. cast<MCSymbolELF>(S)->setBinding(ELF::STB_WEAK);
  430. }
  431. void MCELFStreamer::finalizeCGProfile() {
  432. for (MCAssembler::CGProfileEntry &E : getAssembler().CGProfile) {
  433. finalizeCGProfileEntry(E.From);
  434. finalizeCGProfileEntry(E.To);
  435. }
  436. }
  437. void MCELFStreamer::emitInstToFragment(const MCInst &Inst,
  438. const MCSubtargetInfo &STI) {
  439. this->MCObjectStreamer::emitInstToFragment(Inst, STI);
  440. MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
  441. for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
  442. fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
  443. }
  444. // A fragment can only have one Subtarget, and when bundling is enabled we
  445. // sometimes need to use the same fragment. We give an error if there
  446. // are conflicting Subtargets.
  447. static void CheckBundleSubtargets(const MCSubtargetInfo *OldSTI,
  448. const MCSubtargetInfo *NewSTI) {
  449. if (OldSTI && NewSTI && OldSTI != NewSTI)
  450. report_fatal_error("A Bundle can only have one Subtarget.");
  451. }
  452. void MCELFStreamer::emitInstToData(const MCInst &Inst,
  453. const MCSubtargetInfo &STI) {
  454. MCAssembler &Assembler = getAssembler();
  455. SmallVector<MCFixup, 4> Fixups;
  456. SmallString<256> Code;
  457. raw_svector_ostream VecOS(Code);
  458. Assembler.getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
  459. for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
  460. fixSymbolsInTLSFixups(Fixups[i].getValue());
  461. // There are several possibilities here:
  462. //
  463. // If bundling is disabled, append the encoded instruction to the current data
  464. // fragment (or create a new such fragment if the current fragment is not a
  465. // data fragment, or the Subtarget has changed).
  466. //
  467. // If bundling is enabled:
  468. // - If we're not in a bundle-locked group, emit the instruction into a
  469. // fragment of its own. If there are no fixups registered for the
  470. // instruction, emit a MCCompactEncodedInstFragment. Otherwise, emit a
  471. // MCDataFragment.
  472. // - If we're in a bundle-locked group, append the instruction to the current
  473. // data fragment because we want all the instructions in a group to get into
  474. // the same fragment. Be careful not to do that for the first instruction in
  475. // the group, though.
  476. MCDataFragment *DF;
  477. if (Assembler.isBundlingEnabled()) {
  478. MCSection &Sec = *getCurrentSectionOnly();
  479. if (Assembler.getRelaxAll() && isBundleLocked()) {
  480. // If the -mc-relax-all flag is used and we are bundle-locked, we re-use
  481. // the current bundle group.
  482. DF = BundleGroups.back();
  483. CheckBundleSubtargets(DF->getSubtargetInfo(), &STI);
  484. }
  485. else if (Assembler.getRelaxAll() && !isBundleLocked())
  486. // When not in a bundle-locked group and the -mc-relax-all flag is used,
  487. // we create a new temporary fragment which will be later merged into
  488. // the current fragment.
  489. DF = new MCDataFragment();
  490. else if (isBundleLocked() && !Sec.isBundleGroupBeforeFirstInst()) {
  491. // If we are bundle-locked, we re-use the current fragment.
  492. // The bundle-locking directive ensures this is a new data fragment.
  493. DF = cast<MCDataFragment>(getCurrentFragment());
  494. CheckBundleSubtargets(DF->getSubtargetInfo(), &STI);
  495. }
  496. else if (!isBundleLocked() && Fixups.size() == 0) {
  497. // Optimize memory usage by emitting the instruction to a
  498. // MCCompactEncodedInstFragment when not in a bundle-locked group and
  499. // there are no fixups registered.
  500. MCCompactEncodedInstFragment *CEIF = new MCCompactEncodedInstFragment();
  501. insert(CEIF);
  502. CEIF->getContents().append(Code.begin(), Code.end());
  503. CEIF->setHasInstructions(STI);
  504. return;
  505. } else {
  506. DF = new MCDataFragment();
  507. insert(DF);
  508. }
  509. if (Sec.getBundleLockState() == MCSection::BundleLockedAlignToEnd) {
  510. // If this fragment is for a group marked "align_to_end", set a flag
  511. // in the fragment. This can happen after the fragment has already been
  512. // created if there are nested bundle_align groups and an inner one
  513. // is the one marked align_to_end.
  514. DF->setAlignToBundleEnd(true);
  515. }
  516. // We're now emitting an instruction in a bundle group, so this flag has
  517. // to be turned off.
  518. Sec.setBundleGroupBeforeFirstInst(false);
  519. } else {
  520. DF = getOrCreateDataFragment(&STI);
  521. }
  522. // Add the fixups and data.
  523. for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
  524. Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
  525. DF->getFixups().push_back(Fixups[i]);
  526. }
  527. DF->setHasInstructions(STI);
  528. DF->getContents().append(Code.begin(), Code.end());
  529. if (Assembler.isBundlingEnabled() && Assembler.getRelaxAll()) {
  530. if (!isBundleLocked()) {
  531. mergeFragment(getOrCreateDataFragment(&STI), DF);
  532. delete DF;
  533. }
  534. }
  535. }
  536. void MCELFStreamer::emitBundleAlignMode(unsigned AlignPow2) {
  537. assert(AlignPow2 <= 30 && "Invalid bundle alignment");
  538. MCAssembler &Assembler = getAssembler();
  539. if (AlignPow2 > 0 && (Assembler.getBundleAlignSize() == 0 ||
  540. Assembler.getBundleAlignSize() == 1U << AlignPow2))
  541. Assembler.setBundleAlignSize(1U << AlignPow2);
  542. else
  543. report_fatal_error(".bundle_align_mode cannot be changed once set");
  544. }
  545. void MCELFStreamer::emitBundleLock(bool AlignToEnd) {
  546. MCSection &Sec = *getCurrentSectionOnly();
  547. // Sanity checks
  548. //
  549. if (!getAssembler().isBundlingEnabled())
  550. report_fatal_error(".bundle_lock forbidden when bundling is disabled");
  551. if (!isBundleLocked())
  552. Sec.setBundleGroupBeforeFirstInst(true);
  553. if (getAssembler().getRelaxAll() && !isBundleLocked()) {
  554. // TODO: drop the lock state and set directly in the fragment
  555. MCDataFragment *DF = new MCDataFragment();
  556. BundleGroups.push_back(DF);
  557. }
  558. Sec.setBundleLockState(AlignToEnd ? MCSection::BundleLockedAlignToEnd
  559. : MCSection::BundleLocked);
  560. }
  561. void MCELFStreamer::emitBundleUnlock() {
  562. MCSection &Sec = *getCurrentSectionOnly();
  563. // Sanity checks
  564. if (!getAssembler().isBundlingEnabled())
  565. report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
  566. else if (!isBundleLocked())
  567. report_fatal_error(".bundle_unlock without matching lock");
  568. else if (Sec.isBundleGroupBeforeFirstInst())
  569. report_fatal_error("Empty bundle-locked group is forbidden");
  570. // When the -mc-relax-all flag is used, we emit instructions to fragments
  571. // stored on a stack. When the bundle unlock is emitted, we pop a fragment
  572. // from the stack a merge it to the one below.
  573. if (getAssembler().getRelaxAll()) {
  574. assert(!BundleGroups.empty() && "There are no bundle groups");
  575. MCDataFragment *DF = BundleGroups.back();
  576. // FIXME: Use BundleGroups to track the lock state instead.
  577. Sec.setBundleLockState(MCSection::NotBundleLocked);
  578. // FIXME: Use more separate fragments for nested groups.
  579. if (!isBundleLocked()) {
  580. mergeFragment(getOrCreateDataFragment(DF->getSubtargetInfo()), DF);
  581. BundleGroups.pop_back();
  582. delete DF;
  583. }
  584. if (Sec.getBundleLockState() != MCSection::BundleLockedAlignToEnd)
  585. getOrCreateDataFragment()->setAlignToBundleEnd(false);
  586. } else
  587. Sec.setBundleLockState(MCSection::NotBundleLocked);
  588. }
  589. void MCELFStreamer::finishImpl() {
  590. // Ensure the last section gets aligned if necessary.
  591. MCSection *CurSection = getCurrentSectionOnly();
  592. setSectionAlignmentForBundling(getAssembler(), CurSection);
  593. finalizeCGProfile();
  594. emitFrames(nullptr);
  595. this->MCObjectStreamer::finishImpl();
  596. }
  597. void MCELFStreamer::emitThumbFunc(MCSymbol *Func) {
  598. llvm_unreachable("Generic ELF doesn't support this directive");
  599. }
  600. void MCELFStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
  601. llvm_unreachable("ELF doesn't support this directive");
  602. }
  603. void MCELFStreamer::emitZerofill(MCSection *Section, MCSymbol *Symbol,
  604. uint64_t Size, unsigned ByteAlignment,
  605. SMLoc Loc) {
  606. llvm_unreachable("ELF doesn't support this directive");
  607. }
  608. void MCELFStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
  609. uint64_t Size, unsigned ByteAlignment) {
  610. llvm_unreachable("ELF doesn't support this directive");
  611. }
  612. MCStreamer *llvm::createELFStreamer(MCContext &Context,
  613. std::unique_ptr<MCAsmBackend> &&MAB,
  614. std::unique_ptr<MCObjectWriter> &&OW,
  615. std::unique_ptr<MCCodeEmitter> &&CE,
  616. bool RelaxAll) {
  617. MCELFStreamer *S =
  618. new MCELFStreamer(Context, std::move(MAB), std::move(OW), std::move(CE));
  619. if (RelaxAll)
  620. S->getAssembler().setRelaxAll(true);
  621. return S;
  622. }