1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/MC/MCAssembler.h"
11 #include "llvm/ADT/Statistic.h"
12 #include "llvm/ADT/StringExtras.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCAsmLayout.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCDwarf.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCFixupKindInfo.h"
22 #include "llvm/MC/MCObjectWriter.h"
23 #include "llvm/MC/MCSection.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/LEB128.h"
30 #include "llvm/Support/TargetRegistry.h"
31 #include "llvm/Support/raw_ostream.h"
35 #define DEBUG_TYPE "assembler"
39 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
40 STATISTIC(EmittedRelaxableFragments,
41 "Number of emitted assembler fragments - relaxable");
42 STATISTIC(EmittedDataFragments,
43 "Number of emitted assembler fragments - data");
44 STATISTIC(EmittedCompactEncodedInstFragments,
45 "Number of emitted assembler fragments - compact encoded inst");
46 STATISTIC(EmittedAlignFragments,
47 "Number of emitted assembler fragments - align");
48 STATISTIC(EmittedFillFragments,
49 "Number of emitted assembler fragments - fill");
50 STATISTIC(EmittedOrgFragments,
51 "Number of emitted assembler fragments - org");
52 STATISTIC(evaluateFixup, "Number of evaluated fixups");
53 STATISTIC(FragmentLayouts, "Number of fragment layouts");
54 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
55 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
56 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
60 // FIXME FIXME FIXME: There are number of places in this file where we convert
61 // what is a 64-bit assembler value used for computation into a value in the
62 // object file, which may truncate it. We should detect that truncation where
63 // invalid and report errors back.
67 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
68 : Assembler(Asm), LastValidFragment()
70 // Compute the section layout order. Virtual sections must go last.
71 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
72 if (!it->isVirtualSection())
73 SectionOrder.push_back(&*it);
74 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
75 if (it->isVirtualSection())
76 SectionOrder.push_back(&*it);
79 bool MCAsmLayout::isFragmentValid(const MCFragment *F) const {
80 const MCSection *Sec = F->getParent();
81 const MCFragment *LastValid = LastValidFragment.lookup(Sec);
84 assert(LastValid->getParent() == Sec);
85 return F->getLayoutOrder() <= LastValid->getLayoutOrder();
88 void MCAsmLayout::invalidateFragmentsFrom(MCFragment *F) {
89 // If this fragment wasn't already valid, we don't need to do anything.
90 if (!isFragmentValid(F))
93 // Otherwise, reset the last valid fragment to the previous fragment
94 // (if this is the first fragment, it will be NULL).
95 LastValidFragment[F->getParent()] = F->getPrevNode();
98 void MCAsmLayout::ensureValid(const MCFragment *F) const {
99 MCSection *Sec = F->getParent();
100 MCFragment *Cur = LastValidFragment[Sec];
104 Cur = Cur->getNextNode();
106 // Advance the layout position until the fragment is valid.
107 while (!isFragmentValid(F)) {
108 assert(Cur && "Layout bookkeeping error");
109 const_cast<MCAsmLayout*>(this)->layoutFragment(Cur);
110 Cur = Cur->getNextNode();
114 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
116 assert(F->Offset != ~UINT64_C(0) && "Address not set!");
120 // Simple getSymbolOffset helper for the non-varibale case.
121 static bool getLabelOffset(const MCAsmLayout &Layout, const MCSymbol &S,
122 bool ReportError, uint64_t &Val) {
123 if (!S.getFragment()) {
125 report_fatal_error("unable to evaluate offset to undefined symbol '" +
129 Val = Layout.getFragmentOffset(S.getFragment()) + S.getOffset();
133 static bool getSymbolOffsetImpl(const MCAsmLayout &Layout, const MCSymbol &S,
134 bool ReportError, uint64_t &Val) {
136 return getLabelOffset(Layout, S, ReportError, Val);
138 // If SD is a variable, evaluate it.
140 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, &Layout, nullptr))
141 report_fatal_error("unable to evaluate offset for variable '" +
144 uint64_t Offset = Target.getConstant();
146 const MCSymbolRefExpr *A = Target.getSymA();
149 if (!getLabelOffset(Layout, A->getSymbol(), ReportError, ValA))
154 const MCSymbolRefExpr *B = Target.getSymB();
157 if (!getLabelOffset(Layout, B->getSymbol(), ReportError, ValB))
166 bool MCAsmLayout::getSymbolOffset(const MCSymbol &S, uint64_t &Val) const {
167 return getSymbolOffsetImpl(*this, S, false, Val);
170 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbol &S) const {
172 getSymbolOffsetImpl(*this, S, true, Val);
176 const MCSymbol *MCAsmLayout::getBaseSymbol(const MCSymbol &Symbol) const {
177 if (!Symbol.isVariable())
180 const MCExpr *Expr = Symbol.getVariableValue();
182 if (!Expr->evaluateAsValue(Value, *this))
183 llvm_unreachable("Invalid Expression");
185 const MCSymbolRefExpr *RefB = Value.getSymB();
187 Assembler.getContext().reportFatalError(
188 SMLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
189 "' could not be evaluated in a subtraction expression");
191 const MCSymbolRefExpr *A = Value.getSymA();
195 const MCSymbol &ASym = A->getSymbol();
196 const MCAssembler &Asm = getAssembler();
197 if (ASym.isCommon()) {
198 // FIXME: we should probably add a SMLoc to MCExpr.
199 Asm.getContext().reportFatalError(SMLoc(),
200 "Common symbol " + ASym.getName() +
201 " cannot be used in assignment expr");
207 uint64_t MCAsmLayout::getSectionAddressSize(const MCSection *Sec) const {
208 // The size is the last fragment's end offset.
209 const MCFragment &F = Sec->getFragmentList().back();
210 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
213 uint64_t MCAsmLayout::getSectionFileSize(const MCSection *Sec) const {
214 // Virtual sections have no file size.
215 if (Sec->isVirtualSection())
218 // Otherwise, the file size is the same as the address space size.
219 return getSectionAddressSize(Sec);
222 uint64_t llvm::computeBundlePadding(const MCAssembler &Assembler,
224 uint64_t FOffset, uint64_t FSize) {
225 uint64_t BundleSize = Assembler.getBundleAlignSize();
226 assert(BundleSize > 0 &&
227 "computeBundlePadding should only be called if bundling is enabled");
228 uint64_t BundleMask = BundleSize - 1;
229 uint64_t OffsetInBundle = FOffset & BundleMask;
230 uint64_t EndOfFragment = OffsetInBundle + FSize;
232 // There are two kinds of bundling restrictions:
234 // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
235 // *end* on a bundle boundary.
236 // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
237 // would, add padding until the end of the bundle so that the fragment
238 // will start in a new one.
239 if (F->alignToBundleEnd()) {
240 // Three possibilities here:
242 // A) The fragment just happens to end at a bundle boundary, so we're good.
243 // B) The fragment ends before the current bundle boundary: pad it just
244 // enough to reach the boundary.
245 // C) The fragment ends after the current bundle boundary: pad it until it
246 // reaches the end of the next bundle boundary.
248 // Note: this code could be made shorter with some modulo trickery, but it's
249 // intentionally kept in its more explicit form for simplicity.
250 if (EndOfFragment == BundleSize)
252 else if (EndOfFragment < BundleSize)
253 return BundleSize - EndOfFragment;
254 else { // EndOfFragment > BundleSize
255 return 2 * BundleSize - EndOfFragment;
257 } else if (EndOfFragment > BundleSize)
258 return BundleSize - OffsetInBundle;
265 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
268 MCFragment::~MCFragment() {
271 MCFragment::MCFragment(FragmentType Kind, MCSection *Parent)
272 : Kind(Kind), Parent(Parent), Atom(nullptr), Offset(~UINT64_C(0)) {
274 Parent->getFragmentList().push_back(this);
279 MCEncodedFragment::~MCEncodedFragment() {
284 MCEncodedFragmentWithFixups::~MCEncodedFragmentWithFixups() {
289 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
290 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
292 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
293 OS(OS_), BundleAlignSize(0), RelaxAll(false),
294 SubsectionsViaSymbols(false), ELFHeaderEFlags(0) {
295 VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
298 MCAssembler::~MCAssembler() {
301 void MCAssembler::reset() {
304 IndirectSymbols.clear();
306 LinkerOptions.clear();
311 SubsectionsViaSymbols = false;
313 LOHContainer.reset();
314 VersionMinInfo.Major = 0;
316 // reset objects owned by us
317 getBackend().reset();
318 getEmitter().reset();
320 getLOHContainer().reset();
323 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
324 if (ThumbFuncs.count(Symbol))
327 if (!Symbol->isVariable())
330 // FIXME: It looks like gas supports some cases of the form "foo + 2". It
331 // is not clear if that is a bug or a feature.
332 const MCExpr *Expr = Symbol->getVariableValue();
333 const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
337 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
340 const MCSymbol &Sym = Ref->getSymbol();
341 if (!isThumbFunc(&Sym))
344 ThumbFuncs.insert(Symbol); // Cache it.
348 void MCAssembler::addLocalUsedInReloc(const MCSymbol &Sym) {
349 assert(Sym.isTemporary());
350 LocalsUsedInReloc.insert(&Sym);
353 bool MCAssembler::isLocalUsedInReloc(const MCSymbol &Sym) const {
354 assert(Sym.isTemporary());
355 return LocalsUsedInReloc.count(&Sym);
358 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
359 // Non-temporary labels should always be visible to the linker.
360 if (!Symbol.isTemporary())
363 // Absolute temporary labels are never visible.
364 if (!Symbol.isInSection())
367 if (isLocalUsedInReloc(Symbol))
373 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
374 // Linker visible symbols define atoms.
375 if (isSymbolLinkerVisible(S))
378 // Absolute and undefined symbols have no defining atom.
379 if (!S.getFragment())
382 // Non-linker visible symbols in sections which can't be atomized have no
384 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
385 *S.getFragment()->getParent()))
388 // Otherwise, return the atom for the containing fragment.
389 return S.getFragment()->getAtom();
392 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
393 const MCFixup &Fixup, const MCFragment *DF,
394 MCValue &Target, uint64_t &Value) const {
395 ++stats::evaluateFixup;
397 // FIXME: This code has some duplication with RecordRelocation. We should
398 // probably merge the two into a single callback that tries to evaluate a
399 // fixup and records a relocation if one is needed.
400 const MCExpr *Expr = Fixup.getValue();
401 if (!Expr->EvaluateAsRelocatable(Target, &Layout, &Fixup))
402 getContext().reportFatalError(Fixup.getLoc(), "expected relocatable expression");
404 bool IsPCRel = Backend.getFixupKindInfo(
405 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
409 if (Target.getSymB()) {
411 } else if (!Target.getSymA()) {
414 const MCSymbolRefExpr *A = Target.getSymA();
415 const MCSymbol &SA = A->getSymbol();
416 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
419 IsResolved = getWriter().IsSymbolRefDifferenceFullyResolvedImpl(
420 *this, SA, *DF, false, true);
424 IsResolved = Target.isAbsolute();
427 Value = Target.getConstant();
429 if (const MCSymbolRefExpr *A = Target.getSymA()) {
430 const MCSymbol &Sym = A->getSymbol();
432 Value += Layout.getSymbolOffset(Sym);
434 if (const MCSymbolRefExpr *B = Target.getSymB()) {
435 const MCSymbol &Sym = B->getSymbol();
437 Value -= Layout.getSymbolOffset(Sym);
441 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
442 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
443 assert((ShouldAlignPC ? IsPCRel : true) &&
444 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
447 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
449 // A number of ARM fixups in Thumb mode require that the effective PC
450 // address be determined as the 32-bit aligned version of the actual offset.
451 if (ShouldAlignPC) Offset &= ~0x3;
455 // Let the backend adjust the fixup value if necessary, including whether
456 // we need a relocation.
457 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
463 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
464 const MCFragment &F) const {
465 switch (F.getKind()) {
466 case MCFragment::FT_Data:
467 case MCFragment::FT_Relaxable:
468 case MCFragment::FT_CompactEncodedInst:
469 return cast<MCEncodedFragment>(F).getContents().size();
470 case MCFragment::FT_Fill:
471 return cast<MCFillFragment>(F).getSize();
473 case MCFragment::FT_LEB:
474 return cast<MCLEBFragment>(F).getContents().size();
476 case MCFragment::FT_Align: {
477 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
478 unsigned Offset = Layout.getFragmentOffset(&AF);
479 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
480 // If we are padding with nops, force the padding to be larger than the
482 if (Size > 0 && AF.hasEmitNops()) {
483 while (Size % getBackend().getMinimumNopSize())
484 Size += AF.getAlignment();
486 if (Size > AF.getMaxBytesToEmit())
491 case MCFragment::FT_Org: {
492 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
493 int64_t TargetLocation;
494 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
495 report_fatal_error("expected assembly-time absolute expression");
497 // FIXME: We need a way to communicate this error.
498 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
499 int64_t Size = TargetLocation - FragmentOffset;
500 if (Size < 0 || Size >= 0x40000000)
501 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
502 "' (at offset '" + Twine(FragmentOffset) + "')");
506 case MCFragment::FT_Dwarf:
507 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
508 case MCFragment::FT_DwarfFrame:
509 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
512 llvm_unreachable("invalid fragment kind");
515 void MCAsmLayout::layoutFragment(MCFragment *F) {
516 MCFragment *Prev = F->getPrevNode();
518 // We should never try to recompute something which is valid.
519 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
520 // We should never try to compute the fragment layout if its predecessor
522 assert((!Prev || isFragmentValid(Prev)) &&
523 "Attempt to compute fragment before its predecessor!");
525 ++stats::FragmentLayouts;
527 // Compute fragment offset and size.
529 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
532 LastValidFragment[F->getParent()] = F;
534 // If bundling is enabled and this fragment has instructions in it, it has to
535 // obey the bundling restrictions. With padding, we'll have:
540 // -------------------------------------
541 // Prev |##########| F |
542 // -------------------------------------
547 // The fragment's offset will point to after the padding, and its computed
548 // size won't include the padding.
550 // When the -mc-relax-all flag is used, we optimize bundling by writting the
551 // bundle padding directly into fragments when the instructions are emitted
552 // inside the streamer.
554 if (Assembler.isBundlingEnabled() && !Assembler.getRelaxAll() &&
555 F->hasInstructions()) {
556 assert(isa<MCEncodedFragment>(F) &&
557 "Only MCEncodedFragment implementations have instructions");
558 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
560 if (FSize > Assembler.getBundleAlignSize())
561 report_fatal_error("Fragment can't be larger than a bundle size");
563 uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
565 if (RequiredBundlePadding > UINT8_MAX)
566 report_fatal_error("Padding cannot exceed 255 bytes");
567 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
568 F->Offset += RequiredBundlePadding;
572 /// \brief Write the contents of a fragment to the given object writer. Expects
573 /// a MCEncodedFragment.
574 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
575 const MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
576 OW->WriteBytes(EF.getContents());
579 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
580 MCObjectWriter *OW) const {
581 // Should NOP padding be written out before this fragment?
582 unsigned BundlePadding = F.getBundlePadding();
583 if (BundlePadding > 0) {
584 assert(isBundlingEnabled() &&
585 "Writing bundle padding with disabled bundling");
586 assert(F.hasInstructions() &&
587 "Writing bundle padding for a fragment without instructions");
589 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
590 if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
591 // If the padding itself crosses a bundle boundary, it must be emitted
592 // in 2 pieces, since even nop instructions must not cross boundaries.
593 // v--------------v <- BundleAlignSize
594 // v---------v <- BundlePadding
595 // ----------------------------
596 // | Prev |####|####| F |
597 // ----------------------------
598 // ^-------------------^ <- TotalLength
599 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
600 if (!getBackend().writeNopData(DistanceToBoundary, OW))
601 report_fatal_error("unable to write NOP sequence of " +
602 Twine(DistanceToBoundary) + " bytes");
603 BundlePadding -= DistanceToBoundary;
605 if (!getBackend().writeNopData(BundlePadding, OW))
606 report_fatal_error("unable to write NOP sequence of " +
607 Twine(BundlePadding) + " bytes");
611 /// \brief Write the fragment \p F to the output file.
612 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
613 const MCFragment &F) {
614 MCObjectWriter *OW = &Asm.getWriter();
616 // FIXME: Embed in fragments instead?
617 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
619 Asm.writeFragmentPadding(F, FragmentSize, OW);
621 // This variable (and its dummy usage) is to participate in the assert at
622 // the end of the function.
623 uint64_t Start = OW->getStream().tell();
626 ++stats::EmittedFragments;
628 switch (F.getKind()) {
629 case MCFragment::FT_Align: {
630 ++stats::EmittedAlignFragments;
631 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
632 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
634 uint64_t Count = FragmentSize / AF.getValueSize();
636 // FIXME: This error shouldn't actually occur (the front end should emit
637 // multiple .align directives to enforce the semantics it wants), but is
638 // severe enough that we want to report it. How to handle this?
639 if (Count * AF.getValueSize() != FragmentSize)
640 report_fatal_error("undefined .align directive, value size '" +
641 Twine(AF.getValueSize()) +
642 "' is not a divisor of padding size '" +
643 Twine(FragmentSize) + "'");
645 // See if we are aligning with nops, and if so do that first to try to fill
646 // the Count bytes. Then if that did not fill any bytes or there are any
647 // bytes left to fill use the Value and ValueSize to fill the rest.
648 // If we are aligning with nops, ask that target to emit the right data.
649 if (AF.hasEmitNops()) {
650 if (!Asm.getBackend().writeNopData(Count, OW))
651 report_fatal_error("unable to write nop sequence of " +
652 Twine(Count) + " bytes");
656 // Otherwise, write out in multiples of the value size.
657 for (uint64_t i = 0; i != Count; ++i) {
658 switch (AF.getValueSize()) {
659 default: llvm_unreachable("Invalid size!");
660 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
661 case 2: OW->Write16(uint16_t(AF.getValue())); break;
662 case 4: OW->Write32(uint32_t(AF.getValue())); break;
663 case 8: OW->Write64(uint64_t(AF.getValue())); break;
669 case MCFragment::FT_Data:
670 ++stats::EmittedDataFragments;
671 writeFragmentContents(F, OW);
674 case MCFragment::FT_Relaxable:
675 ++stats::EmittedRelaxableFragments;
676 writeFragmentContents(F, OW);
679 case MCFragment::FT_CompactEncodedInst:
680 ++stats::EmittedCompactEncodedInstFragments;
681 writeFragmentContents(F, OW);
684 case MCFragment::FT_Fill: {
685 ++stats::EmittedFillFragments;
686 const MCFillFragment &FF = cast<MCFillFragment>(F);
688 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
690 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
691 switch (FF.getValueSize()) {
692 default: llvm_unreachable("Invalid size!");
693 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
694 case 2: OW->Write16(uint16_t(FF.getValue())); break;
695 case 4: OW->Write32(uint32_t(FF.getValue())); break;
696 case 8: OW->Write64(uint64_t(FF.getValue())); break;
702 case MCFragment::FT_LEB: {
703 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
704 OW->WriteBytes(LF.getContents());
708 case MCFragment::FT_Org: {
709 ++stats::EmittedOrgFragments;
710 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
712 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
713 OW->Write8(uint8_t(OF.getValue()));
718 case MCFragment::FT_Dwarf: {
719 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
720 OW->WriteBytes(OF.getContents());
723 case MCFragment::FT_DwarfFrame: {
724 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
725 OW->WriteBytes(CF.getContents());
730 assert(OW->getStream().tell() - Start == FragmentSize &&
731 "The stream should advance by fragment size");
734 void MCAssembler::writeSectionData(const MCSection *Sec,
735 const MCAsmLayout &Layout) const {
736 // Ignore virtual sections.
737 if (Sec->isVirtualSection()) {
738 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
740 // Check that contents are only things legal inside a virtual section.
741 for (MCSection::const_iterator it = Sec->begin(), ie = Sec->end(); it != ie;
743 switch (it->getKind()) {
744 default: llvm_unreachable("Invalid fragment in virtual section!");
745 case MCFragment::FT_Data: {
746 // Check that we aren't trying to write a non-zero contents (or fixups)
747 // into a virtual section. This is to support clients which use standard
748 // directives to fill the contents of virtual sections.
749 const MCDataFragment &DF = cast<MCDataFragment>(*it);
750 assert(DF.fixup_begin() == DF.fixup_end() &&
751 "Cannot have fixups in virtual section!");
752 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
753 if (DF.getContents()[i]) {
754 if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
755 report_fatal_error("non-zero initializer found in section '" +
756 ELFSec->getSectionName() + "'");
758 report_fatal_error("non-zero initializer found in virtual section");
762 case MCFragment::FT_Align:
763 // Check that we aren't trying to write a non-zero value into a virtual
765 assert((cast<MCAlignFragment>(it)->getValueSize() == 0 ||
766 cast<MCAlignFragment>(it)->getValue() == 0) &&
767 "Invalid align in virtual section!");
769 case MCFragment::FT_Fill:
770 assert((cast<MCFillFragment>(it)->getValueSize() == 0 ||
771 cast<MCFillFragment>(it)->getValue() == 0) &&
772 "Invalid fill in virtual section!");
780 uint64_t Start = getWriter().getStream().tell();
783 for (MCSection::const_iterator it = Sec->begin(), ie = Sec->end(); it != ie;
785 writeFragment(*this, Layout, *it);
787 assert(getWriter().getStream().tell() - Start ==
788 Layout.getSectionAddressSize(Sec));
791 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
793 const MCFixup &Fixup) {
794 // Evaluate the fixup.
797 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
798 MCFixupKindInfo::FKF_IsPCRel;
799 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
800 // The fixup was unresolved, we need a relocation. Inform the object
801 // writer of the relocation, and give it an opportunity to adjust the
802 // fixup value if need be.
803 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
806 return std::make_pair(FixedValue, IsPCRel);
809 void MCAssembler::Finish() {
810 DEBUG_WITH_TYPE("mc-dump", {
811 llvm::errs() << "assembler backend - pre-layout\n--\n";
814 // Create the layout object.
815 MCAsmLayout Layout(*this);
817 // Create dummy fragments and assign section ordinals.
818 unsigned SectionIndex = 0;
819 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
820 // Create dummy fragments to eliminate any empty sections, this simplifies
822 if (it->getFragmentList().empty())
823 new MCDataFragment(&*it);
825 it->setOrdinal(SectionIndex++);
828 // Assign layout order indices to sections and fragments.
829 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
830 MCSection *Sec = Layout.getSectionOrder()[i];
831 Sec->setLayoutOrder(i);
833 unsigned FragmentIndex = 0;
834 for (MCSection::iterator iFrag = Sec->begin(), iFragEnd = Sec->end();
835 iFrag != iFragEnd; ++iFrag)
836 iFrag->setLayoutOrder(FragmentIndex++);
839 // Layout until everything fits.
840 while (layoutOnce(Layout))
843 DEBUG_WITH_TYPE("mc-dump", {
844 llvm::errs() << "assembler backend - post-relaxation\n--\n";
847 // Finalize the layout, including fragment lowering.
848 finishLayout(Layout);
850 DEBUG_WITH_TYPE("mc-dump", {
851 llvm::errs() << "assembler backend - final-layout\n--\n";
854 uint64_t StartOffset = OS.tell();
856 // Allow the object writer a chance to perform post-layout binding (for
857 // example, to set the index fields in the symbol data).
858 getWriter().ExecutePostLayoutBinding(*this, Layout);
860 // Evaluate and apply the fixups, generating relocation entries as necessary.
861 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
862 for (MCSection::iterator it2 = it->begin(), ie2 = it->end(); it2 != ie2;
864 MCEncodedFragmentWithFixups *F =
865 dyn_cast<MCEncodedFragmentWithFixups>(it2);
867 for (MCEncodedFragmentWithFixups::fixup_iterator it3 = F->fixup_begin(),
868 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
869 MCFixup &Fixup = *it3;
872 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
873 getBackend().applyFixup(Fixup, F->getContents().data(),
874 F->getContents().size(), FixedValue, IsPCRel);
880 // Write the object file.
881 getWriter().WriteObject(*this, Layout);
883 stats::ObjectBytes += OS.tell() - StartOffset;
886 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
887 const MCRelaxableFragment *DF,
888 const MCAsmLayout &Layout) const {
889 // If we cannot resolve the fixup value, it requires relaxation.
892 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
895 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
898 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
899 const MCAsmLayout &Layout) const {
900 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
901 // are intentionally pushing out inst fragments, or because we relaxed a
902 // previous instruction to one that doesn't need relaxation.
903 if (!getBackend().mayNeedRelaxation(F->getInst()))
906 for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
907 ie = F->fixup_end(); it != ie; ++it)
908 if (fixupNeedsRelaxation(*it, F, Layout))
914 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
915 MCRelaxableFragment &F) {
916 if (!fragmentNeedsRelaxation(&F, Layout))
919 ++stats::RelaxedInstructions;
921 // FIXME-PERF: We could immediately lower out instructions if we can tell
922 // they are fully resolved, to avoid retesting on later passes.
924 // Relax the fragment.
927 getBackend().relaxInstruction(F.getInst(), Relaxed);
929 // Encode the new instruction.
931 // FIXME-PERF: If it matters, we could let the target do this. It can
932 // probably do so more efficiently in many cases.
933 SmallVector<MCFixup, 4> Fixups;
934 SmallString<256> Code;
935 raw_svector_ostream VecOS(Code);
936 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
939 // Update the fragment.
941 F.getContents() = Code;
942 F.getFixups() = Fixups;
947 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
948 uint64_t OldSize = LF.getContents().size();
950 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
952 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
953 SmallString<8> &Data = LF.getContents();
955 raw_svector_ostream OSE(Data);
957 encodeSLEB128(Value, OSE);
959 encodeULEB128(Value, OSE);
961 return OldSize != LF.getContents().size();
964 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
965 MCDwarfLineAddrFragment &DF) {
966 MCContext &Context = Layout.getAssembler().getContext();
967 uint64_t OldSize = DF.getContents().size();
969 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
970 assert(Abs && "We created a line delta with an invalid expression");
973 LineDelta = DF.getLineDelta();
974 SmallString<8> &Data = DF.getContents();
976 raw_svector_ostream OSE(Data);
977 MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OSE);
979 return OldSize != Data.size();
982 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
983 MCDwarfCallFrameFragment &DF) {
984 MCContext &Context = Layout.getAssembler().getContext();
985 uint64_t OldSize = DF.getContents().size();
987 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
988 assert(Abs && "We created call frame with an invalid expression");
990 SmallString<8> &Data = DF.getContents();
992 raw_svector_ostream OSE(Data);
993 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
995 return OldSize != Data.size();
998 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
999 // Holds the first fragment which needed relaxing during this layout. It will
1000 // remain NULL if none were relaxed.
1001 // When a fragment is relaxed, all the fragments following it should get
1002 // invalidated because their offset is going to change.
1003 MCFragment *FirstRelaxedFragment = nullptr;
1005 // Attempt to relax all the fragments in the section.
1006 for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
1007 // Check if this is a fragment that needs relaxation.
1008 bool RelaxedFrag = false;
1009 switch(I->getKind()) {
1012 case MCFragment::FT_Relaxable:
1013 assert(!getRelaxAll() &&
1014 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1015 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
1017 case MCFragment::FT_Dwarf:
1018 RelaxedFrag = relaxDwarfLineAddr(Layout,
1019 *cast<MCDwarfLineAddrFragment>(I));
1021 case MCFragment::FT_DwarfFrame:
1023 relaxDwarfCallFrameFragment(Layout,
1024 *cast<MCDwarfCallFrameFragment>(I));
1026 case MCFragment::FT_LEB:
1027 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1030 if (RelaxedFrag && !FirstRelaxedFragment)
1031 FirstRelaxedFragment = I;
1033 if (FirstRelaxedFragment) {
1034 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1040 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1041 ++stats::RelaxationSteps;
1043 bool WasRelaxed = false;
1044 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1045 MCSection &Sec = *it;
1046 while (layoutSectionOnce(Layout, Sec))
1053 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1054 // The layout is done. Mark every fragment as valid.
1055 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1056 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1060 // Debugging methods
1064 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1065 OS << "<MCFixup" << " Offset:" << AF.getOffset()
1066 << " Value:" << *AF.getValue()
1067 << " Kind:" << AF.getKind() << ">";
1073 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1074 void MCFragment::dump() {
1075 raw_ostream &OS = llvm::errs();
1078 switch (getKind()) {
1079 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1080 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1081 case MCFragment::FT_CompactEncodedInst:
1082 OS << "MCCompactEncodedInstFragment"; break;
1083 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1084 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1085 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1086 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1087 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1088 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1091 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1092 << " Offset:" << Offset
1093 << " HasInstructions:" << hasInstructions()
1094 << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1096 switch (getKind()) {
1097 case MCFragment::FT_Align: {
1098 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1099 if (AF->hasEmitNops())
1100 OS << " (emit nops)";
1102 OS << " Alignment:" << AF->getAlignment()
1103 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1104 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1107 case MCFragment::FT_Data: {
1108 const MCDataFragment *DF = cast<MCDataFragment>(this);
1110 OS << " Contents:[";
1111 const SmallVectorImpl<char> &Contents = DF->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)";
1118 if (DF->fixup_begin() != DF->fixup_end()) {
1121 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1122 ie = DF->fixup_end(); it != ie; ++it) {
1123 if (it != DF->fixup_begin()) OS << ",\n ";
1130 case MCFragment::FT_CompactEncodedInst: {
1131 const MCCompactEncodedInstFragment *CEIF =
1132 cast<MCCompactEncodedInstFragment>(this);
1134 OS << " Contents:[";
1135 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1136 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1138 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1140 OS << "] (" << Contents.size() << " bytes)";
1143 case MCFragment::FT_Fill: {
1144 const MCFillFragment *FF = cast<MCFillFragment>(this);
1145 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1146 << " Size:" << FF->getSize();
1149 case MCFragment::FT_Relaxable: {
1150 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1153 F->getInst().dump_pretty(OS);
1156 case MCFragment::FT_Org: {
1157 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1159 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1162 case MCFragment::FT_Dwarf: {
1163 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1165 OS << " AddrDelta:" << OF->getAddrDelta()
1166 << " LineDelta:" << OF->getLineDelta();
1169 case MCFragment::FT_DwarfFrame: {
1170 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1172 OS << " AddrDelta:" << CF->getAddrDelta();
1175 case MCFragment::FT_LEB: {
1176 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1178 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1185 void MCAssembler::dump() {
1186 raw_ostream &OS = llvm::errs();
1188 OS << "<MCAssembler\n";
1189 OS << " Sections:[\n ";
1190 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1191 if (it != begin()) OS << ",\n ";
1197 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1198 if (it != symbol_begin()) OS << ",\n ";
1201 OS << ", Index:" << it->getIndex() << ", ";
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() { }