MCFragment.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. //===- lib/MC/MCFragment.cpp - Assembler Fragment Implementation ----------===//
  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. #include "llvm/MC/MCFragment.h"
  9. #include "llvm/ADT/SmallVector.h"
  10. #include "llvm/ADT/StringExtras.h"
  11. #include "llvm/ADT/Twine.h"
  12. #include "llvm/Config/llvm-config.h"
  13. #include "llvm/MC/MCAsmLayout.h"
  14. #include "llvm/MC/MCAssembler.h"
  15. #include "llvm/MC/MCContext.h"
  16. #include "llvm/MC/MCExpr.h"
  17. #include "llvm/MC/MCFixup.h"
  18. #include "llvm/MC/MCSection.h"
  19. #include "llvm/MC/MCSymbol.h"
  20. #include "llvm/MC/MCValue.h"
  21. #include "llvm/Support/Casting.h"
  22. #include "llvm/Support/Compiler.h"
  23. #include "llvm/Support/ErrorHandling.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include <cassert>
  26. #include <cstdint>
  27. #include <utility>
  28. using namespace llvm;
  29. MCAsmLayout::MCAsmLayout(MCAssembler &Asm) : Assembler(Asm) {
  30. // Compute the section layout order. Virtual sections must go last.
  31. for (MCSection &Sec : Asm)
  32. if (!Sec.isVirtualSection())
  33. SectionOrder.push_back(&Sec);
  34. for (MCSection &Sec : Asm)
  35. if (Sec.isVirtualSection())
  36. SectionOrder.push_back(&Sec);
  37. }
  38. bool MCAsmLayout::isFragmentValid(const MCFragment *F) const {
  39. const MCSection *Sec = F->getParent();
  40. const MCFragment *LastValid = LastValidFragment.lookup(Sec);
  41. if (!LastValid)
  42. return false;
  43. assert(LastValid->getParent() == Sec);
  44. return F->getLayoutOrder() <= LastValid->getLayoutOrder();
  45. }
  46. bool MCAsmLayout::canGetFragmentOffset(const MCFragment *F) const {
  47. MCSection *Sec = F->getParent();
  48. MCSection::iterator I;
  49. if (MCFragment *LastValid = LastValidFragment[Sec]) {
  50. // Fragment already valid, offset is available.
  51. if (F->getLayoutOrder() <= LastValid->getLayoutOrder())
  52. return true;
  53. I = ++MCSection::iterator(LastValid);
  54. } else
  55. I = Sec->begin();
  56. // A fragment ordered before F is currently being laid out.
  57. const MCFragment *FirstInvalidFragment = &*I;
  58. if (FirstInvalidFragment->IsBeingLaidOut)
  59. return false;
  60. return true;
  61. }
  62. void MCAsmLayout::invalidateFragmentsFrom(MCFragment *F) {
  63. // If this fragment wasn't already valid, we don't need to do anything.
  64. if (!isFragmentValid(F))
  65. return;
  66. // Otherwise, reset the last valid fragment to the previous fragment
  67. // (if this is the first fragment, it will be NULL).
  68. LastValidFragment[F->getParent()] = F->getPrevNode();
  69. }
  70. void MCAsmLayout::ensureValid(const MCFragment *F) const {
  71. MCSection *Sec = F->getParent();
  72. MCSection::iterator I;
  73. if (MCFragment *Cur = LastValidFragment[Sec])
  74. I = ++MCSection::iterator(Cur);
  75. else
  76. I = Sec->begin();
  77. // Advance the layout position until the fragment is valid.
  78. while (!isFragmentValid(F)) {
  79. assert(I != Sec->end() && "Layout bookkeeping error");
  80. const_cast<MCAsmLayout *>(this)->layoutFragment(&*I);
  81. ++I;
  82. }
  83. }
  84. uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
  85. ensureValid(F);
  86. assert(F->Offset != ~UINT64_C(0) && "Address not set!");
  87. return F->Offset;
  88. }
  89. // Simple getSymbolOffset helper for the non-variable case.
  90. static bool getLabelOffset(const MCAsmLayout &Layout, const MCSymbol &S,
  91. bool ReportError, uint64_t &Val) {
  92. if (!S.getFragment()) {
  93. if (ReportError)
  94. report_fatal_error("unable to evaluate offset to undefined symbol '" +
  95. S.getName() + "'");
  96. return false;
  97. }
  98. Val = Layout.getFragmentOffset(S.getFragment()) + S.getOffset();
  99. return true;
  100. }
  101. static bool getSymbolOffsetImpl(const MCAsmLayout &Layout, const MCSymbol &S,
  102. bool ReportError, uint64_t &Val) {
  103. if (!S.isVariable())
  104. return getLabelOffset(Layout, S, ReportError, Val);
  105. // If SD is a variable, evaluate it.
  106. MCValue Target;
  107. if (!S.getVariableValue()->evaluateAsValue(Target, Layout))
  108. report_fatal_error("unable to evaluate offset for variable '" +
  109. S.getName() + "'");
  110. uint64_t Offset = Target.getConstant();
  111. const MCSymbolRefExpr *A = Target.getSymA();
  112. if (A) {
  113. uint64_t ValA;
  114. // FIXME: On most platforms, `Target`'s component symbols are labels from
  115. // having been simplified during evaluation, but on Mach-O they can be
  116. // variables due to PR19203. This, and the line below for `B` can be
  117. // restored to call `getLabelOffset` when PR19203 is fixed.
  118. if (!getSymbolOffsetImpl(Layout, A->getSymbol(), ReportError, ValA))
  119. return false;
  120. Offset += ValA;
  121. }
  122. const MCSymbolRefExpr *B = Target.getSymB();
  123. if (B) {
  124. uint64_t ValB;
  125. if (!getSymbolOffsetImpl(Layout, B->getSymbol(), ReportError, ValB))
  126. return false;
  127. Offset -= ValB;
  128. }
  129. Val = Offset;
  130. return true;
  131. }
  132. bool MCAsmLayout::getSymbolOffset(const MCSymbol &S, uint64_t &Val) const {
  133. return getSymbolOffsetImpl(*this, S, false, Val);
  134. }
  135. uint64_t MCAsmLayout::getSymbolOffset(const MCSymbol &S) const {
  136. uint64_t Val;
  137. getSymbolOffsetImpl(*this, S, true, Val);
  138. return Val;
  139. }
  140. const MCSymbol *MCAsmLayout::getBaseSymbol(const MCSymbol &Symbol) const {
  141. if (!Symbol.isVariable())
  142. return &Symbol;
  143. const MCExpr *Expr = Symbol.getVariableValue();
  144. MCValue Value;
  145. if (!Expr->evaluateAsValue(Value, *this)) {
  146. Assembler.getContext().reportError(
  147. Expr->getLoc(), "expression could not be evaluated");
  148. return nullptr;
  149. }
  150. const MCSymbolRefExpr *RefB = Value.getSymB();
  151. if (RefB) {
  152. Assembler.getContext().reportError(
  153. Expr->getLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
  154. "' could not be evaluated in a subtraction expression");
  155. return nullptr;
  156. }
  157. const MCSymbolRefExpr *A = Value.getSymA();
  158. if (!A)
  159. return nullptr;
  160. const MCSymbol &ASym = A->getSymbol();
  161. const MCAssembler &Asm = getAssembler();
  162. if (ASym.isCommon()) {
  163. Asm.getContext().reportError(Expr->getLoc(),
  164. "Common symbol '" + ASym.getName() +
  165. "' cannot be used in assignment expr");
  166. return nullptr;
  167. }
  168. return &ASym;
  169. }
  170. uint64_t MCAsmLayout::getSectionAddressSize(const MCSection *Sec) const {
  171. // The size is the last fragment's end offset.
  172. const MCFragment &F = Sec->getFragmentList().back();
  173. return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
  174. }
  175. uint64_t MCAsmLayout::getSectionFileSize(const MCSection *Sec) const {
  176. // Virtual sections have no file size.
  177. if (Sec->isVirtualSection())
  178. return 0;
  179. // Otherwise, the file size is the same as the address space size.
  180. return getSectionAddressSize(Sec);
  181. }
  182. uint64_t llvm::computeBundlePadding(const MCAssembler &Assembler,
  183. const MCEncodedFragment *F,
  184. uint64_t FOffset, uint64_t FSize) {
  185. uint64_t BundleSize = Assembler.getBundleAlignSize();
  186. assert(BundleSize > 0 &&
  187. "computeBundlePadding should only be called if bundling is enabled");
  188. uint64_t BundleMask = BundleSize - 1;
  189. uint64_t OffsetInBundle = FOffset & BundleMask;
  190. uint64_t EndOfFragment = OffsetInBundle + FSize;
  191. // There are two kinds of bundling restrictions:
  192. //
  193. // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
  194. // *end* on a bundle boundary.
  195. // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
  196. // would, add padding until the end of the bundle so that the fragment
  197. // will start in a new one.
  198. if (F->alignToBundleEnd()) {
  199. // Three possibilities here:
  200. //
  201. // A) The fragment just happens to end at a bundle boundary, so we're good.
  202. // B) The fragment ends before the current bundle boundary: pad it just
  203. // enough to reach the boundary.
  204. // C) The fragment ends after the current bundle boundary: pad it until it
  205. // reaches the end of the next bundle boundary.
  206. //
  207. // Note: this code could be made shorter with some modulo trickery, but it's
  208. // intentionally kept in its more explicit form for simplicity.
  209. if (EndOfFragment == BundleSize)
  210. return 0;
  211. else if (EndOfFragment < BundleSize)
  212. return BundleSize - EndOfFragment;
  213. else { // EndOfFragment > BundleSize
  214. return 2 * BundleSize - EndOfFragment;
  215. }
  216. } else if (OffsetInBundle > 0 && EndOfFragment > BundleSize)
  217. return BundleSize - OffsetInBundle;
  218. else
  219. return 0;
  220. }
  221. /* *** */
  222. void ilist_alloc_traits<MCFragment>::deleteNode(MCFragment *V) { V->destroy(); }
  223. MCFragment::MCFragment(FragmentType Kind, bool HasInstructions,
  224. MCSection *Parent)
  225. : Parent(Parent), Atom(nullptr), Offset(~UINT64_C(0)), LayoutOrder(0),
  226. Kind(Kind), IsBeingLaidOut(false), HasInstructions(HasInstructions) {
  227. if (Parent && !isa<MCDummyFragment>(*this))
  228. Parent->getFragmentList().push_back(this);
  229. }
  230. void MCFragment::destroy() {
  231. // First check if we are the sentinal.
  232. if (Kind == FragmentType(~0)) {
  233. delete this;
  234. return;
  235. }
  236. switch (Kind) {
  237. case FT_Align:
  238. delete cast<MCAlignFragment>(this);
  239. return;
  240. case FT_Data:
  241. delete cast<MCDataFragment>(this);
  242. return;
  243. case FT_CompactEncodedInst:
  244. delete cast<MCCompactEncodedInstFragment>(this);
  245. return;
  246. case FT_Fill:
  247. delete cast<MCFillFragment>(this);
  248. return;
  249. case FT_Nops:
  250. delete cast<MCNopsFragment>(this);
  251. return;
  252. case FT_Relaxable:
  253. delete cast<MCRelaxableFragment>(this);
  254. return;
  255. case FT_Org:
  256. delete cast<MCOrgFragment>(this);
  257. return;
  258. case FT_Dwarf:
  259. delete cast<MCDwarfLineAddrFragment>(this);
  260. return;
  261. case FT_DwarfFrame:
  262. delete cast<MCDwarfCallFrameFragment>(this);
  263. return;
  264. case FT_LEB:
  265. delete cast<MCLEBFragment>(this);
  266. return;
  267. case FT_BoundaryAlign:
  268. delete cast<MCBoundaryAlignFragment>(this);
  269. return;
  270. case FT_SymbolId:
  271. delete cast<MCSymbolIdFragment>(this);
  272. return;
  273. case FT_CVInlineLines:
  274. delete cast<MCCVInlineLineTableFragment>(this);
  275. return;
  276. case FT_CVDefRange:
  277. delete cast<MCCVDefRangeFragment>(this);
  278. return;
  279. case FT_PseudoProbe:
  280. delete cast<MCPseudoProbeAddrFragment>(this);
  281. return;
  282. case FT_Dummy:
  283. delete cast<MCDummyFragment>(this);
  284. return;
  285. }
  286. }
  287. // Debugging methods
  288. namespace llvm {
  289. raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
  290. OS << "<MCFixup" << " Offset:" << AF.getOffset()
  291. << " Value:" << *AF.getValue()
  292. << " Kind:" << AF.getKind() << ">";
  293. return OS;
  294. }
  295. } // end namespace llvm
  296. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  297. LLVM_DUMP_METHOD void MCFragment::dump() const {
  298. raw_ostream &OS = errs();
  299. OS << "<";
  300. switch (getKind()) {
  301. case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
  302. case MCFragment::FT_Data: OS << "MCDataFragment"; break;
  303. case MCFragment::FT_CompactEncodedInst:
  304. OS << "MCCompactEncodedInstFragment"; break;
  305. case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
  306. case MCFragment::FT_Nops:
  307. OS << "MCFNopsFragment";
  308. break;
  309. case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
  310. case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
  311. case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
  312. case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
  313. case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
  314. case MCFragment::FT_BoundaryAlign: OS<<"MCBoundaryAlignFragment"; break;
  315. case MCFragment::FT_SymbolId: OS << "MCSymbolIdFragment"; break;
  316. case MCFragment::FT_CVInlineLines: OS << "MCCVInlineLineTableFragment"; break;
  317. case MCFragment::FT_CVDefRange: OS << "MCCVDefRangeTableFragment"; break;
  318. case MCFragment::FT_PseudoProbe:
  319. OS << "MCPseudoProbe";
  320. break;
  321. case MCFragment::FT_Dummy: OS << "MCDummyFragment"; break;
  322. }
  323. OS << "<MCFragment " << (const void *)this << " LayoutOrder:" << LayoutOrder
  324. << " Offset:" << Offset << " HasInstructions:" << hasInstructions();
  325. if (const auto *EF = dyn_cast<MCEncodedFragment>(this))
  326. OS << " BundlePadding:" << static_cast<unsigned>(EF->getBundlePadding());
  327. OS << ">";
  328. switch (getKind()) {
  329. case MCFragment::FT_Align: {
  330. const auto *AF = cast<MCAlignFragment>(this);
  331. if (AF->hasEmitNops())
  332. OS << " (emit nops)";
  333. OS << "\n ";
  334. OS << " Alignment:" << AF->getAlignment()
  335. << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
  336. << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
  337. break;
  338. }
  339. case MCFragment::FT_Data: {
  340. const auto *DF = cast<MCDataFragment>(this);
  341. OS << "\n ";
  342. OS << " Contents:[";
  343. const SmallVectorImpl<char> &Contents = DF->getContents();
  344. for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
  345. if (i) OS << ",";
  346. OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
  347. }
  348. OS << "] (" << Contents.size() << " bytes)";
  349. if (DF->fixup_begin() != DF->fixup_end()) {
  350. OS << ",\n ";
  351. OS << " Fixups:[";
  352. for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
  353. ie = DF->fixup_end(); it != ie; ++it) {
  354. if (it != DF->fixup_begin()) OS << ",\n ";
  355. OS << *it;
  356. }
  357. OS << "]";
  358. }
  359. break;
  360. }
  361. case MCFragment::FT_CompactEncodedInst: {
  362. const auto *CEIF =
  363. cast<MCCompactEncodedInstFragment>(this);
  364. OS << "\n ";
  365. OS << " Contents:[";
  366. const SmallVectorImpl<char> &Contents = CEIF->getContents();
  367. for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
  368. if (i) OS << ",";
  369. OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
  370. }
  371. OS << "] (" << Contents.size() << " bytes)";
  372. break;
  373. }
  374. case MCFragment::FT_Fill: {
  375. const auto *FF = cast<MCFillFragment>(this);
  376. OS << " Value:" << static_cast<unsigned>(FF->getValue())
  377. << " ValueSize:" << static_cast<unsigned>(FF->getValueSize())
  378. << " NumValues:" << FF->getNumValues();
  379. break;
  380. }
  381. case MCFragment::FT_Nops: {
  382. const auto *NF = cast<MCNopsFragment>(this);
  383. OS << " NumBytes:" << NF->getNumBytes()
  384. << " ControlledNopLength:" << NF->getControlledNopLength();
  385. break;
  386. }
  387. case MCFragment::FT_Relaxable: {
  388. const auto *F = cast<MCRelaxableFragment>(this);
  389. OS << "\n ";
  390. OS << " Inst:";
  391. F->getInst().dump_pretty(OS);
  392. OS << " (" << F->getContents().size() << " bytes)";
  393. break;
  394. }
  395. case MCFragment::FT_Org: {
  396. const auto *OF = cast<MCOrgFragment>(this);
  397. OS << "\n ";
  398. OS << " Offset:" << OF->getOffset()
  399. << " Value:" << static_cast<unsigned>(OF->getValue());
  400. break;
  401. }
  402. case MCFragment::FT_Dwarf: {
  403. const auto *OF = cast<MCDwarfLineAddrFragment>(this);
  404. OS << "\n ";
  405. OS << " AddrDelta:" << OF->getAddrDelta()
  406. << " LineDelta:" << OF->getLineDelta();
  407. break;
  408. }
  409. case MCFragment::FT_DwarfFrame: {
  410. const auto *CF = cast<MCDwarfCallFrameFragment>(this);
  411. OS << "\n ";
  412. OS << " AddrDelta:" << CF->getAddrDelta();
  413. break;
  414. }
  415. case MCFragment::FT_LEB: {
  416. const auto *LF = cast<MCLEBFragment>(this);
  417. OS << "\n ";
  418. OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
  419. break;
  420. }
  421. case MCFragment::FT_BoundaryAlign: {
  422. const auto *BF = cast<MCBoundaryAlignFragment>(this);
  423. OS << "\n ";
  424. OS << " BoundarySize:" << BF->getAlignment().value()
  425. << " LastFragment:" << BF->getLastFragment()
  426. << " Size:" << BF->getSize();
  427. break;
  428. }
  429. case MCFragment::FT_SymbolId: {
  430. const auto *F = cast<MCSymbolIdFragment>(this);
  431. OS << "\n ";
  432. OS << " Sym:" << F->getSymbol();
  433. break;
  434. }
  435. case MCFragment::FT_CVInlineLines: {
  436. const auto *F = cast<MCCVInlineLineTableFragment>(this);
  437. OS << "\n ";
  438. OS << " Sym:" << *F->getFnStartSym();
  439. break;
  440. }
  441. case MCFragment::FT_CVDefRange: {
  442. const auto *F = cast<MCCVDefRangeFragment>(this);
  443. OS << "\n ";
  444. for (std::pair<const MCSymbol *, const MCSymbol *> RangeStartEnd :
  445. F->getRanges()) {
  446. OS << " RangeStart:" << RangeStartEnd.first;
  447. OS << " RangeEnd:" << RangeStartEnd.second;
  448. }
  449. break;
  450. }
  451. case MCFragment::FT_PseudoProbe: {
  452. const auto *OF = cast<MCPseudoProbeAddrFragment>(this);
  453. OS << "\n ";
  454. OS << " AddrDelta:" << OF->getAddrDelta();
  455. break;
  456. }
  457. case MCFragment::FT_Dummy:
  458. break;
  459. }
  460. OS << ">";
  461. }
  462. #endif