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 // Simple getSymbolOffset helper for the non-varibale case.
121 static uint64_t getLabelOffset(const MCAsmLayout &Layout,
122 const MCSymbolData &SD) {
123 if (!SD.getFragment())
124 report_fatal_error("unable to evaluate offset to undefined symbol '" +
125 SD.getSymbol().getName() + "'");
126 return Layout.getFragmentOffset(SD.getFragment()) + SD.getOffset();
129 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData *SD) const {
130 const MCSymbol &S = SD->getSymbol();
133 return getLabelOffset(*this, *SD);
135 // If SD is a variable, evaluate it.
137 if (!S.getVariableValue()->EvaluateAsValue(Target, this))
138 report_fatal_error("unable to evaluate offset for variable '" +
141 uint64_t Offset = Target.getConstant();
143 const MCSymbolRefExpr *A = Target.getSymA();
145 Offset += getLabelOffset(*this, Assembler.getSymbolData(A->getSymbol()));
147 const MCSymbolRefExpr *B = Target.getSymB();
149 Offset -= getLabelOffset(*this, Assembler.getSymbolData(B->getSymbol()));
154 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
155 // The size is the last fragment's end offset.
156 const MCFragment &F = SD->getFragmentList().back();
157 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
160 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
161 // Virtual sections have no file size.
162 if (SD->getSection().isVirtualSection())
165 // Otherwise, the file size is the same as the address space size.
166 return getSectionAddressSize(SD);
169 uint64_t MCAsmLayout::computeBundlePadding(const MCFragment *F,
170 uint64_t FOffset, uint64_t FSize) {
171 uint64_t BundleSize = Assembler.getBundleAlignSize();
172 assert(BundleSize > 0 &&
173 "computeBundlePadding should only be called if bundling is enabled");
174 uint64_t BundleMask = BundleSize - 1;
175 uint64_t OffsetInBundle = FOffset & BundleMask;
176 uint64_t EndOfFragment = OffsetInBundle + FSize;
178 // There are two kinds of bundling restrictions:
180 // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
181 // *end* on a bundle boundary.
182 // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
183 // would, add padding until the end of the bundle so that the fragment
184 // will start in a new one.
185 if (F->alignToBundleEnd()) {
186 // Three possibilities here:
188 // A) The fragment just happens to end at a bundle boundary, so we're good.
189 // B) The fragment ends before the current bundle boundary: pad it just
190 // enough to reach the boundary.
191 // C) The fragment ends after the current bundle boundary: pad it until it
192 // reaches the end of the next bundle boundary.
194 // Note: this code could be made shorter with some modulo trickery, but it's
195 // intentionally kept in its more explicit form for simplicity.
196 if (EndOfFragment == BundleSize)
198 else if (EndOfFragment < BundleSize)
199 return BundleSize - EndOfFragment;
200 else { // EndOfFragment > BundleSize
201 return 2 * BundleSize - EndOfFragment;
203 } else if (EndOfFragment > BundleSize)
204 return BundleSize - OffsetInBundle;
211 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
214 MCFragment::~MCFragment() {
217 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
218 : Kind(_Kind), Parent(_Parent), Atom(nullptr), Offset(~UINT64_C(0))
221 Parent->getFragmentList().push_back(this);
226 MCEncodedFragment::~MCEncodedFragment() {
231 MCEncodedFragmentWithFixups::~MCEncodedFragmentWithFixups() {
236 MCSectionData::MCSectionData() : Section(nullptr) {}
238 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
239 : Section(&_Section),
240 Ordinal(~UINT32_C(0)),
242 BundleLockState(NotBundleLocked), BundleGroupBeforeFirstInst(false),
243 HasInstructions(false)
246 A->getSectionList().push_back(this);
249 MCSectionData::iterator
250 MCSectionData::getSubsectionInsertionPoint(unsigned Subsection) {
251 if (Subsection == 0 && SubsectionFragmentMap.empty())
254 SmallVectorImpl<std::pair<unsigned, MCFragment *> >::iterator MI =
255 std::lower_bound(SubsectionFragmentMap.begin(), SubsectionFragmentMap.end(),
256 std::make_pair(Subsection, (MCFragment *)nullptr));
257 bool ExactMatch = false;
258 if (MI != SubsectionFragmentMap.end()) {
259 ExactMatch = MI->first == Subsection;
264 if (MI == SubsectionFragmentMap.end())
268 if (!ExactMatch && Subsection != 0) {
269 // The GNU as documentation claims that subsections have an alignment of 4,
270 // although this appears not to be the case.
271 MCFragment *F = new MCDataFragment();
272 SubsectionFragmentMap.insert(MI, std::make_pair(Subsection, F));
273 getFragmentList().insert(IP, F);
281 MCSymbolData::MCSymbolData() : Symbol(nullptr) {}
283 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
284 uint64_t _Offset, MCAssembler *A)
285 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
286 IsExternal(false), IsPrivateExtern(false),
287 CommonSize(0), SymbolSize(nullptr), CommonAlign(0),
291 A->getSymbolList().push_back(this);
296 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
297 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
299 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
300 OS(OS_), BundleAlignSize(0), RelaxAll(false), NoExecStack(false),
301 SubsectionsViaSymbols(false), ELFHeaderEFlags(0) {
302 VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
305 MCAssembler::~MCAssembler() {
308 void MCAssembler::reset() {
313 IndirectSymbols.clear();
318 SubsectionsViaSymbols = false;
321 // reset objects owned by us
322 getBackend().reset();
323 getEmitter().reset();
325 getLOHContainer().reset();
328 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
329 if (ThumbFuncs.count(Symbol))
332 if (!Symbol->isVariable())
335 // FIXME: It looks like gas support some cases of the form "foo + 2". It
336 // is not clear if that is a bug or a feature.
337 const MCExpr *Expr = Symbol->getVariableValue();
338 const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
342 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
345 const MCSymbol &Sym = Ref->getSymbol();
346 if (!isThumbFunc(&Sym))
349 ThumbFuncs.insert(Symbol); // Cache it.
353 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
354 // Non-temporary labels should always be visible to the linker.
355 if (!Symbol.isTemporary())
358 // Absolute temporary labels are never visible.
359 if (!Symbol.isInSection())
362 // Otherwise, check if the section requires symbols even for temporary labels.
363 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
366 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
367 // Linker visible symbols define atoms.
368 if (isSymbolLinkerVisible(SD->getSymbol()))
371 // Absolute and undefined symbols have no defining atom.
372 if (!SD->getFragment())
375 // Non-linker visible symbols in sections which can't be atomized have no
377 if (!getBackend().isSectionAtomizable(
378 SD->getFragment()->getParent()->getSection()))
381 // Otherwise, return the atom for the containing fragment.
382 return SD->getFragment()->getAtom();
385 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
386 const MCFixup &Fixup, const MCFragment *DF,
387 MCValue &Target, uint64_t &Value) const {
388 ++stats::evaluateFixup;
390 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, &Layout))
391 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
393 bool IsPCRel = Backend.getFixupKindInfo(
394 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
398 if (Target.getSymB()) {
400 } else if (!Target.getSymA()) {
403 const MCSymbolRefExpr *A = Target.getSymA();
404 const MCSymbol &SA = A->getSymbol();
405 if (A->getKind() != MCSymbolRefExpr::VK_None ||
406 SA.AliasedSymbol().isUndefined()) {
409 const MCSymbolData &DataA = getSymbolData(SA);
411 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
416 IsResolved = Target.isAbsolute();
419 Value = Target.getConstant();
421 if (const MCSymbolRefExpr *A = Target.getSymA()) {
422 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
424 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
426 if (const MCSymbolRefExpr *B = Target.getSymB()) {
427 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
429 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
433 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
434 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
435 assert((ShouldAlignPC ? IsPCRel : true) &&
436 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
439 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
441 // A number of ARM fixups in Thumb mode require that the effective PC
442 // address be determined as the 32-bit aligned version of the actual offset.
443 if (ShouldAlignPC) Offset &= ~0x3;
447 // Let the backend adjust the fixup value if necessary, including whether
448 // we need a relocation.
449 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
455 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
456 const MCFragment &F) const {
457 switch (F.getKind()) {
458 case MCFragment::FT_Data:
459 case MCFragment::FT_Relaxable:
460 case MCFragment::FT_CompactEncodedInst:
461 return cast<MCEncodedFragment>(F).getContents().size();
462 case MCFragment::FT_Fill:
463 return cast<MCFillFragment>(F).getSize();
465 case MCFragment::FT_LEB:
466 return cast<MCLEBFragment>(F).getContents().size();
468 case MCFragment::FT_Align: {
469 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
470 unsigned Offset = Layout.getFragmentOffset(&AF);
471 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
472 // If we are padding with nops, force the padding to be larger than the
474 if (Size > 0 && AF.hasEmitNops()) {
475 while (Size % getBackend().getMinimumNopSize())
476 Size += AF.getAlignment();
478 if (Size > AF.getMaxBytesToEmit())
483 case MCFragment::FT_Org: {
484 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
485 int64_t TargetLocation;
486 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
487 report_fatal_error("expected assembly-time absolute expression");
489 // FIXME: We need a way to communicate this error.
490 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
491 int64_t Size = TargetLocation - FragmentOffset;
492 if (Size < 0 || Size >= 0x40000000)
493 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
494 "' (at offset '" + Twine(FragmentOffset) + "')");
498 case MCFragment::FT_Dwarf:
499 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
500 case MCFragment::FT_DwarfFrame:
501 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
504 llvm_unreachable("invalid fragment kind");
507 void MCAsmLayout::layoutFragment(MCFragment *F) {
508 MCFragment *Prev = F->getPrevNode();
510 // We should never try to recompute something which is valid.
511 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
512 // We should never try to compute the fragment layout if its predecessor
514 assert((!Prev || isFragmentValid(Prev)) &&
515 "Attempt to compute fragment before its predecessor!");
517 ++stats::FragmentLayouts;
519 // Compute fragment offset and size.
521 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
524 LastValidFragment[F->getParent()] = F;
526 // If bundling is enabled and this fragment has instructions in it, it has to
527 // obey the bundling restrictions. With padding, we'll have:
532 // -------------------------------------
533 // Prev |##########| F |
534 // -------------------------------------
539 // The fragment's offset will point to after the padding, and its computed
540 // size won't include the padding.
542 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
543 assert(isa<MCEncodedFragment>(F) &&
544 "Only MCEncodedFragment implementations have instructions");
545 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
547 if (FSize > Assembler.getBundleAlignSize())
548 report_fatal_error("Fragment can't be larger than a bundle size");
550 uint64_t RequiredBundlePadding = computeBundlePadding(F, F->Offset, FSize);
551 if (RequiredBundlePadding > UINT8_MAX)
552 report_fatal_error("Padding cannot exceed 255 bytes");
553 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
554 F->Offset += RequiredBundlePadding;
558 /// \brief Write the contents of a fragment to the given object writer. Expects
559 /// a MCEncodedFragment.
560 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
561 const MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
562 OW->WriteBytes(EF.getContents());
565 /// \brief Write the fragment \p F to the output file.
566 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
567 const MCFragment &F) {
568 MCObjectWriter *OW = &Asm.getWriter();
570 // FIXME: Embed in fragments instead?
571 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
573 // Should NOP padding be written out before this fragment?
574 unsigned BundlePadding = F.getBundlePadding();
575 if (BundlePadding > 0) {
576 assert(Asm.isBundlingEnabled() &&
577 "Writing bundle padding with disabled bundling");
578 assert(F.hasInstructions() &&
579 "Writing bundle padding for a fragment without instructions");
581 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FragmentSize);
582 if (F.alignToBundleEnd() && TotalLength > Asm.getBundleAlignSize()) {
583 // If the padding itself crosses a bundle boundary, it must be emitted
584 // in 2 pieces, since even nop instructions must not cross boundaries.
585 // v--------------v <- BundleAlignSize
586 // v---------v <- BundlePadding
587 // ----------------------------
588 // | Prev |####|####| F |
589 // ----------------------------
590 // ^-------------------^ <- TotalLength
591 unsigned DistanceToBoundary = TotalLength - Asm.getBundleAlignSize();
592 if (!Asm.getBackend().writeNopData(DistanceToBoundary, OW))
593 report_fatal_error("unable to write NOP sequence of " +
594 Twine(DistanceToBoundary) + " bytes");
595 BundlePadding -= DistanceToBoundary;
597 if (!Asm.getBackend().writeNopData(BundlePadding, OW))
598 report_fatal_error("unable to write NOP sequence of " +
599 Twine(BundlePadding) + " bytes");
602 // This variable (and its dummy usage) is to participate in the assert at
603 // the end of the function.
604 uint64_t Start = OW->getStream().tell();
607 ++stats::EmittedFragments;
609 switch (F.getKind()) {
610 case MCFragment::FT_Align: {
611 ++stats::EmittedAlignFragments;
612 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
613 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
615 uint64_t Count = FragmentSize / AF.getValueSize();
617 // FIXME: This error shouldn't actually occur (the front end should emit
618 // multiple .align directives to enforce the semantics it wants), but is
619 // severe enough that we want to report it. How to handle this?
620 if (Count * AF.getValueSize() != FragmentSize)
621 report_fatal_error("undefined .align directive, value size '" +
622 Twine(AF.getValueSize()) +
623 "' is not a divisor of padding size '" +
624 Twine(FragmentSize) + "'");
626 // See if we are aligning with nops, and if so do that first to try to fill
627 // the Count bytes. Then if that did not fill any bytes or there are any
628 // bytes left to fill use the Value and ValueSize to fill the rest.
629 // If we are aligning with nops, ask that target to emit the right data.
630 if (AF.hasEmitNops()) {
631 if (!Asm.getBackend().writeNopData(Count, OW))
632 report_fatal_error("unable to write nop sequence of " +
633 Twine(Count) + " bytes");
637 // Otherwise, write out in multiples of the value size.
638 for (uint64_t i = 0; i != Count; ++i) {
639 switch (AF.getValueSize()) {
640 default: llvm_unreachable("Invalid size!");
641 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
642 case 2: OW->Write16(uint16_t(AF.getValue())); break;
643 case 4: OW->Write32(uint32_t(AF.getValue())); break;
644 case 8: OW->Write64(uint64_t(AF.getValue())); break;
650 case MCFragment::FT_Data:
651 ++stats::EmittedDataFragments;
652 writeFragmentContents(F, OW);
655 case MCFragment::FT_Relaxable:
656 ++stats::EmittedRelaxableFragments;
657 writeFragmentContents(F, OW);
660 case MCFragment::FT_CompactEncodedInst:
661 ++stats::EmittedCompactEncodedInstFragments;
662 writeFragmentContents(F, OW);
665 case MCFragment::FT_Fill: {
666 ++stats::EmittedFillFragments;
667 const MCFillFragment &FF = cast<MCFillFragment>(F);
669 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
671 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
672 switch (FF.getValueSize()) {
673 default: llvm_unreachable("Invalid size!");
674 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
675 case 2: OW->Write16(uint16_t(FF.getValue())); break;
676 case 4: OW->Write32(uint32_t(FF.getValue())); break;
677 case 8: OW->Write64(uint64_t(FF.getValue())); break;
683 case MCFragment::FT_LEB: {
684 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
685 OW->WriteBytes(LF.getContents().str());
689 case MCFragment::FT_Org: {
690 ++stats::EmittedOrgFragments;
691 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
693 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
694 OW->Write8(uint8_t(OF.getValue()));
699 case MCFragment::FT_Dwarf: {
700 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
701 OW->WriteBytes(OF.getContents().str());
704 case MCFragment::FT_DwarfFrame: {
705 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
706 OW->WriteBytes(CF.getContents().str());
711 assert(OW->getStream().tell() - Start == FragmentSize &&
712 "The stream should advance by fragment size");
715 void MCAssembler::writeSectionData(const MCSectionData *SD,
716 const MCAsmLayout &Layout) const {
717 // Ignore virtual sections.
718 if (SD->getSection().isVirtualSection()) {
719 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
721 // Check that contents are only things legal inside a virtual section.
722 for (MCSectionData::const_iterator it = SD->begin(),
723 ie = SD->end(); it != ie; ++it) {
724 switch (it->getKind()) {
725 default: llvm_unreachable("Invalid fragment in virtual section!");
726 case MCFragment::FT_Data: {
727 // Check that we aren't trying to write a non-zero contents (or fixups)
728 // into a virtual section. This is to support clients which use standard
729 // directives to fill the contents of virtual sections.
730 const MCDataFragment &DF = cast<MCDataFragment>(*it);
731 assert(DF.fixup_begin() == DF.fixup_end() &&
732 "Cannot have fixups in virtual section!");
733 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
734 assert(DF.getContents()[i] == 0 &&
735 "Invalid data value for virtual section!");
738 case MCFragment::FT_Align:
739 // Check that we aren't trying to write a non-zero value into a virtual
741 assert((cast<MCAlignFragment>(it)->getValueSize() == 0 ||
742 cast<MCAlignFragment>(it)->getValue() == 0) &&
743 "Invalid align in virtual section!");
745 case MCFragment::FT_Fill:
746 assert((cast<MCFillFragment>(it)->getValueSize() == 0 ||
747 cast<MCFillFragment>(it)->getValue() == 0) &&
748 "Invalid fill in virtual section!");
756 uint64_t Start = getWriter().getStream().tell();
759 for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
761 writeFragment(*this, Layout, *it);
763 assert(getWriter().getStream().tell() - Start ==
764 Layout.getSectionAddressSize(SD));
767 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
769 const MCFixup &Fixup) {
770 // Evaluate the fixup.
773 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
774 MCFixupKindInfo::FKF_IsPCRel;
775 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
776 // The fixup was unresolved, we need a relocation. Inform the object
777 // writer of the relocation, and give it an opportunity to adjust the
778 // fixup value if need be.
779 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
782 return std::make_pair(FixedValue, IsPCRel);
785 void MCAssembler::Finish() {
786 DEBUG_WITH_TYPE("mc-dump", {
787 llvm::errs() << "assembler backend - pre-layout\n--\n";
790 // Create the layout object.
791 MCAsmLayout Layout(*this);
793 // Create dummy fragments and assign section ordinals.
794 unsigned SectionIndex = 0;
795 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
796 // Create dummy fragments to eliminate any empty sections, this simplifies
798 if (it->getFragmentList().empty())
799 new MCDataFragment(it);
801 it->setOrdinal(SectionIndex++);
804 // Assign layout order indices to sections and fragments.
805 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
806 MCSectionData *SD = Layout.getSectionOrder()[i];
807 SD->setLayoutOrder(i);
809 unsigned FragmentIndex = 0;
810 for (MCSectionData::iterator iFrag = SD->begin(), iFragEnd = SD->end();
811 iFrag != iFragEnd; ++iFrag)
812 iFrag->setLayoutOrder(FragmentIndex++);
815 // Layout until everything fits.
816 while (layoutOnce(Layout))
819 DEBUG_WITH_TYPE("mc-dump", {
820 llvm::errs() << "assembler backend - post-relaxation\n--\n";
823 // Finalize the layout, including fragment lowering.
824 finishLayout(Layout);
826 DEBUG_WITH_TYPE("mc-dump", {
827 llvm::errs() << "assembler backend - final-layout\n--\n";
830 uint64_t StartOffset = OS.tell();
832 // Allow the object writer a chance to perform post-layout binding (for
833 // example, to set the index fields in the symbol data).
834 getWriter().ExecutePostLayoutBinding(*this, Layout);
836 // Evaluate and apply the fixups, generating relocation entries as necessary.
837 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
838 for (MCSectionData::iterator it2 = it->begin(),
839 ie2 = it->end(); it2 != ie2; ++it2) {
840 MCEncodedFragmentWithFixups *F =
841 dyn_cast<MCEncodedFragmentWithFixups>(it2);
843 for (MCEncodedFragmentWithFixups::fixup_iterator it3 = F->fixup_begin(),
844 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
845 MCFixup &Fixup = *it3;
848 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
849 getBackend().applyFixup(Fixup, F->getContents().data(),
850 F->getContents().size(), FixedValue, IsPCRel);
856 // Write the object file.
857 getWriter().WriteObject(*this, Layout);
859 stats::ObjectBytes += OS.tell() - StartOffset;
862 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
863 const MCRelaxableFragment *DF,
864 const MCAsmLayout &Layout) const {
865 // If we cannot resolve the fixup value, it requires relaxation.
868 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
871 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
874 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
875 const MCAsmLayout &Layout) const {
876 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
877 // are intentionally pushing out inst fragments, or because we relaxed a
878 // previous instruction to one that doesn't need relaxation.
879 if (!getBackend().mayNeedRelaxation(F->getInst()))
882 for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
883 ie = F->fixup_end(); it != ie; ++it)
884 if (fixupNeedsRelaxation(*it, F, Layout))
890 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
891 MCRelaxableFragment &F) {
892 if (!fragmentNeedsRelaxation(&F, Layout))
895 ++stats::RelaxedInstructions;
897 // FIXME-PERF: We could immediately lower out instructions if we can tell
898 // they are fully resolved, to avoid retesting on later passes.
900 // Relax the fragment.
903 getBackend().relaxInstruction(F.getInst(), Relaxed);
905 // Encode the new instruction.
907 // FIXME-PERF: If it matters, we could let the target do this. It can
908 // probably do so more efficiently in many cases.
909 SmallVector<MCFixup, 4> Fixups;
910 SmallString<256> Code;
911 raw_svector_ostream VecOS(Code);
912 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
915 // Update the fragment.
917 F.getContents() = Code;
918 F.getFixups() = Fixups;
923 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
925 uint64_t OldSize = LF.getContents().size();
926 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
929 SmallString<8> &Data = LF.getContents();
931 raw_svector_ostream OSE(Data);
933 encodeSLEB128(Value, OSE);
935 encodeULEB128(Value, OSE);
937 return OldSize != LF.getContents().size();
940 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
941 MCDwarfLineAddrFragment &DF) {
942 MCContext &Context = Layout.getAssembler().getContext();
943 int64_t AddrDelta = 0;
944 uint64_t OldSize = DF.getContents().size();
945 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
949 LineDelta = DF.getLineDelta();
950 SmallString<8> &Data = DF.getContents();
952 raw_svector_ostream OSE(Data);
953 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OSE);
955 return OldSize != Data.size();
958 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
959 MCDwarfCallFrameFragment &DF) {
960 MCContext &Context = Layout.getAssembler().getContext();
961 int64_t AddrDelta = 0;
962 uint64_t OldSize = DF.getContents().size();
963 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
966 SmallString<8> &Data = DF.getContents();
968 raw_svector_ostream OSE(Data);
969 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
971 return OldSize != Data.size();
974 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD) {
975 // Holds the first fragment which needed relaxing during this layout. It will
976 // remain NULL if none were relaxed.
977 // When a fragment is relaxed, all the fragments following it should get
978 // invalidated because their offset is going to change.
979 MCFragment *FirstRelaxedFragment = nullptr;
981 // Attempt to relax all the fragments in the section.
982 for (MCSectionData::iterator I = SD.begin(), IE = SD.end(); I != IE; ++I) {
983 // Check if this is a fragment that needs relaxation.
984 bool RelaxedFrag = false;
985 switch(I->getKind()) {
988 case MCFragment::FT_Relaxable:
989 assert(!getRelaxAll() &&
990 "Did not expect a MCRelaxableFragment in RelaxAll mode");
991 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
993 case MCFragment::FT_Dwarf:
994 RelaxedFrag = relaxDwarfLineAddr(Layout,
995 *cast<MCDwarfLineAddrFragment>(I));
997 case MCFragment::FT_DwarfFrame:
999 relaxDwarfCallFrameFragment(Layout,
1000 *cast<MCDwarfCallFrameFragment>(I));
1002 case MCFragment::FT_LEB:
1003 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1006 if (RelaxedFrag && !FirstRelaxedFragment)
1007 FirstRelaxedFragment = I;
1009 if (FirstRelaxedFragment) {
1010 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1016 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1017 ++stats::RelaxationSteps;
1019 bool WasRelaxed = false;
1020 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1021 MCSectionData &SD = *it;
1022 while (layoutSectionOnce(Layout, SD))
1029 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1030 // The layout is done. Mark every fragment as valid.
1031 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1032 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1036 // Debugging methods
1040 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1041 OS << "<MCFixup" << " Offset:" << AF.getOffset()
1042 << " Value:" << *AF.getValue()
1043 << " Kind:" << AF.getKind() << ">";
1049 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1050 void MCFragment::dump() {
1051 raw_ostream &OS = llvm::errs();
1054 switch (getKind()) {
1055 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1056 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1057 case MCFragment::FT_CompactEncodedInst:
1058 OS << "MCCompactEncodedInstFragment"; break;
1059 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1060 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1061 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1062 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1063 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1064 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1067 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1068 << " Offset:" << Offset
1069 << " HasInstructions:" << hasInstructions()
1070 << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1072 switch (getKind()) {
1073 case MCFragment::FT_Align: {
1074 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1075 if (AF->hasEmitNops())
1076 OS << " (emit nops)";
1078 OS << " Alignment:" << AF->getAlignment()
1079 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1080 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1083 case MCFragment::FT_Data: {
1084 const MCDataFragment *DF = cast<MCDataFragment>(this);
1086 OS << " Contents:[";
1087 const SmallVectorImpl<char> &Contents = DF->getContents();
1088 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1090 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1092 OS << "] (" << Contents.size() << " bytes)";
1094 if (DF->fixup_begin() != DF->fixup_end()) {
1097 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1098 ie = DF->fixup_end(); it != ie; ++it) {
1099 if (it != DF->fixup_begin()) OS << ",\n ";
1106 case MCFragment::FT_CompactEncodedInst: {
1107 const MCCompactEncodedInstFragment *CEIF =
1108 cast<MCCompactEncodedInstFragment>(this);
1110 OS << " Contents:[";
1111 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1112 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1114 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1116 OS << "] (" << Contents.size() << " bytes)";
1119 case MCFragment::FT_Fill: {
1120 const MCFillFragment *FF = cast<MCFillFragment>(this);
1121 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1122 << " Size:" << FF->getSize();
1125 case MCFragment::FT_Relaxable: {
1126 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1129 F->getInst().dump_pretty(OS);
1132 case MCFragment::FT_Org: {
1133 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1135 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1138 case MCFragment::FT_Dwarf: {
1139 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1141 OS << " AddrDelta:" << OF->getAddrDelta()
1142 << " LineDelta:" << OF->getLineDelta();
1145 case MCFragment::FT_DwarfFrame: {
1146 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1148 OS << " AddrDelta:" << CF->getAddrDelta();
1151 case MCFragment::FT_LEB: {
1152 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1154 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1161 void MCSectionData::dump() {
1162 raw_ostream &OS = llvm::errs();
1164 OS << "<MCSectionData";
1165 OS << " Alignment:" << getAlignment()
1166 << " Fragments:[\n ";
1167 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1168 if (it != begin()) OS << ",\n ";
1174 void MCSymbolData::dump() {
1175 raw_ostream &OS = llvm::errs();
1177 OS << "<MCSymbolData Symbol:" << getSymbol()
1178 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1179 << " Flags:" << getFlags() << " Index:" << getIndex();
1181 OS << " (common, size:" << getCommonSize()
1182 << " align: " << getCommonAlignment() << ")";
1184 OS << " (external)";
1185 if (isPrivateExtern())
1186 OS << " (private extern)";
1190 void MCAssembler::dump() {
1191 raw_ostream &OS = llvm::errs();
1193 OS << "<MCAssembler\n";
1194 OS << " Sections:[\n ";
1195 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1196 if (it != begin()) OS << ",\n ";
1202 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1203 if (it != symbol_begin()) OS << ",\n ";
1210 // anchors for MC*Fragment vtables
1211 void MCEncodedFragment::anchor() { }
1212 void MCEncodedFragmentWithFixups::anchor() { }
1213 void MCDataFragment::anchor() { }
1214 void MCCompactEncodedInstFragment::anchor() { }
1215 void MCRelaxableFragment::anchor() { }
1216 void MCAlignFragment::anchor() { }
1217 void MCFillFragment::anchor() { }
1218 void MCOrgFragment::anchor() { }
1219 void MCLEBFragment::anchor() { }
1220 void MCDwarfLineAddrFragment::anchor() { }
1221 void MCDwarfCallFrameFragment::anchor() { }