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);
165 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
168 MCFragment::~MCFragment() {
171 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
172 : Kind(_Kind), Parent(_Parent), Atom(0), Offset(~UINT64_C(0))
175 Parent->getFragmentList().push_back(this);
180 MCEncodedFragment::~MCEncodedFragment() {
185 MCSectionData::MCSectionData() : Section(0) {}
187 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
188 : Section(&_Section),
189 Ordinal(~UINT32_C(0)),
191 HasInstructions(false)
194 A->getSectionList().push_back(this);
199 MCSymbolData::MCSymbolData() : Symbol(0) {}
201 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
202 uint64_t _Offset, MCAssembler *A)
203 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
204 IsExternal(false), IsPrivateExtern(false),
205 CommonSize(0), SymbolSize(0), CommonAlign(0),
209 A->getSymbolList().push_back(this);
214 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
215 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
217 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
218 OS(OS_), RelaxAll(false), NoExecStack(false), SubsectionsViaSymbols(false) {
221 MCAssembler::~MCAssembler() {
224 void MCAssembler::reset() {
229 IndirectSymbols.clear();
234 SubsectionsViaSymbols = false;
236 // reset objects owned by us
237 getBackend().reset();
238 getEmitter().reset();
242 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
243 // Non-temporary labels should always be visible to the linker.
244 if (!Symbol.isTemporary())
247 // Absolute temporary labels are never visible.
248 if (!Symbol.isInSection())
251 // Otherwise, check if the section requires symbols even for temporary labels.
252 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
255 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
256 // Linker visible symbols define atoms.
257 if (isSymbolLinkerVisible(SD->getSymbol()))
260 // Absolute and undefined symbols have no defining atom.
261 if (!SD->getFragment())
264 // Non-linker visible symbols in sections which can't be atomized have no
266 if (!getBackend().isSectionAtomizable(
267 SD->getFragment()->getParent()->getSection()))
270 // Otherwise, return the atom for the containing fragment.
271 return SD->getFragment()->getAtom();
274 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
275 const MCFixup &Fixup, const MCFragment *DF,
276 MCValue &Target, uint64_t &Value) const {
277 ++stats::evaluateFixup;
279 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
280 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
282 bool IsPCRel = Backend.getFixupKindInfo(
283 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
287 if (Target.getSymB()) {
289 } else if (!Target.getSymA()) {
292 const MCSymbolRefExpr *A = Target.getSymA();
293 const MCSymbol &SA = A->getSymbol();
294 if (A->getKind() != MCSymbolRefExpr::VK_None ||
295 SA.AliasedSymbol().isUndefined()) {
298 const MCSymbolData &DataA = getSymbolData(SA);
300 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
305 IsResolved = Target.isAbsolute();
308 Value = Target.getConstant();
310 if (const MCSymbolRefExpr *A = Target.getSymA()) {
311 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
313 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
315 if (const MCSymbolRefExpr *B = Target.getSymB()) {
316 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
318 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
322 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
323 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
324 assert((ShouldAlignPC ? IsPCRel : true) &&
325 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
328 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
330 // A number of ARM fixups in Thumb mode require that the effective PC
331 // address be determined as the 32-bit aligned version of the actual offset.
332 if (ShouldAlignPC) Offset &= ~0x3;
336 // Let the backend adjust the fixup value if necessary, including whether
337 // we need a relocation.
338 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
344 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
345 const MCFragment &F) const {
346 switch (F.getKind()) {
347 case MCFragment::FT_Data:
348 return cast<MCDataFragment>(F).getContents().size();
349 case MCFragment::FT_Fill:
350 return cast<MCFillFragment>(F).getSize();
351 case MCFragment::FT_Inst:
352 return cast<MCInstFragment>(F).getInstSize();
354 case MCFragment::FT_LEB:
355 return cast<MCLEBFragment>(F).getContents().size();
357 case MCFragment::FT_Align: {
358 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
359 unsigned Offset = Layout.getFragmentOffset(&AF);
360 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
361 // If we are padding with nops, force the padding to be larger than the
363 if (Size > 0 && AF.hasEmitNops()) {
364 while (Size % getBackend().getMinimumNopSize())
365 Size += AF.getAlignment();
367 if (Size > AF.getMaxBytesToEmit())
372 case MCFragment::FT_Org: {
373 MCOrgFragment &OF = cast<MCOrgFragment>(F);
374 int64_t TargetLocation;
375 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
376 report_fatal_error("expected assembly-time absolute expression");
378 // FIXME: We need a way to communicate this error.
379 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
380 int64_t Size = TargetLocation - FragmentOffset;
381 if (Size < 0 || Size >= 0x40000000)
382 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
383 "' (at offset '" + Twine(FragmentOffset) + "')");
387 case MCFragment::FT_Dwarf:
388 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
389 case MCFragment::FT_DwarfFrame:
390 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
393 llvm_unreachable("invalid fragment kind");
396 void MCAsmLayout::layoutFragment(MCFragment *F) {
397 MCFragment *Prev = F->getPrevNode();
399 // We should never try to recompute something which is valid.
400 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
401 // We should never try to compute the fragment layout if its predecessor
403 assert((!Prev || isFragmentValid(Prev)) &&
404 "Attempt to compute fragment before its predecessor!");
406 ++stats::FragmentLayouts;
408 // Compute fragment offset and size.
411 Offset += Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
414 LastValidFragment[F->getParent()] = F;
417 /// \brief Write the contents of a fragment to the given object writer. Expects
418 /// a MCEncodedFragment.
419 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
420 MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
421 OW->WriteBytes(EF.getContents());
424 /// \brief Write the fragment \p F to the output file.
425 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
426 const MCFragment &F) {
427 MCObjectWriter *OW = &Asm.getWriter();
428 uint64_t Start = OW->getStream().tell();
431 ++stats::EmittedFragments;
433 // FIXME: Embed in fragments instead?
434 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
435 switch (F.getKind()) {
436 case MCFragment::FT_Align: {
437 ++stats::EmittedAlignFragments;
438 MCAlignFragment &AF = cast<MCAlignFragment>(F);
439 uint64_t Count = FragmentSize / AF.getValueSize();
441 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
443 // FIXME: This error shouldn't actually occur (the front end should emit
444 // multiple .align directives to enforce the semantics it wants), but is
445 // severe enough that we want to report it. How to handle this?
446 if (Count * AF.getValueSize() != FragmentSize)
447 report_fatal_error("undefined .align directive, value size '" +
448 Twine(AF.getValueSize()) +
449 "' is not a divisor of padding size '" +
450 Twine(FragmentSize) + "'");
452 // See if we are aligning with nops, and if so do that first to try to fill
453 // the Count bytes. Then if that did not fill any bytes or there are any
454 // bytes left to fill use the Value and ValueSize to fill the rest.
455 // If we are aligning with nops, ask that target to emit the right data.
456 if (AF.hasEmitNops()) {
457 if (!Asm.getBackend().writeNopData(Count, OW))
458 report_fatal_error("unable to write nop sequence of " +
459 Twine(Count) + " bytes");
463 // Otherwise, write out in multiples of the value size.
464 for (uint64_t i = 0; i != Count; ++i) {
465 switch (AF.getValueSize()) {
466 default: llvm_unreachable("Invalid size!");
467 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
468 case 2: OW->Write16(uint16_t(AF.getValue())); break;
469 case 4: OW->Write32(uint32_t(AF.getValue())); break;
470 case 8: OW->Write64(uint64_t(AF.getValue())); break;
476 case MCFragment::FT_Data:
477 ++stats::EmittedDataFragments;
478 writeFragmentContents(F, OW);
481 case MCFragment::FT_Inst:
482 ++stats::EmittedInstFragments;
483 writeFragmentContents(F, OW);
486 case MCFragment::FT_Fill: {
487 ++stats::EmittedFillFragments;
488 MCFillFragment &FF = cast<MCFillFragment>(F);
490 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
492 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
493 switch (FF.getValueSize()) {
494 default: llvm_unreachable("Invalid size!");
495 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
496 case 2: OW->Write16(uint16_t(FF.getValue())); break;
497 case 4: OW->Write32(uint32_t(FF.getValue())); break;
498 case 8: OW->Write64(uint64_t(FF.getValue())); break;
504 case MCFragment::FT_LEB: {
505 MCLEBFragment &LF = cast<MCLEBFragment>(F);
506 OW->WriteBytes(LF.getContents().str());
510 case MCFragment::FT_Org: {
511 ++stats::EmittedOrgFragments;
512 MCOrgFragment &OF = cast<MCOrgFragment>(F);
514 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
515 OW->Write8(uint8_t(OF.getValue()));
520 case MCFragment::FT_Dwarf: {
521 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
522 OW->WriteBytes(OF.getContents().str());
525 case MCFragment::FT_DwarfFrame: {
526 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
527 OW->WriteBytes(CF.getContents().str());
532 assert(OW->getStream().tell() - Start == FragmentSize);
535 void MCAssembler::writeSectionData(const MCSectionData *SD,
536 const MCAsmLayout &Layout) const {
537 // Ignore virtual sections.
538 if (SD->getSection().isVirtualSection()) {
539 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
541 // Check that contents are only things legal inside a virtual section.
542 for (MCSectionData::const_iterator it = SD->begin(),
543 ie = SD->end(); it != ie; ++it) {
544 switch (it->getKind()) {
545 default: llvm_unreachable("Invalid fragment in virtual section!");
546 case MCFragment::FT_Data: {
547 // Check that we aren't trying to write a non-zero contents (or fixups)
548 // into a virtual section. This is to support clients which use standard
549 // directives to fill the contents of virtual sections.
550 MCDataFragment &DF = cast<MCDataFragment>(*it);
551 assert(DF.fixup_begin() == DF.fixup_end() &&
552 "Cannot have fixups in virtual section!");
553 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
554 assert(DF.getContents()[i] == 0 &&
555 "Invalid data value for virtual section!");
558 case MCFragment::FT_Align:
559 // Check that we aren't trying to write a non-zero value into a virtual
561 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
562 !cast<MCAlignFragment>(it)->getValue()) &&
563 "Invalid align in virtual section!");
565 case MCFragment::FT_Fill:
566 assert(!cast<MCFillFragment>(it)->getValueSize() &&
567 "Invalid fill in virtual section!");
575 uint64_t Start = getWriter().getStream().tell();
578 for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
580 writeFragment(*this, Layout, *it);
582 assert(getWriter().getStream().tell() - Start ==
583 Layout.getSectionAddressSize(SD));
587 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
589 const MCFixup &Fixup) {
590 // Evaluate the fixup.
593 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
594 // The fixup was unresolved, we need a relocation. Inform the object
595 // writer of the relocation, and give it an opportunity to adjust the
596 // fixup value if need be.
597 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
602 void MCAssembler::Finish() {
603 DEBUG_WITH_TYPE("mc-dump", {
604 llvm::errs() << "assembler backend - pre-layout\n--\n";
607 // Create the layout object.
608 MCAsmLayout Layout(*this);
610 // Create dummy fragments and assign section ordinals.
611 unsigned SectionIndex = 0;
612 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
613 // Create dummy fragments to eliminate any empty sections, this simplifies
615 if (it->getFragmentList().empty())
616 new MCDataFragment(it);
618 it->setOrdinal(SectionIndex++);
621 // Assign layout order indices to sections and fragments.
622 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
623 MCSectionData *SD = Layout.getSectionOrder()[i];
624 SD->setLayoutOrder(i);
626 unsigned FragmentIndex = 0;
627 for (MCSectionData::iterator iFrag = SD->begin(), iFragEnd = SD->end();
628 iFrag != iFragEnd; ++iFrag)
629 iFrag->setLayoutOrder(FragmentIndex++);
632 // Layout until everything fits.
633 while (layoutOnce(Layout))
636 DEBUG_WITH_TYPE("mc-dump", {
637 llvm::errs() << "assembler backend - post-relaxation\n--\n";
640 // Finalize the layout, including fragment lowering.
641 finishLayout(Layout);
643 DEBUG_WITH_TYPE("mc-dump", {
644 llvm::errs() << "assembler backend - final-layout\n--\n";
647 uint64_t StartOffset = OS.tell();
649 // Allow the object writer a chance to perform post-layout binding (for
650 // example, to set the index fields in the symbol data).
651 getWriter().ExecutePostLayoutBinding(*this, Layout);
653 // Evaluate and apply the fixups, generating relocation entries as necessary.
654 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
655 for (MCSectionData::iterator it2 = it->begin(),
656 ie2 = it->end(); it2 != ie2; ++it2) {
657 MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(it2);
659 for (MCEncodedFragment::fixup_iterator it3 = F->fixup_begin(),
660 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
661 MCFixup &Fixup = *it3;
662 uint64_t FixedValue = handleFixup(Layout, *F, Fixup);
663 getBackend().applyFixup(Fixup, F->getContents().data(),
664 F->getContents().size(), FixedValue);
670 // Write the object file.
671 getWriter().WriteObject(*this, Layout);
673 stats::ObjectBytes += OS.tell() - StartOffset;
676 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
677 const MCInstFragment *DF,
678 const MCAsmLayout &Layout) const {
679 // If we cannot resolve the fixup value, it requires relaxation.
682 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
685 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
688 bool MCAssembler::fragmentNeedsRelaxation(const MCInstFragment *IF,
689 const MCAsmLayout &Layout) const {
690 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
691 // are intentionally pushing out inst fragments, or because we relaxed a
692 // previous instruction to one that doesn't need relaxation.
693 if (!getBackend().mayNeedRelaxation(IF->getInst()))
696 for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
697 ie = IF->fixup_end(); it != ie; ++it)
698 if (fixupNeedsRelaxation(*it, IF, Layout))
704 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
705 MCInstFragment &IF) {
706 if (!fragmentNeedsRelaxation(&IF, Layout))
709 ++stats::RelaxedInstructions;
711 // FIXME-PERF: We could immediately lower out instructions if we can tell
712 // they are fully resolved, to avoid retesting on later passes.
714 // Relax the fragment.
717 getBackend().relaxInstruction(IF.getInst(), Relaxed);
719 // Encode the new instruction.
721 // FIXME-PERF: If it matters, we could let the target do this. It can
722 // probably do so more efficiently in many cases.
723 SmallVector<MCFixup, 4> Fixups;
724 SmallString<256> Code;
725 raw_svector_ostream VecOS(Code);
726 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
729 // Update the instruction fragment.
731 IF.getContents() = Code;
732 IF.getFixups() = Fixups;
737 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
739 uint64_t OldSize = LF.getContents().size();
740 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
743 SmallString<8> &Data = LF.getContents();
745 raw_svector_ostream OSE(Data);
747 encodeSLEB128(Value, OSE);
749 encodeULEB128(Value, OSE);
751 return OldSize != LF.getContents().size();
754 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
755 MCDwarfLineAddrFragment &DF) {
756 int64_t AddrDelta = 0;
757 uint64_t OldSize = DF.getContents().size();
758 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
762 LineDelta = DF.getLineDelta();
763 SmallString<8> &Data = DF.getContents();
765 raw_svector_ostream OSE(Data);
766 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
768 return OldSize != Data.size();
771 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
772 MCDwarfCallFrameFragment &DF) {
773 int64_t AddrDelta = 0;
774 uint64_t OldSize = DF.getContents().size();
775 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
778 SmallString<8> &Data = DF.getContents();
780 raw_svector_ostream OSE(Data);
781 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
783 return OldSize != Data.size();
786 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD) {
787 // Holds the first fragment which needed relaxing during this layout. It will
788 // remain NULL if none were relaxed.
789 // When a fragment is relaxed, all the fragments following it should get
790 // invalidated because their offset is going to change.
791 MCFragment *FirstRelaxedFragment = NULL;
793 // Attempt to relax all the fragments in the section.
794 for (MCSectionData::iterator I = SD.begin(), IE = SD.end(); I != IE; ++I) {
795 // Check if this is a fragment that needs relaxation.
796 bool RelaxedFrag = false;
797 switch(I->getKind()) {
800 case MCFragment::FT_Inst:
801 assert(!getRelaxAll() &&
802 "Did not expect a MCInstFragment in RelaxAll mode");
803 RelaxedFrag = relaxInstruction(Layout, *cast<MCInstFragment>(I));
805 case MCFragment::FT_Dwarf:
806 RelaxedFrag = relaxDwarfLineAddr(Layout,
807 *cast<MCDwarfLineAddrFragment>(I));
809 case MCFragment::FT_DwarfFrame:
811 relaxDwarfCallFrameFragment(Layout,
812 *cast<MCDwarfCallFrameFragment>(I));
814 case MCFragment::FT_LEB:
815 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
818 if (RelaxedFrag && !FirstRelaxedFragment)
819 FirstRelaxedFragment = I;
821 if (FirstRelaxedFragment) {
822 Layout.invalidateFragmentsAfter(FirstRelaxedFragment);
828 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
829 ++stats::RelaxationSteps;
831 bool WasRelaxed = false;
832 for (iterator it = begin(), ie = end(); it != ie; ++it) {
833 MCSectionData &SD = *it;
834 while (layoutSectionOnce(Layout, SD))
841 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
842 // The layout is done. Mark every fragment as valid.
843 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
844 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
852 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
853 OS << "<MCFixup" << " Offset:" << AF.getOffset()
854 << " Value:" << *AF.getValue()
855 << " Kind:" << AF.getKind() << ">";
861 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
862 void MCFragment::dump() {
863 raw_ostream &OS = llvm::errs();
867 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
868 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
869 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
870 case MCFragment::FT_Inst: OS << "MCInstFragment"; break;
871 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
872 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
873 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
874 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
877 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
878 << " Offset:" << Offset << ">";
881 case MCFragment::FT_Align: {
882 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
883 if (AF->hasEmitNops())
884 OS << " (emit nops)";
886 OS << " Alignment:" << AF->getAlignment()
887 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
888 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
891 case MCFragment::FT_Data: {
892 const MCDataFragment *DF = cast<MCDataFragment>(this);
895 const SmallVectorImpl<char> &Contents = DF->getContents();
896 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
898 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
900 OS << "] (" << Contents.size() << " bytes)";
902 if (DF->fixup_begin() != DF->fixup_end()) {
905 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
906 ie = DF->fixup_end(); it != ie; ++it) {
907 if (it != DF->fixup_begin()) OS << ",\n ";
914 case MCFragment::FT_Fill: {
915 const MCFillFragment *FF = cast<MCFillFragment>(this);
916 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
917 << " Size:" << FF->getSize();
920 case MCFragment::FT_Inst: {
921 const MCInstFragment *IF = cast<MCInstFragment>(this);
924 IF->getInst().dump_pretty(OS);
927 case MCFragment::FT_Org: {
928 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
930 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
933 case MCFragment::FT_Dwarf: {
934 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
936 OS << " AddrDelta:" << OF->getAddrDelta()
937 << " LineDelta:" << OF->getLineDelta();
940 case MCFragment::FT_DwarfFrame: {
941 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
943 OS << " AddrDelta:" << CF->getAddrDelta();
946 case MCFragment::FT_LEB: {
947 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
949 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
956 void MCSectionData::dump() {
957 raw_ostream &OS = llvm::errs();
959 OS << "<MCSectionData";
960 OS << " Alignment:" << getAlignment() << " Fragments:[\n ";
961 for (iterator it = begin(), ie = end(); it != ie; ++it) {
962 if (it != begin()) OS << ",\n ";
968 void MCSymbolData::dump() {
969 raw_ostream &OS = llvm::errs();
971 OS << "<MCSymbolData Symbol:" << getSymbol()
972 << " Fragment:" << getFragment() << " Offset:" << getOffset()
973 << " Flags:" << getFlags() << " Index:" << getIndex();
975 OS << " (common, size:" << getCommonSize()
976 << " align: " << getCommonAlignment() << ")";
979 if (isPrivateExtern())
980 OS << " (private extern)";
984 void MCAssembler::dump() {
985 raw_ostream &OS = llvm::errs();
987 OS << "<MCAssembler\n";
988 OS << " Sections:[\n ";
989 for (iterator it = begin(), ie = end(); it != ie; ++it) {
990 if (it != begin()) OS << ",\n ";
996 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
997 if (it != symbol_begin()) OS << ",\n ";
1004 // anchors for MC*Fragment vtables
1005 void MCEncodedFragment::anchor() { }
1006 void MCDataFragment::anchor() { }
1007 void MCInstFragment::anchor() { }
1008 void MCAlignFragment::anchor() { }
1009 void MCFillFragment::anchor() { }
1010 void MCOrgFragment::anchor() { }
1011 void MCLEBFragment::anchor() { }
1012 void MCDwarfLineAddrFragment::anchor() { }
1013 void MCDwarfCallFrameFragment::anchor() { }