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 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()->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)) {
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);
327 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
328 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_)
329 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
330 BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
332 VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
335 MCAssembler::~MCAssembler() {
338 void MCAssembler::reset() {
341 IndirectSymbols.clear();
343 LinkerOptions.clear();
348 SubsectionsViaSymbols = false;
350 LOHContainer.reset();
351 VersionMinInfo.Major = 0;
353 // reset objects owned by us
354 getBackend().reset();
355 getEmitter().reset();
357 getLOHContainer().reset();
360 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
361 if (ThumbFuncs.count(Symbol))
364 if (!Symbol->isVariable())
367 // FIXME: It looks like gas supports some cases of the form "foo + 2". It
368 // is not clear if that is a bug or a feature.
369 const MCExpr *Expr = Symbol->getVariableValue();
370 const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
374 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
377 const MCSymbol &Sym = Ref->getSymbol();
378 if (!isThumbFunc(&Sym))
381 ThumbFuncs.insert(Symbol); // Cache it.
385 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
386 // Non-temporary labels should always be visible to the linker.
387 if (!Symbol.isTemporary())
390 // Absolute temporary labels are never visible.
391 if (!Symbol.isInSection())
394 if (Symbol.isUsedInReloc())
400 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
401 // Linker visible symbols define atoms.
402 if (isSymbolLinkerVisible(S))
405 // Absolute and undefined symbols have no defining atom.
406 if (!S.getFragment())
409 // Non-linker visible symbols in sections which can't be atomized have no
411 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
412 *S.getFragment()->getParent()))
415 // Otherwise, return the atom for the containing fragment.
416 return S.getFragment()->getAtom();
419 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
420 const MCFixup &Fixup, const MCFragment *DF,
421 MCValue &Target, uint64_t &Value) const {
422 ++stats::evaluateFixup;
424 // FIXME: This code has some duplication with recordRelocation. We should
425 // probably merge the two into a single callback that tries to evaluate a
426 // fixup and records a relocation if one is needed.
427 const MCExpr *Expr = Fixup.getValue();
428 if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup))
429 getContext().reportFatalError(Fixup.getLoc(), "expected relocatable expression");
431 bool IsPCRel = Backend.getFixupKindInfo(
432 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
436 if (Target.getSymB()) {
438 } else if (!Target.getSymA()) {
441 const MCSymbolRefExpr *A = Target.getSymA();
442 const MCSymbol &SA = A->getSymbol();
443 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
446 IsResolved = getWriter().isSymbolRefDifferenceFullyResolvedImpl(
447 *this, SA, *DF, false, true);
451 IsResolved = Target.isAbsolute();
454 Value = Target.getConstant();
456 if (const MCSymbolRefExpr *A = Target.getSymA()) {
457 const MCSymbol &Sym = A->getSymbol();
459 Value += Layout.getSymbolOffset(Sym);
461 if (const MCSymbolRefExpr *B = Target.getSymB()) {
462 const MCSymbol &Sym = B->getSymbol();
464 Value -= Layout.getSymbolOffset(Sym);
468 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
469 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
470 assert((ShouldAlignPC ? IsPCRel : true) &&
471 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
474 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
476 // A number of ARM fixups in Thumb mode require that the effective PC
477 // address be determined as the 32-bit aligned version of the actual offset.
478 if (ShouldAlignPC) Offset &= ~0x3;
482 // Let the backend adjust the fixup value if necessary, including whether
483 // we need a relocation.
484 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
490 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
491 const MCFragment &F) const {
492 switch (F.getKind()) {
493 case MCFragment::FT_Data:
494 return cast<MCDataFragment>(F).getContents().size();
495 case MCFragment::FT_Relaxable:
496 return cast<MCRelaxableFragment>(F).getContents().size();
497 case MCFragment::FT_CompactEncodedInst:
498 return cast<MCCompactEncodedInstFragment>(F).getContents().size();
499 case MCFragment::FT_Fill:
500 return cast<MCFillFragment>(F).getSize();
502 case MCFragment::FT_LEB:
503 return cast<MCLEBFragment>(F).getContents().size();
505 case MCFragment::FT_SafeSEH:
508 case MCFragment::FT_Align: {
509 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
510 unsigned Offset = Layout.getFragmentOffset(&AF);
511 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
512 // If we are padding with nops, force the padding to be larger than the
514 if (Size > 0 && AF.hasEmitNops()) {
515 while (Size % getBackend().getMinimumNopSize())
516 Size += AF.getAlignment();
518 if (Size > AF.getMaxBytesToEmit())
523 case MCFragment::FT_Org: {
524 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
525 int64_t TargetLocation;
526 if (!OF.getOffset().evaluateAsAbsolute(TargetLocation, Layout))
527 report_fatal_error("expected assembly-time absolute expression");
529 // FIXME: We need a way to communicate this error.
530 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
531 int64_t Size = TargetLocation - FragmentOffset;
532 if (Size < 0 || Size >= 0x40000000)
533 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
534 "' (at offset '" + Twine(FragmentOffset) + "')");
538 case MCFragment::FT_Dwarf:
539 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
540 case MCFragment::FT_DwarfFrame:
541 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
544 llvm_unreachable("invalid fragment kind");
547 void MCAsmLayout::layoutFragment(MCFragment *F) {
548 MCFragment *Prev = F->getPrevNode();
550 // We should never try to recompute something which is valid.
551 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
552 // We should never try to compute the fragment layout if its predecessor
554 assert((!Prev || isFragmentValid(Prev)) &&
555 "Attempt to compute fragment before its predecessor!");
557 ++stats::FragmentLayouts;
559 // Compute fragment offset and size.
561 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
564 LastValidFragment[F->getParent()] = F;
566 // If bundling is enabled and this fragment has instructions in it, it has to
567 // obey the bundling restrictions. With padding, we'll have:
572 // -------------------------------------
573 // Prev |##########| F |
574 // -------------------------------------
579 // The fragment's offset will point to after the padding, and its computed
580 // size won't include the padding.
582 // When the -mc-relax-all flag is used, we optimize bundling by writting the
583 // padding directly into fragments when the instructions are emitted inside
584 // the streamer. When the fragment is larger than the bundle size, we need to
585 // ensure that it's bundle aligned. This means that if we end up with
586 // multiple fragments, we must emit bundle padding between fragments.
588 // ".align N" is an example of a directive that introduces multiple
589 // fragments. We could add a special case to handle ".align N" by emitting
590 // within-fragment padding (which would produce less padding when N is less
591 // than the bundle size), but for now we don't.
593 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
594 assert(isa<MCEncodedFragment>(F) &&
595 "Only MCEncodedFragment implementations have instructions");
596 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
598 if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
599 report_fatal_error("Fragment can't be larger than a bundle size");
601 uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
603 if (RequiredBundlePadding > UINT8_MAX)
604 report_fatal_error("Padding cannot exceed 255 bytes");
605 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
606 F->Offset += RequiredBundlePadding;
610 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
611 bool New = !Symbol.isRegistered();
615 Symbol.setIsRegistered(true);
616 Symbols.push_back(&Symbol);
620 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
621 MCObjectWriter *OW) const {
622 // Should NOP padding be written out before this fragment?
623 unsigned BundlePadding = F.getBundlePadding();
624 if (BundlePadding > 0) {
625 assert(isBundlingEnabled() &&
626 "Writing bundle padding with disabled bundling");
627 assert(F.hasInstructions() &&
628 "Writing bundle padding for a fragment without instructions");
630 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
631 if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
632 // If the padding itself crosses a bundle boundary, it must be emitted
633 // in 2 pieces, since even nop instructions must not cross boundaries.
634 // v--------------v <- BundleAlignSize
635 // v---------v <- BundlePadding
636 // ----------------------------
637 // | Prev |####|####| F |
638 // ----------------------------
639 // ^-------------------^ <- TotalLength
640 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
641 if (!getBackend().writeNopData(DistanceToBoundary, OW))
642 report_fatal_error("unable to write NOP sequence of " +
643 Twine(DistanceToBoundary) + " bytes");
644 BundlePadding -= DistanceToBoundary;
646 if (!getBackend().writeNopData(BundlePadding, OW))
647 report_fatal_error("unable to write NOP sequence of " +
648 Twine(BundlePadding) + " bytes");
652 /// \brief Write the fragment \p F to the output file.
653 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
654 const MCFragment &F) {
655 MCObjectWriter *OW = &Asm.getWriter();
657 // FIXME: Embed in fragments instead?
658 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
660 Asm.writeFragmentPadding(F, FragmentSize, OW);
662 // This variable (and its dummy usage) is to participate in the assert at
663 // the end of the function.
664 uint64_t Start = OW->getStream().tell();
667 ++stats::EmittedFragments;
669 switch (F.getKind()) {
670 case MCFragment::FT_Align: {
671 ++stats::EmittedAlignFragments;
672 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
673 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
675 uint64_t Count = FragmentSize / AF.getValueSize();
677 // FIXME: This error shouldn't actually occur (the front end should emit
678 // multiple .align directives to enforce the semantics it wants), but is
679 // severe enough that we want to report it. How to handle this?
680 if (Count * AF.getValueSize() != FragmentSize)
681 report_fatal_error("undefined .align directive, value size '" +
682 Twine(AF.getValueSize()) +
683 "' is not a divisor of padding size '" +
684 Twine(FragmentSize) + "'");
686 // See if we are aligning with nops, and if so do that first to try to fill
687 // the Count bytes. Then if that did not fill any bytes or there are any
688 // bytes left to fill use the Value and ValueSize to fill the rest.
689 // If we are aligning with nops, ask that target to emit the right data.
690 if (AF.hasEmitNops()) {
691 if (!Asm.getBackend().writeNopData(Count, OW))
692 report_fatal_error("unable to write nop sequence of " +
693 Twine(Count) + " bytes");
697 // Otherwise, write out in multiples of the value size.
698 for (uint64_t i = 0; i != Count; ++i) {
699 switch (AF.getValueSize()) {
700 default: llvm_unreachable("Invalid size!");
701 case 1: OW->write8 (uint8_t (AF.getValue())); break;
702 case 2: OW->write16(uint16_t(AF.getValue())); break;
703 case 4: OW->write32(uint32_t(AF.getValue())); break;
704 case 8: OW->write64(uint64_t(AF.getValue())); break;
710 case MCFragment::FT_Data:
711 ++stats::EmittedDataFragments;
712 OW->writeBytes(cast<MCDataFragment>(F).getContents());
715 case MCFragment::FT_Relaxable:
716 ++stats::EmittedRelaxableFragments;
717 OW->writeBytes(cast<MCRelaxableFragment>(F).getContents());
720 case MCFragment::FT_CompactEncodedInst:
721 ++stats::EmittedCompactEncodedInstFragments;
722 OW->writeBytes(cast<MCCompactEncodedInstFragment>(F).getContents());
725 case MCFragment::FT_Fill: {
726 ++stats::EmittedFillFragments;
727 const MCFillFragment &FF = cast<MCFillFragment>(F);
729 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
731 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
732 switch (FF.getValueSize()) {
733 default: llvm_unreachable("Invalid size!");
734 case 1: OW->write8 (uint8_t (FF.getValue())); break;
735 case 2: OW->write16(uint16_t(FF.getValue())); break;
736 case 4: OW->write32(uint32_t(FF.getValue())); break;
737 case 8: OW->write64(uint64_t(FF.getValue())); break;
743 case MCFragment::FT_LEB: {
744 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
745 OW->writeBytes(LF.getContents());
749 case MCFragment::FT_SafeSEH: {
750 const MCSafeSEHFragment &SF = cast<MCSafeSEHFragment>(F);
751 OW->write32(SF.getSymbol()->getIndex());
755 case MCFragment::FT_Org: {
756 ++stats::EmittedOrgFragments;
757 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
759 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
760 OW->write8(uint8_t(OF.getValue()));
765 case MCFragment::FT_Dwarf: {
766 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
767 OW->writeBytes(OF.getContents());
770 case MCFragment::FT_DwarfFrame: {
771 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
772 OW->writeBytes(CF.getContents());
777 assert(OW->getStream().tell() - Start == FragmentSize &&
778 "The stream should advance by fragment size");
781 void MCAssembler::writeSectionData(const MCSection *Sec,
782 const MCAsmLayout &Layout) const {
783 // Ignore virtual sections.
784 if (Sec->isVirtualSection()) {
785 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
787 // Check that contents are only things legal inside a virtual section.
788 for (const MCFragment &F : *Sec) {
789 switch (F.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>(F);
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>(Sec))
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>(F).getValueSize() == 0 ||
812 cast<MCAlignFragment>(F).getValue() == 0) &&
813 "Invalid align in virtual section!");
815 case MCFragment::FT_Fill:
816 assert((cast<MCFillFragment>(F).getValueSize() == 0 ||
817 cast<MCFillFragment>(F).getValue() == 0) &&
818 "Invalid fill in virtual section!");
826 uint64_t Start = getWriter().getStream().tell();
829 for (const MCFragment &F : *Sec)
830 writeFragment(*this, Layout, F);
832 assert(getWriter().getStream().tell() - Start ==
833 Layout.getSectionAddressSize(Sec));
836 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
838 const MCFixup &Fixup) {
839 // Evaluate the fixup.
842 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
843 MCFixupKindInfo::FKF_IsPCRel;
844 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
845 // The fixup was unresolved, we need a relocation. Inform the object
846 // writer of the relocation, and give it an opportunity to adjust the
847 // fixup value if need be.
848 getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
851 return std::make_pair(FixedValue, IsPCRel);
854 void MCAssembler::layout(MCAsmLayout &Layout) {
855 DEBUG_WITH_TYPE("mc-dump", {
856 llvm::errs() << "assembler backend - pre-layout\n--\n";
859 // Create dummy fragments and assign section ordinals.
860 unsigned SectionIndex = 0;
861 for (MCSection &Sec : *this) {
862 // Create dummy fragments to eliminate any empty sections, this simplifies
864 if (Sec.getFragmentList().empty())
865 new MCDataFragment(&Sec);
867 Sec.setOrdinal(SectionIndex++);
870 // Assign layout order indices to sections and fragments.
871 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
872 MCSection *Sec = Layout.getSectionOrder()[i];
873 Sec->setLayoutOrder(i);
875 unsigned FragmentIndex = 0;
876 for (MCFragment &Frag : *Sec)
877 Frag.setLayoutOrder(FragmentIndex++);
880 // Layout until everything fits.
881 while (layoutOnce(Layout))
884 DEBUG_WITH_TYPE("mc-dump", {
885 llvm::errs() << "assembler backend - post-relaxation\n--\n";
888 // Finalize the layout, including fragment lowering.
889 finishLayout(Layout);
891 DEBUG_WITH_TYPE("mc-dump", {
892 llvm::errs() << "assembler backend - final-layout\n--\n";
895 // Allow the object writer a chance to perform post-layout binding (for
896 // example, to set the index fields in the symbol data).
897 getWriter().executePostLayoutBinding(*this, Layout);
899 // Evaluate and apply the fixups, generating relocation entries as necessary.
900 for (MCSection &Sec : *this) {
901 for (MCFragment &Frag : Sec) {
902 MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(&Frag);
903 // Data and relaxable fragments both have fixups. So only process
905 // FIXME: Is there a better way to do this? MCEncodedFragmentWithFixups
906 // being templated makes this tricky.
907 if (!F || isa<MCCompactEncodedInstFragment>(F))
909 ArrayRef<MCFixup> Fixups;
910 MutableArrayRef<char> Contents;
911 if (auto *FragWithFixups = dyn_cast<MCDataFragment>(F)) {
912 Fixups = FragWithFixups->getFixups();
913 Contents = FragWithFixups->getContents();
914 } else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(F)) {
915 Fixups = FragWithFixups->getFixups();
916 Contents = FragWithFixups->getContents();
918 llvm_unreachable("Unknown fragment with fixups!");
919 for (const MCFixup &Fixup : Fixups) {
922 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
923 getBackend().applyFixup(Fixup, Contents.data(),
924 Contents.size(), FixedValue, IsPCRel);
930 void MCAssembler::Finish() {
931 // Create the layout object.
932 MCAsmLayout Layout(*this);
935 raw_ostream &OS = getWriter().getStream();
936 uint64_t StartOffset = OS.tell();
938 // Write the object file.
939 getWriter().writeObject(*this, Layout);
941 stats::ObjectBytes += OS.tell() - StartOffset;
944 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
945 const MCRelaxableFragment *DF,
946 const MCAsmLayout &Layout) const {
949 bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value);
950 return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
954 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
955 const MCAsmLayout &Layout) const {
956 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
957 // are intentionally pushing out inst fragments, or because we relaxed a
958 // previous instruction to one that doesn't need relaxation.
959 if (!getBackend().mayNeedRelaxation(F->getInst()))
962 for (const MCFixup &Fixup : F->getFixups())
963 if (fixupNeedsRelaxation(Fixup, F, Layout))
969 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
970 MCRelaxableFragment &F) {
971 if (!fragmentNeedsRelaxation(&F, Layout))
974 ++stats::RelaxedInstructions;
976 // FIXME-PERF: We could immediately lower out instructions if we can tell
977 // they are fully resolved, to avoid retesting on later passes.
979 // Relax the fragment.
982 getBackend().relaxInstruction(F.getInst(), Relaxed);
984 // Encode the new instruction.
986 // FIXME-PERF: If it matters, we could let the target do this. It can
987 // probably do so more efficiently in many cases.
988 SmallVector<MCFixup, 4> Fixups;
989 SmallString<256> Code;
990 raw_svector_ostream VecOS(Code);
991 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
993 // Update the fragment.
995 F.getContents() = Code;
996 F.getFixups() = Fixups;
1001 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
1002 uint64_t OldSize = LF.getContents().size();
1004 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
1006 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
1007 SmallString<8> &Data = LF.getContents();
1009 raw_svector_ostream OSE(Data);
1011 encodeSLEB128(Value, OSE);
1013 encodeULEB128(Value, OSE);
1014 return OldSize != LF.getContents().size();
1017 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1018 MCDwarfLineAddrFragment &DF) {
1019 MCContext &Context = Layout.getAssembler().getContext();
1020 uint64_t OldSize = DF.getContents().size();
1022 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1023 assert(Abs && "We created a line delta with an invalid expression");
1026 LineDelta = DF.getLineDelta();
1027 SmallString<8> &Data = DF.getContents();
1029 raw_svector_ostream OSE(Data);
1030 MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
1032 return OldSize != Data.size();
1035 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1036 MCDwarfCallFrameFragment &DF) {
1037 MCContext &Context = Layout.getAssembler().getContext();
1038 uint64_t OldSize = DF.getContents().size();
1040 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1041 assert(Abs && "We created call frame with an invalid expression");
1043 SmallString<8> &Data = DF.getContents();
1045 raw_svector_ostream OSE(Data);
1046 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
1047 return OldSize != Data.size();
1050 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1051 // Holds the first fragment which needed relaxing during this layout. It will
1052 // remain NULL if none were relaxed.
1053 // When a fragment is relaxed, all the fragments following it should get
1054 // invalidated because their offset is going to change.
1055 MCFragment *FirstRelaxedFragment = nullptr;
1057 // Attempt to relax all the fragments in the section.
1058 for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
1059 // Check if this is a fragment that needs relaxation.
1060 bool RelaxedFrag = false;
1061 switch(I->getKind()) {
1064 case MCFragment::FT_Relaxable:
1065 assert(!getRelaxAll() &&
1066 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1067 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
1069 case MCFragment::FT_Dwarf:
1070 RelaxedFrag = relaxDwarfLineAddr(Layout,
1071 *cast<MCDwarfLineAddrFragment>(I));
1073 case MCFragment::FT_DwarfFrame:
1075 relaxDwarfCallFrameFragment(Layout,
1076 *cast<MCDwarfCallFrameFragment>(I));
1078 case MCFragment::FT_LEB:
1079 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1082 if (RelaxedFrag && !FirstRelaxedFragment)
1083 FirstRelaxedFragment = I;
1085 if (FirstRelaxedFragment) {
1086 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1092 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1093 ++stats::RelaxationSteps;
1095 bool WasRelaxed = false;
1096 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1097 MCSection &Sec = *it;
1098 while (layoutSectionOnce(Layout, Sec))
1105 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1106 // The layout is done. Mark every fragment as valid.
1107 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1108 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1112 // Debugging methods
1116 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1117 OS << "<MCFixup" << " Offset:" << AF.getOffset()
1118 << " Value:" << *AF.getValue()
1119 << " Kind:" << AF.getKind() << ">";
1125 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1126 void MCFragment::dump() {
1127 raw_ostream &OS = llvm::errs();
1130 switch (getKind()) {
1131 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1132 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
1133 case MCFragment::FT_CompactEncodedInst:
1134 OS << "MCCompactEncodedInstFragment"; break;
1135 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
1136 case MCFragment::FT_Relaxable: OS << "MCRelaxableFragment"; break;
1137 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
1138 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1139 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1140 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
1141 case MCFragment::FT_SafeSEH: OS << "MCSafeSEHFragment"; break;
1144 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1145 << " Offset:" << Offset
1146 << " HasInstructions:" << hasInstructions()
1147 << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1149 switch (getKind()) {
1150 case MCFragment::FT_Align: {
1151 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1152 if (AF->hasEmitNops())
1153 OS << " (emit nops)";
1155 OS << " Alignment:" << AF->getAlignment()
1156 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1157 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1160 case MCFragment::FT_Data: {
1161 const MCDataFragment *DF = cast<MCDataFragment>(this);
1163 OS << " Contents:[";
1164 const SmallVectorImpl<char> &Contents = DF->getContents();
1165 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1167 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1169 OS << "] (" << Contents.size() << " bytes)";
1171 if (DF->fixup_begin() != DF->fixup_end()) {
1174 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1175 ie = DF->fixup_end(); it != ie; ++it) {
1176 if (it != DF->fixup_begin()) OS << ",\n ";
1183 case MCFragment::FT_CompactEncodedInst: {
1184 const MCCompactEncodedInstFragment *CEIF =
1185 cast<MCCompactEncodedInstFragment>(this);
1187 OS << " Contents:[";
1188 const SmallVectorImpl<char> &Contents = CEIF->getContents();
1189 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1191 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1193 OS << "] (" << Contents.size() << " bytes)";
1196 case MCFragment::FT_Fill: {
1197 const MCFillFragment *FF = cast<MCFillFragment>(this);
1198 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1199 << " Size:" << FF->getSize();
1202 case MCFragment::FT_Relaxable: {
1203 const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1206 F->getInst().dump_pretty(OS);
1209 case MCFragment::FT_Org: {
1210 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1212 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1215 case MCFragment::FT_Dwarf: {
1216 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1218 OS << " AddrDelta:" << OF->getAddrDelta()
1219 << " LineDelta:" << OF->getLineDelta();
1222 case MCFragment::FT_DwarfFrame: {
1223 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1225 OS << " AddrDelta:" << CF->getAddrDelta();
1228 case MCFragment::FT_LEB: {
1229 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1231 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1234 case MCFragment::FT_SafeSEH: {
1235 const MCSafeSEHFragment *F = cast<MCSafeSEHFragment>(this);
1237 OS << " Sym:" << F->getSymbol();
1244 void MCAssembler::dump() {
1245 raw_ostream &OS = llvm::errs();
1247 OS << "<MCAssembler\n";
1248 OS << " Sections:[\n ";
1249 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1250 if (it != begin()) OS << ",\n ";
1256 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1257 if (it != symbol_begin()) OS << ",\n ";
1260 OS << ", Index:" << it->getIndex() << ", ";