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->getSection().isVirtualSection())
73 SectionOrder.push_back(&*it);
74 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
75 if (it->getSection().isVirtualSection())
76 SectionOrder.push_back(&*it);
79 bool MCAsmLayout::isFragmentValid(const MCFragment *F) const {
80 const MCSectionData &SD = *F->getParent();
81 const MCFragment *LastValid = LastValidFragment.lookup(&SD);
84 assert(LastValid->getParent() == F->getParent());
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 const MCSectionData &SD = *F->getParent();
96 LastValidFragment[&SD] = F->getPrevNode();
99 void MCAsmLayout::ensureValid(const MCFragment *F) const {
100 MCSectionData &SD = *F->getParent();
102 MCFragment *Cur = LastValidFragment[&SD];
106 Cur = Cur->getNextNode();
108 // Advance the layout position until the fragment is valid.
109 while (!isFragmentValid(F)) {
110 assert(Cur && "Layout bookkeeping error");
111 const_cast<MCAsmLayout*>(this)->layoutFragment(Cur);
112 Cur = Cur->getNextNode();
116 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
118 assert(F->Offset != ~UINT64_C(0) && "Address not set!");
122 // Simple getSymbolOffset helper for the non-varibale case.
123 static bool getLabelOffset(const MCAsmLayout &Layout, const MCSymbol &S,
124 bool ReportError, uint64_t &Val) {
125 const MCSymbolData &SD = S.getData();
126 if (!SD.getFragment()) {
128 report_fatal_error("unable to evaluate offset to undefined symbol '" +
132 Val = Layout.getFragmentOffset(SD.getFragment()) + SD.getOffset();
136 static bool getSymbolOffsetImpl(const MCAsmLayout &Layout, const MCSymbol &S,
137 bool ReportError, uint64_t &Val) {
139 return getLabelOffset(Layout, S, ReportError, Val);
141 // If SD is a variable, evaluate it.
143 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, &Layout, nullptr))
144 report_fatal_error("unable to evaluate offset for variable '" +
147 uint64_t Offset = Target.getConstant();
149 const MCSymbolRefExpr *A = Target.getSymA();
152 if (!getLabelOffset(Layout, A->getSymbol(), ReportError, ValA))
157 const MCSymbolRefExpr *B = Target.getSymB();
160 if (!getLabelOffset(Layout, B->getSymbol(), ReportError, ValB))
169 bool MCAsmLayout::getSymbolOffset(const MCSymbol &S, uint64_t &Val) const {
170 return getSymbolOffsetImpl(*this, S, false, Val);
173 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbol &S) const {
175 getSymbolOffsetImpl(*this, S, true, Val);
179 const MCSymbol *MCAsmLayout::getBaseSymbol(const MCSymbol &Symbol) const {
180 if (!Symbol.isVariable())
183 const MCExpr *Expr = Symbol.getVariableValue();
185 if (!Expr->evaluateAsValue(Value, *this))
186 llvm_unreachable("Invalid Expression");
188 const MCSymbolRefExpr *RefB = Value.getSymB();
190 Assembler.getContext().reportFatalError(
191 SMLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
192 "' could not be evaluated in a subtraction expression");
194 const MCSymbolRefExpr *A = Value.getSymA();
198 const MCSymbol &ASym = A->getSymbol();
199 const MCAssembler &Asm = getAssembler();
200 const MCSymbolData &ASD = Asm.getSymbolData(ASym);
201 if (ASD.isCommon()) {
202 // FIXME: we should probably add a SMLoc to MCExpr.
203 Asm.getContext().reportFatalError(SMLoc(),
204 "Common symbol " + ASym.getName() +
205 " cannot be used in assignment expr");
211 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
212 // The size is the last fragment's end offset.
213 const MCFragment &F = SD->getFragmentList().back();
214 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
217 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
218 // Virtual sections have no file size.
219 if (SD->getSection().isVirtualSection())
222 // Otherwise, the file size is the same as the address space size.
223 return getSectionAddressSize(SD);
226 uint64_t llvm::computeBundlePadding(const MCAssembler &Assembler,
228 uint64_t FOffset, uint64_t FSize) {
229 uint64_t BundleSize = Assembler.getBundleAlignSize();
230 assert(BundleSize > 0 &&
231 "computeBundlePadding should only be called if bundling is enabled");
232 uint64_t BundleMask = BundleSize - 1;
233 uint64_t OffsetInBundle = FOffset & BundleMask;
234 uint64_t EndOfFragment = OffsetInBundle + FSize;
236 // There are two kinds of bundling restrictions:
238 // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
239 // *end* on a bundle boundary.
240 // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
241 // would, add padding until the end of the bundle so that the fragment
242 // will start in a new one.
243 if (F->alignToBundleEnd()) {
244 // Three possibilities here:
246 // A) The fragment just happens to end at a bundle boundary, so we're good.
247 // B) The fragment ends before the current bundle boundary: pad it just
248 // enough to reach the boundary.
249 // C) The fragment ends after the current bundle boundary: pad it until it
250 // reaches the end of the next bundle boundary.
252 // Note: this code could be made shorter with some modulo trickery, but it's
253 // intentionally kept in its more explicit form for simplicity.
254 if (EndOfFragment == BundleSize)
256 else if (EndOfFragment < BundleSize)
257 return BundleSize - EndOfFragment;
258 else { // EndOfFragment > BundleSize
259 return 2 * BundleSize - EndOfFragment;
261 } else if (EndOfFragment > BundleSize)
262 return BundleSize - OffsetInBundle;
269 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
272 MCFragment::~MCFragment() {
275 MCFragment::MCFragment(FragmentType Kind, MCSectionData *Parent)
276 : Kind(Kind), Parent(Parent), Atom(nullptr), Offset(~UINT64_C(0)) {
278 Parent->getFragmentList().push_back(this);
283 MCEncodedFragment::~MCEncodedFragment() {
288 MCEncodedFragmentWithFixups::~MCEncodedFragmentWithFixups() {
293 MCSectionData::MCSectionData() : Section(nullptr) {}
295 MCSectionData::MCSectionData(MCSection &Section, MCAssembler *A)
296 : Section(&Section) {
298 A->getSectionList().push_back(this);
301 MCSectionData::iterator
302 MCSectionData::getSubsectionInsertionPoint(unsigned Subsection) {
303 if (Subsection == 0 && SubsectionFragmentMap.empty())
306 SmallVectorImpl<std::pair<unsigned, MCFragment *> >::iterator MI =
307 std::lower_bound(SubsectionFragmentMap.begin(), SubsectionFragmentMap.end(),
308 std::make_pair(Subsection, (MCFragment *)nullptr));
309 bool ExactMatch = false;
310 if (MI != SubsectionFragmentMap.end()) {
311 ExactMatch = MI->first == Subsection;
316 if (MI == SubsectionFragmentMap.end())
320 if (!ExactMatch && Subsection != 0) {
321 // The GNU as documentation claims that subsections have an alignment of 4,
322 // although this appears not to be the case.
323 MCFragment *F = new MCDataFragment();
324 SubsectionFragmentMap.insert(MI, std::make_pair(Subsection, F));
325 getFragmentList().insert(IP, F);
334 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
335 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
337 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
338 OS(OS_), BundleAlignSize(0), RelaxAll(false),
339 SubsectionsViaSymbols(false), ELFHeaderEFlags(0) {
340 VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
343 MCAssembler::~MCAssembler() {
346 void MCAssembler::reset() {
350 IndirectSymbols.clear();
352 LinkerOptions.clear();
357 SubsectionsViaSymbols = false;
359 LOHContainer.reset();
360 VersionMinInfo.Major = 0;
362 // reset objects owned by us
363 getBackend().reset();
364 getEmitter().reset();
366 getLOHContainer().reset();
369 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
370 if (ThumbFuncs.count(Symbol))
373 if (!Symbol->isVariable())
376 // FIXME: It looks like gas supports some cases of the form "foo + 2". It
377 // is not clear if that is a bug or a feature.
378 const MCExpr *Expr = Symbol->getVariableValue();
379 const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
383 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
386 const MCSymbol &Sym = Ref->getSymbol();
387 if (!isThumbFunc(&Sym))
390 ThumbFuncs.insert(Symbol); // Cache it.
394 void MCAssembler::addLocalUsedInReloc(const MCSymbol &Sym) {
395 assert(Sym.isTemporary());
396 LocalsUsedInReloc.insert(&Sym);
399 bool MCAssembler::isLocalUsedInReloc(const MCSymbol &Sym) const {
400 assert(Sym.isTemporary());
401 return LocalsUsedInReloc.count(&Sym);
404 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
405 // Non-temporary labels should always be visible to the linker.
406 if (!Symbol.isTemporary())
409 // Absolute temporary labels are never visible.
410 if (!Symbol.isInSection())
413 if (isLocalUsedInReloc(Symbol))
419 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
420 // Linker visible symbols define atoms.
421 if (isSymbolLinkerVisible(S))
424 // Absolute and undefined symbols have no defining atom.
425 if (!S.getData().getFragment())
428 // Non-linker visible symbols in sections which can't be atomized have no
430 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
431 S.getData().getFragment()->getParent()->getSection()))
434 // Otherwise, return the atom for the containing fragment.
435 return S.getData().getFragment()->getAtom();
438 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
439 const MCFixup &Fixup, const MCFragment *DF,
440 MCValue &Target, uint64_t &Value) const {
441 ++stats::evaluateFixup;
443 // FIXME: This code has some duplication with RecordRelocation. We should
444 // probably merge the two into a single callback that tries to evaluate a
445 // fixup and records a relocation if one is needed.
446 const MCExpr *Expr = Fixup.getValue();
447 if (!Expr->EvaluateAsRelocatable(Target, &Layout, &Fixup))
448 getContext().reportFatalError(Fixup.getLoc(), "expected relocatable expression");
450 bool IsPCRel = Backend.getFixupKindInfo(
451 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
455 if (Target.getSymB()) {
457 } else if (!Target.getSymA()) {
460 const MCSymbolRefExpr *A = Target.getSymA();
461 const MCSymbol &SA = A->getSymbol();
462 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
465 IsResolved = getWriter().IsSymbolRefDifferenceFullyResolvedImpl(
466 *this, SA, *DF, false, true);
470 IsResolved = Target.isAbsolute();
473 Value = Target.getConstant();
475 if (const MCSymbolRefExpr *A = Target.getSymA()) {
476 const MCSymbol &Sym = A->getSymbol();
478 Value += Layout.getSymbolOffset(Sym);
480 if (const MCSymbolRefExpr *B = Target.getSymB()) {
481 const MCSymbol &Sym = B->getSymbol();
483 Value -= Layout.getSymbolOffset(Sym);
487 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
488 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
489 assert((ShouldAlignPC ? IsPCRel : true) &&
490 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
493 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
495 // A number of ARM fixups in Thumb mode require that the effective PC
496 // address be determined as the 32-bit aligned version of the actual offset.
497 if (ShouldAlignPC) Offset &= ~0x3;
501 // Let the backend adjust the fixup value if necessary, including whether
502 // we need a relocation.
503 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
509 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
510 const MCFragment &F) const {
511 switch (F.getKind()) {
512 case MCFragment::FT_Data:
513 case MCFragment::FT_Relaxable:
514 case MCFragment::FT_CompactEncodedInst:
515 return cast<MCEncodedFragment>(F).getContents().size();
516 case MCFragment::FT_Fill:
517 return cast<MCFillFragment>(F).getSize();
519 case MCFragment::FT_LEB:
520 return cast<MCLEBFragment>(F).getContents().size();
522 case MCFragment::FT_Align: {
523 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
524 unsigned Offset = Layout.getFragmentOffset(&AF);
525 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
526 // If we are padding with nops, force the padding to be larger than the
528 if (Size > 0 && AF.hasEmitNops()) {
529 while (Size % getBackend().getMinimumNopSize())
530 Size += AF.getAlignment();
532 if (Size > AF.getMaxBytesToEmit())
537 case MCFragment::FT_Org: {
538 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
539 int64_t TargetLocation;
540 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
541 report_fatal_error("expected assembly-time absolute expression");
543 // FIXME: We need a way to communicate this error.
544 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
545 int64_t Size = TargetLocation - FragmentOffset;
546 if (Size < 0 || Size >= 0x40000000)
547 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
548 "' (at offset '" + Twine(FragmentOffset) + "')");
552 case MCFragment::FT_Dwarf:
553 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
554 case MCFragment::FT_DwarfFrame:
555 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
558 llvm_unreachable("invalid fragment kind");
561 void MCAsmLayout::layoutFragment(MCFragment *F) {
562 MCFragment *Prev = F->getPrevNode();
564 // We should never try to recompute something which is valid.
565 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
566 // We should never try to compute the fragment layout if its predecessor
568 assert((!Prev || isFragmentValid(Prev)) &&
569 "Attempt to compute fragment before its predecessor!");
571 ++stats::FragmentLayouts;
573 // Compute fragment offset and size.
575 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
578 LastValidFragment[F->getParent()] = F;
580 // If bundling is enabled and this fragment has instructions in it, it has to
581 // obey the bundling restrictions. With padding, we'll have:
586 // -------------------------------------
587 // Prev |##########| F |
588 // -------------------------------------
593 // The fragment's offset will point to after the padding, and its computed
594 // size won't include the padding.
596 // When the -mc-relax-all flag is used, we optimize bundling by writting the
597 // bundle padding directly into fragments when the instructions are emitted
598 // inside the streamer.
600 if (Assembler.isBundlingEnabled() && !Assembler.getRelaxAll() &&
601 F->hasInstructions()) {
602 assert(isa<MCEncodedFragment>(F) &&
603 "Only MCEncodedFragment implementations have instructions");
604 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
606 if (FSize > Assembler.getBundleAlignSize())
607 report_fatal_error("Fragment can't be larger than a bundle size");
609 uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
611 if (RequiredBundlePadding > UINT8_MAX)
612 report_fatal_error("Padding cannot exceed 255 bytes");
613 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
614 F->Offset += RequiredBundlePadding;
618 /// \brief Write the contents of a fragment to the given object writer. Expects
619 /// a MCEncodedFragment.
620 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
621 const MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
622 OW->WriteBytes(EF.getContents());
625 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
626 MCObjectWriter *OW) const {
627 // Should NOP padding be written out before this fragment?
628 unsigned BundlePadding = F.getBundlePadding();
629 if (BundlePadding > 0) {
630 assert(isBundlingEnabled() &&
631 "Writing bundle padding with disabled bundling");
632 assert(F.hasInstructions() &&
633 "Writing bundle padding for a fragment without instructions");
635 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
636 if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
637 // If the padding itself crosses a bundle boundary, it must be emitted
638 // in 2 pieces, since even nop instructions must not cross boundaries.
639 // v--------------v <- BundleAlignSize
640 // v---------v <- BundlePadding
641 // ----------------------------
642 // | Prev |####|####| F |
643 // ----------------------------
644 // ^-------------------^ <- TotalLength
645 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
646 if (!getBackend().writeNopData(DistanceToBoundary, OW))
647 report_fatal_error("unable to write NOP sequence of " +
648 Twine(DistanceToBoundary) + " bytes");
649 BundlePadding -= DistanceToBoundary;
651 if (!getBackend().writeNopData(BundlePadding, OW))
652 report_fatal_error("unable to write NOP sequence of " +
653 Twine(BundlePadding) + " bytes");
657 /// \brief Write the fragment \p F to the output file.
658 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
659 const MCFragment &F) {
660 MCObjectWriter *OW = &Asm.getWriter();
662 // FIXME: Embed in fragments instead?
663 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
665 Asm.writeFragmentPadding(F, FragmentSize, OW);
667 // This variable (and its dummy usage) is to participate in the assert at
668 // the end of the function.
669 uint64_t Start = OW->getStream().tell();
672 ++stats::EmittedFragments;
674 switch (F.getKind()) {
675 case MCFragment::FT_Align: {
676 ++stats::EmittedAlignFragments;
677 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
678 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
680 uint64_t Count = FragmentSize / AF.getValueSize();
682 // FIXME: This error shouldn't actually occur (the front end should emit
683 // multiple .align directives to enforce the semantics it wants), but is
684 // severe enough that we want to report it. How to handle this?
685 if (Count * AF.getValueSize() != FragmentSize)
686 report_fatal_error("undefined .align directive, value size '" +
687 Twine(AF.getValueSize()) +
688 "' is not a divisor of padding size '" +
689 Twine(FragmentSize) + "'");
691 // See if we are aligning with nops, and if so do that first to try to fill
692 // the Count bytes. Then if that did not fill any bytes or there are any
693 // bytes left to fill use the Value and ValueSize to fill the rest.
694 // If we are aligning with nops, ask that target to emit the right data.
695 if (AF.hasEmitNops()) {
696 if (!Asm.getBackend().writeNopData(Count, OW))
697 report_fatal_error("unable to write nop sequence of " +
698 Twine(Count) + " bytes");
702 // Otherwise, write out in multiples of the value size.
703 for (uint64_t i = 0; i != Count; ++i) {
704 switch (AF.getValueSize()) {
705 default: llvm_unreachable("Invalid size!");
706 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
707 case 2: OW->Write16(uint16_t(AF.getValue())); break;
708 case 4: OW->Write32(uint32_t(AF.getValue())); break;
709 case 8: OW->Write64(uint64_t(AF.getValue())); break;
715 case MCFragment::FT_Data:
716 ++stats::EmittedDataFragments;
717 writeFragmentContents(F, OW);
720 case MCFragment::FT_Relaxable:
721 ++stats::EmittedRelaxableFragments;
722 writeFragmentContents(F, OW);
725 case MCFragment::FT_CompactEncodedInst:
726 ++stats::EmittedCompactEncodedInstFragments;
727 writeFragmentContents(F, OW);
730 case MCFragment::FT_Fill: {
731 ++stats::EmittedFillFragments;
732 const MCFillFragment &FF = cast<MCFillFragment>(F);
734 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
736 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
737 switch (FF.getValueSize()) {
738 default: llvm_unreachable("Invalid size!");
739 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
740 case 2: OW->Write16(uint16_t(FF.getValue())); break;
741 case 4: OW->Write32(uint32_t(FF.getValue())); break;
742 case 8: OW->Write64(uint64_t(FF.getValue())); break;
748 case MCFragment::FT_LEB: {
749 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
750 OW->WriteBytes(LF.getContents());
754 case MCFragment::FT_Org: {
755 ++stats::EmittedOrgFragments;
756 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
758 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
759 OW->Write8(uint8_t(OF.getValue()));
764 case MCFragment::FT_Dwarf: {
765 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
766 OW->WriteBytes(OF.getContents());
769 case MCFragment::FT_DwarfFrame: {
770 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
771 OW->WriteBytes(CF.getContents());
776 assert(OW->getStream().tell() - Start == FragmentSize &&
777 "The stream should advance by fragment size");
780 void MCAssembler::writeSectionData(const MCSectionData *SD,
781 const MCAsmLayout &Layout) const {
782 // Ignore virtual sections.
783 if (SD->getSection().isVirtualSection()) {
784 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
786 // Check that contents are only things legal inside a virtual section.
787 for (MCSectionData::const_iterator it = SD->begin(),
788 ie = SD->end(); it != ie; ++it) {
789 switch (it->getKind()) {
790 default: llvm_unreachable("Invalid fragment in virtual section!");
791 case MCFragment::FT_Data: {
792 // Check that we aren't trying to write a non-zero contents (or fixups)
793 // into a virtual section. This is to support clients which use standard
794 // directives to fill the contents of virtual sections.
795 const MCDataFragment &DF = cast<MCDataFragment>(*it);
796 assert(DF.fixup_begin() == DF.fixup_end() &&
797 "Cannot have fixups in virtual section!");
798 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
799 if (DF.getContents()[i]) {
800 if (auto *ELFSec = dyn_cast<const MCSectionELF>(&SD->getSection()))
801 report_fatal_error("non-zero initializer found in section '" +
802 ELFSec->getSectionName() + "'");
804 report_fatal_error("non-zero initializer found in virtual section");
808 case MCFragment::FT_Align:
809 // Check that we aren't trying to write a non-zero value into a virtual
811 assert((cast<MCAlignFragment>(it)->getValueSize() == 0 ||
812 cast<MCAlignFragment>(it)->getValue() == 0) &&
813 "Invalid align in virtual section!");
815 case MCFragment::FT_Fill:
816 assert((cast<MCFillFragment>(it)->getValueSize() == 0 ||
817 cast<MCFillFragment>(it)->getValue() == 0) &&
818 "Invalid fill in virtual section!");
826 uint64_t Start = getWriter().getStream().tell();
829 for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
831 writeFragment(*this, Layout, *it);
833 assert(getWriter().getStream().tell() - Start ==
834 Layout.getSectionAddressSize(SD));
837 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
839 const MCFixup &Fixup) {
840 // Evaluate the fixup.
843 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
844 MCFixupKindInfo::FKF_IsPCRel;
845 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
846 // The fixup was unresolved, we need a relocation. Inform the object
847 // writer of the relocation, and give it an opportunity to adjust the
848 // fixup value if need be.
849 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
852 return std::make_pair(FixedValue, IsPCRel);
855 void MCAssembler::Finish() {
856 DEBUG_WITH_TYPE("mc-dump", {
857 llvm::errs() << "assembler backend - pre-layout\n--\n";
860 // Create the layout object.
861 MCAsmLayout Layout(*this);
863 // Create dummy fragments and assign section ordinals.
864 unsigned SectionIndex = 0;
865 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
866 // Create dummy fragments to eliminate any empty sections, this simplifies
868 if (it->getFragmentList().empty())
869 new MCDataFragment(it);
871 it->getSection().setOrdinal(SectionIndex++);
874 // Assign layout order indices to sections and fragments.
875 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
876 MCSectionData *SD = Layout.getSectionOrder()[i];
877 SD->getSection().setLayoutOrder(i);
879 unsigned FragmentIndex = 0;
880 for (MCSectionData::iterator iFrag = SD->begin(), iFragEnd = SD->end();
881 iFrag != iFragEnd; ++iFrag)
882 iFrag->setLayoutOrder(FragmentIndex++);
885 // Layout until everything fits.
886 while (layoutOnce(Layout))
889 DEBUG_WITH_TYPE("mc-dump", {
890 llvm::errs() << "assembler backend - post-relaxation\n--\n";
893 // Finalize the layout, including fragment lowering.
894 finishLayout(Layout);
896 DEBUG_WITH_TYPE("mc-dump", {
897 llvm::errs() << "assembler backend - final-layout\n--\n";
900 uint64_t StartOffset = OS.tell();
902 // Allow the object writer a chance to perform post-layout binding (for
903 // example, to set the index fields in the symbol data).
904 getWriter().ExecutePostLayoutBinding(*this, Layout);
906 // Evaluate and apply the fixups, generating relocation entries as necessary.
907 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
908 for (MCSectionData::iterator it2 = it->begin(),
909 ie2 = it->end(); it2 != ie2; ++it2) {
910 MCEncodedFragmentWithFixups *F =
911 dyn_cast<MCEncodedFragmentWithFixups>(it2);
913 for (MCEncodedFragmentWithFixups::fixup_iterator it3 = F->fixup_begin(),
914 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
915 MCFixup &Fixup = *it3;
918 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
919 getBackend().applyFixup(Fixup, F->getContents().data(),
920 F->getContents().size(), FixedValue, IsPCRel);
926 // Write the object file.
927 getWriter().WriteObject(*this, Layout);
929 stats::ObjectBytes += OS.tell() - StartOffset;
932 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
933 const MCRelaxableFragment *DF,
934 const MCAsmLayout &Layout) const {
935 // If we cannot resolve the fixup value, it requires relaxation.
938 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
941 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
944 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
945 const MCAsmLayout &Layout) const {
946 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
947 // are intentionally pushing out inst fragments, or because we relaxed a
948 // previous instruction to one that doesn't need relaxation.
949 if (!getBackend().mayNeedRelaxation(F->getInst()))
952 for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
953 ie = F->fixup_end(); it != ie; ++it)
954 if (fixupNeedsRelaxation(*it, F, Layout))
960 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
961 MCRelaxableFragment &F) {
962 if (!fragmentNeedsRelaxation(&F, Layout))
965 ++stats::RelaxedInstructions;
967 // FIXME-PERF: We could immediately lower out instructions if we can tell
968 // they are fully resolved, to avoid retesting on later passes.
970 // Relax the fragment.
973 getBackend().relaxInstruction(F.getInst(), Relaxed);
975 // Encode the new instruction.
977 // FIXME-PERF: If it matters, we could let the target do this. It can
978 // probably do so more efficiently in many cases.
979 SmallVector<MCFixup, 4> Fixups;
980 SmallString<256> Code;
981 raw_svector_ostream VecOS(Code);
982 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
985 // Update the fragment.
987 F.getContents() = Code;
988 F.getFixups() = Fixups;
993 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
994 uint64_t OldSize = LF.getContents().size();
996 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
998 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
999 SmallString<8> &Data = LF.getContents();
1001 raw_svector_ostream OSE(Data);
1003 encodeSLEB128(Value, OSE);
1005 encodeULEB128(Value, OSE);
1007 return OldSize != LF.getContents().size();
1010 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1011 MCDwarfLineAddrFragment &DF) {
1012 MCContext &Context = Layout.getAssembler().getContext();
1013 uint64_t OldSize = DF.getContents().size();
1015 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1016 assert(Abs && "We created a line delta with an invalid expression");
1019 LineDelta = DF.getLineDelta();
1020 SmallString<8> &Data = DF.getContents();
1022 raw_svector_ostream OSE(Data);
1023 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OSE);
1025 return OldSize != Data.size();
1028 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1029 MCDwarfCallFrameFragment &DF) {
1030 MCContext &Context = Layout.getAssembler().getContext();
1031 uint64_t OldSize = DF.getContents().size();
1033 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1034 assert(Abs && "We created call frame with an invalid expression");
1036 SmallString<8> &Data = DF.getContents();
1038 raw_svector_ostream OSE(Data);
1039 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
1041 return OldSize != Data.size();
1044 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD) {
1045 // Holds the first fragment which needed relaxing during this layout. It will
1046 // remain NULL if none were relaxed.
1047 // When a fragment is relaxed, all the fragments following it should get
1048 // invalidated because their offset is going to change.
1049 MCFragment *FirstRelaxedFragment = nullptr;
1051 // Attempt to relax all the fragments in the section.
1052 for (MCSectionData::iterator I = SD.begin(), IE = SD.end(); I != IE; ++I) {
1053 // Check if this is a fragment that needs relaxation.
1054 bool RelaxedFrag = false;
1055 switch(I->getKind()) {
1058 case MCFragment::FT_Relaxable:
1059 assert(!getRelaxAll() &&
1060 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1061 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
1063 case MCFragment::FT_Dwarf:
1064 RelaxedFrag = relaxDwarfLineAddr(Layout,
1065 *cast<MCDwarfLineAddrFragment>(I));
1067 case MCFragment::FT_DwarfFrame:
1069 relaxDwarfCallFrameFragment(Layout,
1070 *cast<MCDwarfCallFrameFragment>(I));
1072 case MCFragment::FT_LEB:
1073 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1076 if (RelaxedFrag && !FirstRelaxedFragment)
1077 FirstRelaxedFragment = I;
1079 if (FirstRelaxedFragment) {
1080 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1086 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1087 ++stats::RelaxationSteps;
1089 bool WasRelaxed = false;
1090 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1091 MCSectionData &SD = *it;
1092 while (layoutSectionOnce(Layout, SD))
1099 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1100 // The layout is done. Mark every fragment as valid.
1101 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1102 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1106 // Debugging methods
1110 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1111 OS << "<MCFixup" << " Offset:" << AF.getOffset()
1112 << " Value:" << *AF.getValue()
1113 << " Kind:" << AF.getKind() << ">";
1119 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1120 void MCFragment::dump() {
1121 raw_ostream &OS = llvm::errs();
1124 switch (getKind()) {
1125 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1126 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1127 case MCFragment::FT_CompactEncodedInst:
1128 OS << "MCCompactEncodedInstFragment"; break;
1129 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1130 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1131 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1132 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1133 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1134 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1137 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1138 << " Offset:" << Offset
1139 << " HasInstructions:" << hasInstructions()
1140 << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1142 switch (getKind()) {
1143 case MCFragment::FT_Align: {
1144 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1145 if (AF->hasEmitNops())
1146 OS << " (emit nops)";
1148 OS << " Alignment:" << AF->getAlignment()
1149 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1150 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1153 case MCFragment::FT_Data: {
1154 const MCDataFragment *DF = cast<MCDataFragment>(this);
1156 OS << " Contents:[";
1157 const SmallVectorImpl<char> &Contents = DF->getContents();
1158 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1160 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1162 OS << "] (" << Contents.size() << " bytes)";
1164 if (DF->fixup_begin() != DF->fixup_end()) {
1167 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1168 ie = DF->fixup_end(); it != ie; ++it) {
1169 if (it != DF->fixup_begin()) OS << ",\n ";
1176 case MCFragment::FT_CompactEncodedInst: {
1177 const MCCompactEncodedInstFragment *CEIF =
1178 cast<MCCompactEncodedInstFragment>(this);
1180 OS << " Contents:[";
1181 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1182 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1184 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1186 OS << "] (" << Contents.size() << " bytes)";
1189 case MCFragment::FT_Fill: {
1190 const MCFillFragment *FF = cast<MCFillFragment>(this);
1191 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1192 << " Size:" << FF->getSize();
1195 case MCFragment::FT_Relaxable: {
1196 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1199 F->getInst().dump_pretty(OS);
1202 case MCFragment::FT_Org: {
1203 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1205 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1208 case MCFragment::FT_Dwarf: {
1209 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1211 OS << " AddrDelta:" << OF->getAddrDelta()
1212 << " LineDelta:" << OF->getLineDelta();
1215 case MCFragment::FT_DwarfFrame: {
1216 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1218 OS << " AddrDelta:" << CF->getAddrDelta();
1221 case MCFragment::FT_LEB: {
1222 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1224 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1231 void MCSectionData::dump() {
1232 raw_ostream &OS = llvm::errs();
1234 OS << "<MCSectionData";
1235 OS << " Fragments:[\n ";
1236 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1237 if (it != begin()) OS << ",\n ";
1243 void MCSymbolData::dump() const {
1244 raw_ostream &OS = llvm::errs();
1246 OS << "<MCSymbolData"
1247 << " Fragment:" << getFragment();
1249 OS << " Offset:" << getOffset();
1250 OS << " Flags:" << getFlags();
1252 OS << " (common, size:" << getCommonSize()
1253 << " align: " << getCommonAlignment() << ")";
1255 OS << " (external)";
1256 if (isPrivateExtern())
1257 OS << " (private extern)";
1261 void MCAssembler::dump() {
1262 raw_ostream &OS = llvm::errs();
1264 OS << "<MCAssembler\n";
1265 OS << " Sections:[\n ";
1266 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1267 if (it != begin()) OS << ",\n ";
1273 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1274 if (it != symbol_begin()) OS << ",\n ";
1277 OS << ", Index:" << it->getIndex() << ", ";
1278 it->getData().dump();
1285 // anchors for MC*Fragment vtables
1286 void MCEncodedFragment::anchor() { }
1287 void MCEncodedFragmentWithFixups::anchor() { }
1288 void MCDataFragment::anchor() { }
1289 void MCCompactEncodedInstFragment::anchor() { }
1290 void MCRelaxableFragment::anchor() { }
1291 void MCAlignFragment::anchor() { }
1292 void MCFillFragment::anchor() { }
1293 void MCOrgFragment::anchor() { }
1294 void MCLEBFragment::anchor() { }
1295 void MCDwarfLineAddrFragment::anchor() { }
1296 void MCDwarfCallFrameFragment::anchor() { }