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/MCAsmLayout.h"
16 #include "llvm/MC/MCCodeEmitter.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCDwarf.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCFixupKindInfo.h"
21 #include "llvm/MC/MCObjectWriter.h"
22 #include "llvm/MC/MCSection.h"
23 #include "llvm/MC/MCSymbol.h"
24 #include "llvm/MC/MCValue.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/LEB128.h"
28 #include "llvm/Support/TargetRegistry.h"
29 #include "llvm/Support/raw_ostream.h"
33 #define DEBUG_TYPE "assembler"
37 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
38 STATISTIC(EmittedRelaxableFragments,
39 "Number of emitted assembler fragments - relaxable");
40 STATISTIC(EmittedDataFragments,
41 "Number of emitted assembler fragments - data");
42 STATISTIC(EmittedCompactEncodedInstFragments,
43 "Number of emitted assembler fragments - compact encoded inst");
44 STATISTIC(EmittedAlignFragments,
45 "Number of emitted assembler fragments - align");
46 STATISTIC(EmittedFillFragments,
47 "Number of emitted assembler fragments - fill");
48 STATISTIC(EmittedOrgFragments,
49 "Number of emitted assembler fragments - org");
50 STATISTIC(evaluateFixup, "Number of evaluated fixups");
51 STATISTIC(FragmentLayouts, "Number of fragment layouts");
52 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
53 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
54 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
58 // FIXME FIXME FIXME: There are number of places in this file where we convert
59 // what is a 64-bit assembler value used for computation into a value in the
60 // object file, which may truncate it. We should detect that truncation where
61 // invalid and report errors back.
65 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
66 : Assembler(Asm), LastValidFragment()
68 // Compute the section layout order. Virtual sections must go last.
69 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
70 if (!it->getSection().isVirtualSection())
71 SectionOrder.push_back(&*it);
72 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
73 if (it->getSection().isVirtualSection())
74 SectionOrder.push_back(&*it);
77 bool MCAsmLayout::isFragmentValid(const MCFragment *F) const {
78 const MCSectionData &SD = *F->getParent();
79 const MCFragment *LastValid = LastValidFragment.lookup(&SD);
82 assert(LastValid->getParent() == F->getParent());
83 return F->getLayoutOrder() <= LastValid->getLayoutOrder();
86 void MCAsmLayout::invalidateFragmentsFrom(MCFragment *F) {
87 // If this fragment wasn't already valid, we don't need to do anything.
88 if (!isFragmentValid(F))
91 // Otherwise, reset the last valid fragment to the previous fragment
92 // (if this is the first fragment, it will be NULL).
93 const MCSectionData &SD = *F->getParent();
94 LastValidFragment[&SD] = F->getPrevNode();
97 void MCAsmLayout::ensureValid(const MCFragment *F) const {
98 MCSectionData &SD = *F->getParent();
100 MCFragment *Cur = LastValidFragment[&SD];
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 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData *SD) const {
121 const MCSymbol &S = SD->getSymbol();
123 // If this is a variable, then recursively evaluate now.
124 if (S.isVariable()) {
126 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, this))
127 report_fatal_error("unable to evaluate offset for variable '" +
130 // Verify that any used symbols are defined.
131 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
132 report_fatal_error("unable to evaluate offset to undefined symbol '" +
133 Target.getSymA()->getSymbol().getName() + "'");
134 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
135 report_fatal_error("unable to evaluate offset to undefined symbol '" +
136 Target.getSymB()->getSymbol().getName() + "'");
138 uint64_t Offset = Target.getConstant();
139 if (Target.getSymA())
140 Offset += getSymbolOffset(&Assembler.getSymbolData(
141 Target.getSymA()->getSymbol()));
142 if (Target.getSymB())
143 Offset -= getSymbolOffset(&Assembler.getSymbolData(
144 Target.getSymB()->getSymbol()));
148 assert(SD->getFragment() && "Invalid getOffset() on undefined symbol!");
149 return getFragmentOffset(SD->getFragment()) + SD->getOffset();
152 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
153 // The size is the last fragment's end offset.
154 const MCFragment &F = SD->getFragmentList().back();
155 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
158 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
159 // Virtual sections have no file size.
160 if (SD->getSection().isVirtualSection())
163 // Otherwise, the file size is the same as the address space size.
164 return getSectionAddressSize(SD);
167 uint64_t MCAsmLayout::computeBundlePadding(const MCFragment *F,
168 uint64_t FOffset, uint64_t FSize) {
169 uint64_t BundleSize = Assembler.getBundleAlignSize();
170 assert(BundleSize > 0 &&
171 "computeBundlePadding should only be called if bundling is enabled");
172 uint64_t BundleMask = BundleSize - 1;
173 uint64_t OffsetInBundle = FOffset & BundleMask;
174 uint64_t EndOfFragment = OffsetInBundle + FSize;
176 // There are two kinds of bundling restrictions:
178 // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
179 // *end* on a bundle boundary.
180 // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
181 // would, add padding until the end of the bundle so that the fragment
182 // will start in a new one.
183 if (F->alignToBundleEnd()) {
184 // Three possibilities here:
186 // A) The fragment just happens to end at a bundle boundary, so we're good.
187 // B) The fragment ends before the current bundle boundary: pad it just
188 // enough to reach the boundary.
189 // C) The fragment ends after the current bundle boundary: pad it until it
190 // reaches the end of the next bundle boundary.
192 // Note: this code could be made shorter with some modulo trickery, but it's
193 // intentionally kept in its more explicit form for simplicity.
194 if (EndOfFragment == BundleSize)
196 else if (EndOfFragment < BundleSize)
197 return BundleSize - EndOfFragment;
198 else { // EndOfFragment > BundleSize
199 return 2 * BundleSize - EndOfFragment;
201 } else if (EndOfFragment > BundleSize)
202 return BundleSize - OffsetInBundle;
209 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
212 MCFragment::~MCFragment() {
215 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
216 : Kind(_Kind), Parent(_Parent), Atom(nullptr), Offset(~UINT64_C(0))
219 Parent->getFragmentList().push_back(this);
224 MCEncodedFragment::~MCEncodedFragment() {
229 MCEncodedFragmentWithFixups::~MCEncodedFragmentWithFixups() {
234 MCSectionData::MCSectionData() : Section(nullptr) {}
236 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
237 : Section(&_Section),
238 Ordinal(~UINT32_C(0)),
240 BundleLockState(NotBundleLocked), BundleGroupBeforeFirstInst(false),
241 HasInstructions(false)
244 A->getSectionList().push_back(this);
247 MCSectionData::iterator
248 MCSectionData::getSubsectionInsertionPoint(unsigned Subsection) {
249 if (Subsection == 0 && SubsectionFragmentMap.empty())
252 SmallVectorImpl<std::pair<unsigned, MCFragment *> >::iterator MI =
253 std::lower_bound(SubsectionFragmentMap.begin(), SubsectionFragmentMap.end(),
254 std::make_pair(Subsection, (MCFragment *)nullptr));
255 bool ExactMatch = false;
256 if (MI != SubsectionFragmentMap.end()) {
257 ExactMatch = MI->first == Subsection;
262 if (MI == SubsectionFragmentMap.end())
266 if (!ExactMatch && Subsection != 0) {
267 // The GNU as documentation claims that subsections have an alignment of 4,
268 // although this appears not to be the case.
269 MCFragment *F = new MCDataFragment();
270 SubsectionFragmentMap.insert(MI, std::make_pair(Subsection, F));
271 getFragmentList().insert(IP, F);
279 MCSymbolData::MCSymbolData() : Symbol(nullptr) {}
281 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
282 uint64_t _Offset, MCAssembler *A)
283 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
284 IsExternal(false), IsPrivateExtern(false),
285 CommonSize(0), SymbolSize(nullptr), CommonAlign(0),
289 A->getSymbolList().push_back(this);
294 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
295 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
297 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
298 OS(OS_), BundleAlignSize(0), RelaxAll(false), NoExecStack(false),
299 SubsectionsViaSymbols(false), ELFHeaderEFlags(0) {
300 VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
303 MCAssembler::~MCAssembler() {
306 void MCAssembler::reset() {
311 IndirectSymbols.clear();
316 SubsectionsViaSymbols = false;
319 // reset objects owned by us
320 getBackend().reset();
321 getEmitter().reset();
323 getLOHContainer().reset();
326 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
327 if (ThumbFuncs.count(Symbol))
330 if (!Symbol->isVariable())
333 // FIXME: It looks like gas support some cases of the form "foo + 2". It
334 // is not clear if that is a bug or a feature.
335 const MCExpr *Expr = Symbol->getVariableValue();
336 const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
340 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
343 const MCSymbol &Sym = Ref->getSymbol();
344 if (!isThumbFunc(&Sym))
347 ThumbFuncs.insert(Symbol); // Cache it.
351 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
352 // Non-temporary labels should always be visible to the linker.
353 if (!Symbol.isTemporary())
356 // Absolute temporary labels are never visible.
357 if (!Symbol.isInSection())
360 // Otherwise, check if the section requires symbols even for temporary labels.
361 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
364 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
365 // Linker visible symbols define atoms.
366 if (isSymbolLinkerVisible(SD->getSymbol()))
369 // Absolute and undefined symbols have no defining atom.
370 if (!SD->getFragment())
373 // Non-linker visible symbols in sections which can't be atomized have no
375 if (!getBackend().isSectionAtomizable(
376 SD->getFragment()->getParent()->getSection()))
379 // Otherwise, return the atom for the containing fragment.
380 return SD->getFragment()->getAtom();
383 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
384 const MCFixup &Fixup, const MCFragment *DF,
385 MCValue &Target, uint64_t &Value) const {
386 ++stats::evaluateFixup;
388 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, &Layout))
389 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
391 bool IsPCRel = Backend.getFixupKindInfo(
392 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
396 if (Target.getSymB()) {
398 } else if (!Target.getSymA()) {
401 const MCSymbolRefExpr *A = Target.getSymA();
402 const MCSymbol &SA = A->getSymbol();
403 if (A->getKind() != MCSymbolRefExpr::VK_None ||
404 SA.AliasedSymbol().isUndefined()) {
407 const MCSymbolData &DataA = getSymbolData(SA);
409 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
414 IsResolved = Target.isAbsolute();
417 Value = Target.getConstant();
419 if (const MCSymbolRefExpr *A = Target.getSymA()) {
420 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
422 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
424 if (const MCSymbolRefExpr *B = Target.getSymB()) {
425 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
427 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
431 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
432 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
433 assert((ShouldAlignPC ? IsPCRel : true) &&
434 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
437 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
439 // A number of ARM fixups in Thumb mode require that the effective PC
440 // address be determined as the 32-bit aligned version of the actual offset.
441 if (ShouldAlignPC) Offset &= ~0x3;
445 // Let the backend adjust the fixup value if necessary, including whether
446 // we need a relocation.
447 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
453 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
454 const MCFragment &F) const {
455 switch (F.getKind()) {
456 case MCFragment::FT_Data:
457 case MCFragment::FT_Relaxable:
458 case MCFragment::FT_CompactEncodedInst:
459 return cast<MCEncodedFragment>(F).getContents().size();
460 case MCFragment::FT_Fill:
461 return cast<MCFillFragment>(F).getSize();
463 case MCFragment::FT_LEB:
464 return cast<MCLEBFragment>(F).getContents().size();
466 case MCFragment::FT_Align: {
467 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
468 unsigned Offset = Layout.getFragmentOffset(&AF);
469 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
470 // If we are padding with nops, force the padding to be larger than the
472 if (Size > 0 && AF.hasEmitNops()) {
473 while (Size % getBackend().getMinimumNopSize())
474 Size += AF.getAlignment();
476 if (Size > AF.getMaxBytesToEmit())
481 case MCFragment::FT_Org: {
482 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
483 int64_t TargetLocation;
484 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
485 report_fatal_error("expected assembly-time absolute expression");
487 // FIXME: We need a way to communicate this error.
488 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
489 int64_t Size = TargetLocation - FragmentOffset;
490 if (Size < 0 || Size >= 0x40000000)
491 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
492 "' (at offset '" + Twine(FragmentOffset) + "')");
496 case MCFragment::FT_Dwarf:
497 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
498 case MCFragment::FT_DwarfFrame:
499 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
502 llvm_unreachable("invalid fragment kind");
505 void MCAsmLayout::layoutFragment(MCFragment *F) {
506 MCFragment *Prev = F->getPrevNode();
508 // We should never try to recompute something which is valid.
509 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
510 // We should never try to compute the fragment layout if its predecessor
512 assert((!Prev || isFragmentValid(Prev)) &&
513 "Attempt to compute fragment before its predecessor!");
515 ++stats::FragmentLayouts;
517 // Compute fragment offset and size.
519 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
522 LastValidFragment[F->getParent()] = F;
524 // If bundling is enabled and this fragment has instructions in it, it has to
525 // obey the bundling restrictions. With padding, we'll have:
530 // -------------------------------------
531 // Prev |##########| F |
532 // -------------------------------------
537 // The fragment's offset will point to after the padding, and its computed
538 // size won't include the padding.
540 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
541 assert(isa<MCEncodedFragment>(F) &&
542 "Only MCEncodedFragment implementations have instructions");
543 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
545 if (FSize > Assembler.getBundleAlignSize())
546 report_fatal_error("Fragment can't be larger than a bundle size");
548 uint64_t RequiredBundlePadding = computeBundlePadding(F, F->Offset, FSize);
549 if (RequiredBundlePadding > UINT8_MAX)
550 report_fatal_error("Padding cannot exceed 255 bytes");
551 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
552 F->Offset += RequiredBundlePadding;
556 /// \brief Write the contents of a fragment to the given object writer. Expects
557 /// a MCEncodedFragment.
558 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
559 const MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
560 OW->WriteBytes(EF.getContents());
563 /// \brief Write the fragment \p F to the output file.
564 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
565 const MCFragment &F) {
566 MCObjectWriter *OW = &Asm.getWriter();
568 // FIXME: Embed in fragments instead?
569 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
571 // Should NOP padding be written out before this fragment?
572 unsigned BundlePadding = F.getBundlePadding();
573 if (BundlePadding > 0) {
574 assert(Asm.isBundlingEnabled() &&
575 "Writing bundle padding with disabled bundling");
576 assert(F.hasInstructions() &&
577 "Writing bundle padding for a fragment without instructions");
579 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FragmentSize);
580 if (F.alignToBundleEnd() && TotalLength > Asm.getBundleAlignSize()) {
581 // If the padding itself crosses a bundle boundary, it must be emitted
582 // in 2 pieces, since even nop instructions must not cross boundaries.
583 // v--------------v <- BundleAlignSize
584 // v---------v <- BundlePadding
585 // ----------------------------
586 // | Prev |####|####| F |
587 // ----------------------------
588 // ^-------------------^ <- TotalLength
589 unsigned DistanceToBoundary = TotalLength - Asm.getBundleAlignSize();
590 if (!Asm.getBackend().writeNopData(DistanceToBoundary, OW))
591 report_fatal_error("unable to write NOP sequence of " +
592 Twine(DistanceToBoundary) + " bytes");
593 BundlePadding -= DistanceToBoundary;
595 if (!Asm.getBackend().writeNopData(BundlePadding, OW))
596 report_fatal_error("unable to write NOP sequence of " +
597 Twine(BundlePadding) + " bytes");
600 // This variable (and its dummy usage) is to participate in the assert at
601 // the end of the function.
602 uint64_t Start = OW->getStream().tell();
605 ++stats::EmittedFragments;
607 switch (F.getKind()) {
608 case MCFragment::FT_Align: {
609 ++stats::EmittedAlignFragments;
610 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
611 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
613 uint64_t Count = FragmentSize / AF.getValueSize();
615 // FIXME: This error shouldn't actually occur (the front end should emit
616 // multiple .align directives to enforce the semantics it wants), but is
617 // severe enough that we want to report it. How to handle this?
618 if (Count * AF.getValueSize() != FragmentSize)
619 report_fatal_error("undefined .align directive, value size '" +
620 Twine(AF.getValueSize()) +
621 "' is not a divisor of padding size '" +
622 Twine(FragmentSize) + "'");
624 // See if we are aligning with nops, and if so do that first to try to fill
625 // the Count bytes. Then if that did not fill any bytes or there are any
626 // bytes left to fill use the Value and ValueSize to fill the rest.
627 // If we are aligning with nops, ask that target to emit the right data.
628 if (AF.hasEmitNops()) {
629 if (!Asm.getBackend().writeNopData(Count, OW))
630 report_fatal_error("unable to write nop sequence of " +
631 Twine(Count) + " bytes");
635 // Otherwise, write out in multiples of the value size.
636 for (uint64_t i = 0; i != Count; ++i) {
637 switch (AF.getValueSize()) {
638 default: llvm_unreachable("Invalid size!");
639 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
640 case 2: OW->Write16(uint16_t(AF.getValue())); break;
641 case 4: OW->Write32(uint32_t(AF.getValue())); break;
642 case 8: OW->Write64(uint64_t(AF.getValue())); break;
648 case MCFragment::FT_Data:
649 ++stats::EmittedDataFragments;
650 writeFragmentContents(F, OW);
653 case MCFragment::FT_Relaxable:
654 ++stats::EmittedRelaxableFragments;
655 writeFragmentContents(F, OW);
658 case MCFragment::FT_CompactEncodedInst:
659 ++stats::EmittedCompactEncodedInstFragments;
660 writeFragmentContents(F, OW);
663 case MCFragment::FT_Fill: {
664 ++stats::EmittedFillFragments;
665 const MCFillFragment &FF = cast<MCFillFragment>(F);
667 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
669 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
670 switch (FF.getValueSize()) {
671 default: llvm_unreachable("Invalid size!");
672 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
673 case 2: OW->Write16(uint16_t(FF.getValue())); break;
674 case 4: OW->Write32(uint32_t(FF.getValue())); break;
675 case 8: OW->Write64(uint64_t(FF.getValue())); break;
681 case MCFragment::FT_LEB: {
682 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
683 OW->WriteBytes(LF.getContents().str());
687 case MCFragment::FT_Org: {
688 ++stats::EmittedOrgFragments;
689 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
691 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
692 OW->Write8(uint8_t(OF.getValue()));
697 case MCFragment::FT_Dwarf: {
698 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
699 OW->WriteBytes(OF.getContents().str());
702 case MCFragment::FT_DwarfFrame: {
703 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
704 OW->WriteBytes(CF.getContents().str());
709 assert(OW->getStream().tell() - Start == FragmentSize &&
710 "The stream should advance by fragment size");
713 void MCAssembler::writeSectionData(const MCSectionData *SD,
714 const MCAsmLayout &Layout) const {
715 // Ignore virtual sections.
716 if (SD->getSection().isVirtualSection()) {
717 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
719 // Check that contents are only things legal inside a virtual section.
720 for (MCSectionData::const_iterator it = SD->begin(),
721 ie = SD->end(); it != ie; ++it) {
722 switch (it->getKind()) {
723 default: llvm_unreachable("Invalid fragment in virtual section!");
724 case MCFragment::FT_Data: {
725 // Check that we aren't trying to write a non-zero contents (or fixups)
726 // into a virtual section. This is to support clients which use standard
727 // directives to fill the contents of virtual sections.
728 const MCDataFragment &DF = cast<MCDataFragment>(*it);
729 assert(DF.fixup_begin() == DF.fixup_end() &&
730 "Cannot have fixups in virtual section!");
731 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
732 assert(DF.getContents()[i] == 0 &&
733 "Invalid data value for virtual section!");
736 case MCFragment::FT_Align:
737 // Check that we aren't trying to write a non-zero value into a virtual
739 assert((cast<MCAlignFragment>(it)->getValueSize() == 0 ||
740 cast<MCAlignFragment>(it)->getValue() == 0) &&
741 "Invalid align in virtual section!");
743 case MCFragment::FT_Fill:
744 assert((cast<MCFillFragment>(it)->getValueSize() == 0 ||
745 cast<MCFillFragment>(it)->getValue() == 0) &&
746 "Invalid fill in virtual section!");
754 uint64_t Start = getWriter().getStream().tell();
757 for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
759 writeFragment(*this, Layout, *it);
761 assert(getWriter().getStream().tell() - Start ==
762 Layout.getSectionAddressSize(SD));
765 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
767 const MCFixup &Fixup) {
768 // Evaluate the fixup.
771 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
772 MCFixupKindInfo::FKF_IsPCRel;
773 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
774 // The fixup was unresolved, we need a relocation. Inform the object
775 // writer of the relocation, and give it an opportunity to adjust the
776 // fixup value if need be.
777 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
780 return std::make_pair(FixedValue, IsPCRel);
783 void MCAssembler::Finish() {
784 DEBUG_WITH_TYPE("mc-dump", {
785 llvm::errs() << "assembler backend - pre-layout\n--\n";
788 // Create the layout object.
789 MCAsmLayout Layout(*this);
791 // Create dummy fragments and assign section ordinals.
792 unsigned SectionIndex = 0;
793 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
794 // Create dummy fragments to eliminate any empty sections, this simplifies
796 if (it->getFragmentList().empty())
797 new MCDataFragment(it);
799 it->setOrdinal(SectionIndex++);
802 // Assign layout order indices to sections and fragments.
803 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
804 MCSectionData *SD = Layout.getSectionOrder()[i];
805 SD->setLayoutOrder(i);
807 unsigned FragmentIndex = 0;
808 for (MCSectionData::iterator iFrag = SD->begin(), iFragEnd = SD->end();
809 iFrag != iFragEnd; ++iFrag)
810 iFrag->setLayoutOrder(FragmentIndex++);
813 // Layout until everything fits.
814 while (layoutOnce(Layout))
817 DEBUG_WITH_TYPE("mc-dump", {
818 llvm::errs() << "assembler backend - post-relaxation\n--\n";
821 // Finalize the layout, including fragment lowering.
822 finishLayout(Layout);
824 DEBUG_WITH_TYPE("mc-dump", {
825 llvm::errs() << "assembler backend - final-layout\n--\n";
828 uint64_t StartOffset = OS.tell();
830 // Allow the object writer a chance to perform post-layout binding (for
831 // example, to set the index fields in the symbol data).
832 getWriter().ExecutePostLayoutBinding(*this, Layout);
834 // Evaluate and apply the fixups, generating relocation entries as necessary.
835 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
836 for (MCSectionData::iterator it2 = it->begin(),
837 ie2 = it->end(); it2 != ie2; ++it2) {
838 MCEncodedFragmentWithFixups *F =
839 dyn_cast<MCEncodedFragmentWithFixups>(it2);
841 for (MCEncodedFragmentWithFixups::fixup_iterator it3 = F->fixup_begin(),
842 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
843 MCFixup &Fixup = *it3;
846 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
847 getBackend().applyFixup(Fixup, F->getContents().data(),
848 F->getContents().size(), FixedValue, IsPCRel);
854 // Write the object file.
855 getWriter().WriteObject(*this, Layout);
857 stats::ObjectBytes += OS.tell() - StartOffset;
860 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
861 const MCRelaxableFragment *DF,
862 const MCAsmLayout &Layout) const {
863 // If we cannot resolve the fixup value, it requires relaxation.
866 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
869 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
872 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
873 const MCAsmLayout &Layout) const {
874 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
875 // are intentionally pushing out inst fragments, or because we relaxed a
876 // previous instruction to one that doesn't need relaxation.
877 if (!getBackend().mayNeedRelaxation(F->getInst()))
880 for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
881 ie = F->fixup_end(); it != ie; ++it)
882 if (fixupNeedsRelaxation(*it, F, Layout))
888 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
889 MCRelaxableFragment &F) {
890 if (!fragmentNeedsRelaxation(&F, Layout))
893 ++stats::RelaxedInstructions;
895 // FIXME-PERF: We could immediately lower out instructions if we can tell
896 // they are fully resolved, to avoid retesting on later passes.
898 // Relax the fragment.
901 getBackend().relaxInstruction(F.getInst(), Relaxed);
903 // Encode the new instruction.
905 // FIXME-PERF: If it matters, we could let the target do this. It can
906 // probably do so more efficiently in many cases.
907 SmallVector<MCFixup, 4> Fixups;
908 SmallString<256> Code;
909 raw_svector_ostream VecOS(Code);
910 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
913 // Update the fragment.
915 F.getContents() = Code;
916 F.getFixups() = Fixups;
921 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
923 uint64_t OldSize = LF.getContents().size();
924 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
927 SmallString<8> &Data = LF.getContents();
929 raw_svector_ostream OSE(Data);
931 encodeSLEB128(Value, OSE);
933 encodeULEB128(Value, OSE);
935 return OldSize != LF.getContents().size();
938 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
939 MCDwarfLineAddrFragment &DF) {
940 MCContext &Context = Layout.getAssembler().getContext();
941 int64_t AddrDelta = 0;
942 uint64_t OldSize = DF.getContents().size();
943 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
947 LineDelta = DF.getLineDelta();
948 SmallString<8> &Data = DF.getContents();
950 raw_svector_ostream OSE(Data);
951 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OSE);
953 return OldSize != Data.size();
956 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
957 MCDwarfCallFrameFragment &DF) {
958 MCContext &Context = Layout.getAssembler().getContext();
959 int64_t AddrDelta = 0;
960 uint64_t OldSize = DF.getContents().size();
961 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
964 SmallString<8> &Data = DF.getContents();
966 raw_svector_ostream OSE(Data);
967 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
969 return OldSize != Data.size();
972 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD) {
973 // Holds the first fragment which needed relaxing during this layout. It will
974 // remain NULL if none were relaxed.
975 // When a fragment is relaxed, all the fragments following it should get
976 // invalidated because their offset is going to change.
977 MCFragment *FirstRelaxedFragment = nullptr;
979 // Attempt to relax all the fragments in the section.
980 for (MCSectionData::iterator I = SD.begin(), IE = SD.end(); I != IE; ++I) {
981 // Check if this is a fragment that needs relaxation.
982 bool RelaxedFrag = false;
983 switch(I->getKind()) {
986 case MCFragment::FT_Relaxable:
987 assert(!getRelaxAll() &&
988 "Did not expect a MCRelaxableFragment in RelaxAll mode");
989 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
991 case MCFragment::FT_Dwarf:
992 RelaxedFrag = relaxDwarfLineAddr(Layout,
993 *cast<MCDwarfLineAddrFragment>(I));
995 case MCFragment::FT_DwarfFrame:
997 relaxDwarfCallFrameFragment(Layout,
998 *cast<MCDwarfCallFrameFragment>(I));
1000 case MCFragment::FT_LEB:
1001 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1004 if (RelaxedFrag && !FirstRelaxedFragment)
1005 FirstRelaxedFragment = I;
1007 if (FirstRelaxedFragment) {
1008 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1014 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1015 ++stats::RelaxationSteps;
1017 bool WasRelaxed = false;
1018 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1019 MCSectionData &SD = *it;
1020 while (layoutSectionOnce(Layout, SD))
1027 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1028 // The layout is done. Mark every fragment as valid.
1029 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1030 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1034 // Debugging methods
1038 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1039 OS << "<MCFixup" << " Offset:" << AF.getOffset()
1040 << " Value:" << *AF.getValue()
1041 << " Kind:" << AF.getKind() << ">";
1047 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1048 void MCFragment::dump() {
1049 raw_ostream &OS = llvm::errs();
1052 switch (getKind()) {
1053 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1054 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1055 case MCFragment::FT_CompactEncodedInst:
1056 OS << "MCCompactEncodedInstFragment"; break;
1057 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1058 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1059 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1060 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1061 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1062 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1065 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1066 << " Offset:" << Offset
1067 << " HasInstructions:" << hasInstructions()
1068 << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1070 switch (getKind()) {
1071 case MCFragment::FT_Align: {
1072 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1073 if (AF->hasEmitNops())
1074 OS << " (emit nops)";
1076 OS << " Alignment:" << AF->getAlignment()
1077 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1078 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1081 case MCFragment::FT_Data: {
1082 const MCDataFragment *DF = cast<MCDataFragment>(this);
1084 OS << " Contents:[";
1085 const SmallVectorImpl<char> &Contents = DF->getContents();
1086 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1088 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1090 OS << "] (" << Contents.size() << " bytes)";
1092 if (DF->fixup_begin() != DF->fixup_end()) {
1095 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1096 ie = DF->fixup_end(); it != ie; ++it) {
1097 if (it != DF->fixup_begin()) OS << ",\n ";
1104 case MCFragment::FT_CompactEncodedInst: {
1105 const MCCompactEncodedInstFragment *CEIF =
1106 cast<MCCompactEncodedInstFragment>(this);
1108 OS << " Contents:[";
1109 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1110 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1112 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1114 OS << "] (" << Contents.size() << " bytes)";
1117 case MCFragment::FT_Fill: {
1118 const MCFillFragment *FF = cast<MCFillFragment>(this);
1119 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1120 << " Size:" << FF->getSize();
1123 case MCFragment::FT_Relaxable: {
1124 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1127 F->getInst().dump_pretty(OS);
1130 case MCFragment::FT_Org: {
1131 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1133 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1136 case MCFragment::FT_Dwarf: {
1137 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1139 OS << " AddrDelta:" << OF->getAddrDelta()
1140 << " LineDelta:" << OF->getLineDelta();
1143 case MCFragment::FT_DwarfFrame: {
1144 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1146 OS << " AddrDelta:" << CF->getAddrDelta();
1149 case MCFragment::FT_LEB: {
1150 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1152 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1159 void MCSectionData::dump() {
1160 raw_ostream &OS = llvm::errs();
1162 OS << "<MCSectionData";
1163 OS << " Alignment:" << getAlignment()
1164 << " Fragments:[\n ";
1165 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1166 if (it != begin()) OS << ",\n ";
1172 void MCSymbolData::dump() {
1173 raw_ostream &OS = llvm::errs();
1175 OS << "<MCSymbolData Symbol:" << getSymbol()
1176 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1177 << " Flags:" << getFlags() << " Index:" << getIndex();
1179 OS << " (common, size:" << getCommonSize()
1180 << " align: " << getCommonAlignment() << ")";
1182 OS << " (external)";
1183 if (isPrivateExtern())
1184 OS << " (private extern)";
1188 void MCAssembler::dump() {
1189 raw_ostream &OS = llvm::errs();
1191 OS << "<MCAssembler\n";
1192 OS << " Sections:[\n ";
1193 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1194 if (it != begin()) OS << ",\n ";
1200 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1201 if (it != symbol_begin()) OS << ",\n ";
1208 // anchors for MC*Fragment vtables
1209 void MCEncodedFragment::anchor() { }
1210 void MCEncodedFragmentWithFixups::anchor() { }
1211 void MCDataFragment::anchor() { }
1212 void MCCompactEncodedInstFragment::anchor() { }
1213 void MCRelaxableFragment::anchor() { }
1214 void MCAlignFragment::anchor() { }
1215 void MCFillFragment::anchor() { }
1216 void MCOrgFragment::anchor() { }
1217 void MCLEBFragment::anchor() { }
1218 void MCDwarfLineAddrFragment::anchor() { }
1219 void MCDwarfCallFrameFragment::anchor() { }