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 #define DEBUG_TYPE "assembler"
11 #include "llvm/MC/MCAssembler.h"
12 #include "llvm/ADT/Statistic.h"
13 #include "llvm/ADT/StringExtras.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/MC/MCAsmBackend.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/MCSymbol.h"
25 #include "llvm/MC/MCValue.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/LEB128.h"
29 #include "llvm/Support/TargetRegistry.h"
30 #include "llvm/Support/raw_ostream.h"
36 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
37 STATISTIC(EmittedInstFragments,
38 "Number of emitted assembler fragments - instruction");
39 STATISTIC(EmittedDataFragments,
40 "Number of emitted assembler fragments - data");
41 STATISTIC(EmittedAlignFragments,
42 "Number of emitted assembler fragments - align");
43 STATISTIC(EmittedFillFragments,
44 "Number of emitted assembler fragments - fill");
45 STATISTIC(EmittedOrgFragments,
46 "Number of emitted assembler fragments - org");
47 STATISTIC(evaluateFixup, "Number of evaluated fixups");
48 STATISTIC(FragmentLayouts, "Number of fragment layouts");
49 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
50 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
51 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
55 // FIXME FIXME FIXME: There are number of places in this file where we convert
56 // what is a 64-bit assembler value used for computation into a value in the
57 // object file, which may truncate it. We should detect that truncation where
58 // invalid and report errors back.
62 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
63 : Assembler(Asm), LastValidFragment()
65 // Compute the section layout order. Virtual sections must go last.
66 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
67 if (!it->getSection().isVirtualSection())
68 SectionOrder.push_back(&*it);
69 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
70 if (it->getSection().isVirtualSection())
71 SectionOrder.push_back(&*it);
74 bool MCAsmLayout::isFragmentValid(const MCFragment *F) const {
75 const MCSectionData &SD = *F->getParent();
76 const MCFragment *LastValid = LastValidFragment.lookup(&SD);
79 assert(LastValid->getParent() == F->getParent());
80 return F->getLayoutOrder() <= LastValid->getLayoutOrder();
83 void MCAsmLayout::invalidateFragmentsAfter(MCFragment *F) {
84 // If this fragment wasn't already valid, we don't need to do anything.
85 if (!isFragmentValid(F))
88 // Otherwise, reset the last valid fragment to this fragment.
89 const MCSectionData &SD = *F->getParent();
90 LastValidFragment[&SD] = F;
93 void MCAsmLayout::ensureValid(const MCFragment *F) const {
94 MCSectionData &SD = *F->getParent();
96 MCFragment *Cur = LastValidFragment[&SD];
100 Cur = Cur->getNextNode();
102 // Advance the layout position until the fragment is valid.
103 while (!isFragmentValid(F)) {
104 assert(Cur && "Layout bookkeeping error");
105 const_cast<MCAsmLayout*>(this)->layoutFragment(Cur);
106 Cur = Cur->getNextNode();
110 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
112 assert(F->Offset != ~UINT64_C(0) && "Address not set!");
116 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData *SD) const {
117 const MCSymbol &S = SD->getSymbol();
119 // If this is a variable, then recursively evaluate now.
120 if (S.isVariable()) {
122 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, *this))
123 report_fatal_error("unable to evaluate offset for variable '" +
126 // Verify that any used symbols are defined.
127 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
128 report_fatal_error("unable to evaluate offset to undefined symbol '" +
129 Target.getSymA()->getSymbol().getName() + "'");
130 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
131 report_fatal_error("unable to evaluate offset to undefined symbol '" +
132 Target.getSymB()->getSymbol().getName() + "'");
134 uint64_t Offset = Target.getConstant();
135 if (Target.getSymA())
136 Offset += getSymbolOffset(&Assembler.getSymbolData(
137 Target.getSymA()->getSymbol()));
138 if (Target.getSymB())
139 Offset -= getSymbolOffset(&Assembler.getSymbolData(
140 Target.getSymB()->getSymbol()));
144 assert(SD->getFragment() && "Invalid getOffset() on undefined symbol!");
145 return getFragmentOffset(SD->getFragment()) + SD->getOffset();
148 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
149 // The size is the last fragment's end offset.
150 const MCFragment &F = SD->getFragmentList().back();
151 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
154 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
155 // Virtual sections have no file size.
156 if (SD->getSection().isVirtualSection())
159 // Otherwise, the file size is the same as the address space size.
160 return getSectionAddressSize(SD);
163 uint64_t MCAsmLayout::computeBundlePadding(const MCFragment *F,
164 uint64_t FOffset, uint64_t FSize) {
165 uint64_t BundleSize = Assembler.getBundleAlignSize();
166 assert(BundleSize > 0 &&
167 "computeBundlePadding should only be called if bundling is enabled");
168 uint64_t BundleMask = BundleSize - 1;
169 uint64_t OffsetInBundle = FOffset & BundleMask;
171 // If the fragment would cross a bundle boundary, add enough padding until
172 // the end of the current bundle.
173 if (OffsetInBundle + FSize > BundleSize)
174 return BundleSize - OffsetInBundle;
181 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
184 MCFragment::~MCFragment() {
187 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
188 : Kind(_Kind), Parent(_Parent), Atom(0), Offset(~UINT64_C(0))
191 Parent->getFragmentList().push_back(this);
196 MCEncodedFragment::~MCEncodedFragment() {
201 MCSectionData::MCSectionData() : Section(0) {}
203 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
204 : Section(&_Section),
205 Ordinal(~UINT32_C(0)),
207 BundleLocked(false), BundleGroupBeforeFirstInst(false),
208 HasInstructions(false)
211 A->getSectionList().push_back(this);
216 MCSymbolData::MCSymbolData() : Symbol(0) {}
218 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
219 uint64_t _Offset, MCAssembler *A)
220 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
221 IsExternal(false), IsPrivateExtern(false),
222 CommonSize(0), SymbolSize(0), CommonAlign(0),
226 A->getSymbolList().push_back(this);
231 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
232 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
234 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
235 OS(OS_), BundleAlignSize(0), RelaxAll(false), NoExecStack(false),
236 SubsectionsViaSymbols(false) {
239 MCAssembler::~MCAssembler() {
242 void MCAssembler::reset() {
247 IndirectSymbols.clear();
252 SubsectionsViaSymbols = false;
254 // reset objects owned by us
255 getBackend().reset();
256 getEmitter().reset();
260 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
261 // Non-temporary labels should always be visible to the linker.
262 if (!Symbol.isTemporary())
265 // Absolute temporary labels are never visible.
266 if (!Symbol.isInSection())
269 // Otherwise, check if the section requires symbols even for temporary labels.
270 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
273 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
274 // Linker visible symbols define atoms.
275 if (isSymbolLinkerVisible(SD->getSymbol()))
278 // Absolute and undefined symbols have no defining atom.
279 if (!SD->getFragment())
282 // Non-linker visible symbols in sections which can't be atomized have no
284 if (!getBackend().isSectionAtomizable(
285 SD->getFragment()->getParent()->getSection()))
288 // Otherwise, return the atom for the containing fragment.
289 return SD->getFragment()->getAtom();
292 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
293 const MCFixup &Fixup, const MCFragment *DF,
294 MCValue &Target, uint64_t &Value) const {
295 ++stats::evaluateFixup;
297 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
298 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
300 bool IsPCRel = Backend.getFixupKindInfo(
301 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
305 if (Target.getSymB()) {
307 } else if (!Target.getSymA()) {
310 const MCSymbolRefExpr *A = Target.getSymA();
311 const MCSymbol &SA = A->getSymbol();
312 if (A->getKind() != MCSymbolRefExpr::VK_None ||
313 SA.AliasedSymbol().isUndefined()) {
316 const MCSymbolData &DataA = getSymbolData(SA);
318 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
323 IsResolved = Target.isAbsolute();
326 Value = Target.getConstant();
328 if (const MCSymbolRefExpr *A = Target.getSymA()) {
329 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
331 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
333 if (const MCSymbolRefExpr *B = Target.getSymB()) {
334 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
336 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
340 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
341 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
342 assert((ShouldAlignPC ? IsPCRel : true) &&
343 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
346 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
348 // A number of ARM fixups in Thumb mode require that the effective PC
349 // address be determined as the 32-bit aligned version of the actual offset.
350 if (ShouldAlignPC) Offset &= ~0x3;
354 // Let the backend adjust the fixup value if necessary, including whether
355 // we need a relocation.
356 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
362 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
363 const MCFragment &F) const {
364 switch (F.getKind()) {
365 case MCFragment::FT_Data:
366 return cast<MCDataFragment>(F).getContents().size();
367 case MCFragment::FT_Fill:
368 return cast<MCFillFragment>(F).getSize();
369 case MCFragment::FT_Inst:
370 return cast<MCInstFragment>(F).getInstSize();
372 case MCFragment::FT_LEB:
373 return cast<MCLEBFragment>(F).getContents().size();
375 case MCFragment::FT_Align: {
376 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
377 unsigned Offset = Layout.getFragmentOffset(&AF);
378 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
379 // If we are padding with nops, force the padding to be larger than the
381 if (Size > 0 && AF.hasEmitNops()) {
382 while (Size % getBackend().getMinimumNopSize())
383 Size += AF.getAlignment();
385 if (Size > AF.getMaxBytesToEmit())
390 case MCFragment::FT_Org: {
391 MCOrgFragment &OF = cast<MCOrgFragment>(F);
392 int64_t TargetLocation;
393 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
394 report_fatal_error("expected assembly-time absolute expression");
396 // FIXME: We need a way to communicate this error.
397 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
398 int64_t Size = TargetLocation - FragmentOffset;
399 if (Size < 0 || Size >= 0x40000000)
400 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
401 "' (at offset '" + Twine(FragmentOffset) + "')");
405 case MCFragment::FT_Dwarf:
406 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
407 case MCFragment::FT_DwarfFrame:
408 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
411 llvm_unreachable("invalid fragment kind");
414 void MCAsmLayout::layoutFragment(MCFragment *F) {
415 MCFragment *Prev = F->getPrevNode();
417 // We should never try to recompute something which is valid.
418 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
419 // We should never try to compute the fragment layout if its predecessor
421 assert((!Prev || isFragmentValid(Prev)) &&
422 "Attempt to compute fragment before its predecessor!");
424 ++stats::FragmentLayouts;
426 // Compute fragment offset and size.
428 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
431 LastValidFragment[F->getParent()] = F;
433 // If bundling is enabled and this fragment has instructions in it, it has to
434 // obey the bundling restrictions. With padding, we'll have:
439 // -------------------------------------
440 // Prev |##########| F |
441 // -------------------------------------
446 // The fragment's offset will point to after the padding, and its computed
447 // size won't include the padding.
449 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
450 assert(isa<MCEncodedFragment>(F) &&
451 "Only MCEncodedFragment implementations have instructions");
452 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
454 if (FSize > Assembler.getBundleAlignSize())
455 report_fatal_error("Fragment can't be larger than a bundle size");
457 uint64_t RequiredBundlePadding = computeBundlePadding(F, F->Offset, FSize);
458 if (RequiredBundlePadding > UINT8_MAX)
459 report_fatal_error("Padding cannot exceed 255 bytes");
460 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
461 F->Offset += RequiredBundlePadding;
465 /// \brief Write the contents of a fragment to the given object writer. Expects
466 /// a MCEncodedFragment.
467 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
468 MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
469 OW->WriteBytes(EF.getContents());
472 /// \brief Write the fragment \p F to the output file.
473 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
474 const MCFragment &F) {
475 MCObjectWriter *OW = &Asm.getWriter();
477 // Should NOP padding be written out before this fragment?
478 unsigned BundlePadding = F.getBundlePadding();
479 if (BundlePadding > 0) {
480 assert(Asm.isBundlingEnabled() &&
481 "Writing bundle padding with disabled bundling");
482 assert(F.hasInstructions() &&
483 "Writing bundle padding for a fragment without instructions");
485 if (!Asm.getBackend().writeNopData(BundlePadding, OW))
486 report_fatal_error("unable to write NOP sequence of " +
487 Twine(BundlePadding) + " bytes");
490 // This variable (and its dummy usage) is to participate in the assert at
491 // the end of the function.
492 uint64_t Start = OW->getStream().tell();
495 ++stats::EmittedFragments;
497 // FIXME: Embed in fragments instead?
498 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
499 switch (F.getKind()) {
500 case MCFragment::FT_Align: {
501 ++stats::EmittedAlignFragments;
502 MCAlignFragment &AF = cast<MCAlignFragment>(F);
503 uint64_t Count = FragmentSize / AF.getValueSize();
505 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
507 // FIXME: This error shouldn't actually occur (the front end should emit
508 // multiple .align directives to enforce the semantics it wants), but is
509 // severe enough that we want to report it. How to handle this?
510 if (Count * AF.getValueSize() != FragmentSize)
511 report_fatal_error("undefined .align directive, value size '" +
512 Twine(AF.getValueSize()) +
513 "' is not a divisor of padding size '" +
514 Twine(FragmentSize) + "'");
516 // See if we are aligning with nops, and if so do that first to try to fill
517 // the Count bytes. Then if that did not fill any bytes or there are any
518 // bytes left to fill use the Value and ValueSize to fill the rest.
519 // If we are aligning with nops, ask that target to emit the right data.
520 if (AF.hasEmitNops()) {
521 if (!Asm.getBackend().writeNopData(Count, OW))
522 report_fatal_error("unable to write nop sequence of " +
523 Twine(Count) + " bytes");
527 // Otherwise, write out in multiples of the value size.
528 for (uint64_t i = 0; i != Count; ++i) {
529 switch (AF.getValueSize()) {
530 default: llvm_unreachable("Invalid size!");
531 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
532 case 2: OW->Write16(uint16_t(AF.getValue())); break;
533 case 4: OW->Write32(uint32_t(AF.getValue())); break;
534 case 8: OW->Write64(uint64_t(AF.getValue())); break;
540 case MCFragment::FT_Data:
541 ++stats::EmittedDataFragments;
542 writeFragmentContents(F, OW);
545 case MCFragment::FT_Inst:
546 ++stats::EmittedInstFragments;
547 writeFragmentContents(F, OW);
550 case MCFragment::FT_Fill: {
551 ++stats::EmittedFillFragments;
552 MCFillFragment &FF = cast<MCFillFragment>(F);
554 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
556 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
557 switch (FF.getValueSize()) {
558 default: llvm_unreachable("Invalid size!");
559 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
560 case 2: OW->Write16(uint16_t(FF.getValue())); break;
561 case 4: OW->Write32(uint32_t(FF.getValue())); break;
562 case 8: OW->Write64(uint64_t(FF.getValue())); break;
568 case MCFragment::FT_LEB: {
569 MCLEBFragment &LF = cast<MCLEBFragment>(F);
570 OW->WriteBytes(LF.getContents().str());
574 case MCFragment::FT_Org: {
575 ++stats::EmittedOrgFragments;
576 MCOrgFragment &OF = cast<MCOrgFragment>(F);
578 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
579 OW->Write8(uint8_t(OF.getValue()));
584 case MCFragment::FT_Dwarf: {
585 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
586 OW->WriteBytes(OF.getContents().str());
589 case MCFragment::FT_DwarfFrame: {
590 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
591 OW->WriteBytes(CF.getContents().str());
596 assert(OW->getStream().tell() - Start == FragmentSize &&
597 "The stream should advance by fragment size");
600 void MCAssembler::writeSectionData(const MCSectionData *SD,
601 const MCAsmLayout &Layout) const {
602 // Ignore virtual sections.
603 if (SD->getSection().isVirtualSection()) {
604 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
606 // Check that contents are only things legal inside a virtual section.
607 for (MCSectionData::const_iterator it = SD->begin(),
608 ie = SD->end(); it != ie; ++it) {
609 switch (it->getKind()) {
610 default: llvm_unreachable("Invalid fragment in virtual section!");
611 case MCFragment::FT_Data: {
612 // Check that we aren't trying to write a non-zero contents (or fixups)
613 // into a virtual section. This is to support clients which use standard
614 // directives to fill the contents of virtual sections.
615 MCDataFragment &DF = cast<MCDataFragment>(*it);
616 assert(DF.fixup_begin() == DF.fixup_end() &&
617 "Cannot have fixups in virtual section!");
618 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
619 assert(DF.getContents()[i] == 0 &&
620 "Invalid data value for virtual section!");
623 case MCFragment::FT_Align:
624 // Check that we aren't trying to write a non-zero value into a virtual
626 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
627 !cast<MCAlignFragment>(it)->getValue()) &&
628 "Invalid align in virtual section!");
630 case MCFragment::FT_Fill:
631 assert(!cast<MCFillFragment>(it)->getValueSize() &&
632 "Invalid fill in virtual section!");
640 uint64_t Start = getWriter().getStream().tell();
643 for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
645 writeFragment(*this, Layout, *it);
647 assert(getWriter().getStream().tell() - Start ==
648 Layout.getSectionAddressSize(SD));
652 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
654 const MCFixup &Fixup) {
655 // Evaluate the fixup.
658 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
659 // The fixup was unresolved, we need a relocation. Inform the object
660 // writer of the relocation, and give it an opportunity to adjust the
661 // fixup value if need be.
662 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
667 void MCAssembler::Finish() {
668 DEBUG_WITH_TYPE("mc-dump", {
669 llvm::errs() << "assembler backend - pre-layout\n--\n";
672 // Create the layout object.
673 MCAsmLayout Layout(*this);
675 // Create dummy fragments and assign section ordinals.
676 unsigned SectionIndex = 0;
677 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
678 // Create dummy fragments to eliminate any empty sections, this simplifies
680 if (it->getFragmentList().empty())
681 new MCDataFragment(it);
683 it->setOrdinal(SectionIndex++);
686 // Assign layout order indices to sections and fragments.
687 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
688 MCSectionData *SD = Layout.getSectionOrder()[i];
689 SD->setLayoutOrder(i);
691 unsigned FragmentIndex = 0;
692 for (MCSectionData::iterator iFrag = SD->begin(), iFragEnd = SD->end();
693 iFrag != iFragEnd; ++iFrag)
694 iFrag->setLayoutOrder(FragmentIndex++);
697 // Layout until everything fits.
698 while (layoutOnce(Layout))
701 DEBUG_WITH_TYPE("mc-dump", {
702 llvm::errs() << "assembler backend - post-relaxation\n--\n";
705 // Finalize the layout, including fragment lowering.
706 finishLayout(Layout);
708 DEBUG_WITH_TYPE("mc-dump", {
709 llvm::errs() << "assembler backend - final-layout\n--\n";
712 uint64_t StartOffset = OS.tell();
714 // Allow the object writer a chance to perform post-layout binding (for
715 // example, to set the index fields in the symbol data).
716 getWriter().ExecutePostLayoutBinding(*this, Layout);
718 // Evaluate and apply the fixups, generating relocation entries as necessary.
719 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
720 for (MCSectionData::iterator it2 = it->begin(),
721 ie2 = it->end(); it2 != ie2; ++it2) {
722 MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(it2);
724 for (MCEncodedFragment::fixup_iterator it3 = F->fixup_begin(),
725 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
726 MCFixup &Fixup = *it3;
727 uint64_t FixedValue = handleFixup(Layout, *F, Fixup);
728 getBackend().applyFixup(Fixup, F->getContents().data(),
729 F->getContents().size(), FixedValue);
735 // Write the object file.
736 getWriter().WriteObject(*this, Layout);
738 stats::ObjectBytes += OS.tell() - StartOffset;
741 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
742 const MCInstFragment *DF,
743 const MCAsmLayout &Layout) const {
744 // If we cannot resolve the fixup value, it requires relaxation.
747 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
750 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
753 bool MCAssembler::fragmentNeedsRelaxation(const MCInstFragment *IF,
754 const MCAsmLayout &Layout) const {
755 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
756 // are intentionally pushing out inst fragments, or because we relaxed a
757 // previous instruction to one that doesn't need relaxation.
758 if (!getBackend().mayNeedRelaxation(IF->getInst()))
761 for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
762 ie = IF->fixup_end(); it != ie; ++it)
763 if (fixupNeedsRelaxation(*it, IF, Layout))
769 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
770 MCInstFragment &IF) {
771 if (!fragmentNeedsRelaxation(&IF, Layout))
774 ++stats::RelaxedInstructions;
776 // FIXME-PERF: We could immediately lower out instructions if we can tell
777 // they are fully resolved, to avoid retesting on later passes.
779 // Relax the fragment.
782 getBackend().relaxInstruction(IF.getInst(), Relaxed);
784 // Encode the new instruction.
786 // FIXME-PERF: If it matters, we could let the target do this. It can
787 // probably do so more efficiently in many cases.
788 SmallVector<MCFixup, 4> Fixups;
789 SmallString<256> Code;
790 raw_svector_ostream VecOS(Code);
791 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
794 // Update the instruction fragment.
796 IF.getContents() = Code;
797 IF.getFixups() = Fixups;
802 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
804 uint64_t OldSize = LF.getContents().size();
805 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
808 SmallString<8> &Data = LF.getContents();
810 raw_svector_ostream OSE(Data);
812 encodeSLEB128(Value, OSE);
814 encodeULEB128(Value, OSE);
816 return OldSize != LF.getContents().size();
819 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
820 MCDwarfLineAddrFragment &DF) {
821 int64_t AddrDelta = 0;
822 uint64_t OldSize = DF.getContents().size();
823 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
827 LineDelta = DF.getLineDelta();
828 SmallString<8> &Data = DF.getContents();
830 raw_svector_ostream OSE(Data);
831 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
833 return OldSize != Data.size();
836 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
837 MCDwarfCallFrameFragment &DF) {
838 int64_t AddrDelta = 0;
839 uint64_t OldSize = DF.getContents().size();
840 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
843 SmallString<8> &Data = DF.getContents();
845 raw_svector_ostream OSE(Data);
846 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
848 return OldSize != Data.size();
851 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD) {
852 // Holds the first fragment which needed relaxing during this layout. It will
853 // remain NULL if none were relaxed.
854 // When a fragment is relaxed, all the fragments following it should get
855 // invalidated because their offset is going to change.
856 MCFragment *FirstRelaxedFragment = NULL;
858 // Attempt to relax all the fragments in the section.
859 for (MCSectionData::iterator I = SD.begin(), IE = SD.end(); I != IE; ++I) {
860 // Check if this is a fragment that needs relaxation.
861 bool RelaxedFrag = false;
862 switch(I->getKind()) {
865 case MCFragment::FT_Inst:
866 assert(!getRelaxAll() &&
867 "Did not expect a MCInstFragment in RelaxAll mode");
868 RelaxedFrag = relaxInstruction(Layout, *cast<MCInstFragment>(I));
870 case MCFragment::FT_Dwarf:
871 RelaxedFrag = relaxDwarfLineAddr(Layout,
872 *cast<MCDwarfLineAddrFragment>(I));
874 case MCFragment::FT_DwarfFrame:
876 relaxDwarfCallFrameFragment(Layout,
877 *cast<MCDwarfCallFrameFragment>(I));
879 case MCFragment::FT_LEB:
880 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
883 if (RelaxedFrag && !FirstRelaxedFragment)
884 FirstRelaxedFragment = I;
886 if (FirstRelaxedFragment) {
887 Layout.invalidateFragmentsAfter(FirstRelaxedFragment);
893 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
894 ++stats::RelaxationSteps;
896 bool WasRelaxed = false;
897 for (iterator it = begin(), ie = end(); it != ie; ++it) {
898 MCSectionData &SD = *it;
899 while (layoutSectionOnce(Layout, SD))
906 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
907 // The layout is done. Mark every fragment as valid.
908 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
909 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
917 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
918 OS << "<MCFixup" << " Offset:" << AF.getOffset()
919 << " Value:" << *AF.getValue()
920 << " Kind:" << AF.getKind() << ">";
926 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
927 void MCFragment::dump() {
928 raw_ostream &OS = llvm::errs();
932 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
933 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
934 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
935 case MCFragment::FT_Inst: OS << "MCInstFragment"; break;
936 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
937 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
938 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
939 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
942 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
943 << " Offset:" << Offset
944 << " HasInstructions:" << hasInstructions()
945 << " BundlePadding:" << getBundlePadding() << ">";
948 case MCFragment::FT_Align: {
949 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
950 if (AF->hasEmitNops())
951 OS << " (emit nops)";
953 OS << " Alignment:" << AF->getAlignment()
954 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
955 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
958 case MCFragment::FT_Data: {
959 const MCDataFragment *DF = cast<MCDataFragment>(this);
962 const SmallVectorImpl<char> &Contents = DF->getContents();
963 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
965 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
967 OS << "] (" << Contents.size() << " bytes)";
969 if (DF->fixup_begin() != DF->fixup_end()) {
972 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
973 ie = DF->fixup_end(); it != ie; ++it) {
974 if (it != DF->fixup_begin()) OS << ",\n ";
981 case MCFragment::FT_Fill: {
982 const MCFillFragment *FF = cast<MCFillFragment>(this);
983 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
984 << " Size:" << FF->getSize();
987 case MCFragment::FT_Inst: {
988 const MCInstFragment *IF = cast<MCInstFragment>(this);
991 IF->getInst().dump_pretty(OS);
994 case MCFragment::FT_Org: {
995 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
997 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1000 case MCFragment::FT_Dwarf: {
1001 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1003 OS << " AddrDelta:" << OF->getAddrDelta()
1004 << " LineDelta:" << OF->getLineDelta();
1007 case MCFragment::FT_DwarfFrame: {
1008 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1010 OS << " AddrDelta:" << CF->getAddrDelta();
1013 case MCFragment::FT_LEB: {
1014 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1016 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1023 void MCSectionData::dump() {
1024 raw_ostream &OS = llvm::errs();
1026 OS << "<MCSectionData";
1027 OS << " Alignment:" << getAlignment()
1028 << " Fragments:[\n ";
1029 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1030 if (it != begin()) OS << ",\n ";
1036 void MCSymbolData::dump() {
1037 raw_ostream &OS = llvm::errs();
1039 OS << "<MCSymbolData Symbol:" << getSymbol()
1040 << " Fragment:" << getFragment() << " Offset:" << getOffset()
1041 << " Flags:" << getFlags() << " Index:" << getIndex();
1043 OS << " (common, size:" << getCommonSize()
1044 << " align: " << getCommonAlignment() << ")";
1046 OS << " (external)";
1047 if (isPrivateExtern())
1048 OS << " (private extern)";
1052 void MCAssembler::dump() {
1053 raw_ostream &OS = llvm::errs();
1055 OS << "<MCAssembler\n";
1056 OS << " Sections:[\n ";
1057 for (iterator it = begin(), ie = end(); it != ie; ++it) {
1058 if (it != begin()) OS << ",\n ";
1064 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1065 if (it != symbol_begin()) OS << ",\n ";
1072 // anchors for MC*Fragment vtables
1073 void MCEncodedFragment::anchor() { }
1074 void MCDataFragment::anchor() { }
1075 void MCInstFragment::anchor() { }
1076 void MCAlignFragment::anchor() { }
1077 void MCFillFragment::anchor() { }
1078 void MCOrgFragment::anchor() { }
1079 void MCLEBFragment::anchor() { }
1080 void MCDwarfLineAddrFragment::anchor() { }
1081 void MCDwarfCallFrameFragment::anchor() { }