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 (MCSection &Sec : Asm)
72 if (!Sec.isVirtualSection())
73 SectionOrder.push_back(&Sec);
74 for (MCSection &Sec : Asm)
75 if (Sec.isVirtualSection())
76 SectionOrder.push_back(&Sec);
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 MCSection::iterator I;
101 if (MCFragment *Cur = LastValidFragment[Sec])
102 I = ++MCSection::iterator(Cur);
106 // Advance the layout position until the fragment is valid.
107 while (!isFragmentValid(F)) {
108 assert(I != Sec->end() && "Layout bookkeeping error");
109 const_cast<MCAsmLayout *>(this)->layoutFragment(&*I);
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()->evaluateAsValue(Target, Layout))
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 (OffsetInBundle > 0 && EndOfFragment > BundleSize)
258 return BundleSize - OffsetInBundle;
265 void ilist_node_traits<MCFragment>::deleteNode(MCFragment *V) {
269 MCFragment::MCFragment() : Kind(FragmentType(~0)), HasInstructions(false),
270 AlignToBundleEnd(false), BundlePadding(0) {
273 MCFragment::~MCFragment() { }
275 MCFragment::MCFragment(FragmentType Kind, bool HasInstructions,
276 uint8_t BundlePadding, MCSection *Parent)
277 : Kind(Kind), HasInstructions(HasInstructions), AlignToBundleEnd(false),
278 BundlePadding(BundlePadding), Parent(Parent), Atom(nullptr),
279 Offset(~UINT64_C(0)) {
280 if (Parent && !isDummy())
281 Parent->getFragmentList().push_back(this);
284 void MCFragment::destroy() {
285 // First check if we are the sentinal.
286 if (Kind == FragmentType(~0)) {
293 delete cast<MCAlignFragment>(this);
296 delete cast<MCDataFragment>(this);
298 case FT_CompactEncodedInst:
299 delete cast<MCCompactEncodedInstFragment>(this);
302 delete cast<MCFillFragment>(this);
305 delete cast<MCRelaxableFragment>(this);
308 delete cast<MCOrgFragment>(this);
311 delete cast<MCDwarfLineAddrFragment>(this);
314 delete cast<MCDwarfCallFrameFragment>(this);
317 delete cast<MCLEBFragment>(this);
320 delete cast<MCSafeSEHFragment>(this);
323 delete cast<MCDummyFragment>(this);
330 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
331 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_)
332 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
333 BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
335 VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
338 MCAssembler::~MCAssembler() {
341 void MCAssembler::reset() {
344 IndirectSymbols.clear();
346 LinkerOptions.clear();
351 SubsectionsViaSymbols = false;
353 LOHContainer.reset();
354 VersionMinInfo.Major = 0;
356 // reset objects owned by us
357 getBackend().reset();
358 getEmitter().reset();
360 getLOHContainer().reset();
363 bool MCAssembler::registerSection(MCSection &Section) {
364 if (Section.isRegistered())
366 Sections.push_back(&Section);
367 Section.setIsRegistered(true);
371 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
372 if (ThumbFuncs.count(Symbol))
375 if (!Symbol->isVariable())
378 // FIXME: It looks like gas supports some cases of the form "foo + 2". It
379 // is not clear if that is a bug or a feature.
380 const MCExpr *Expr = Symbol->getVariableValue();
381 const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
385 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
388 const MCSymbol &Sym = Ref->getSymbol();
389 if (!isThumbFunc(&Sym))
392 ThumbFuncs.insert(Symbol); // Cache it.
396 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
397 // Non-temporary labels should always be visible to the linker.
398 if (!Symbol.isTemporary())
401 // Absolute temporary labels are never visible.
402 if (!Symbol.isInSection())
405 if (Symbol.isUsedInReloc())
411 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
412 // Linker visible symbols define atoms.
413 if (isSymbolLinkerVisible(S))
416 // Absolute and undefined symbols have no defining atom.
417 if (!S.isInSection())
420 // Non-linker visible symbols in sections which can't be atomized have no
422 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
423 *S.getFragment()->getParent()))
426 // Otherwise, return the atom for the containing fragment.
427 return S.getFragment()->getAtom();
430 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
431 const MCFixup &Fixup, const MCFragment *DF,
432 MCValue &Target, uint64_t &Value) const {
433 ++stats::evaluateFixup;
435 // FIXME: This code has some duplication with recordRelocation. We should
436 // probably merge the two into a single callback that tries to evaluate a
437 // fixup and records a relocation if one is needed.
438 const MCExpr *Expr = Fixup.getValue();
439 if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup))
440 getContext().reportFatalError(Fixup.getLoc(), "expected relocatable expression");
442 bool IsPCRel = Backend.getFixupKindInfo(
443 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
447 if (Target.getSymB()) {
449 } else if (!Target.getSymA()) {
452 const MCSymbolRefExpr *A = Target.getSymA();
453 const MCSymbol &SA = A->getSymbol();
454 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
457 IsResolved = getWriter().isSymbolRefDifferenceFullyResolvedImpl(
458 *this, SA, *DF, false, true);
462 IsResolved = Target.isAbsolute();
465 Value = Target.getConstant();
467 if (const MCSymbolRefExpr *A = Target.getSymA()) {
468 const MCSymbol &Sym = A->getSymbol();
470 Value += Layout.getSymbolOffset(Sym);
472 if (const MCSymbolRefExpr *B = Target.getSymB()) {
473 const MCSymbol &Sym = B->getSymbol();
475 Value -= Layout.getSymbolOffset(Sym);
479 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
480 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
481 assert((ShouldAlignPC ? IsPCRel : true) &&
482 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
485 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
487 // A number of ARM fixups in Thumb mode require that the effective PC
488 // address be determined as the 32-bit aligned version of the actual offset.
489 if (ShouldAlignPC) Offset &= ~0x3;
493 // Let the backend adjust the fixup value if necessary, including whether
494 // we need a relocation.
495 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
501 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
502 const MCFragment &F) const {
503 switch (F.getKind()) {
504 case MCFragment::FT_Data:
505 return cast<MCDataFragment>(F).getContents().size();
506 case MCFragment::FT_Relaxable:
507 return cast<MCRelaxableFragment>(F).getContents().size();
508 case MCFragment::FT_CompactEncodedInst:
509 return cast<MCCompactEncodedInstFragment>(F).getContents().size();
510 case MCFragment::FT_Fill:
511 return cast<MCFillFragment>(F).getSize();
513 case MCFragment::FT_LEB:
514 return cast<MCLEBFragment>(F).getContents().size();
516 case MCFragment::FT_SafeSEH:
519 case MCFragment::FT_Align: {
520 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
521 unsigned Offset = Layout.getFragmentOffset(&AF);
522 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
523 // If we are padding with nops, force the padding to be larger than the
525 if (Size > 0 && AF.hasEmitNops()) {
526 while (Size % getBackend().getMinimumNopSize())
527 Size += AF.getAlignment();
529 if (Size > AF.getMaxBytesToEmit())
534 case MCFragment::FT_Org: {
535 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
537 if (!OF.getOffset().evaluateAsValue(Value, Layout))
538 report_fatal_error("expected assembly-time absolute expression");
540 // FIXME: We need a way to communicate this error.
541 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
542 int64_t TargetLocation = Value.getConstant();
543 if (const MCSymbolRefExpr *A = Value.getSymA()) {
545 if (!Layout.getSymbolOffset(A->getSymbol(), Val))
546 report_fatal_error("expected absolute expression");
547 TargetLocation += Val;
549 int64_t Size = TargetLocation - FragmentOffset;
550 if (Size < 0 || Size >= 0x40000000)
551 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
552 "' (at offset '" + Twine(FragmentOffset) + "')");
556 case MCFragment::FT_Dwarf:
557 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
558 case MCFragment::FT_DwarfFrame:
559 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
560 case MCFragment::FT_Dummy:
561 llvm_unreachable("Should not have been added");
564 llvm_unreachable("invalid fragment kind");
567 void MCAsmLayout::layoutFragment(MCFragment *F) {
568 MCFragment *Prev = F->getPrevNode();
570 // We should never try to recompute something which is valid.
571 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
572 // We should never try to compute the fragment layout if its predecessor
574 assert((!Prev || isFragmentValid(Prev)) &&
575 "Attempt to compute fragment before its predecessor!");
577 ++stats::FragmentLayouts;
579 // Compute fragment offset and size.
581 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
584 LastValidFragment[F->getParent()] = F;
586 // If bundling is enabled and this fragment has instructions in it, it has to
587 // obey the bundling restrictions. With padding, we'll have:
592 // -------------------------------------
593 // Prev |##########| F |
594 // -------------------------------------
599 // The fragment's offset will point to after the padding, and its computed
600 // size won't include the padding.
602 // When the -mc-relax-all flag is used, we optimize bundling by writting the
603 // padding directly into fragments when the instructions are emitted inside
604 // the streamer. When the fragment is larger than the bundle size, we need to
605 // ensure that it's bundle aligned. This means that if we end up with
606 // multiple fragments, we must emit bundle padding between fragments.
608 // ".align N" is an example of a directive that introduces multiple
609 // fragments. We could add a special case to handle ".align N" by emitting
610 // within-fragment padding (which would produce less padding when N is less
611 // than the bundle size), but for now we don't.
613 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
614 assert(isa<MCEncodedFragment>(F) &&
615 "Only MCEncodedFragment implementations have instructions");
616 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
618 if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
619 report_fatal_error("Fragment can't be larger than a bundle size");
621 uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
623 if (RequiredBundlePadding > UINT8_MAX)
624 report_fatal_error("Padding cannot exceed 255 bytes");
625 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
626 F->Offset += RequiredBundlePadding;
630 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
631 bool New = !Symbol.isRegistered();
635 Symbol.setIsRegistered(true);
636 Symbols.push_back(&Symbol);
640 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
641 MCObjectWriter *OW) const {
642 // Should NOP padding be written out before this fragment?
643 unsigned BundlePadding = F.getBundlePadding();
644 if (BundlePadding > 0) {
645 assert(isBundlingEnabled() &&
646 "Writing bundle padding with disabled bundling");
647 assert(F.hasInstructions() &&
648 "Writing bundle padding for a fragment without instructions");
650 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
651 if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
652 // If the padding itself crosses a bundle boundary, it must be emitted
653 // in 2 pieces, since even nop instructions must not cross boundaries.
654 // v--------------v <- BundleAlignSize
655 // v---------v <- BundlePadding
656 // ----------------------------
657 // | Prev |####|####| F |
658 // ----------------------------
659 // ^-------------------^ <- TotalLength
660 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
661 if (!getBackend().writeNopData(DistanceToBoundary, OW))
662 report_fatal_error("unable to write NOP sequence of " +
663 Twine(DistanceToBoundary) + " bytes");
664 BundlePadding -= DistanceToBoundary;
666 if (!getBackend().writeNopData(BundlePadding, OW))
667 report_fatal_error("unable to write NOP sequence of " +
668 Twine(BundlePadding) + " bytes");
672 /// \brief Write the fragment \p F to the output file.
673 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
674 const MCFragment &F) {
675 MCObjectWriter *OW = &Asm.getWriter();
677 // FIXME: Embed in fragments instead?
678 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
680 Asm.writeFragmentPadding(F, FragmentSize, OW);
682 // This variable (and its dummy usage) is to participate in the assert at
683 // the end of the function.
684 uint64_t Start = OW->getStream().tell();
687 ++stats::EmittedFragments;
689 switch (F.getKind()) {
690 case MCFragment::FT_Align: {
691 ++stats::EmittedAlignFragments;
692 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
693 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
695 uint64_t Count = FragmentSize / AF.getValueSize();
697 // FIXME: This error shouldn't actually occur (the front end should emit
698 // multiple .align directives to enforce the semantics it wants), but is
699 // severe enough that we want to report it. How to handle this?
700 if (Count * AF.getValueSize() != FragmentSize)
701 report_fatal_error("undefined .align directive, value size '" +
702 Twine(AF.getValueSize()) +
703 "' is not a divisor of padding size '" +
704 Twine(FragmentSize) + "'");
706 // See if we are aligning with nops, and if so do that first to try to fill
707 // the Count bytes. Then if that did not fill any bytes or there are any
708 // bytes left to fill use the Value and ValueSize to fill the rest.
709 // If we are aligning with nops, ask that target to emit the right data.
710 if (AF.hasEmitNops()) {
711 if (!Asm.getBackend().writeNopData(Count, OW))
712 report_fatal_error("unable to write nop sequence of " +
713 Twine(Count) + " bytes");
717 // Otherwise, write out in multiples of the value size.
718 for (uint64_t i = 0; i != Count; ++i) {
719 switch (AF.getValueSize()) {
720 default: llvm_unreachable("Invalid size!");
721 case 1: OW->write8 (uint8_t (AF.getValue())); break;
722 case 2: OW->write16(uint16_t(AF.getValue())); break;
723 case 4: OW->write32(uint32_t(AF.getValue())); break;
724 case 8: OW->write64(uint64_t(AF.getValue())); break;
730 case MCFragment::FT_Data:
731 ++stats::EmittedDataFragments;
732 OW->writeBytes(cast<MCDataFragment>(F).getContents());
735 case MCFragment::FT_Relaxable:
736 ++stats::EmittedRelaxableFragments;
737 OW->writeBytes(cast<MCRelaxableFragment>(F).getContents());
740 case MCFragment::FT_CompactEncodedInst:
741 ++stats::EmittedCompactEncodedInstFragments;
742 OW->writeBytes(cast<MCCompactEncodedInstFragment>(F).getContents());
745 case MCFragment::FT_Fill: {
746 ++stats::EmittedFillFragments;
747 const MCFillFragment &FF = cast<MCFillFragment>(F);
749 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
751 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
752 switch (FF.getValueSize()) {
753 default: llvm_unreachable("Invalid size!");
754 case 1: OW->write8 (uint8_t (FF.getValue())); break;
755 case 2: OW->write16(uint16_t(FF.getValue())); break;
756 case 4: OW->write32(uint32_t(FF.getValue())); break;
757 case 8: OW->write64(uint64_t(FF.getValue())); break;
763 case MCFragment::FT_LEB: {
764 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
765 OW->writeBytes(LF.getContents());
769 case MCFragment::FT_SafeSEH: {
770 const MCSafeSEHFragment &SF = cast<MCSafeSEHFragment>(F);
771 OW->write32(SF.getSymbol()->getIndex());
775 case MCFragment::FT_Org: {
776 ++stats::EmittedOrgFragments;
777 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
779 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
780 OW->write8(uint8_t(OF.getValue()));
785 case MCFragment::FT_Dwarf: {
786 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
787 OW->writeBytes(OF.getContents());
790 case MCFragment::FT_DwarfFrame: {
791 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
792 OW->writeBytes(CF.getContents());
795 case MCFragment::FT_Dummy:
796 llvm_unreachable("Should not have been added");
799 assert(OW->getStream().tell() - Start == FragmentSize &&
800 "The stream should advance by fragment size");
803 void MCAssembler::writeSectionData(const MCSection *Sec,
804 const MCAsmLayout &Layout) const {
805 // Ignore virtual sections.
806 if (Sec->isVirtualSection()) {
807 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
809 // Check that contents are only things legal inside a virtual section.
810 for (const MCFragment &F : *Sec) {
811 switch (F.getKind()) {
812 default: llvm_unreachable("Invalid fragment in virtual section!");
813 case MCFragment::FT_Data: {
814 // Check that we aren't trying to write a non-zero contents (or fixups)
815 // into a virtual section. This is to support clients which use standard
816 // directives to fill the contents of virtual sections.
817 const MCDataFragment &DF = cast<MCDataFragment>(F);
818 assert(DF.fixup_begin() == DF.fixup_end() &&
819 "Cannot have fixups in virtual section!");
820 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
821 if (DF.getContents()[i]) {
822 if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
823 report_fatal_error("non-zero initializer found in section '" +
824 ELFSec->getSectionName() + "'");
826 report_fatal_error("non-zero initializer found in virtual section");
830 case MCFragment::FT_Align:
831 // Check that we aren't trying to write a non-zero value into a virtual
833 assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
834 cast<MCAlignFragment>(F).getValue() == 0) &&
835 "Invalid align in virtual section!");
837 case MCFragment::FT_Fill:
838 assert((cast<MCFillFragment>(F).getValueSize() == 0 ||
839 cast<MCFillFragment>(F).getValue() == 0) &&
840 "Invalid fill in virtual section!");
848 uint64_t Start = getWriter().getStream().tell();
851 for (const MCFragment &F : *Sec)
852 writeFragment(*this, Layout, F);
854 assert(getWriter().getStream().tell() - Start ==
855 Layout.getSectionAddressSize(Sec));
858 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
860 const MCFixup &Fixup) {
861 // Evaluate the fixup.
864 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
865 MCFixupKindInfo::FKF_IsPCRel;
866 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
867 // The fixup was unresolved, we need a relocation. Inform the object
868 // writer of the relocation, and give it an opportunity to adjust the
869 // fixup value if need be.
870 getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
873 return std::make_pair(FixedValue, IsPCRel);
876 void MCAssembler::layout(MCAsmLayout &Layout) {
877 DEBUG_WITH_TYPE("mc-dump", {
878 llvm::errs() << "assembler backend - pre-layout\n--\n";
881 // Create dummy fragments and assign section ordinals.
882 unsigned SectionIndex = 0;
883 for (MCSection &Sec : *this) {
884 // Create dummy fragments to eliminate any empty sections, this simplifies
886 if (Sec.getFragmentList().empty())
887 new MCDataFragment(&Sec);
889 Sec.setOrdinal(SectionIndex++);
892 // Assign layout order indices to sections and fragments.
893 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
894 MCSection *Sec = Layout.getSectionOrder()[i];
895 Sec->setLayoutOrder(i);
897 unsigned FragmentIndex = 0;
898 for (MCFragment &Frag : *Sec)
899 Frag.setLayoutOrder(FragmentIndex++);
902 // Layout until everything fits.
903 while (layoutOnce(Layout))
906 DEBUG_WITH_TYPE("mc-dump", {
907 llvm::errs() << "assembler backend - post-relaxation\n--\n";
910 // Finalize the layout, including fragment lowering.
911 finishLayout(Layout);
913 DEBUG_WITH_TYPE("mc-dump", {
914 llvm::errs() << "assembler backend - final-layout\n--\n";
917 // Allow the object writer a chance to perform post-layout binding (for
918 // example, to set the index fields in the symbol data).
919 getWriter().executePostLayoutBinding(*this, Layout);
921 // Evaluate and apply the fixups, generating relocation entries as necessary.
922 for (MCSection &Sec : *this) {
923 for (MCFragment &Frag : Sec) {
924 MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(&Frag);
925 // Data and relaxable fragments both have fixups. So only process
927 // FIXME: Is there a better way to do this? MCEncodedFragmentWithFixups
928 // being templated makes this tricky.
929 if (!F || isa<MCCompactEncodedInstFragment>(F))
931 ArrayRef<MCFixup> Fixups;
932 MutableArrayRef<char> Contents;
933 if (auto *FragWithFixups = dyn_cast<MCDataFragment>(F)) {
934 Fixups = FragWithFixups->getFixups();
935 Contents = FragWithFixups->getContents();
936 } else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(F)) {
937 Fixups = FragWithFixups->getFixups();
938 Contents = FragWithFixups->getContents();
940 llvm_unreachable("Unknown fragment with fixups!");
941 for (const MCFixup &Fixup : Fixups) {
944 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
945 getBackend().applyFixup(Fixup, Contents.data(),
946 Contents.size(), FixedValue, IsPCRel);
952 void MCAssembler::Finish() {
953 // Create the layout object.
954 MCAsmLayout Layout(*this);
957 raw_ostream &OS = getWriter().getStream();
958 uint64_t StartOffset = OS.tell();
960 // Write the object file.
961 getWriter().writeObject(*this, Layout);
963 stats::ObjectBytes += OS.tell() - StartOffset;
966 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
967 const MCRelaxableFragment *DF,
968 const MCAsmLayout &Layout) const {
971 bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value);
972 return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
976 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
977 const MCAsmLayout &Layout) const {
978 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
979 // are intentionally pushing out inst fragments, or because we relaxed a
980 // previous instruction to one that doesn't need relaxation.
981 if (!getBackend().mayNeedRelaxation(F->getInst()))
984 for (const MCFixup &Fixup : F->getFixups())
985 if (fixupNeedsRelaxation(Fixup, F, Layout))
991 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
992 MCRelaxableFragment &F) {
993 if (!fragmentNeedsRelaxation(&F, Layout))
996 ++stats::RelaxedInstructions;
998 // FIXME-PERF: We could immediately lower out instructions if we can tell
999 // they are fully resolved, to avoid retesting on later passes.
1001 // Relax the fragment.
1004 getBackend().relaxInstruction(F.getInst(), Relaxed);
1006 // Encode the new instruction.
1008 // FIXME-PERF: If it matters, we could let the target do this. It can
1009 // probably do so more efficiently in many cases.
1010 SmallVector<MCFixup, 4> Fixups;
1011 SmallString<256> Code;
1012 raw_svector_ostream VecOS(Code);
1013 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
1015 // Update the fragment.
1017 F.getContents() = Code;
1018 F.getFixups() = Fixups;
1023 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
1024 uint64_t OldSize = LF.getContents().size();
1026 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
1028 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
1029 SmallString<8> &Data = LF.getContents();
1031 raw_svector_ostream OSE(Data);
1033 encodeSLEB128(Value, OSE);
1035 encodeULEB128(Value, OSE);
1036 return OldSize != LF.getContents().size();
1039 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1040 MCDwarfLineAddrFragment &DF) {
1041 MCContext &Context = Layout.getAssembler().getContext();
1042 uint64_t OldSize = DF.getContents().size();
1044 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1045 assert(Abs && "We created a line delta with an invalid expression");
1048 LineDelta = DF.getLineDelta();
1049 SmallString<8> &Data = DF.getContents();
1051 raw_svector_ostream OSE(Data);
1052 MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
1054 return OldSize != Data.size();
1057 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1058 MCDwarfCallFrameFragment &DF) {
1059 MCContext &Context = Layout.getAssembler().getContext();
1060 uint64_t OldSize = DF.getContents().size();
1062 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1063 assert(Abs && "We created call frame with an invalid expression");
1065 SmallString<8> &Data = DF.getContents();
1067 raw_svector_ostream OSE(Data);
1068 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
1069 return OldSize != Data.size();
1072 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1073 // Holds the first fragment which needed relaxing during this layout. It will
1074 // remain NULL if none were relaxed.
1075 // When a fragment is relaxed, all the fragments following it should get
1076 // invalidated because their offset is going to change.
1077 MCFragment *FirstRelaxedFragment = nullptr;
1079 // Attempt to relax all the fragments in the section.
1080 for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
1081 // Check if this is a fragment that needs relaxation.
1082 bool RelaxedFrag = false;
1083 switch(I->getKind()) {
1086 case MCFragment::FT_Relaxable:
1087 assert(!getRelaxAll() &&
1088 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1089 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
1091 case MCFragment::FT_Dwarf:
1092 RelaxedFrag = relaxDwarfLineAddr(Layout,
1093 *cast<MCDwarfLineAddrFragment>(I));
1095 case MCFragment::FT_DwarfFrame:
1097 relaxDwarfCallFrameFragment(Layout,
1098 *cast<MCDwarfCallFrameFragment>(I));
1100 case MCFragment::FT_LEB:
1101 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1104 if (RelaxedFrag && !FirstRelaxedFragment)
1105 FirstRelaxedFragment = &*I;
1107 if (FirstRelaxedFragment) {
1108 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1114 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1115 ++stats::RelaxationSteps;
1117 bool WasRelaxed = false;
1118 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1119 MCSection &Sec = *it;
1120 while (layoutSectionOnce(Layout, Sec))
1127 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1128 // The layout is done. Mark every fragment as valid.
1129 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1130 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1134 // Debugging methods
1138 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1139 OS << "<MCFixup" << " Offset:" << AF.getOffset()
1140 << " Value:" << *AF.getValue()
1141 << " Kind:" << AF.getKind() << ">";
1147 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1148 void MCFragment::dump() {
1149 raw_ostream &OS = llvm::errs();
1152 switch (getKind()) {
1153 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1154 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1155 case MCFragment::FT_CompactEncodedInst:
1156 OS << "MCCompactEncodedInstFragment"; break;
1157 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1158 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1159 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1160 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1161 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1162 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1163 case MCFragment::FT_SafeSEH: OS << "MCSafeSEHFragment"; break;
1164 case MCFragment::FT_Dummy:
1165 OS << "MCDummyFragment";
1169 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1170 << " Offset:" << Offset
1171 << " HasInstructions:" << hasInstructions()
1172 << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1174 switch (getKind()) {
1175 case MCFragment::FT_Align: {
1176 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1177 if (AF->hasEmitNops())
1178 OS << " (emit nops)";
1180 OS << " Alignment:" << AF->getAlignment()
1181 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1182 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1185 case MCFragment::FT_Data: {
1186 const MCDataFragment *DF = cast<MCDataFragment>(this);
1188 OS << " Contents:[";
1189 const SmallVectorImpl<char> &Contents = DF->getContents();
1190 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1192 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1194 OS << "] (" << Contents.size() << " bytes)";
1196 if (DF->fixup_begin() != DF->fixup_end()) {
1199 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1200 ie = DF->fixup_end(); it != ie; ++it) {
1201 if (it != DF->fixup_begin()) OS << ",\n ";
1208 case MCFragment::FT_CompactEncodedInst: {
1209 const MCCompactEncodedInstFragment *CEIF =
1210 cast<MCCompactEncodedInstFragment>(this);
1212 OS << " Contents:[";
1213 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1214 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1216 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1218 OS << "] (" << Contents.size() << " bytes)";
1221 case MCFragment::FT_Fill: {
1222 const MCFillFragment *FF = cast<MCFillFragment>(this);
1223 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1224 << " Size:" << FF->getSize();
1227 case MCFragment::FT_Relaxable: {
1228 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1231 F->getInst().dump_pretty(OS);
1234 case MCFragment::FT_Org: {
1235 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1237 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1240 case MCFragment::FT_Dwarf: {
1241 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1243 OS << " AddrDelta:" << OF->getAddrDelta()
1244 << " LineDelta:" << OF->getLineDelta();
1247 case MCFragment::FT_DwarfFrame: {
1248 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1250 OS << " AddrDelta:" << CF->getAddrDelta();
1253 case MCFragment::FT_LEB: {
1254 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1256 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1259 case MCFragment::FT_SafeSEH: {
1260 const MCSafeSEHFragment *F = cast<MCSafeSEHFragment>(this);
1262 OS << " Sym:" << F->getSymbol();
1265 case MCFragment::FT_Dummy:
1271 void MCAssembler::dump() {
1272 raw_ostream &OS = llvm::errs();
1274 OS << "<MCAssembler\n";
1275 OS << " Sections:[\n ";
1276 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1277 if (it != begin()) OS << ",\n ";
1283 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1284 if (it != symbol_begin()) OS << ",\n ";
1287 OS << ", Index:" << it->getIndex() << ", ";