MCAssembler.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  1. //===- lib/MC/MCAssembler.cpp - Assembler Backend 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/MCAssembler.h"
  9. #include "llvm/ADT/ArrayRef.h"
  10. #include "llvm/ADT/SmallString.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/ADT/Statistic.h"
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/ADT/Twine.h"
  15. #include "llvm/MC/MCAsmBackend.h"
  16. #include "llvm/MC/MCAsmInfo.h"
  17. #include "llvm/MC/MCAsmLayout.h"
  18. #include "llvm/MC/MCCodeEmitter.h"
  19. #include "llvm/MC/MCCodeView.h"
  20. #include "llvm/MC/MCContext.h"
  21. #include "llvm/MC/MCDwarf.h"
  22. #include "llvm/MC/MCExpr.h"
  23. #include "llvm/MC/MCFixup.h"
  24. #include "llvm/MC/MCFixupKindInfo.h"
  25. #include "llvm/MC/MCFragment.h"
  26. #include "llvm/MC/MCInst.h"
  27. #include "llvm/MC/MCObjectWriter.h"
  28. #include "llvm/MC/MCSection.h"
  29. #include "llvm/MC/MCSectionELF.h"
  30. #include "llvm/MC/MCSymbol.h"
  31. #include "llvm/MC/MCValue.h"
  32. #include "llvm/Support/Alignment.h"
  33. #include "llvm/Support/Casting.h"
  34. #include "llvm/Support/Debug.h"
  35. #include "llvm/Support/EndianStream.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/Support/LEB128.h"
  38. #include "llvm/Support/MathExtras.h"
  39. #include "llvm/Support/raw_ostream.h"
  40. #include <cassert>
  41. #include <cstdint>
  42. #include <cstring>
  43. #include <tuple>
  44. #include <utility>
  45. using namespace llvm;
  46. #define DEBUG_TYPE "assembler"
  47. namespace {
  48. namespace stats {
  49. STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
  50. STATISTIC(EmittedRelaxableFragments,
  51. "Number of emitted assembler fragments - relaxable");
  52. STATISTIC(EmittedDataFragments,
  53. "Number of emitted assembler fragments - data");
  54. STATISTIC(EmittedCompactEncodedInstFragments,
  55. "Number of emitted assembler fragments - compact encoded inst");
  56. STATISTIC(EmittedAlignFragments,
  57. "Number of emitted assembler fragments - align");
  58. STATISTIC(EmittedFillFragments,
  59. "Number of emitted assembler fragments - fill");
  60. STATISTIC(EmittedNopsFragments, "Number of emitted assembler fragments - nops");
  61. STATISTIC(EmittedOrgFragments, "Number of emitted assembler fragments - org");
  62. STATISTIC(evaluateFixup, "Number of evaluated fixups");
  63. STATISTIC(FragmentLayouts, "Number of fragment layouts");
  64. STATISTIC(ObjectBytes, "Number of emitted object file bytes");
  65. STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
  66. STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
  67. } // end namespace stats
  68. } // end anonymous namespace
  69. // FIXME FIXME FIXME: There are number of places in this file where we convert
  70. // what is a 64-bit assembler value used for computation into a value in the
  71. // object file, which may truncate it. We should detect that truncation where
  72. // invalid and report errors back.
  73. /* *** */
  74. MCAssembler::MCAssembler(MCContext &Context,
  75. std::unique_ptr<MCAsmBackend> Backend,
  76. std::unique_ptr<MCCodeEmitter> Emitter,
  77. std::unique_ptr<MCObjectWriter> Writer)
  78. : Context(Context), Backend(std::move(Backend)),
  79. Emitter(std::move(Emitter)), Writer(std::move(Writer)),
  80. BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
  81. IncrementalLinkerCompatible(false), ELFHeaderEFlags(0) {
  82. VersionInfo.Major = 0; // Major version == 0 for "none specified"
  83. DarwinTargetVariantVersionInfo.Major = 0;
  84. }
  85. MCAssembler::~MCAssembler() = default;
  86. void MCAssembler::reset() {
  87. Sections.clear();
  88. Symbols.clear();
  89. IndirectSymbols.clear();
  90. DataRegions.clear();
  91. LinkerOptions.clear();
  92. FileNames.clear();
  93. ThumbFuncs.clear();
  94. BundleAlignSize = 0;
  95. RelaxAll = false;
  96. SubsectionsViaSymbols = false;
  97. IncrementalLinkerCompatible = false;
  98. ELFHeaderEFlags = 0;
  99. LOHContainer.reset();
  100. VersionInfo.Major = 0;
  101. VersionInfo.SDKVersion = VersionTuple();
  102. DarwinTargetVariantVersionInfo.Major = 0;
  103. DarwinTargetVariantVersionInfo.SDKVersion = VersionTuple();
  104. // reset objects owned by us
  105. if (getBackendPtr())
  106. getBackendPtr()->reset();
  107. if (getEmitterPtr())
  108. getEmitterPtr()->reset();
  109. if (getWriterPtr())
  110. getWriterPtr()->reset();
  111. getLOHContainer().reset();
  112. }
  113. bool MCAssembler::registerSection(MCSection &Section) {
  114. if (Section.isRegistered())
  115. return false;
  116. Sections.push_back(&Section);
  117. Section.setIsRegistered(true);
  118. return true;
  119. }
  120. bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
  121. if (ThumbFuncs.count(Symbol))
  122. return true;
  123. if (!Symbol->isVariable())
  124. return false;
  125. const MCExpr *Expr = Symbol->getVariableValue();
  126. MCValue V;
  127. if (!Expr->evaluateAsRelocatable(V, nullptr, nullptr))
  128. return false;
  129. if (V.getSymB() || V.getRefKind() != MCSymbolRefExpr::VK_None)
  130. return false;
  131. const MCSymbolRefExpr *Ref = V.getSymA();
  132. if (!Ref)
  133. return false;
  134. if (Ref->getKind() != MCSymbolRefExpr::VK_None)
  135. return false;
  136. const MCSymbol &Sym = Ref->getSymbol();
  137. if (!isThumbFunc(&Sym))
  138. return false;
  139. ThumbFuncs.insert(Symbol); // Cache it.
  140. return true;
  141. }
  142. bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
  143. // Non-temporary labels should always be visible to the linker.
  144. if (!Symbol.isTemporary())
  145. return true;
  146. if (Symbol.isUsedInReloc())
  147. return true;
  148. return false;
  149. }
  150. const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
  151. // Linker visible symbols define atoms.
  152. if (isSymbolLinkerVisible(S))
  153. return &S;
  154. // Absolute and undefined symbols have no defining atom.
  155. if (!S.isInSection())
  156. return nullptr;
  157. // Non-linker visible symbols in sections which can't be atomized have no
  158. // defining atom.
  159. if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
  160. *S.getFragment()->getParent()))
  161. return nullptr;
  162. // Otherwise, return the atom for the containing fragment.
  163. return S.getFragment()->getAtom();
  164. }
  165. bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
  166. const MCFixup &Fixup, const MCFragment *DF,
  167. MCValue &Target, uint64_t &Value,
  168. bool &WasForced) const {
  169. ++stats::evaluateFixup;
  170. // FIXME: This code has some duplication with recordRelocation. We should
  171. // probably merge the two into a single callback that tries to evaluate a
  172. // fixup and records a relocation if one is needed.
  173. // On error claim to have completely evaluated the fixup, to prevent any
  174. // further processing from being done.
  175. const MCExpr *Expr = Fixup.getValue();
  176. MCContext &Ctx = getContext();
  177. Value = 0;
  178. WasForced = false;
  179. if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) {
  180. Ctx.reportError(Fixup.getLoc(), "expected relocatable expression");
  181. return true;
  182. }
  183. if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
  184. if (RefB->getKind() != MCSymbolRefExpr::VK_None) {
  185. Ctx.reportError(Fixup.getLoc(),
  186. "unsupported subtraction of qualified symbol");
  187. return true;
  188. }
  189. }
  190. assert(getBackendPtr() && "Expected assembler backend");
  191. bool IsTarget = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
  192. MCFixupKindInfo::FKF_IsTarget;
  193. if (IsTarget)
  194. return getBackend().evaluateTargetFixup(*this, Layout, Fixup, DF, Target,
  195. Value, WasForced);
  196. unsigned FixupFlags = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags;
  197. bool IsPCRel = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
  198. MCFixupKindInfo::FKF_IsPCRel;
  199. bool IsResolved = false;
  200. if (IsPCRel) {
  201. if (Target.getSymB()) {
  202. IsResolved = false;
  203. } else if (!Target.getSymA()) {
  204. IsResolved = false;
  205. } else {
  206. const MCSymbolRefExpr *A = Target.getSymA();
  207. const MCSymbol &SA = A->getSymbol();
  208. if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
  209. IsResolved = false;
  210. } else if (auto *Writer = getWriterPtr()) {
  211. IsResolved = (FixupFlags & MCFixupKindInfo::FKF_Constant) ||
  212. Writer->isSymbolRefDifferenceFullyResolvedImpl(
  213. *this, SA, *DF, false, true);
  214. }
  215. }
  216. } else {
  217. IsResolved = Target.isAbsolute();
  218. }
  219. Value = Target.getConstant();
  220. if (const MCSymbolRefExpr *A = Target.getSymA()) {
  221. const MCSymbol &Sym = A->getSymbol();
  222. if (Sym.isDefined())
  223. Value += Layout.getSymbolOffset(Sym);
  224. }
  225. if (const MCSymbolRefExpr *B = Target.getSymB()) {
  226. const MCSymbol &Sym = B->getSymbol();
  227. if (Sym.isDefined())
  228. Value -= Layout.getSymbolOffset(Sym);
  229. }
  230. bool ShouldAlignPC = getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
  231. MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
  232. assert((ShouldAlignPC ? IsPCRel : true) &&
  233. "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
  234. if (IsPCRel) {
  235. uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
  236. // A number of ARM fixups in Thumb mode require that the effective PC
  237. // address be determined as the 32-bit aligned version of the actual offset.
  238. if (ShouldAlignPC) Offset &= ~0x3;
  239. Value -= Offset;
  240. }
  241. // Let the backend force a relocation if needed.
  242. if (IsResolved && getBackend().shouldForceRelocation(*this, Fixup, Target)) {
  243. IsResolved = false;
  244. WasForced = true;
  245. }
  246. return IsResolved;
  247. }
  248. uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
  249. const MCFragment &F) const {
  250. assert(getBackendPtr() && "Requires assembler backend");
  251. switch (F.getKind()) {
  252. case MCFragment::FT_Data:
  253. return cast<MCDataFragment>(F).getContents().size();
  254. case MCFragment::FT_Relaxable:
  255. return cast<MCRelaxableFragment>(F).getContents().size();
  256. case MCFragment::FT_CompactEncodedInst:
  257. return cast<MCCompactEncodedInstFragment>(F).getContents().size();
  258. case MCFragment::FT_Fill: {
  259. auto &FF = cast<MCFillFragment>(F);
  260. int64_t NumValues = 0;
  261. if (!FF.getNumValues().evaluateAsAbsolute(NumValues, Layout)) {
  262. getContext().reportError(FF.getLoc(),
  263. "expected assembly-time absolute expression");
  264. return 0;
  265. }
  266. int64_t Size = NumValues * FF.getValueSize();
  267. if (Size < 0) {
  268. getContext().reportError(FF.getLoc(), "invalid number of bytes");
  269. return 0;
  270. }
  271. return Size;
  272. }
  273. case MCFragment::FT_Nops:
  274. return cast<MCNopsFragment>(F).getNumBytes();
  275. case MCFragment::FT_LEB:
  276. return cast<MCLEBFragment>(F).getContents().size();
  277. case MCFragment::FT_BoundaryAlign:
  278. return cast<MCBoundaryAlignFragment>(F).getSize();
  279. case MCFragment::FT_SymbolId:
  280. return 4;
  281. case MCFragment::FT_Align: {
  282. const MCAlignFragment &AF = cast<MCAlignFragment>(F);
  283. unsigned Offset = Layout.getFragmentOffset(&AF);
  284. unsigned Size = offsetToAlignment(Offset, Align(AF.getAlignment()));
  285. // Insert extra Nops for code alignment if the target define
  286. // shouldInsertExtraNopBytesForCodeAlign target hook.
  287. if (AF.getParent()->UseCodeAlign() && AF.hasEmitNops() &&
  288. getBackend().shouldInsertExtraNopBytesForCodeAlign(AF, Size))
  289. return Size;
  290. // If we are padding with nops, force the padding to be larger than the
  291. // minimum nop size.
  292. if (Size > 0 && AF.hasEmitNops()) {
  293. while (Size % getBackend().getMinimumNopSize())
  294. Size += AF.getAlignment();
  295. }
  296. if (Size > AF.getMaxBytesToEmit())
  297. return 0;
  298. return Size;
  299. }
  300. case MCFragment::FT_Org: {
  301. const MCOrgFragment &OF = cast<MCOrgFragment>(F);
  302. MCValue Value;
  303. if (!OF.getOffset().evaluateAsValue(Value, Layout)) {
  304. getContext().reportError(OF.getLoc(),
  305. "expected assembly-time absolute expression");
  306. return 0;
  307. }
  308. uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
  309. int64_t TargetLocation = Value.getConstant();
  310. if (const MCSymbolRefExpr *A = Value.getSymA()) {
  311. uint64_t Val;
  312. if (!Layout.getSymbolOffset(A->getSymbol(), Val)) {
  313. getContext().reportError(OF.getLoc(), "expected absolute expression");
  314. return 0;
  315. }
  316. TargetLocation += Val;
  317. }
  318. int64_t Size = TargetLocation - FragmentOffset;
  319. if (Size < 0 || Size >= 0x40000000) {
  320. getContext().reportError(
  321. OF.getLoc(), "invalid .org offset '" + Twine(TargetLocation) +
  322. "' (at offset '" + Twine(FragmentOffset) + "')");
  323. return 0;
  324. }
  325. return Size;
  326. }
  327. case MCFragment::FT_Dwarf:
  328. return cast<MCDwarfLineAddrFragment>(F).getContents().size();
  329. case MCFragment::FT_DwarfFrame:
  330. return cast<MCDwarfCallFrameFragment>(F).getContents().size();
  331. case MCFragment::FT_CVInlineLines:
  332. return cast<MCCVInlineLineTableFragment>(F).getContents().size();
  333. case MCFragment::FT_CVDefRange:
  334. return cast<MCCVDefRangeFragment>(F).getContents().size();
  335. case MCFragment::FT_PseudoProbe:
  336. return cast<MCPseudoProbeAddrFragment>(F).getContents().size();
  337. case MCFragment::FT_Dummy:
  338. llvm_unreachable("Should not have been added");
  339. }
  340. llvm_unreachable("invalid fragment kind");
  341. }
  342. void MCAsmLayout::layoutFragment(MCFragment *F) {
  343. MCFragment *Prev = F->getPrevNode();
  344. // We should never try to recompute something which is valid.
  345. assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
  346. // We should never try to compute the fragment layout if its predecessor
  347. // isn't valid.
  348. assert((!Prev || isFragmentValid(Prev)) &&
  349. "Attempt to compute fragment before its predecessor!");
  350. assert(!F->IsBeingLaidOut && "Already being laid out!");
  351. F->IsBeingLaidOut = true;
  352. ++stats::FragmentLayouts;
  353. // Compute fragment offset and size.
  354. if (Prev)
  355. F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
  356. else
  357. F->Offset = 0;
  358. F->IsBeingLaidOut = false;
  359. LastValidFragment[F->getParent()] = F;
  360. // If bundling is enabled and this fragment has instructions in it, it has to
  361. // obey the bundling restrictions. With padding, we'll have:
  362. //
  363. //
  364. // BundlePadding
  365. // |||
  366. // -------------------------------------
  367. // Prev |##########| F |
  368. // -------------------------------------
  369. // ^
  370. // |
  371. // F->Offset
  372. //
  373. // The fragment's offset will point to after the padding, and its computed
  374. // size won't include the padding.
  375. //
  376. // When the -mc-relax-all flag is used, we optimize bundling by writting the
  377. // padding directly into fragments when the instructions are emitted inside
  378. // the streamer. When the fragment is larger than the bundle size, we need to
  379. // ensure that it's bundle aligned. This means that if we end up with
  380. // multiple fragments, we must emit bundle padding between fragments.
  381. //
  382. // ".align N" is an example of a directive that introduces multiple
  383. // fragments. We could add a special case to handle ".align N" by emitting
  384. // within-fragment padding (which would produce less padding when N is less
  385. // than the bundle size), but for now we don't.
  386. //
  387. if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
  388. assert(isa<MCEncodedFragment>(F) &&
  389. "Only MCEncodedFragment implementations have instructions");
  390. MCEncodedFragment *EF = cast<MCEncodedFragment>(F);
  391. uint64_t FSize = Assembler.computeFragmentSize(*this, *EF);
  392. if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
  393. report_fatal_error("Fragment can't be larger than a bundle size");
  394. uint64_t RequiredBundlePadding =
  395. computeBundlePadding(Assembler, EF, EF->Offset, FSize);
  396. if (RequiredBundlePadding > UINT8_MAX)
  397. report_fatal_error("Padding cannot exceed 255 bytes");
  398. EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
  399. EF->Offset += RequiredBundlePadding;
  400. }
  401. }
  402. void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
  403. bool New = !Symbol.isRegistered();
  404. if (Created)
  405. *Created = New;
  406. if (New) {
  407. Symbol.setIsRegistered(true);
  408. Symbols.push_back(&Symbol);
  409. }
  410. }
  411. void MCAssembler::writeFragmentPadding(raw_ostream &OS,
  412. const MCEncodedFragment &EF,
  413. uint64_t FSize) const {
  414. assert(getBackendPtr() && "Expected assembler backend");
  415. // Should NOP padding be written out before this fragment?
  416. unsigned BundlePadding = EF.getBundlePadding();
  417. if (BundlePadding > 0) {
  418. assert(isBundlingEnabled() &&
  419. "Writing bundle padding with disabled bundling");
  420. assert(EF.hasInstructions() &&
  421. "Writing bundle padding for a fragment without instructions");
  422. unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
  423. const MCSubtargetInfo *STI = EF.getSubtargetInfo();
  424. if (EF.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
  425. // If the padding itself crosses a bundle boundary, it must be emitted
  426. // in 2 pieces, since even nop instructions must not cross boundaries.
  427. // v--------------v <- BundleAlignSize
  428. // v---------v <- BundlePadding
  429. // ----------------------------
  430. // | Prev |####|####| F |
  431. // ----------------------------
  432. // ^-------------------^ <- TotalLength
  433. unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
  434. if (!getBackend().writeNopData(OS, DistanceToBoundary, STI))
  435. report_fatal_error("unable to write NOP sequence of " +
  436. Twine(DistanceToBoundary) + " bytes");
  437. BundlePadding -= DistanceToBoundary;
  438. }
  439. if (!getBackend().writeNopData(OS, BundlePadding, STI))
  440. report_fatal_error("unable to write NOP sequence of " +
  441. Twine(BundlePadding) + " bytes");
  442. }
  443. }
  444. /// Write the fragment \p F to the output file.
  445. static void writeFragment(raw_ostream &OS, const MCAssembler &Asm,
  446. const MCAsmLayout &Layout, const MCFragment &F) {
  447. // FIXME: Embed in fragments instead?
  448. uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
  449. support::endianness Endian = Asm.getBackend().Endian;
  450. if (const MCEncodedFragment *EF = dyn_cast<MCEncodedFragment>(&F))
  451. Asm.writeFragmentPadding(OS, *EF, FragmentSize);
  452. // This variable (and its dummy usage) is to participate in the assert at
  453. // the end of the function.
  454. uint64_t Start = OS.tell();
  455. (void) Start;
  456. ++stats::EmittedFragments;
  457. switch (F.getKind()) {
  458. case MCFragment::FT_Align: {
  459. ++stats::EmittedAlignFragments;
  460. const MCAlignFragment &AF = cast<MCAlignFragment>(F);
  461. assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
  462. uint64_t Count = FragmentSize / AF.getValueSize();
  463. // FIXME: This error shouldn't actually occur (the front end should emit
  464. // multiple .align directives to enforce the semantics it wants), but is
  465. // severe enough that we want to report it. How to handle this?
  466. if (Count * AF.getValueSize() != FragmentSize)
  467. report_fatal_error("undefined .align directive, value size '" +
  468. Twine(AF.getValueSize()) +
  469. "' is not a divisor of padding size '" +
  470. Twine(FragmentSize) + "'");
  471. // See if we are aligning with nops, and if so do that first to try to fill
  472. // the Count bytes. Then if that did not fill any bytes or there are any
  473. // bytes left to fill use the Value and ValueSize to fill the rest.
  474. // If we are aligning with nops, ask that target to emit the right data.
  475. if (AF.hasEmitNops()) {
  476. if (!Asm.getBackend().writeNopData(OS, Count, AF.getSubtargetInfo()))
  477. report_fatal_error("unable to write nop sequence of " +
  478. Twine(Count) + " bytes");
  479. break;
  480. }
  481. // Otherwise, write out in multiples of the value size.
  482. for (uint64_t i = 0; i != Count; ++i) {
  483. switch (AF.getValueSize()) {
  484. default: llvm_unreachable("Invalid size!");
  485. case 1: OS << char(AF.getValue()); break;
  486. case 2:
  487. support::endian::write<uint16_t>(OS, AF.getValue(), Endian);
  488. break;
  489. case 4:
  490. support::endian::write<uint32_t>(OS, AF.getValue(), Endian);
  491. break;
  492. case 8:
  493. support::endian::write<uint64_t>(OS, AF.getValue(), Endian);
  494. break;
  495. }
  496. }
  497. break;
  498. }
  499. case MCFragment::FT_Data:
  500. ++stats::EmittedDataFragments;
  501. OS << cast<MCDataFragment>(F).getContents();
  502. break;
  503. case MCFragment::FT_Relaxable:
  504. ++stats::EmittedRelaxableFragments;
  505. OS << cast<MCRelaxableFragment>(F).getContents();
  506. break;
  507. case MCFragment::FT_CompactEncodedInst:
  508. ++stats::EmittedCompactEncodedInstFragments;
  509. OS << cast<MCCompactEncodedInstFragment>(F).getContents();
  510. break;
  511. case MCFragment::FT_Fill: {
  512. ++stats::EmittedFillFragments;
  513. const MCFillFragment &FF = cast<MCFillFragment>(F);
  514. uint64_t V = FF.getValue();
  515. unsigned VSize = FF.getValueSize();
  516. const unsigned MaxChunkSize = 16;
  517. char Data[MaxChunkSize];
  518. assert(0 < VSize && VSize <= MaxChunkSize && "Illegal fragment fill size");
  519. // Duplicate V into Data as byte vector to reduce number of
  520. // writes done. As such, do endian conversion here.
  521. for (unsigned I = 0; I != VSize; ++I) {
  522. unsigned index = Endian == support::little ? I : (VSize - I - 1);
  523. Data[I] = uint8_t(V >> (index * 8));
  524. }
  525. for (unsigned I = VSize; I < MaxChunkSize; ++I)
  526. Data[I] = Data[I - VSize];
  527. // Set to largest multiple of VSize in Data.
  528. const unsigned NumPerChunk = MaxChunkSize / VSize;
  529. // Set ChunkSize to largest multiple of VSize in Data
  530. const unsigned ChunkSize = VSize * NumPerChunk;
  531. // Do copies by chunk.
  532. StringRef Ref(Data, ChunkSize);
  533. for (uint64_t I = 0, E = FragmentSize / ChunkSize; I != E; ++I)
  534. OS << Ref;
  535. // do remainder if needed.
  536. unsigned TrailingCount = FragmentSize % ChunkSize;
  537. if (TrailingCount)
  538. OS.write(Data, TrailingCount);
  539. break;
  540. }
  541. case MCFragment::FT_Nops: {
  542. ++stats::EmittedNopsFragments;
  543. const MCNopsFragment &NF = cast<MCNopsFragment>(F);
  544. int64_t NumBytes = NF.getNumBytes();
  545. int64_t ControlledNopLength = NF.getControlledNopLength();
  546. int64_t MaximumNopLength =
  547. Asm.getBackend().getMaximumNopSize(*NF.getSubtargetInfo());
  548. assert(NumBytes > 0 && "Expected positive NOPs fragment size");
  549. assert(ControlledNopLength >= 0 && "Expected non-negative NOP size");
  550. if (ControlledNopLength > MaximumNopLength) {
  551. Asm.getContext().reportError(NF.getLoc(),
  552. "illegal NOP size " +
  553. std::to_string(ControlledNopLength) +
  554. ". (expected within [0, " +
  555. std::to_string(MaximumNopLength) + "])");
  556. // Clamp the NOP length as reportError does not stop the execution
  557. // immediately.
  558. ControlledNopLength = MaximumNopLength;
  559. }
  560. // Use maximum value if the size of each NOP is not specified
  561. if (!ControlledNopLength)
  562. ControlledNopLength = MaximumNopLength;
  563. while (NumBytes) {
  564. uint64_t NumBytesToEmit =
  565. (uint64_t)std::min(NumBytes, ControlledNopLength);
  566. assert(NumBytesToEmit && "try to emit empty NOP instruction");
  567. if (!Asm.getBackend().writeNopData(OS, NumBytesToEmit,
  568. NF.getSubtargetInfo())) {
  569. report_fatal_error("unable to write nop sequence of the remaining " +
  570. Twine(NumBytesToEmit) + " bytes");
  571. break;
  572. }
  573. NumBytes -= NumBytesToEmit;
  574. }
  575. break;
  576. }
  577. case MCFragment::FT_LEB: {
  578. const MCLEBFragment &LF = cast<MCLEBFragment>(F);
  579. OS << LF.getContents();
  580. break;
  581. }
  582. case MCFragment::FT_BoundaryAlign: {
  583. const MCBoundaryAlignFragment &BF = cast<MCBoundaryAlignFragment>(F);
  584. if (!Asm.getBackend().writeNopData(OS, FragmentSize, BF.getSubtargetInfo()))
  585. report_fatal_error("unable to write nop sequence of " +
  586. Twine(FragmentSize) + " bytes");
  587. break;
  588. }
  589. case MCFragment::FT_SymbolId: {
  590. const MCSymbolIdFragment &SF = cast<MCSymbolIdFragment>(F);
  591. support::endian::write<uint32_t>(OS, SF.getSymbol()->getIndex(), Endian);
  592. break;
  593. }
  594. case MCFragment::FT_Org: {
  595. ++stats::EmittedOrgFragments;
  596. const MCOrgFragment &OF = cast<MCOrgFragment>(F);
  597. for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
  598. OS << char(OF.getValue());
  599. break;
  600. }
  601. case MCFragment::FT_Dwarf: {
  602. const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
  603. OS << OF.getContents();
  604. break;
  605. }
  606. case MCFragment::FT_DwarfFrame: {
  607. const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
  608. OS << CF.getContents();
  609. break;
  610. }
  611. case MCFragment::FT_CVInlineLines: {
  612. const auto &OF = cast<MCCVInlineLineTableFragment>(F);
  613. OS << OF.getContents();
  614. break;
  615. }
  616. case MCFragment::FT_CVDefRange: {
  617. const auto &DRF = cast<MCCVDefRangeFragment>(F);
  618. OS << DRF.getContents();
  619. break;
  620. }
  621. case MCFragment::FT_PseudoProbe: {
  622. const MCPseudoProbeAddrFragment &PF = cast<MCPseudoProbeAddrFragment>(F);
  623. OS << PF.getContents();
  624. break;
  625. }
  626. case MCFragment::FT_Dummy:
  627. llvm_unreachable("Should not have been added");
  628. }
  629. assert(OS.tell() - Start == FragmentSize &&
  630. "The stream should advance by fragment size");
  631. }
  632. void MCAssembler::writeSectionData(raw_ostream &OS, const MCSection *Sec,
  633. const MCAsmLayout &Layout) const {
  634. assert(getBackendPtr() && "Expected assembler backend");
  635. // Ignore virtual sections.
  636. if (Sec->isVirtualSection()) {
  637. assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
  638. // Check that contents are only things legal inside a virtual section.
  639. for (const MCFragment &F : *Sec) {
  640. switch (F.getKind()) {
  641. default: llvm_unreachable("Invalid fragment in virtual section!");
  642. case MCFragment::FT_Data: {
  643. // Check that we aren't trying to write a non-zero contents (or fixups)
  644. // into a virtual section. This is to support clients which use standard
  645. // directives to fill the contents of virtual sections.
  646. const MCDataFragment &DF = cast<MCDataFragment>(F);
  647. if (DF.fixup_begin() != DF.fixup_end())
  648. getContext().reportError(SMLoc(), Sec->getVirtualSectionKind() +
  649. " section '" + Sec->getName() +
  650. "' cannot have fixups");
  651. for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
  652. if (DF.getContents()[i]) {
  653. getContext().reportError(SMLoc(),
  654. Sec->getVirtualSectionKind() +
  655. " section '" + Sec->getName() +
  656. "' cannot have non-zero initializers");
  657. break;
  658. }
  659. break;
  660. }
  661. case MCFragment::FT_Align:
  662. // Check that we aren't trying to write a non-zero value into a virtual
  663. // section.
  664. assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
  665. cast<MCAlignFragment>(F).getValue() == 0) &&
  666. "Invalid align in virtual section!");
  667. break;
  668. case MCFragment::FT_Fill:
  669. assert((cast<MCFillFragment>(F).getValue() == 0) &&
  670. "Invalid fill in virtual section!");
  671. break;
  672. case MCFragment::FT_Org:
  673. break;
  674. }
  675. }
  676. return;
  677. }
  678. uint64_t Start = OS.tell();
  679. (void)Start;
  680. for (const MCFragment &F : *Sec)
  681. writeFragment(OS, *this, Layout, F);
  682. assert(getContext().hadError() ||
  683. OS.tell() - Start == Layout.getSectionAddressSize(Sec));
  684. }
  685. std::tuple<MCValue, uint64_t, bool>
  686. MCAssembler::handleFixup(const MCAsmLayout &Layout, MCFragment &F,
  687. const MCFixup &Fixup) {
  688. // Evaluate the fixup.
  689. MCValue Target;
  690. uint64_t FixedValue;
  691. bool WasForced;
  692. bool IsResolved = evaluateFixup(Layout, Fixup, &F, Target, FixedValue,
  693. WasForced);
  694. if (!IsResolved) {
  695. // The fixup was unresolved, we need a relocation. Inform the object
  696. // writer of the relocation, and give it an opportunity to adjust the
  697. // fixup value if need be.
  698. getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
  699. }
  700. return std::make_tuple(Target, FixedValue, IsResolved);
  701. }
  702. void MCAssembler::layout(MCAsmLayout &Layout) {
  703. assert(getBackendPtr() && "Expected assembler backend");
  704. DEBUG_WITH_TYPE("mc-dump", {
  705. errs() << "assembler backend - pre-layout\n--\n";
  706. dump(); });
  707. // Create dummy fragments and assign section ordinals.
  708. unsigned SectionIndex = 0;
  709. for (MCSection &Sec : *this) {
  710. // Create dummy fragments to eliminate any empty sections, this simplifies
  711. // layout.
  712. if (Sec.getFragmentList().empty())
  713. new MCDataFragment(&Sec);
  714. Sec.setOrdinal(SectionIndex++);
  715. }
  716. // Assign layout order indices to sections and fragments.
  717. for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
  718. MCSection *Sec = Layout.getSectionOrder()[i];
  719. Sec->setLayoutOrder(i);
  720. unsigned FragmentIndex = 0;
  721. for (MCFragment &Frag : *Sec)
  722. Frag.setLayoutOrder(FragmentIndex++);
  723. }
  724. // Layout until everything fits.
  725. while (layoutOnce(Layout)) {
  726. if (getContext().hadError())
  727. return;
  728. // Size of fragments in one section can depend on the size of fragments in
  729. // another. If any fragment has changed size, we have to re-layout (and
  730. // as a result possibly further relax) all.
  731. for (MCSection &Sec : *this)
  732. Layout.invalidateFragmentsFrom(&*Sec.begin());
  733. }
  734. DEBUG_WITH_TYPE("mc-dump", {
  735. errs() << "assembler backend - post-relaxation\n--\n";
  736. dump(); });
  737. // Finalize the layout, including fragment lowering.
  738. finishLayout(Layout);
  739. DEBUG_WITH_TYPE("mc-dump", {
  740. errs() << "assembler backend - final-layout\n--\n";
  741. dump(); });
  742. // Allow the object writer a chance to perform post-layout binding (for
  743. // example, to set the index fields in the symbol data).
  744. getWriter().executePostLayoutBinding(*this, Layout);
  745. // Evaluate and apply the fixups, generating relocation entries as necessary.
  746. for (MCSection &Sec : *this) {
  747. for (MCFragment &Frag : Sec) {
  748. ArrayRef<MCFixup> Fixups;
  749. MutableArrayRef<char> Contents;
  750. const MCSubtargetInfo *STI = nullptr;
  751. // Process MCAlignFragment and MCEncodedFragmentWithFixups here.
  752. switch (Frag.getKind()) {
  753. default:
  754. continue;
  755. case MCFragment::FT_Align: {
  756. MCAlignFragment &AF = cast<MCAlignFragment>(Frag);
  757. // Insert fixup type for code alignment if the target define
  758. // shouldInsertFixupForCodeAlign target hook.
  759. if (Sec.UseCodeAlign() && AF.hasEmitNops())
  760. getBackend().shouldInsertFixupForCodeAlign(*this, Layout, AF);
  761. continue;
  762. }
  763. case MCFragment::FT_Data: {
  764. MCDataFragment &DF = cast<MCDataFragment>(Frag);
  765. Fixups = DF.getFixups();
  766. Contents = DF.getContents();
  767. STI = DF.getSubtargetInfo();
  768. assert(!DF.hasInstructions() || STI != nullptr);
  769. break;
  770. }
  771. case MCFragment::FT_Relaxable: {
  772. MCRelaxableFragment &RF = cast<MCRelaxableFragment>(Frag);
  773. Fixups = RF.getFixups();
  774. Contents = RF.getContents();
  775. STI = RF.getSubtargetInfo();
  776. assert(!RF.hasInstructions() || STI != nullptr);
  777. break;
  778. }
  779. case MCFragment::FT_CVDefRange: {
  780. MCCVDefRangeFragment &CF = cast<MCCVDefRangeFragment>(Frag);
  781. Fixups = CF.getFixups();
  782. Contents = CF.getContents();
  783. break;
  784. }
  785. case MCFragment::FT_Dwarf: {
  786. MCDwarfLineAddrFragment &DF = cast<MCDwarfLineAddrFragment>(Frag);
  787. Fixups = DF.getFixups();
  788. Contents = DF.getContents();
  789. break;
  790. }
  791. case MCFragment::FT_DwarfFrame: {
  792. MCDwarfCallFrameFragment &DF = cast<MCDwarfCallFrameFragment>(Frag);
  793. Fixups = DF.getFixups();
  794. Contents = DF.getContents();
  795. break;
  796. }
  797. case MCFragment::FT_PseudoProbe: {
  798. MCPseudoProbeAddrFragment &PF = cast<MCPseudoProbeAddrFragment>(Frag);
  799. Fixups = PF.getFixups();
  800. Contents = PF.getContents();
  801. break;
  802. }
  803. }
  804. for (const MCFixup &Fixup : Fixups) {
  805. uint64_t FixedValue;
  806. bool IsResolved;
  807. MCValue Target;
  808. std::tie(Target, FixedValue, IsResolved) =
  809. handleFixup(Layout, Frag, Fixup);
  810. getBackend().applyFixup(*this, Fixup, Target, Contents, FixedValue,
  811. IsResolved, STI);
  812. }
  813. }
  814. }
  815. }
  816. void MCAssembler::Finish() {
  817. // Create the layout object.
  818. MCAsmLayout Layout(*this);
  819. layout(Layout);
  820. // Write the object file.
  821. stats::ObjectBytes += getWriter().writeObject(*this, Layout);
  822. }
  823. bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
  824. const MCRelaxableFragment *DF,
  825. const MCAsmLayout &Layout) const {
  826. assert(getBackendPtr() && "Expected assembler backend");
  827. MCValue Target;
  828. uint64_t Value;
  829. bool WasForced;
  830. bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value, WasForced);
  831. if (Target.getSymA() &&
  832. Target.getSymA()->getKind() == MCSymbolRefExpr::VK_X86_ABS8 &&
  833. Fixup.getKind() == FK_Data_1)
  834. return false;
  835. return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
  836. Layout, WasForced);
  837. }
  838. bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
  839. const MCAsmLayout &Layout) const {
  840. assert(getBackendPtr() && "Expected assembler backend");
  841. // If this inst doesn't ever need relaxation, ignore it. This occurs when we
  842. // are intentionally pushing out inst fragments, or because we relaxed a
  843. // previous instruction to one that doesn't need relaxation.
  844. if (!getBackend().mayNeedRelaxation(F->getInst(), *F->getSubtargetInfo()))
  845. return false;
  846. for (const MCFixup &Fixup : F->getFixups())
  847. if (fixupNeedsRelaxation(Fixup, F, Layout))
  848. return true;
  849. return false;
  850. }
  851. bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
  852. MCRelaxableFragment &F) {
  853. assert(getEmitterPtr() &&
  854. "Expected CodeEmitter defined for relaxInstruction");
  855. if (!fragmentNeedsRelaxation(&F, Layout))
  856. return false;
  857. ++stats::RelaxedInstructions;
  858. // FIXME-PERF: We could immediately lower out instructions if we can tell
  859. // they are fully resolved, to avoid retesting on later passes.
  860. // Relax the fragment.
  861. MCInst Relaxed = F.getInst();
  862. getBackend().relaxInstruction(Relaxed, *F.getSubtargetInfo());
  863. // Encode the new instruction.
  864. //
  865. // FIXME-PERF: If it matters, we could let the target do this. It can
  866. // probably do so more efficiently in many cases.
  867. SmallVector<MCFixup, 4> Fixups;
  868. SmallString<256> Code;
  869. raw_svector_ostream VecOS(Code);
  870. getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, *F.getSubtargetInfo());
  871. // Update the fragment.
  872. F.setInst(Relaxed);
  873. F.getContents() = Code;
  874. F.getFixups() = Fixups;
  875. return true;
  876. }
  877. bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
  878. uint64_t OldSize = LF.getContents().size();
  879. int64_t Value;
  880. bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
  881. if (!Abs)
  882. report_fatal_error("sleb128 and uleb128 expressions must be absolute");
  883. SmallString<8> &Data = LF.getContents();
  884. Data.clear();
  885. raw_svector_ostream OSE(Data);
  886. // The compiler can generate EH table assembly that is impossible to assemble
  887. // without either adding padding to an LEB fragment or adding extra padding
  888. // to a later alignment fragment. To accommodate such tables, relaxation can
  889. // only increase an LEB fragment size here, not decrease it. See PR35809.
  890. if (LF.isSigned())
  891. encodeSLEB128(Value, OSE, OldSize);
  892. else
  893. encodeULEB128(Value, OSE, OldSize);
  894. return OldSize != LF.getContents().size();
  895. }
  896. /// Check if the branch crosses the boundary.
  897. ///
  898. /// \param StartAddr start address of the fused/unfused branch.
  899. /// \param Size size of the fused/unfused branch.
  900. /// \param BoundaryAlignment alignment requirement of the branch.
  901. /// \returns true if the branch cross the boundary.
  902. static bool mayCrossBoundary(uint64_t StartAddr, uint64_t Size,
  903. Align BoundaryAlignment) {
  904. uint64_t EndAddr = StartAddr + Size;
  905. return (StartAddr >> Log2(BoundaryAlignment)) !=
  906. ((EndAddr - 1) >> Log2(BoundaryAlignment));
  907. }
  908. /// Check if the branch is against the boundary.
  909. ///
  910. /// \param StartAddr start address of the fused/unfused branch.
  911. /// \param Size size of the fused/unfused branch.
  912. /// \param BoundaryAlignment alignment requirement of the branch.
  913. /// \returns true if the branch is against the boundary.
  914. static bool isAgainstBoundary(uint64_t StartAddr, uint64_t Size,
  915. Align BoundaryAlignment) {
  916. uint64_t EndAddr = StartAddr + Size;
  917. return (EndAddr & (BoundaryAlignment.value() - 1)) == 0;
  918. }
  919. /// Check if the branch needs padding.
  920. ///
  921. /// \param StartAddr start address of the fused/unfused branch.
  922. /// \param Size size of the fused/unfused branch.
  923. /// \param BoundaryAlignment alignment requirement of the branch.
  924. /// \returns true if the branch needs padding.
  925. static bool needPadding(uint64_t StartAddr, uint64_t Size,
  926. Align BoundaryAlignment) {
  927. return mayCrossBoundary(StartAddr, Size, BoundaryAlignment) ||
  928. isAgainstBoundary(StartAddr, Size, BoundaryAlignment);
  929. }
  930. bool MCAssembler::relaxBoundaryAlign(MCAsmLayout &Layout,
  931. MCBoundaryAlignFragment &BF) {
  932. // BoundaryAlignFragment that doesn't need to align any fragment should not be
  933. // relaxed.
  934. if (!BF.getLastFragment())
  935. return false;
  936. uint64_t AlignedOffset = Layout.getFragmentOffset(&BF);
  937. uint64_t AlignedSize = 0;
  938. for (const MCFragment *F = BF.getLastFragment(); F != &BF;
  939. F = F->getPrevNode())
  940. AlignedSize += computeFragmentSize(Layout, *F);
  941. Align BoundaryAlignment = BF.getAlignment();
  942. uint64_t NewSize = needPadding(AlignedOffset, AlignedSize, BoundaryAlignment)
  943. ? offsetToAlignment(AlignedOffset, BoundaryAlignment)
  944. : 0U;
  945. if (NewSize == BF.getSize())
  946. return false;
  947. BF.setSize(NewSize);
  948. Layout.invalidateFragmentsFrom(&BF);
  949. return true;
  950. }
  951. bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
  952. MCDwarfLineAddrFragment &DF) {
  953. bool WasRelaxed;
  954. if (getBackend().relaxDwarfLineAddr(DF, Layout, WasRelaxed))
  955. return WasRelaxed;
  956. MCContext &Context = Layout.getAssembler().getContext();
  957. uint64_t OldSize = DF.getContents().size();
  958. int64_t AddrDelta;
  959. bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
  960. assert(Abs && "We created a line delta with an invalid expression");
  961. (void)Abs;
  962. int64_t LineDelta;
  963. LineDelta = DF.getLineDelta();
  964. SmallVectorImpl<char> &Data = DF.getContents();
  965. Data.clear();
  966. raw_svector_ostream OSE(Data);
  967. DF.getFixups().clear();
  968. MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
  969. AddrDelta, OSE);
  970. return OldSize != Data.size();
  971. }
  972. bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
  973. MCDwarfCallFrameFragment &DF) {
  974. bool WasRelaxed;
  975. if (getBackend().relaxDwarfCFA(DF, Layout, WasRelaxed))
  976. return WasRelaxed;
  977. MCContext &Context = Layout.getAssembler().getContext();
  978. uint64_t OldSize = DF.getContents().size();
  979. int64_t AddrDelta;
  980. bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
  981. assert(Abs && "We created call frame with an invalid expression");
  982. (void) Abs;
  983. SmallVectorImpl<char> &Data = DF.getContents();
  984. Data.clear();
  985. raw_svector_ostream OSE(Data);
  986. DF.getFixups().clear();
  987. MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
  988. return OldSize != Data.size();
  989. }
  990. bool MCAssembler::relaxCVInlineLineTable(MCAsmLayout &Layout,
  991. MCCVInlineLineTableFragment &F) {
  992. unsigned OldSize = F.getContents().size();
  993. getContext().getCVContext().encodeInlineLineTable(Layout, F);
  994. return OldSize != F.getContents().size();
  995. }
  996. bool MCAssembler::relaxCVDefRange(MCAsmLayout &Layout,
  997. MCCVDefRangeFragment &F) {
  998. unsigned OldSize = F.getContents().size();
  999. getContext().getCVContext().encodeDefRange(Layout, F);
  1000. return OldSize != F.getContents().size();
  1001. }
  1002. bool MCAssembler::relaxPseudoProbeAddr(MCAsmLayout &Layout,
  1003. MCPseudoProbeAddrFragment &PF) {
  1004. uint64_t OldSize = PF.getContents().size();
  1005. int64_t AddrDelta;
  1006. bool Abs = PF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
  1007. assert(Abs && "We created a pseudo probe with an invalid expression");
  1008. (void)Abs;
  1009. SmallVectorImpl<char> &Data = PF.getContents();
  1010. Data.clear();
  1011. raw_svector_ostream OSE(Data);
  1012. PF.getFixups().clear();
  1013. // AddrDelta is a signed integer
  1014. encodeSLEB128(AddrDelta, OSE, OldSize);
  1015. return OldSize != Data.size();
  1016. }
  1017. bool MCAssembler::relaxFragment(MCAsmLayout &Layout, MCFragment &F) {
  1018. switch(F.getKind()) {
  1019. default:
  1020. return false;
  1021. case MCFragment::FT_Relaxable:
  1022. assert(!getRelaxAll() &&
  1023. "Did not expect a MCRelaxableFragment in RelaxAll mode");
  1024. return relaxInstruction(Layout, cast<MCRelaxableFragment>(F));
  1025. case MCFragment::FT_Dwarf:
  1026. return relaxDwarfLineAddr(Layout, cast<MCDwarfLineAddrFragment>(F));
  1027. case MCFragment::FT_DwarfFrame:
  1028. return relaxDwarfCallFrameFragment(Layout,
  1029. cast<MCDwarfCallFrameFragment>(F));
  1030. case MCFragment::FT_LEB:
  1031. return relaxLEB(Layout, cast<MCLEBFragment>(F));
  1032. case MCFragment::FT_BoundaryAlign:
  1033. return relaxBoundaryAlign(Layout, cast<MCBoundaryAlignFragment>(F));
  1034. case MCFragment::FT_CVInlineLines:
  1035. return relaxCVInlineLineTable(Layout, cast<MCCVInlineLineTableFragment>(F));
  1036. case MCFragment::FT_CVDefRange:
  1037. return relaxCVDefRange(Layout, cast<MCCVDefRangeFragment>(F));
  1038. case MCFragment::FT_PseudoProbe:
  1039. return relaxPseudoProbeAddr(Layout, cast<MCPseudoProbeAddrFragment>(F));
  1040. }
  1041. }
  1042. bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
  1043. // Holds the first fragment which needed relaxing during this layout. It will
  1044. // remain NULL if none were relaxed.
  1045. // When a fragment is relaxed, all the fragments following it should get
  1046. // invalidated because their offset is going to change.
  1047. MCFragment *FirstRelaxedFragment = nullptr;
  1048. // Attempt to relax all the fragments in the section.
  1049. for (MCFragment &Frag : Sec) {
  1050. // Check if this is a fragment that needs relaxation.
  1051. bool RelaxedFrag = relaxFragment(Layout, Frag);
  1052. if (RelaxedFrag && !FirstRelaxedFragment)
  1053. FirstRelaxedFragment = &Frag;
  1054. }
  1055. if (FirstRelaxedFragment) {
  1056. Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
  1057. return true;
  1058. }
  1059. return false;
  1060. }
  1061. bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
  1062. ++stats::RelaxationSteps;
  1063. bool WasRelaxed = false;
  1064. for (MCSection &Sec : *this) {
  1065. while (layoutSectionOnce(Layout, Sec))
  1066. WasRelaxed = true;
  1067. }
  1068. return WasRelaxed;
  1069. }
  1070. void MCAssembler::finishLayout(MCAsmLayout &Layout) {
  1071. assert(getBackendPtr() && "Expected assembler backend");
  1072. // The layout is done. Mark every fragment as valid.
  1073. for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
  1074. MCSection &Section = *Layout.getSectionOrder()[i];
  1075. Layout.getFragmentOffset(&*Section.getFragmentList().rbegin());
  1076. computeFragmentSize(Layout, *Section.getFragmentList().rbegin());
  1077. }
  1078. getBackend().finishLayout(*this, Layout);
  1079. }
  1080. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1081. LLVM_DUMP_METHOD void MCAssembler::dump() const{
  1082. raw_ostream &OS = errs();
  1083. OS << "<MCAssembler\n";
  1084. OS << " Sections:[\n ";
  1085. for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
  1086. if (it != begin()) OS << ",\n ";
  1087. it->dump();
  1088. }
  1089. OS << "],\n";
  1090. OS << " Symbols:[";
  1091. for (const_symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
  1092. if (it != symbol_begin()) OS << ",\n ";
  1093. OS << "(";
  1094. it->dump();
  1095. OS << ", Index:" << it->getIndex() << ", ";
  1096. OS << ")";
  1097. }
  1098. OS << "]>\n";
  1099. }
  1100. #endif