MCELFStreamer.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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/MC/TargetRegistry.h"
  32. #include "llvm/Support/Casting.h"
  33. #include "llvm/Support/ErrorHandling.h"
  34. #include "llvm/Support/LEB128.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include <cassert>
  37. #include <cstdint>
  38. using namespace llvm;
  39. MCELFStreamer::MCELFStreamer(MCContext &Context,
  40. std::unique_ptr<MCAsmBackend> TAB,
  41. std::unique_ptr<MCObjectWriter> OW,
  42. std::unique_ptr<MCCodeEmitter> Emitter)
  43. : MCObjectStreamer(Context, std::move(TAB), std::move(OW),
  44. std::move(Emitter)) {}
  45. bool MCELFStreamer::isBundleLocked() const {
  46. return getCurrentSectionOnly()->isBundleLocked();
  47. }
  48. void MCELFStreamer::mergeFragment(MCDataFragment *DF,
  49. MCDataFragment *EF) {
  50. MCAssembler &Assembler = getAssembler();
  51. if (Assembler.isBundlingEnabled() && Assembler.getRelaxAll()) {
  52. uint64_t FSize = EF->getContents().size();
  53. if (FSize > Assembler.getBundleAlignSize())
  54. report_fatal_error("Fragment can't be larger than a bundle size");
  55. uint64_t RequiredBundlePadding = computeBundlePadding(
  56. Assembler, EF, DF->getContents().size(), FSize);
  57. if (RequiredBundlePadding > UINT8_MAX)
  58. report_fatal_error("Padding cannot exceed 255 bytes");
  59. if (RequiredBundlePadding > 0) {
  60. SmallString<256> Code;
  61. raw_svector_ostream VecOS(Code);
  62. EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
  63. Assembler.writeFragmentPadding(VecOS, *EF, FSize);
  64. DF->getContents().append(Code.begin(), Code.end());
  65. }
  66. }
  67. flushPendingLabels(DF, DF->getContents().size());
  68. for (unsigned i = 0, e = EF->getFixups().size(); i != e; ++i) {
  69. EF->getFixups()[i].setOffset(EF->getFixups()[i].getOffset() +
  70. DF->getContents().size());
  71. DF->getFixups().push_back(EF->getFixups()[i]);
  72. }
  73. if (DF->getSubtargetInfo() == nullptr && EF->getSubtargetInfo())
  74. DF->setHasInstructions(*EF->getSubtargetInfo());
  75. DF->getContents().append(EF->getContents().begin(), EF->getContents().end());
  76. }
  77. void MCELFStreamer::initSections(bool NoExecStack, const MCSubtargetInfo &STI) {
  78. MCContext &Ctx = getContext();
  79. switchSection(Ctx.getObjectFileInfo()->getTextSection());
  80. emitCodeAlignment(Align(Ctx.getObjectFileInfo()->getTextSectionAlignment()),
  81. &STI);
  82. if (NoExecStack)
  83. switchSection(Ctx.getAsmInfo()->getNonexecutableStackSection(Ctx));
  84. }
  85. void MCELFStreamer::emitLabel(MCSymbol *S, SMLoc Loc) {
  86. auto *Symbol = cast<MCSymbolELF>(S);
  87. MCObjectStreamer::emitLabel(Symbol, Loc);
  88. const MCSectionELF &Section =
  89. static_cast<const MCSectionELF &>(*getCurrentSectionOnly());
  90. if (Section.getFlags() & ELF::SHF_TLS)
  91. Symbol->setType(ELF::STT_TLS);
  92. }
  93. void MCELFStreamer::emitLabelAtPos(MCSymbol *S, SMLoc Loc, MCFragment *F,
  94. uint64_t Offset) {
  95. auto *Symbol = cast<MCSymbolELF>(S);
  96. MCObjectStreamer::emitLabelAtPos(Symbol, Loc, F, Offset);
  97. const MCSectionELF &Section =
  98. static_cast<const MCSectionELF &>(*getCurrentSectionOnly());
  99. if (Section.getFlags() & ELF::SHF_TLS)
  100. Symbol->setType(ELF::STT_TLS);
  101. }
  102. void MCELFStreamer::emitAssemblerFlag(MCAssemblerFlag Flag) {
  103. // Let the target do whatever target specific stuff it needs to do.
  104. getAssembler().getBackend().handleAssemblerFlag(Flag);
  105. // Do any generic stuff we need to do.
  106. switch (Flag) {
  107. case MCAF_SyntaxUnified: return; // no-op here.
  108. case MCAF_Code16: return; // Change parsing mode; no-op here.
  109. case MCAF_Code32: return; // Change parsing mode; no-op here.
  110. case MCAF_Code64: return; // Change parsing mode; no-op here.
  111. case MCAF_SubsectionsViaSymbols:
  112. getAssembler().setSubsectionsViaSymbols(true);
  113. return;
  114. }
  115. llvm_unreachable("invalid assembler flag!");
  116. }
  117. // If bundle alignment is used and there are any instructions in the section, it
  118. // needs to be aligned to at least the bundle size.
  119. static void setSectionAlignmentForBundling(const MCAssembler &Assembler,
  120. MCSection *Section) {
  121. if (Section && Assembler.isBundlingEnabled() && Section->hasInstructions())
  122. Section->ensureMinAlignment(Align(Assembler.getBundleAlignSize()));
  123. }
  124. void MCELFStreamer::changeSection(MCSection *Section,
  125. const MCExpr *Subsection) {
  126. MCSection *CurSection = getCurrentSectionOnly();
  127. if (CurSection && isBundleLocked())
  128. report_fatal_error("Unterminated .bundle_lock when changing a section");
  129. MCAssembler &Asm = getAssembler();
  130. // Ensure the previous section gets aligned if necessary.
  131. setSectionAlignmentForBundling(Asm, CurSection);
  132. auto *SectionELF = static_cast<const MCSectionELF *>(Section);
  133. const MCSymbol *Grp = SectionELF->getGroup();
  134. if (Grp)
  135. Asm.registerSymbol(*Grp);
  136. if (SectionELF->getFlags() & ELF::SHF_GNU_RETAIN)
  137. Asm.getWriter().markGnuAbi();
  138. changeSectionImpl(Section, Subsection);
  139. Asm.registerSymbol(*Section->getBeginSymbol());
  140. }
  141. void MCELFStreamer::emitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
  142. getAssembler().registerSymbol(*Symbol);
  143. const MCExpr *Value = MCSymbolRefExpr::create(
  144. Symbol, MCSymbolRefExpr::VK_WEAKREF, getContext());
  145. Alias->setVariableValue(Value);
  146. }
  147. // When GNU as encounters more than one .type declaration for an object it seems
  148. // to use a mechanism similar to the one below to decide which type is actually
  149. // used in the object file. The greater of T1 and T2 is selected based on the
  150. // following ordering:
  151. // STT_NOTYPE < STT_OBJECT < STT_FUNC < STT_GNU_IFUNC < STT_TLS < anything else
  152. // If neither T1 < T2 nor T2 < T1 according to this ordering, use T2 (the user
  153. // provided type).
  154. static unsigned CombineSymbolTypes(unsigned T1, unsigned T2) {
  155. for (unsigned Type : {ELF::STT_NOTYPE, ELF::STT_OBJECT, ELF::STT_FUNC,
  156. ELF::STT_GNU_IFUNC, ELF::STT_TLS}) {
  157. if (T1 == Type)
  158. return T2;
  159. if (T2 == Type)
  160. return T1;
  161. }
  162. return T2;
  163. }
  164. bool MCELFStreamer::emitSymbolAttribute(MCSymbol *S, MCSymbolAttr Attribute) {
  165. auto *Symbol = cast<MCSymbolELF>(S);
  166. // Adding a symbol attribute always introduces the symbol, note that an
  167. // important side effect of calling registerSymbol here is to register
  168. // the symbol with the assembler.
  169. getAssembler().registerSymbol(*Symbol);
  170. // The implementation of symbol attributes is designed to match 'as', but it
  171. // leaves much to desired. It doesn't really make sense to arbitrarily add and
  172. // remove flags, but 'as' allows this (in particular, see .desc).
  173. //
  174. // In the future it might be worth trying to make these operations more well
  175. // defined.
  176. switch (Attribute) {
  177. case MCSA_Cold:
  178. case MCSA_Extern:
  179. case MCSA_LazyReference:
  180. case MCSA_Reference:
  181. case MCSA_SymbolResolver:
  182. case MCSA_PrivateExtern:
  183. case MCSA_WeakDefinition:
  184. case MCSA_WeakDefAutoPrivate:
  185. case MCSA_Invalid:
  186. case MCSA_IndirectSymbol:
  187. case MCSA_Exported:
  188. return false;
  189. case MCSA_NoDeadStrip:
  190. // Ignore for now.
  191. break;
  192. case MCSA_ELF_TypeGnuUniqueObject:
  193. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_OBJECT));
  194. Symbol->setBinding(ELF::STB_GNU_UNIQUE);
  195. getAssembler().getWriter().markGnuAbi();
  196. break;
  197. case MCSA_Global:
  198. // For `.weak x; .global x`, GNU as sets the binding to STB_WEAK while we
  199. // traditionally set the binding to STB_GLOBAL. This is error-prone, so we
  200. // error on such cases. Note, we also disallow changed binding from .local.
  201. if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_GLOBAL)
  202. getContext().reportError(getStartTokLoc(),
  203. Symbol->getName() +
  204. " changed binding to STB_GLOBAL");
  205. Symbol->setBinding(ELF::STB_GLOBAL);
  206. break;
  207. case MCSA_WeakReference:
  208. case MCSA_Weak:
  209. // For `.global x; .weak x`, both MC and GNU as set the binding to STB_WEAK.
  210. // We emit a warning for now but may switch to an error in the future.
  211. if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_WEAK)
  212. getContext().reportWarning(
  213. getStartTokLoc(), Symbol->getName() + " changed binding to STB_WEAK");
  214. Symbol->setBinding(ELF::STB_WEAK);
  215. break;
  216. case MCSA_Local:
  217. if (Symbol->isBindingSet() && Symbol->getBinding() != ELF::STB_LOCAL)
  218. getContext().reportError(getStartTokLoc(),
  219. Symbol->getName() +
  220. " changed binding to STB_LOCAL");
  221. Symbol->setBinding(ELF::STB_LOCAL);
  222. break;
  223. case MCSA_ELF_TypeFunction:
  224. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_FUNC));
  225. break;
  226. case MCSA_ELF_TypeIndFunction:
  227. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_GNU_IFUNC));
  228. getAssembler().getWriter().markGnuAbi();
  229. break;
  230. case MCSA_ELF_TypeObject:
  231. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_OBJECT));
  232. break;
  233. case MCSA_ELF_TypeTLS:
  234. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_TLS));
  235. break;
  236. case MCSA_ELF_TypeCommon:
  237. // TODO: Emit these as a common symbol.
  238. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_OBJECT));
  239. break;
  240. case MCSA_ELF_TypeNoType:
  241. Symbol->setType(CombineSymbolTypes(Symbol->getType(), ELF::STT_NOTYPE));
  242. break;
  243. case MCSA_Protected:
  244. Symbol->setVisibility(ELF::STV_PROTECTED);
  245. break;
  246. case MCSA_Memtag:
  247. Symbol->setMemtag(true);
  248. break;
  249. case MCSA_Hidden:
  250. Symbol->setVisibility(ELF::STV_HIDDEN);
  251. break;
  252. case MCSA_Internal:
  253. Symbol->setVisibility(ELF::STV_INTERNAL);
  254. break;
  255. case MCSA_AltEntry:
  256. llvm_unreachable("ELF doesn't support the .alt_entry attribute");
  257. case MCSA_LGlobal:
  258. llvm_unreachable("ELF doesn't support the .lglobl attribute");
  259. }
  260. return true;
  261. }
  262. void MCELFStreamer::emitCommonSymbol(MCSymbol *S, uint64_t Size,
  263. Align ByteAlignment) {
  264. auto *Symbol = cast<MCSymbolELF>(S);
  265. getAssembler().registerSymbol(*Symbol);
  266. if (!Symbol->isBindingSet())
  267. Symbol->setBinding(ELF::STB_GLOBAL);
  268. Symbol->setType(ELF::STT_OBJECT);
  269. if (Symbol->getBinding() == ELF::STB_LOCAL) {
  270. MCSection &Section = *getAssembler().getContext().getELFSection(
  271. ".bss", ELF::SHT_NOBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
  272. MCSectionSubPair P = getCurrentSection();
  273. switchSection(&Section);
  274. emitValueToAlignment(ByteAlignment, 0, 1, 0);
  275. emitLabel(Symbol);
  276. emitZeros(Size);
  277. switchSection(P.first, P.second);
  278. } else {
  279. if (Symbol->declareCommon(Size, ByteAlignment))
  280. report_fatal_error(Twine("Symbol: ") + Symbol->getName() +
  281. " redeclared as different type");
  282. }
  283. cast<MCSymbolELF>(Symbol)
  284. ->setSize(MCConstantExpr::create(Size, getContext()));
  285. }
  286. void MCELFStreamer::emitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
  287. cast<MCSymbolELF>(Symbol)->setSize(Value);
  288. }
  289. void MCELFStreamer::emitELFSymverDirective(const MCSymbol *OriginalSym,
  290. StringRef Name,
  291. bool KeepOriginalSym) {
  292. getAssembler().Symvers.push_back(MCAssembler::Symver{
  293. getStartTokLoc(), OriginalSym, Name, KeepOriginalSym});
  294. }
  295. void MCELFStreamer::emitLocalCommonSymbol(MCSymbol *S, uint64_t Size,
  296. Align ByteAlignment) {
  297. auto *Symbol = cast<MCSymbolELF>(S);
  298. // FIXME: Should this be caught and done earlier?
  299. getAssembler().registerSymbol(*Symbol);
  300. Symbol->setBinding(ELF::STB_LOCAL);
  301. emitCommonSymbol(Symbol, Size, ByteAlignment);
  302. }
  303. void MCELFStreamer::emitValueImpl(const MCExpr *Value, unsigned Size,
  304. SMLoc Loc) {
  305. if (isBundleLocked())
  306. report_fatal_error("Emitting values inside a locked bundle is forbidden");
  307. fixSymbolsInTLSFixups(Value);
  308. MCObjectStreamer::emitValueImpl(Value, Size, Loc);
  309. }
  310. void MCELFStreamer::emitValueToAlignment(Align Alignment, int64_t Value,
  311. unsigned ValueSize,
  312. unsigned MaxBytesToEmit) {
  313. if (isBundleLocked())
  314. report_fatal_error("Emitting values inside a locked bundle is forbidden");
  315. MCObjectStreamer::emitValueToAlignment(Alignment, Value, ValueSize,
  316. MaxBytesToEmit);
  317. }
  318. void MCELFStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
  319. const MCSymbolRefExpr *To,
  320. uint64_t Count) {
  321. getAssembler().CGProfile.push_back({From, To, Count});
  322. }
  323. void MCELFStreamer::emitIdent(StringRef IdentString) {
  324. MCSection *Comment = getAssembler().getContext().getELFSection(
  325. ".comment", ELF::SHT_PROGBITS, ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
  326. pushSection();
  327. switchSection(Comment);
  328. if (!SeenIdent) {
  329. emitInt8(0);
  330. SeenIdent = true;
  331. }
  332. emitBytes(IdentString);
  333. emitInt8(0);
  334. popSection();
  335. }
  336. void MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
  337. switch (expr->getKind()) {
  338. case MCExpr::Target:
  339. cast<MCTargetExpr>(expr)->fixELFSymbolsInTLSFixups(getAssembler());
  340. break;
  341. case MCExpr::Constant:
  342. break;
  343. case MCExpr::Binary: {
  344. const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
  345. fixSymbolsInTLSFixups(be->getLHS());
  346. fixSymbolsInTLSFixups(be->getRHS());
  347. break;
  348. }
  349. case MCExpr::SymbolRef: {
  350. const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
  351. switch (symRef.getKind()) {
  352. default:
  353. return;
  354. case MCSymbolRefExpr::VK_GOTTPOFF:
  355. case MCSymbolRefExpr::VK_INDNTPOFF:
  356. case MCSymbolRefExpr::VK_NTPOFF:
  357. case MCSymbolRefExpr::VK_GOTNTPOFF:
  358. case MCSymbolRefExpr::VK_TLSCALL:
  359. case MCSymbolRefExpr::VK_TLSDESC:
  360. case MCSymbolRefExpr::VK_TLSGD:
  361. case MCSymbolRefExpr::VK_TLSLD:
  362. case MCSymbolRefExpr::VK_TLSLDM:
  363. case MCSymbolRefExpr::VK_TPOFF:
  364. case MCSymbolRefExpr::VK_TPREL:
  365. case MCSymbolRefExpr::VK_DTPOFF:
  366. case MCSymbolRefExpr::VK_DTPREL:
  367. case MCSymbolRefExpr::VK_PPC_DTPMOD:
  368. case MCSymbolRefExpr::VK_PPC_TPREL_LO:
  369. case MCSymbolRefExpr::VK_PPC_TPREL_HI:
  370. case MCSymbolRefExpr::VK_PPC_TPREL_HA:
  371. case MCSymbolRefExpr::VK_PPC_TPREL_HIGH:
  372. case MCSymbolRefExpr::VK_PPC_TPREL_HIGHA:
  373. case MCSymbolRefExpr::VK_PPC_TPREL_HIGHER:
  374. case MCSymbolRefExpr::VK_PPC_TPREL_HIGHERA:
  375. case MCSymbolRefExpr::VK_PPC_TPREL_HIGHEST:
  376. case MCSymbolRefExpr::VK_PPC_TPREL_HIGHESTA:
  377. case MCSymbolRefExpr::VK_PPC_DTPREL_LO:
  378. case MCSymbolRefExpr::VK_PPC_DTPREL_HI:
  379. case MCSymbolRefExpr::VK_PPC_DTPREL_HA:
  380. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGH:
  381. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHA:
  382. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHER:
  383. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHERA:
  384. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHEST:
  385. case MCSymbolRefExpr::VK_PPC_DTPREL_HIGHESTA:
  386. case MCSymbolRefExpr::VK_PPC_GOT_TPREL:
  387. case MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO:
  388. case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HI:
  389. case MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA:
  390. case MCSymbolRefExpr::VK_PPC_GOT_TPREL_PCREL:
  391. case MCSymbolRefExpr::VK_PPC_GOT_DTPREL:
  392. case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_LO:
  393. case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HI:
  394. case MCSymbolRefExpr::VK_PPC_GOT_DTPREL_HA:
  395. case MCSymbolRefExpr::VK_PPC_TLS:
  396. case MCSymbolRefExpr::VK_PPC_TLS_PCREL:
  397. case MCSymbolRefExpr::VK_PPC_GOT_TLSGD:
  398. case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO:
  399. case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HI:
  400. case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA:
  401. case MCSymbolRefExpr::VK_PPC_GOT_TLSGD_PCREL:
  402. case MCSymbolRefExpr::VK_PPC_TLSGD:
  403. case MCSymbolRefExpr::VK_PPC_GOT_TLSLD:
  404. case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO:
  405. case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HI:
  406. case MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA:
  407. case MCSymbolRefExpr::VK_PPC_TLSLD:
  408. break;
  409. }
  410. getAssembler().registerSymbol(symRef.getSymbol());
  411. cast<MCSymbolELF>(symRef.getSymbol()).setType(ELF::STT_TLS);
  412. break;
  413. }
  414. case MCExpr::Unary:
  415. fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
  416. break;
  417. }
  418. }
  419. void MCELFStreamer::finalizeCGProfileEntry(const MCSymbolRefExpr *&SRE,
  420. uint64_t Offset) {
  421. const MCSymbol *S = &SRE->getSymbol();
  422. if (S->isTemporary()) {
  423. if (!S->isInSection()) {
  424. getContext().reportError(
  425. SRE->getLoc(), Twine("Reference to undefined temporary symbol ") +
  426. "`" + S->getName() + "`");
  427. return;
  428. }
  429. S = S->getSection().getBeginSymbol();
  430. S->setUsedInReloc();
  431. SRE = MCSymbolRefExpr::create(S, MCSymbolRefExpr::VK_None, getContext(),
  432. SRE->getLoc());
  433. }
  434. const MCConstantExpr *MCOffset = MCConstantExpr::create(Offset, getContext());
  435. MCObjectStreamer::visitUsedExpr(*SRE);
  436. if (std::optional<std::pair<bool, std::string>> Err =
  437. MCObjectStreamer::emitRelocDirective(
  438. *MCOffset, "BFD_RELOC_NONE", SRE, SRE->getLoc(),
  439. *getContext().getSubtargetInfo()))
  440. report_fatal_error("Relocation for CG Profile could not be created: " +
  441. Twine(Err->second));
  442. }
  443. void MCELFStreamer::finalizeCGProfile() {
  444. MCAssembler &Asm = getAssembler();
  445. if (Asm.CGProfile.empty())
  446. return;
  447. MCSection *CGProfile = getAssembler().getContext().getELFSection(
  448. ".llvm.call-graph-profile", ELF::SHT_LLVM_CALL_GRAPH_PROFILE,
  449. ELF::SHF_EXCLUDE, /*sizeof(Elf_CGProfile_Impl<>)=*/8);
  450. pushSection();
  451. switchSection(CGProfile);
  452. uint64_t Offset = 0;
  453. for (MCAssembler::CGProfileEntry &E : Asm.CGProfile) {
  454. finalizeCGProfileEntry(E.From, Offset);
  455. finalizeCGProfileEntry(E.To, Offset);
  456. emitIntValue(E.Count, sizeof(uint64_t));
  457. Offset += sizeof(uint64_t);
  458. }
  459. popSection();
  460. }
  461. void MCELFStreamer::emitInstToFragment(const MCInst &Inst,
  462. const MCSubtargetInfo &STI) {
  463. this->MCObjectStreamer::emitInstToFragment(Inst, STI);
  464. MCRelaxableFragment &F = *cast<MCRelaxableFragment>(getCurrentFragment());
  465. for (auto &Fixup : F.getFixups())
  466. fixSymbolsInTLSFixups(Fixup.getValue());
  467. }
  468. // A fragment can only have one Subtarget, and when bundling is enabled we
  469. // sometimes need to use the same fragment. We give an error if there
  470. // are conflicting Subtargets.
  471. static void CheckBundleSubtargets(const MCSubtargetInfo *OldSTI,
  472. const MCSubtargetInfo *NewSTI) {
  473. if (OldSTI && NewSTI && OldSTI != NewSTI)
  474. report_fatal_error("A Bundle can only have one Subtarget.");
  475. }
  476. void MCELFStreamer::emitInstToData(const MCInst &Inst,
  477. const MCSubtargetInfo &STI) {
  478. MCAssembler &Assembler = getAssembler();
  479. SmallVector<MCFixup, 4> Fixups;
  480. SmallString<256> Code;
  481. raw_svector_ostream VecOS(Code);
  482. Assembler.getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
  483. for (auto &Fixup : Fixups)
  484. fixSymbolsInTLSFixups(Fixup.getValue());
  485. // There are several possibilities here:
  486. //
  487. // If bundling is disabled, append the encoded instruction to the current data
  488. // fragment (or create a new such fragment if the current fragment is not a
  489. // data fragment, or the Subtarget has changed).
  490. //
  491. // If bundling is enabled:
  492. // - If we're not in a bundle-locked group, emit the instruction into a
  493. // fragment of its own. If there are no fixups registered for the
  494. // instruction, emit a MCCompactEncodedInstFragment. Otherwise, emit a
  495. // MCDataFragment.
  496. // - If we're in a bundle-locked group, append the instruction to the current
  497. // data fragment because we want all the instructions in a group to get into
  498. // the same fragment. Be careful not to do that for the first instruction in
  499. // the group, though.
  500. MCDataFragment *DF;
  501. if (Assembler.isBundlingEnabled()) {
  502. MCSection &Sec = *getCurrentSectionOnly();
  503. if (Assembler.getRelaxAll() && isBundleLocked()) {
  504. // If the -mc-relax-all flag is used and we are bundle-locked, we re-use
  505. // the current bundle group.
  506. DF = BundleGroups.back();
  507. CheckBundleSubtargets(DF->getSubtargetInfo(), &STI);
  508. }
  509. else if (Assembler.getRelaxAll() && !isBundleLocked())
  510. // When not in a bundle-locked group and the -mc-relax-all flag is used,
  511. // we create a new temporary fragment which will be later merged into
  512. // the current fragment.
  513. DF = new MCDataFragment();
  514. else if (isBundleLocked() && !Sec.isBundleGroupBeforeFirstInst()) {
  515. // If we are bundle-locked, we re-use the current fragment.
  516. // The bundle-locking directive ensures this is a new data fragment.
  517. DF = cast<MCDataFragment>(getCurrentFragment());
  518. CheckBundleSubtargets(DF->getSubtargetInfo(), &STI);
  519. }
  520. else if (!isBundleLocked() && Fixups.size() == 0) {
  521. // Optimize memory usage by emitting the instruction to a
  522. // MCCompactEncodedInstFragment when not in a bundle-locked group and
  523. // there are no fixups registered.
  524. MCCompactEncodedInstFragment *CEIF = new MCCompactEncodedInstFragment();
  525. insert(CEIF);
  526. CEIF->getContents().append(Code.begin(), Code.end());
  527. CEIF->setHasInstructions(STI);
  528. return;
  529. } else {
  530. DF = new MCDataFragment();
  531. insert(DF);
  532. }
  533. if (Sec.getBundleLockState() == MCSection::BundleLockedAlignToEnd) {
  534. // If this fragment is for a group marked "align_to_end", set a flag
  535. // in the fragment. This can happen after the fragment has already been
  536. // created if there are nested bundle_align groups and an inner one
  537. // is the one marked align_to_end.
  538. DF->setAlignToBundleEnd(true);
  539. }
  540. // We're now emitting an instruction in a bundle group, so this flag has
  541. // to be turned off.
  542. Sec.setBundleGroupBeforeFirstInst(false);
  543. } else {
  544. DF = getOrCreateDataFragment(&STI);
  545. }
  546. // Add the fixups and data.
  547. for (auto &Fixup : Fixups) {
  548. Fixup.setOffset(Fixup.getOffset() + DF->getContents().size());
  549. DF->getFixups().push_back(Fixup);
  550. }
  551. DF->setHasInstructions(STI);
  552. DF->getContents().append(Code.begin(), Code.end());
  553. if (Assembler.isBundlingEnabled() && Assembler.getRelaxAll()) {
  554. if (!isBundleLocked()) {
  555. mergeFragment(getOrCreateDataFragment(&STI), DF);
  556. delete DF;
  557. }
  558. }
  559. }
  560. void MCELFStreamer::emitBundleAlignMode(Align Alignment) {
  561. assert(Log2(Alignment) <= 30 && "Invalid bundle alignment");
  562. MCAssembler &Assembler = getAssembler();
  563. if (Alignment > 1 && (Assembler.getBundleAlignSize() == 0 ||
  564. Assembler.getBundleAlignSize() == Alignment.value()))
  565. Assembler.setBundleAlignSize(Alignment.value());
  566. else
  567. report_fatal_error(".bundle_align_mode cannot be changed once set");
  568. }
  569. void MCELFStreamer::emitBundleLock(bool AlignToEnd) {
  570. MCSection &Sec = *getCurrentSectionOnly();
  571. if (!getAssembler().isBundlingEnabled())
  572. report_fatal_error(".bundle_lock forbidden when bundling is disabled");
  573. if (!isBundleLocked())
  574. Sec.setBundleGroupBeforeFirstInst(true);
  575. if (getAssembler().getRelaxAll() && !isBundleLocked()) {
  576. // TODO: drop the lock state and set directly in the fragment
  577. MCDataFragment *DF = new MCDataFragment();
  578. BundleGroups.push_back(DF);
  579. }
  580. Sec.setBundleLockState(AlignToEnd ? MCSection::BundleLockedAlignToEnd
  581. : MCSection::BundleLocked);
  582. }
  583. void MCELFStreamer::emitBundleUnlock() {
  584. MCSection &Sec = *getCurrentSectionOnly();
  585. if (!getAssembler().isBundlingEnabled())
  586. report_fatal_error(".bundle_unlock forbidden when bundling is disabled");
  587. else if (!isBundleLocked())
  588. report_fatal_error(".bundle_unlock without matching lock");
  589. else if (Sec.isBundleGroupBeforeFirstInst())
  590. report_fatal_error("Empty bundle-locked group is forbidden");
  591. // When the -mc-relax-all flag is used, we emit instructions to fragments
  592. // stored on a stack. When the bundle unlock is emitted, we pop a fragment
  593. // from the stack a merge it to the one below.
  594. if (getAssembler().getRelaxAll()) {
  595. assert(!BundleGroups.empty() && "There are no bundle groups");
  596. MCDataFragment *DF = BundleGroups.back();
  597. // FIXME: Use BundleGroups to track the lock state instead.
  598. Sec.setBundleLockState(MCSection::NotBundleLocked);
  599. // FIXME: Use more separate fragments for nested groups.
  600. if (!isBundleLocked()) {
  601. mergeFragment(getOrCreateDataFragment(DF->getSubtargetInfo()), DF);
  602. BundleGroups.pop_back();
  603. delete DF;
  604. }
  605. if (Sec.getBundleLockState() != MCSection::BundleLockedAlignToEnd)
  606. getOrCreateDataFragment()->setAlignToBundleEnd(false);
  607. } else
  608. Sec.setBundleLockState(MCSection::NotBundleLocked);
  609. }
  610. void MCELFStreamer::finishImpl() {
  611. // Emit the .gnu attributes section if any attributes have been added.
  612. if (!GNUAttributes.empty()) {
  613. MCSection *DummyAttributeSection = nullptr;
  614. createAttributesSection("gnu", ".gnu.attributes", ELF::SHT_GNU_ATTRIBUTES,
  615. DummyAttributeSection, GNUAttributes);
  616. }
  617. // Ensure the last section gets aligned if necessary.
  618. MCSection *CurSection = getCurrentSectionOnly();
  619. setSectionAlignmentForBundling(getAssembler(), CurSection);
  620. finalizeCGProfile();
  621. emitFrames(nullptr);
  622. this->MCObjectStreamer::finishImpl();
  623. }
  624. void MCELFStreamer::emitThumbFunc(MCSymbol *Func) {
  625. llvm_unreachable("Generic ELF doesn't support this directive");
  626. }
  627. void MCELFStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
  628. llvm_unreachable("ELF doesn't support this directive");
  629. }
  630. void MCELFStreamer::emitZerofill(MCSection *Section, MCSymbol *Symbol,
  631. uint64_t Size, Align ByteAlignment,
  632. SMLoc Loc) {
  633. llvm_unreachable("ELF doesn't support this directive");
  634. }
  635. void MCELFStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
  636. uint64_t Size, Align ByteAlignment) {
  637. llvm_unreachable("ELF doesn't support this directive");
  638. }
  639. void MCELFStreamer::setAttributeItem(unsigned Attribute, unsigned Value,
  640. bool OverwriteExisting) {
  641. // Look for existing attribute item
  642. if (AttributeItem *Item = getAttributeItem(Attribute)) {
  643. if (!OverwriteExisting)
  644. return;
  645. Item->Type = AttributeItem::NumericAttribute;
  646. Item->IntValue = Value;
  647. return;
  648. }
  649. // Create new attribute item
  650. AttributeItem Item = {AttributeItem::NumericAttribute, Attribute, Value,
  651. std::string(StringRef(""))};
  652. Contents.push_back(Item);
  653. }
  654. void MCELFStreamer::setAttributeItem(unsigned Attribute, StringRef Value,
  655. bool OverwriteExisting) {
  656. // Look for existing attribute item
  657. if (AttributeItem *Item = getAttributeItem(Attribute)) {
  658. if (!OverwriteExisting)
  659. return;
  660. Item->Type = AttributeItem::TextAttribute;
  661. Item->StringValue = std::string(Value);
  662. return;
  663. }
  664. // Create new attribute item
  665. AttributeItem Item = {AttributeItem::TextAttribute, Attribute, 0,
  666. std::string(Value)};
  667. Contents.push_back(Item);
  668. }
  669. void MCELFStreamer::setAttributeItems(unsigned Attribute, unsigned IntValue,
  670. StringRef StringValue,
  671. bool OverwriteExisting) {
  672. // Look for existing attribute item
  673. if (AttributeItem *Item = getAttributeItem(Attribute)) {
  674. if (!OverwriteExisting)
  675. return;
  676. Item->Type = AttributeItem::NumericAndTextAttributes;
  677. Item->IntValue = IntValue;
  678. Item->StringValue = std::string(StringValue);
  679. return;
  680. }
  681. // Create new attribute item
  682. AttributeItem Item = {AttributeItem::NumericAndTextAttributes, Attribute,
  683. IntValue, std::string(StringValue)};
  684. Contents.push_back(Item);
  685. }
  686. MCELFStreamer::AttributeItem *
  687. MCELFStreamer::getAttributeItem(unsigned Attribute) {
  688. for (size_t I = 0; I < Contents.size(); ++I)
  689. if (Contents[I].Tag == Attribute)
  690. return &Contents[I];
  691. return nullptr;
  692. }
  693. size_t
  694. MCELFStreamer::calculateContentSize(SmallVector<AttributeItem, 64> &AttrsVec) {
  695. size_t Result = 0;
  696. for (size_t I = 0; I < AttrsVec.size(); ++I) {
  697. AttributeItem Item = AttrsVec[I];
  698. switch (Item.Type) {
  699. case AttributeItem::HiddenAttribute:
  700. break;
  701. case AttributeItem::NumericAttribute:
  702. Result += getULEB128Size(Item.Tag);
  703. Result += getULEB128Size(Item.IntValue);
  704. break;
  705. case AttributeItem::TextAttribute:
  706. Result += getULEB128Size(Item.Tag);
  707. Result += Item.StringValue.size() + 1; // string + '\0'
  708. break;
  709. case AttributeItem::NumericAndTextAttributes:
  710. Result += getULEB128Size(Item.Tag);
  711. Result += getULEB128Size(Item.IntValue);
  712. Result += Item.StringValue.size() + 1; // string + '\0';
  713. break;
  714. }
  715. }
  716. return Result;
  717. }
  718. void MCELFStreamer::createAttributesSection(
  719. StringRef Vendor, const Twine &Section, unsigned Type,
  720. MCSection *&AttributeSection, SmallVector<AttributeItem, 64> &AttrsVec) {
  721. // <format-version>
  722. // [ <section-length> "vendor-name"
  723. // [ <file-tag> <size> <attribute>*
  724. // | <section-tag> <size> <section-number>* 0 <attribute>*
  725. // | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
  726. // ]+
  727. // ]*
  728. // Switch section to AttributeSection or get/create the section.
  729. if (AttributeSection) {
  730. switchSection(AttributeSection);
  731. } else {
  732. AttributeSection = getContext().getELFSection(Section, Type, 0);
  733. switchSection(AttributeSection);
  734. // Format version
  735. emitInt8(0x41);
  736. }
  737. // Vendor size + Vendor name + '\0'
  738. const size_t VendorHeaderSize = 4 + Vendor.size() + 1;
  739. // Tag + Tag Size
  740. const size_t TagHeaderSize = 1 + 4;
  741. const size_t ContentsSize = calculateContentSize(AttrsVec);
  742. emitInt32(VendorHeaderSize + TagHeaderSize + ContentsSize);
  743. emitBytes(Vendor);
  744. emitInt8(0); // '\0'
  745. emitInt8(ARMBuildAttrs::File);
  746. emitInt32(TagHeaderSize + ContentsSize);
  747. // Size should have been accounted for already, now
  748. // emit each field as its type (ULEB or String)
  749. for (size_t I = 0; I < AttrsVec.size(); ++I) {
  750. AttributeItem Item = AttrsVec[I];
  751. emitULEB128IntValue(Item.Tag);
  752. switch (Item.Type) {
  753. default:
  754. llvm_unreachable("Invalid attribute type");
  755. case AttributeItem::NumericAttribute:
  756. emitULEB128IntValue(Item.IntValue);
  757. break;
  758. case AttributeItem::TextAttribute:
  759. emitBytes(Item.StringValue);
  760. emitInt8(0); // '\0'
  761. break;
  762. case AttributeItem::NumericAndTextAttributes:
  763. emitULEB128IntValue(Item.IntValue);
  764. emitBytes(Item.StringValue);
  765. emitInt8(0); // '\0'
  766. break;
  767. }
  768. }
  769. AttrsVec.clear();
  770. }
  771. MCStreamer *llvm::createELFStreamer(MCContext &Context,
  772. std::unique_ptr<MCAsmBackend> &&MAB,
  773. std::unique_ptr<MCObjectWriter> &&OW,
  774. std::unique_ptr<MCCodeEmitter> &&CE,
  775. bool RelaxAll) {
  776. MCELFStreamer *S =
  777. new MCELFStreamer(Context, std::move(MAB), std::move(OW), std::move(CE));
  778. if (RelaxAll)
  779. S->getAssembler().setRelaxAll(true);
  780. return S;
  781. }