1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCAssembler.h"
11 #include "llvm/ADT/Statistic.h"
12 #include "llvm/ADT/StringExtras.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCAsmLayout.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCDwarf.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCFixupKindInfo.h"
22 #include "llvm/MC/MCObjectWriter.h"
23 #include "llvm/MC/MCSection.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/LEB128.h"
30 #include "llvm/Support/TargetRegistry.h"
31 #include "llvm/Support/raw_ostream.h"
35 #define DEBUG_TYPE "assembler"
39 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
40 STATISTIC(EmittedRelaxableFragments,
41 "Number of emitted assembler fragments - relaxable");
42 STATISTIC(EmittedDataFragments,
43 "Number of emitted assembler fragments - data");
44 STATISTIC(EmittedCompactEncodedInstFragments,
45 "Number of emitted assembler fragments - compact encoded inst");
46 STATISTIC(EmittedAlignFragments,
47 "Number of emitted assembler fragments - align");
48 STATISTIC(EmittedFillFragments,
49 "Number of emitted assembler fragments - fill");
50 STATISTIC(EmittedOrgFragments,
51 "Number of emitted assembler fragments - org");
52 STATISTIC(evaluateFixup, "Number of evaluated fixups");
53 STATISTIC(FragmentLayouts, "Number of fragment layouts");
54 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
55 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
56 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
60 // FIXME FIXME FIXME: There are number of places in this file where we convert
61 // what is a 64-bit assembler value used for computation into a value in the
62 // object file, which may truncate it. We should detect that truncation where
63 // invalid and report errors back.
67 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
68 : Assembler(Asm), LastValidFragment()
70 // Compute the section layout order. Virtual sections must go last.
71 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
72 if (!it->isVirtualSection())
73 SectionOrder.push_back(&*it);
74 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
75 if (it->isVirtualSection())
76 SectionOrder.push_back(&*it);
79 bool MCAsmLayout::isFragmentValid(const MCFragment *F) const {
80 const MCSection *Sec = F->getParent();
81 const MCFragment *LastValid = LastValidFragment.lookup(Sec);
84 assert(LastValid->getParent() == Sec);
85 return F->getLayoutOrder() <= LastValid->getLayoutOrder();
88 void MCAsmLayout::invalidateFragmentsFrom(MCFragment *F) {
89 // If this fragment wasn't already valid, we don't need to do anything.
90 if (!isFragmentValid(F))
93 // Otherwise, reset the last valid fragment to the previous fragment
94 // (if this is the first fragment, it will be NULL).
95 LastValidFragment[F->getParent()] = F->getPrevNode();
98 void MCAsmLayout::ensureValid(const MCFragment *F) const {
99 MCSection *Sec = F->getParent();
100 MCFragment *Cur = LastValidFragment[Sec];
104 Cur = Cur->getNextNode();
106 // Advance the layout position until the fragment is valid.
107 while (!isFragmentValid(F)) {
108 assert(Cur && "Layout bookkeeping error");
109 const_cast<MCAsmLayout*>(this)->layoutFragment(Cur);
110 Cur = Cur->getNextNode();
114 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
116 assert(F->Offset != ~UINT64_C(0) && "Address not set!");
120 // Simple getSymbolOffset helper for the non-varibale case.
121 static bool getLabelOffset(const MCAsmLayout &Layout, const MCSymbol &S,
122 bool ReportError, uint64_t &Val) {
123 const MCSymbolData &SD = S.getData();
124 if (!SD.getFragment()) {
126 report_fatal_error("unable to evaluate offset to undefined symbol '" +
130 Val = Layout.getFragmentOffset(SD.getFragment()) + S.getOffset();
134 static bool getSymbolOffsetImpl(const MCAsmLayout &Layout, const MCSymbol &S,
135 bool ReportError, uint64_t &Val) {
137 return getLabelOffset(Layout, S, ReportError, Val);
139 // If SD is a variable, evaluate it.
141 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, &Layout, nullptr))
142 report_fatal_error("unable to evaluate offset for variable '" +
145 uint64_t Offset = Target.getConstant();
147 const MCSymbolRefExpr *A = Target.getSymA();
150 if (!getLabelOffset(Layout, A->getSymbol(), ReportError, ValA))
155 const MCSymbolRefExpr *B = Target.getSymB();
158 if (!getLabelOffset(Layout, B->getSymbol(), ReportError, ValB))
167 bool MCAsmLayout::getSymbolOffset(const MCSymbol &S, uint64_t &Val) const {
168 return getSymbolOffsetImpl(*this, S, false, Val);
171 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbol &S) const {
173 getSymbolOffsetImpl(*this, S, true, Val);
177 const MCSymbol *MCAsmLayout::getBaseSymbol(const MCSymbol &Symbol) const {
178 if (!Symbol.isVariable())
181 const MCExpr *Expr = Symbol.getVariableValue();
183 if (!Expr->evaluateAsValue(Value, *this))
184 llvm_unreachable("Invalid Expression");
186 const MCSymbolRefExpr *RefB = Value.getSymB();
188 Assembler.getContext().reportFatalError(
189 SMLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
190 "' could not be evaluated in a subtraction expression");
192 const MCSymbolRefExpr *A = Value.getSymA();
196 const MCSymbol &ASym = A->getSymbol();
197 const MCAssembler &Asm = getAssembler();
198 if (ASym.isCommon()) {
199 // FIXME: we should probably add a SMLoc to MCExpr.
200 Asm.getContext().reportFatalError(SMLoc(),
201 "Common symbol " + ASym.getName() +
202 " cannot be used in assignment expr");
208 uint64_t MCAsmLayout::getSectionAddressSize(const MCSection *Sec) const {
209 // The size is the last fragment's end offset.
210 const MCFragment &F = Sec->getFragmentList().back();
211 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
214 uint64_t MCAsmLayout::getSectionFileSize(const MCSection *Sec) const {
215 // Virtual sections have no file size.
216 if (Sec->isVirtualSection())
219 // Otherwise, the file size is the same as the address space size.
220 return getSectionAddressSize(Sec);
223 uint64_t llvm::computeBundlePadding(const MCAssembler &Assembler,
225 uint64_t FOffset, uint64_t FSize) {
226 uint64_t BundleSize = Assembler.getBundleAlignSize();
227 assert(BundleSize > 0 &&
228 "computeBundlePadding should only be called if bundling is enabled");
229 uint64_t BundleMask = BundleSize - 1;
230 uint64_t OffsetInBundle = FOffset & BundleMask;
231 uint64_t EndOfFragment = OffsetInBundle + FSize;
233 // There are two kinds of bundling restrictions:
235 // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
236 // *end* on a bundle boundary.
237 // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
238 // would, add padding until the end of the bundle so that the fragment
239 // will start in a new one.
240 if (F->alignToBundleEnd()) {
241 // Three possibilities here:
243 // A) The fragment just happens to end at a bundle boundary, so we're good.
244 // B) The fragment ends before the current bundle boundary: pad it just
245 // enough to reach the boundary.
246 // C) The fragment ends after the current bundle boundary: pad it until it
247 // reaches the end of the next bundle boundary.
249 // Note: this code could be made shorter with some modulo trickery, but it's
250 // intentionally kept in its more explicit form for simplicity.
251 if (EndOfFragment == BundleSize)
253 else if (EndOfFragment < BundleSize)
254 return BundleSize - EndOfFragment;
255 else { // EndOfFragment > BundleSize
256 return 2 * BundleSize - EndOfFragment;
258 } else if (EndOfFragment > BundleSize)
259 return BundleSize - OffsetInBundle;
266 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
269 MCFragment::~MCFragment() {
272 MCFragment::MCFragment(FragmentType Kind, MCSection *Parent)
273 : Kind(Kind), Parent(Parent), Atom(nullptr), Offset(~UINT64_C(0)) {
275 Parent->getFragmentList().push_back(this);
280 MCEncodedFragment::~MCEncodedFragment() {
285 MCEncodedFragmentWithFixups::~MCEncodedFragmentWithFixups() {
290 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
291 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
293 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
294 OS(OS_), BundleAlignSize(0), RelaxAll(false),
295 SubsectionsViaSymbols(false), ELFHeaderEFlags(0) {
296 VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
299 MCAssembler::~MCAssembler() {
302 void MCAssembler::reset() {
305 IndirectSymbols.clear();
307 LinkerOptions.clear();
312 SubsectionsViaSymbols = false;
314 LOHContainer.reset();
315 VersionMinInfo.Major = 0;
317 // reset objects owned by us
318 getBackend().reset();
319 getEmitter().reset();
321 getLOHContainer().reset();
324 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
325 if (ThumbFuncs.count(Symbol))
328 if (!Symbol->isVariable())
331 // FIXME: It looks like gas supports some cases of the form "foo + 2". It
332 // is not clear if that is a bug or a feature.
333 const MCExpr *Expr = Symbol->getVariableValue();
334 const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
338 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
341 const MCSymbol &Sym = Ref->getSymbol();
342 if (!isThumbFunc(&Sym))
345 ThumbFuncs.insert(Symbol); // Cache it.
349 void MCAssembler::addLocalUsedInReloc(const MCSymbol &Sym) {
350 assert(Sym.isTemporary());
351 LocalsUsedInReloc.insert(&Sym);
354 bool MCAssembler::isLocalUsedInReloc(const MCSymbol &Sym) const {
355 assert(Sym.isTemporary());
356 return LocalsUsedInReloc.count(&Sym);
359 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
360 // Non-temporary labels should always be visible to the linker.
361 if (!Symbol.isTemporary())
364 // Absolute temporary labels are never visible.
365 if (!Symbol.isInSection())
368 if (isLocalUsedInReloc(Symbol))
374 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
375 // Linker visible symbols define atoms.
376 if (isSymbolLinkerVisible(S))
379 // Absolute and undefined symbols have no defining atom.
380 if (!S.getData().getFragment())
383 // Non-linker visible symbols in sections which can't be atomized have no
385 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
386 *S.getData().getFragment()->getParent()))
389 // Otherwise, return the atom for the containing fragment.
390 return S.getData().getFragment()->getAtom();
393 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
394 const MCFixup &Fixup, const MCFragment *DF,
395 MCValue &Target, uint64_t &Value) const {
396 ++stats::evaluateFixup;
398 // FIXME: This code has some duplication with RecordRelocation. We should
399 // probably merge the two into a single callback that tries to evaluate a
400 // fixup and records a relocation if one is needed.
401 const MCExpr *Expr = Fixup.getValue();
402 if (!Expr->EvaluateAsRelocatable(Target, &Layout, &Fixup))
403 getContext().reportFatalError(Fixup.getLoc(), "expected relocatable expression");
405 bool IsPCRel = Backend.getFixupKindInfo(
406 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
410 if (Target.getSymB()) {
412 } else if (!Target.getSymA()) {
415 const MCSymbolRefExpr *A = Target.getSymA();
416 const MCSymbol &SA = A->getSymbol();
417 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
420 IsResolved = getWriter().IsSymbolRefDifferenceFullyResolvedImpl(
421 *this, SA, *DF, false, true);
425 IsResolved = Target.isAbsolute();
428 Value = Target.getConstant();
430 if (const MCSymbolRefExpr *A = Target.getSymA()) {
431 const MCSymbol &Sym = A->getSymbol();
433 Value += Layout.getSymbolOffset(Sym);
435 if (const MCSymbolRefExpr *B = Target.getSymB()) {
436 const MCSymbol &Sym = B->getSymbol();
438 Value -= Layout.getSymbolOffset(Sym);
442 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
443 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
444 assert((ShouldAlignPC ? IsPCRel : true) &&
445 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
448 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
450 // A number of ARM fixups in Thumb mode require that the effective PC
451 // address be determined as the 32-bit aligned version of the actual offset.
452 if (ShouldAlignPC) Offset &= ~0x3;
456 // Let the backend adjust the fixup value if necessary, including whether
457 // we need a relocation.
458 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
464 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
465 const MCFragment &F) const {
466 switch (F.getKind()) {
467 case MCFragment::FT_Data:
468 case MCFragment::FT_Relaxable:
469 case MCFragment::FT_CompactEncodedInst:
470 return cast<MCEncodedFragment>(F).getContents().size();
471 case MCFragment::FT_Fill:
472 return cast<MCFillFragment>(F).getSize();
474 case MCFragment::FT_LEB:
475 return cast<MCLEBFragment>(F).getContents().size();
477 case MCFragment::FT_Align: {
478 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
479 unsigned Offset = Layout.getFragmentOffset(&AF);
480 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
481 // If we are padding with nops, force the padding to be larger than the
483 if (Size > 0 && AF.hasEmitNops()) {
484 while (Size % getBackend().getMinimumNopSize())
485 Size += AF.getAlignment();
487 if (Size > AF.getMaxBytesToEmit())
492 case MCFragment::FT_Org: {
493 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
494 int64_t TargetLocation;
495 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
496 report_fatal_error("expected assembly-time absolute expression");
498 // FIXME: We need a way to communicate this error.
499 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
500 int64_t Size = TargetLocation - FragmentOffset;
501 if (Size < 0 || Size >= 0x40000000)
502 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
503 "' (at offset '" + Twine(FragmentOffset) + "')");
507 case MCFragment::FT_Dwarf:
508 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
509 case MCFragment::FT_DwarfFrame:
510 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
513 llvm_unreachable("invalid fragment kind");
516 void MCAsmLayout::layoutFragment(MCFragment *F) {
517 MCFragment *Prev = F->getPrevNode();
519 // We should never try to recompute something which is valid.
520 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
521 // We should never try to compute the fragment layout if its predecessor
523 assert((!Prev || isFragmentValid(Prev)) &&
524 "Attempt to compute fragment before its predecessor!");
526 ++stats::FragmentLayouts;
528 // Compute fragment offset and size.
530 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
533 LastValidFragment[F->getParent()] = F;
535 // If bundling is enabled and this fragment has instructions in it, it has to
536 // obey the bundling restrictions. With padding, we'll have:
541 // -------------------------------------
542 // Prev |##########| F |
543 // -------------------------------------
548 // The fragment's offset will point to after the padding, and its computed
549 // size won't include the padding.
551 // When the -mc-relax-all flag is used, we optimize bundling by writting the
552 // bundle padding directly into fragments when the instructions are emitted
553 // inside the streamer.
555 if (Assembler.isBundlingEnabled() && !Assembler.getRelaxAll() &&
556 F->hasInstructions()) {
557 assert(isa<MCEncodedFragment>(F) &&
558 "Only MCEncodedFragment implementations have instructions");
559 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
561 if (FSize > Assembler.getBundleAlignSize())
562 report_fatal_error("Fragment can't be larger than a bundle size");
564 uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
566 if (RequiredBundlePadding > UINT8_MAX)
567 report_fatal_error("Padding cannot exceed 255 bytes");
568 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
569 F->Offset += RequiredBundlePadding;
573 /// \brief Write the contents of a fragment to the given object writer. Expects
574 /// a MCEncodedFragment.
575 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
576 const MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
577 OW->WriteBytes(EF.getContents());
580 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
581 MCObjectWriter *OW) const {
582 // Should NOP padding be written out before this fragment?
583 unsigned BundlePadding = F.getBundlePadding();
584 if (BundlePadding > 0) {
585 assert(isBundlingEnabled() &&
586 "Writing bundle padding with disabled bundling");
587 assert(F.hasInstructions() &&
588 "Writing bundle padding for a fragment without instructions");
590 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
591 if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
592 // If the padding itself crosses a bundle boundary, it must be emitted
593 // in 2 pieces, since even nop instructions must not cross boundaries.
594 // v--------------v <- BundleAlignSize
595 // v---------v <- BundlePadding
596 // ----------------------------
597 // | Prev |####|####| F |
598 // ----------------------------
599 // ^-------------------^ <- TotalLength
600 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
601 if (!getBackend().writeNopData(DistanceToBoundary, OW))
602 report_fatal_error("unable to write NOP sequence of " +
603 Twine(DistanceToBoundary) + " bytes");
604 BundlePadding -= DistanceToBoundary;
606 if (!getBackend().writeNopData(BundlePadding, OW))
607 report_fatal_error("unable to write NOP sequence of " +
608 Twine(BundlePadding) + " bytes");
612 /// \brief Write the fragment \p F to the output file.
613 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
614 const MCFragment &F) {
615 MCObjectWriter *OW = &Asm.getWriter();
617 // FIXME: Embed in fragments instead?
618 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
620 Asm.writeFragmentPadding(F, FragmentSize, OW);
622 // This variable (and its dummy usage) is to participate in the assert at
623 // the end of the function.
624 uint64_t Start = OW->getStream().tell();
627 ++stats::EmittedFragments;
629 switch (F.getKind()) {
630 case MCFragment::FT_Align: {
631 ++stats::EmittedAlignFragments;
632 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
633 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
635 uint64_t Count = FragmentSize / AF.getValueSize();
637 // FIXME: This error shouldn't actually occur (the front end should emit
638 // multiple .align directives to enforce the semantics it wants), but is
639 // severe enough that we want to report it. How to handle this?
640 if (Count * AF.getValueSize() != FragmentSize)
641 report_fatal_error("undefined .align directive, value size '" +
642 Twine(AF.getValueSize()) +
643 "' is not a divisor of padding size '" +
644 Twine(FragmentSize) + "'");
646 // See if we are aligning with nops, and if so do that first to try to fill
647 // the Count bytes. Then if that did not fill any bytes or there are any
648 // bytes left to fill use the Value and ValueSize to fill the rest.
649 // If we are aligning with nops, ask that target to emit the right data.
650 if (AF.hasEmitNops()) {
651 if (!Asm.getBackend().writeNopData(Count, OW))
652 report_fatal_error("unable to write nop sequence of " +
653 Twine(Count) + " bytes");
657 // Otherwise, write out in multiples of the value size.
658 for (uint64_t i = 0; i != Count; ++i) {
659 switch (AF.getValueSize()) {
660 default: llvm_unreachable("Invalid size!");
661 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
662 case 2: OW->Write16(uint16_t(AF.getValue())); break;
663 case 4: OW->Write32(uint32_t(AF.getValue())); break;
664 case 8: OW->Write64(uint64_t(AF.getValue())); break;
670 case MCFragment::FT_Data:
671 ++stats::EmittedDataFragments;
672 writeFragmentContents(F, OW);
675 case MCFragment::FT_Relaxable:
676 ++stats::EmittedRelaxableFragments;
677 writeFragmentContents(F, OW);
680 case MCFragment::FT_CompactEncodedInst:
681 ++stats::EmittedCompactEncodedInstFragments;
682 writeFragmentContents(F, OW);
685 case MCFragment::FT_Fill: {
686 ++stats::EmittedFillFragments;
687 const MCFillFragment &FF = cast<MCFillFragment>(F);
689 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
691 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
692 switch (FF.getValueSize()) {
693 default: llvm_unreachable("Invalid size!");
694 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
695 case 2: OW->Write16(uint16_t(FF.getValue())); break;
696 case 4: OW->Write32(uint32_t(FF.getValue())); break;
697 case 8: OW->Write64(uint64_t(FF.getValue())); break;
703 case MCFragment::FT_LEB: {
704 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
705 OW->WriteBytes(LF.getContents());
709 case MCFragment::FT_Org: {
710 ++stats::EmittedOrgFragments;
711 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
713 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
714 OW->Write8(uint8_t(OF.getValue()));
719 case MCFragment::FT_Dwarf: {
720 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
721 OW->WriteBytes(OF.getContents());
724 case MCFragment::FT_DwarfFrame: {
725 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
726 OW->WriteBytes(CF.getContents());
731 assert(OW->getStream().tell() - Start == FragmentSize &&
732 "The stream should advance by fragment size");
735 void MCAssembler::writeSectionData(const MCSection *Sec,
736 const MCAsmLayout &Layout) const {
737 // Ignore virtual sections.
738 if (Sec->isVirtualSection()) {
739 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
741 // Check that contents are only things legal inside a virtual section.
742 for (MCSection::const_iterator it = Sec->begin(), ie = Sec->end(); it != ie;
744 switch (it->getKind()) {
745 default: llvm_unreachable("Invalid fragment in virtual section!");
746 case MCFragment::FT_Data: {
747 // Check that we aren't trying to write a non-zero contents (or fixups)
748 // into a virtual section. This is to support clients which use standard
749 // directives to fill the contents of virtual sections.
750 const MCDataFragment &DF = cast<MCDataFragment>(*it);
751 assert(DF.fixup_begin() == DF.fixup_end() &&
752 "Cannot have fixups in virtual section!");
753 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
754 if (DF.getContents()[i]) {
755 if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
756 report_fatal_error("non-zero initializer found in section '" +
757 ELFSec->getSectionName() + "'");
759 report_fatal_error("non-zero initializer found in virtual section");
763 case MCFragment::FT_Align:
764 // Check that we aren't trying to write a non-zero value into a virtual
766 assert((cast<MCAlignFragment>(it)->getValueSize() == 0 ||
767 cast<MCAlignFragment>(it)->getValue() == 0) &&
768 "Invalid align in virtual section!");
770 case MCFragment::FT_Fill:
771 assert((cast<MCFillFragment>(it)->getValueSize() == 0 ||
772 cast<MCFillFragment>(it)->getValue() == 0) &&
773 "Invalid fill in virtual section!");
781 uint64_t Start = getWriter().getStream().tell();
784 for (MCSection::const_iterator it = Sec->begin(), ie = Sec->end(); it != ie;
786 writeFragment(*this, Layout, *it);
788 assert(getWriter().getStream().tell() - Start ==
789 Layout.getSectionAddressSize(Sec));
792 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
794 const MCFixup &Fixup) {
795 // Evaluate the fixup.
798 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
799 MCFixupKindInfo::FKF_IsPCRel;
800 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
801 // The fixup was unresolved, we need a relocation. Inform the object
802 // writer of the relocation, and give it an opportunity to adjust the
803 // fixup value if need be.
804 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
807 return std::make_pair(FixedValue, IsPCRel);
810 void MCAssembler::Finish() {
811 DEBUG_WITH_TYPE("mc-dump", {
812 llvm::errs() << "assembler backend - pre-layout\n--\n";
815 // Create the layout object.
816 MCAsmLayout Layout(*this);
818 // Create dummy fragments and assign section ordinals.
819 unsigned SectionIndex = 0;
820 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
821 // Create dummy fragments to eliminate any empty sections, this simplifies
823 if (it->getFragmentList().empty())
824 new MCDataFragment(&*it);
826 it->setOrdinal(SectionIndex++);
829 // Assign layout order indices to sections and fragments.
830 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
831 MCSection *Sec = Layout.getSectionOrder()[i];
832 Sec->setLayoutOrder(i);
834 unsigned FragmentIndex = 0;
835 for (MCSection::iterator iFrag = Sec->begin(), iFragEnd = Sec->end();
836 iFrag != iFragEnd; ++iFrag)
837 iFrag->setLayoutOrder(FragmentIndex++);
840 // Layout until everything fits.
841 while (layoutOnce(Layout))
844 DEBUG_WITH_TYPE("mc-dump", {
845 llvm::errs() << "assembler backend - post-relaxation\n--\n";
848 // Finalize the layout, including fragment lowering.
849 finishLayout(Layout);
851 DEBUG_WITH_TYPE("mc-dump", {
852 llvm::errs() << "assembler backend - final-layout\n--\n";
855 uint64_t StartOffset = OS.tell();
857 // Allow the object writer a chance to perform post-layout binding (for
858 // example, to set the index fields in the symbol data).
859 getWriter().ExecutePostLayoutBinding(*this, Layout);
861 // Evaluate and apply the fixups, generating relocation entries as necessary.
862 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
863 for (MCSection::iterator it2 = it->begin(), ie2 = it->end(); it2 != ie2;
865 MCEncodedFragmentWithFixups *F =
866 dyn_cast<MCEncodedFragmentWithFixups>(it2);
868 for (MCEncodedFragmentWithFixups::fixup_iterator it3 = F->fixup_begin(),
869 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
870 MCFixup &Fixup = *it3;
873 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
874 getBackend().applyFixup(Fixup, F->getContents().data(),
875 F->getContents().size(), FixedValue, IsPCRel);
881 // Write the object file.
882 getWriter().WriteObject(*this, Layout);
884 stats::ObjectBytes += OS.tell() - StartOffset;
887 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
888 const MCRelaxableFragment *DF,
889 const MCAsmLayout &Layout) const {
890 // If we cannot resolve the fixup value, it requires relaxation.
893 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
896 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
899 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
900 const MCAsmLayout &Layout) const {
901 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
902 // are intentionally pushing out inst fragments, or because we relaxed a
903 // previous instruction to one that doesn't need relaxation.
904 if (!getBackend().mayNeedRelaxation(F->getInst()))
907 for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
908 ie = F->fixup_end(); it != ie; ++it)
909 if (fixupNeedsRelaxation(*it, F, Layout))
915 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
916 MCRelaxableFragment &F) {
917 if (!fragmentNeedsRelaxation(&F, Layout))
920 ++stats::RelaxedInstructions;
922 // FIXME-PERF: We could immediately lower out instructions if we can tell
923 // they are fully resolved, to avoid retesting on later passes.
925 // Relax the fragment.
928 getBackend().relaxInstruction(F.getInst(), Relaxed);
930 // Encode the new instruction.
932 // FIXME-PERF: If it matters, we could let the target do this. It can
933 // probably do so more efficiently in many cases.
934 SmallVector<MCFixup, 4> Fixups;
935 SmallString<256> Code;
936 raw_svector_ostream VecOS(Code);
937 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
940 // Update the fragment.
942 F.getContents() = Code;
943 F.getFixups() = Fixups;
948 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
949 uint64_t OldSize = LF.getContents().size();
951 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
953 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
954 SmallString<8> &Data = LF.getContents();
956 raw_svector_ostream OSE(Data);
958 encodeSLEB128(Value, OSE);
960 encodeULEB128(Value, OSE);
962 return OldSize != LF.getContents().size();
965 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
966 MCDwarfLineAddrFragment &DF) {
967 MCContext &Context = Layout.getAssembler().getContext();
968 uint64_t OldSize = DF.getContents().size();
970 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
971 assert(Abs && "We created a line delta with an invalid expression");
974 LineDelta = DF.getLineDelta();
975 SmallString<8> &Data = DF.getContents();
977 raw_svector_ostream OSE(Data);
978 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OSE);
980 return OldSize != Data.size();
983 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
984 MCDwarfCallFrameFragment &DF) {
985 MCContext &Context = Layout.getAssembler().getContext();
986 uint64_t OldSize = DF.getContents().size();
988 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
989 assert(Abs && "We created call frame with an invalid expression");
991 SmallString<8> &Data = DF.getContents();
993 raw_svector_ostream OSE(Data);
994 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
996 return OldSize != Data.size();
999 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1000 // Holds the first fragment which needed relaxing during this layout. It will
1001 // remain NULL if none were relaxed.
1002 // When a fragment is relaxed, all the fragments following it should get
1003 // invalidated because their offset is going to change.
1004 MCFragment *FirstRelaxedFragment = nullptr;
1006 // Attempt to relax all the fragments in the section.
1007 for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
1008 // Check if this is a fragment that needs relaxation.
1009 bool RelaxedFrag = false;
1010 switch(I->getKind()) {
1013 case MCFragment::FT_Relaxable:
1014 assert(!getRelaxAll() &&
1015 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1016 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
1018 case MCFragment::FT_Dwarf:
1019 RelaxedFrag = relaxDwarfLineAddr(Layout,
1020 *cast<MCDwarfLineAddrFragment>(I));
1022 case MCFragment::FT_DwarfFrame:
1024 relaxDwarfCallFrameFragment(Layout,
1025 *cast<MCDwarfCallFrameFragment>(I));
1027 case MCFragment::FT_LEB:
1028 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1031 if (RelaxedFrag && !FirstRelaxedFragment)
1032 FirstRelaxedFragment = I;
1034 if (FirstRelaxedFragment) {
1035 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1041 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1042 ++stats::RelaxationSteps;
1044 bool WasRelaxed = false;
1045 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1046 MCSection &Sec = *it;
1047 while (layoutSectionOnce(Layout, Sec))
1054 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1055 // The layout is done. Mark every fragment as valid.
1056 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1057 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1061 // Debugging methods
1065 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1066 OS << "<MCFixup" << " Offset:" << AF.getOffset()
1067 << " Value:" << *AF.getValue()
1068 << " Kind:" << AF.getKind() << ">";
1074 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1075 void MCFragment::dump() {
1076 raw_ostream &OS = llvm::errs();
1079 switch (getKind()) {
1080 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1081 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1082 case MCFragment::FT_CompactEncodedInst:
1083 OS << "MCCompactEncodedInstFragment"; break;
1084 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1085 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1086 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1087 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1088 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1089 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1092 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1093 << " Offset:" << Offset
1094 << " HasInstructions:" << hasInstructions()
1095 << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1097 switch (getKind()) {
1098 case MCFragment::FT_Align: {
1099 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1100 if (AF->hasEmitNops())
1101 OS << " (emit nops)";
1103 OS << " Alignment:" << AF->getAlignment()
1104 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1105 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1108 case MCFragment::FT_Data: {
1109 const MCDataFragment *DF = cast<MCDataFragment>(this);
1111 OS << " Contents:[";
1112 const SmallVectorImpl<char> &Contents = DF->getContents();
1113 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1115 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1117 OS << "] (" << Contents.size() << " bytes)";
1119 if (DF->fixup_begin() != DF->fixup_end()) {
1122 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1123 ie = DF->fixup_end(); it != ie; ++it) {
1124 if (it != DF->fixup_begin()) OS << ",\n ";
1131 case MCFragment::FT_CompactEncodedInst: {
1132 const MCCompactEncodedInstFragment *CEIF =
1133 cast<MCCompactEncodedInstFragment>(this);
1135 OS << " Contents:[";
1136 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1137 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1139 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1141 OS << "] (" << Contents.size() << " bytes)";
1144 case MCFragment::FT_Fill: {
1145 const MCFillFragment *FF = cast<MCFillFragment>(this);
1146 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1147 << " Size:" << FF->getSize();
1150 case MCFragment::FT_Relaxable: {
1151 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1154 F->getInst().dump_pretty(OS);
1157 case MCFragment::FT_Org: {
1158 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1160 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1163 case MCFragment::FT_Dwarf: {
1164 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1166 OS << " AddrDelta:" << OF->getAddrDelta()
1167 << " LineDelta:" << OF->getLineDelta();
1170 case MCFragment::FT_DwarfFrame: {
1171 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1173 OS << " AddrDelta:" << CF->getAddrDelta();
1176 case MCFragment::FT_LEB: {
1177 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1179 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1186 void MCSymbolData::dump() const {
1187 raw_ostream &OS = llvm::errs();
1189 OS << "<MCSymbolData"
1190 << " Fragment:" << getFragment();
1191 OS << " Flags:" << getFlags();
1193 OS << " (external)";
1194 if (isPrivateExtern())
1195 OS << " (private extern)";
1199 void MCAssembler::dump() {
1200 raw_ostream &OS = llvm::errs();
1202 OS << "<MCAssembler\n";
1203 OS << " Sections:[\n ";
1204 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1205 if (it != begin()) OS << ",\n ";
1211 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1212 if (it != symbol_begin()) OS << ",\n ";
1215 OS << ", Index:" << it->getIndex() << ", ";
1216 it->getData().dump();
1223 // anchors for MC*Fragment vtables
1224 void MCEncodedFragment::anchor() { }
1225 void MCEncodedFragmentWithFixups::anchor() { }
1226 void MCDataFragment::anchor() { }
1227 void MCCompactEncodedInstFragment::anchor() { }
1228 void MCRelaxableFragment::anchor() { }
1229 void MCAlignFragment::anchor() { }
1230 void MCFillFragment::anchor() { }
1231 void MCOrgFragment::anchor() { }
1232 void MCLEBFragment::anchor() { }
1233 void MCDwarfLineAddrFragment::anchor() { }
1234 void MCDwarfCallFrameFragment::anchor() { }