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;
237 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
238 // Non-temporary labels should always be visible to the linker.
239 if (!Symbol.isTemporary())
242 // Absolute temporary labels are never visible.
243 if (!Symbol.isInSection())
246 // Otherwise, check if the section requires symbols even for temporary labels.
247 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
250 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
251 // Linker visible symbols define atoms.
252 if (isSymbolLinkerVisible(SD->getSymbol()))
255 // Absolute and undefined symbols have no defining atom.
256 if (!SD->getFragment())
259 // Non-linker visible symbols in sections which can't be atomized have no
261 if (!getBackend().isSectionAtomizable(
262 SD->getFragment()->getParent()->getSection()))
265 // Otherwise, return the atom for the containing fragment.
266 return SD->getFragment()->getAtom();
269 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
270 const MCFixup &Fixup, const MCFragment *DF,
271 MCValue &Target, uint64_t &Value) const {
272 ++stats::evaluateFixup;
274 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
275 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
277 bool IsPCRel = Backend.getFixupKindInfo(
278 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
282 if (Target.getSymB()) {
284 } else if (!Target.getSymA()) {
287 const MCSymbolRefExpr *A = Target.getSymA();
288 const MCSymbol &SA = A->getSymbol();
289 if (A->getKind() != MCSymbolRefExpr::VK_None ||
290 SA.AliasedSymbol().isUndefined()) {
293 const MCSymbolData &DataA = getSymbolData(SA);
295 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
300 IsResolved = Target.isAbsolute();
303 Value = Target.getConstant();
305 if (const MCSymbolRefExpr *A = Target.getSymA()) {
306 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
308 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
310 if (const MCSymbolRefExpr *B = Target.getSymB()) {
311 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
313 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
317 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
318 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
319 assert((ShouldAlignPC ? IsPCRel : true) &&
320 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
323 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
325 // A number of ARM fixups in Thumb mode require that the effective PC
326 // address be determined as the 32-bit aligned version of the actual offset.
327 if (ShouldAlignPC) Offset &= ~0x3;
331 // Let the backend adjust the fixup value if necessary, including whether
332 // we need a relocation.
333 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
339 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
340 const MCFragment &F) const {
341 switch (F.getKind()) {
342 case MCFragment::FT_Data:
343 return cast<MCDataFragment>(F).getContents().size();
344 case MCFragment::FT_Fill:
345 return cast<MCFillFragment>(F).getSize();
346 case MCFragment::FT_Inst:
347 return cast<MCInstFragment>(F).getInstSize();
349 case MCFragment::FT_LEB:
350 return cast<MCLEBFragment>(F).getContents().size();
352 case MCFragment::FT_Align: {
353 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
354 unsigned Offset = Layout.getFragmentOffset(&AF);
355 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
356 // If we are padding with nops, force the padding to be larger than the
358 if (Size > 0 && AF.hasEmitNops()) {
359 while (Size % getBackend().getMinimumNopSize())
360 Size += AF.getAlignment();
362 if (Size > AF.getMaxBytesToEmit())
367 case MCFragment::FT_Org: {
368 MCOrgFragment &OF = cast<MCOrgFragment>(F);
369 int64_t TargetLocation;
370 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
371 report_fatal_error("expected assembly-time absolute expression");
373 // FIXME: We need a way to communicate this error.
374 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
375 int64_t Size = TargetLocation - FragmentOffset;
376 if (Size < 0 || Size >= 0x40000000)
377 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
378 "' (at offset '" + Twine(FragmentOffset) + "')");
382 case MCFragment::FT_Dwarf:
383 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
384 case MCFragment::FT_DwarfFrame:
385 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
388 llvm_unreachable("invalid fragment kind");
391 void MCAsmLayout::layoutFragment(MCFragment *F) {
392 MCFragment *Prev = F->getPrevNode();
394 // We should never try to recompute something which is valid.
395 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
396 // We should never try to compute the fragment layout if its predecessor
398 assert((!Prev || isFragmentValid(Prev)) &&
399 "Attempt to compute fragment before its predecessor!");
401 ++stats::FragmentLayouts;
403 // Compute fragment offset and size.
406 Offset += Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
409 LastValidFragment[F->getParent()] = F;
412 /// \brief Write the contents of a fragment to the given object writer. Expects
413 /// a MCEncodedFragment.
414 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
415 MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
416 OW->WriteBytes(EF.getContents());
419 /// \brief Write the fragment \p F to the output file.
420 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
421 const MCFragment &F) {
422 MCObjectWriter *OW = &Asm.getWriter();
423 uint64_t Start = OW->getStream().tell();
426 ++stats::EmittedFragments;
428 // FIXME: Embed in fragments instead?
429 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
430 switch (F.getKind()) {
431 case MCFragment::FT_Align: {
432 ++stats::EmittedAlignFragments;
433 MCAlignFragment &AF = cast<MCAlignFragment>(F);
434 uint64_t Count = FragmentSize / AF.getValueSize();
436 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
438 // FIXME: This error shouldn't actually occur (the front end should emit
439 // multiple .align directives to enforce the semantics it wants), but is
440 // severe enough that we want to report it. How to handle this?
441 if (Count * AF.getValueSize() != FragmentSize)
442 report_fatal_error("undefined .align directive, value size '" +
443 Twine(AF.getValueSize()) +
444 "' is not a divisor of padding size '" +
445 Twine(FragmentSize) + "'");
447 // See if we are aligning with nops, and if so do that first to try to fill
448 // the Count bytes. Then if that did not fill any bytes or there are any
449 // bytes left to fill use the Value and ValueSize to fill the rest.
450 // If we are aligning with nops, ask that target to emit the right data.
451 if (AF.hasEmitNops()) {
452 if (!Asm.getBackend().writeNopData(Count, OW))
453 report_fatal_error("unable to write nop sequence of " +
454 Twine(Count) + " bytes");
458 // Otherwise, write out in multiples of the value size.
459 for (uint64_t i = 0; i != Count; ++i) {
460 switch (AF.getValueSize()) {
461 default: llvm_unreachable("Invalid size!");
462 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
463 case 2: OW->Write16(uint16_t(AF.getValue())); break;
464 case 4: OW->Write32(uint32_t(AF.getValue())); break;
465 case 8: OW->Write64(uint64_t(AF.getValue())); break;
471 case MCFragment::FT_Data:
472 ++stats::EmittedDataFragments;
473 writeFragmentContents(F, OW);
476 case MCFragment::FT_Inst:
477 ++stats::EmittedInstFragments;
478 writeFragmentContents(F, OW);
481 case MCFragment::FT_Fill: {
482 ++stats::EmittedFillFragments;
483 MCFillFragment &FF = cast<MCFillFragment>(F);
485 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
487 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
488 switch (FF.getValueSize()) {
489 default: llvm_unreachable("Invalid size!");
490 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
491 case 2: OW->Write16(uint16_t(FF.getValue())); break;
492 case 4: OW->Write32(uint32_t(FF.getValue())); break;
493 case 8: OW->Write64(uint64_t(FF.getValue())); break;
499 case MCFragment::FT_LEB: {
500 MCLEBFragment &LF = cast<MCLEBFragment>(F);
501 OW->WriteBytes(LF.getContents().str());
505 case MCFragment::FT_Org: {
506 ++stats::EmittedOrgFragments;
507 MCOrgFragment &OF = cast<MCOrgFragment>(F);
509 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
510 OW->Write8(uint8_t(OF.getValue()));
515 case MCFragment::FT_Dwarf: {
516 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
517 OW->WriteBytes(OF.getContents().str());
520 case MCFragment::FT_DwarfFrame: {
521 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
522 OW->WriteBytes(CF.getContents().str());
527 assert(OW->getStream().tell() - Start == FragmentSize);
530 void MCAssembler::writeSectionData(const MCSectionData *SD,
531 const MCAsmLayout &Layout) const {
532 // Ignore virtual sections.
533 if (SD->getSection().isVirtualSection()) {
534 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
536 // Check that contents are only things legal inside a virtual section.
537 for (MCSectionData::const_iterator it = SD->begin(),
538 ie = SD->end(); it != ie; ++it) {
539 switch (it->getKind()) {
540 default: llvm_unreachable("Invalid fragment in virtual section!");
541 case MCFragment::FT_Data: {
542 // Check that we aren't trying to write a non-zero contents (or fixups)
543 // into a virtual section. This is to support clients which use standard
544 // directives to fill the contents of virtual sections.
545 MCDataFragment &DF = cast<MCDataFragment>(*it);
546 assert(DF.fixup_begin() == DF.fixup_end() &&
547 "Cannot have fixups in virtual section!");
548 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
549 assert(DF.getContents()[i] == 0 &&
550 "Invalid data value for virtual section!");
553 case MCFragment::FT_Align:
554 // Check that we aren't trying to write a non-zero value into a virtual
556 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
557 !cast<MCAlignFragment>(it)->getValue()) &&
558 "Invalid align in virtual section!");
560 case MCFragment::FT_Fill:
561 assert(!cast<MCFillFragment>(it)->getValueSize() &&
562 "Invalid fill in virtual section!");
570 uint64_t Start = getWriter().getStream().tell();
573 for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
575 writeFragment(*this, Layout, *it);
577 assert(getWriter().getStream().tell() - Start ==
578 Layout.getSectionAddressSize(SD));
582 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
584 const MCFixup &Fixup) {
585 // Evaluate the fixup.
588 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
589 // The fixup was unresolved, we need a relocation. Inform the object
590 // writer of the relocation, and give it an opportunity to adjust the
591 // fixup value if need be.
592 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
597 void MCAssembler::Finish() {
598 DEBUG_WITH_TYPE("mc-dump", {
599 llvm::errs() << "assembler backend - pre-layout\n--\n";
602 // Create the layout object.
603 MCAsmLayout Layout(*this);
605 // Create dummy fragments and assign section ordinals.
606 unsigned SectionIndex = 0;
607 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
608 // Create dummy fragments to eliminate any empty sections, this simplifies
610 if (it->getFragmentList().empty())
611 new MCDataFragment(it);
613 it->setOrdinal(SectionIndex++);
616 // Assign layout order indices to sections and fragments.
617 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
618 MCSectionData *SD = Layout.getSectionOrder()[i];
619 SD->setLayoutOrder(i);
621 unsigned FragmentIndex = 0;
622 for (MCSectionData::iterator iFrag = SD->begin(), iFragEnd = SD->end();
623 iFrag != iFragEnd; ++iFrag)
624 iFrag->setLayoutOrder(FragmentIndex++);
627 // Layout until everything fits.
628 while (layoutOnce(Layout))
631 DEBUG_WITH_TYPE("mc-dump", {
632 llvm::errs() << "assembler backend - post-relaxation\n--\n";
635 // Finalize the layout, including fragment lowering.
636 finishLayout(Layout);
638 DEBUG_WITH_TYPE("mc-dump", {
639 llvm::errs() << "assembler backend - final-layout\n--\n";
642 uint64_t StartOffset = OS.tell();
644 // Allow the object writer a chance to perform post-layout binding (for
645 // example, to set the index fields in the symbol data).
646 getWriter().ExecutePostLayoutBinding(*this, Layout);
648 // Evaluate and apply the fixups, generating relocation entries as necessary.
649 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
650 for (MCSectionData::iterator it2 = it->begin(),
651 ie2 = it->end(); it2 != ie2; ++it2) {
652 MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(it2);
654 for (MCEncodedFragment::fixup_iterator it3 = F->fixup_begin(),
655 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
656 MCFixup &Fixup = *it3;
657 uint64_t FixedValue = handleFixup(Layout, *F, Fixup);
658 getBackend().applyFixup(Fixup, F->getContents().data(),
659 F->getContents().size(), FixedValue);
665 // Write the object file.
666 getWriter().WriteObject(*this, Layout);
668 stats::ObjectBytes += OS.tell() - StartOffset;
671 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
672 const MCInstFragment *DF,
673 const MCAsmLayout &Layout) const {
674 // If we cannot resolve the fixup value, it requires relaxation.
677 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
680 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
683 bool MCAssembler::fragmentNeedsRelaxation(const MCInstFragment *IF,
684 const MCAsmLayout &Layout) const {
685 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
686 // are intentionally pushing out inst fragments, or because we relaxed a
687 // previous instruction to one that doesn't need relaxation.
688 if (!getBackend().mayNeedRelaxation(IF->getInst()))
691 for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
692 ie = IF->fixup_end(); it != ie; ++it)
693 if (fixupNeedsRelaxation(*it, IF, Layout))
699 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
700 MCInstFragment &IF) {
701 if (!fragmentNeedsRelaxation(&IF, Layout))
704 ++stats::RelaxedInstructions;
706 // FIXME-PERF: We could immediately lower out instructions if we can tell
707 // they are fully resolved, to avoid retesting on later passes.
709 // Relax the fragment.
712 getBackend().relaxInstruction(IF.getInst(), Relaxed);
714 // Encode the new instruction.
716 // FIXME-PERF: If it matters, we could let the target do this. It can
717 // probably do so more efficiently in many cases.
718 SmallVector<MCFixup, 4> Fixups;
719 SmallString<256> Code;
720 raw_svector_ostream VecOS(Code);
721 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
724 // Update the instruction fragment.
726 IF.getContents() = Code;
727 IF.getFixups() = Fixups;
732 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
734 uint64_t OldSize = LF.getContents().size();
735 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
738 SmallString<8> &Data = LF.getContents();
740 raw_svector_ostream OSE(Data);
742 encodeSLEB128(Value, OSE);
744 encodeULEB128(Value, OSE);
746 return OldSize != LF.getContents().size();
749 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
750 MCDwarfLineAddrFragment &DF) {
751 int64_t AddrDelta = 0;
752 uint64_t OldSize = DF.getContents().size();
753 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
757 LineDelta = DF.getLineDelta();
758 SmallString<8> &Data = DF.getContents();
760 raw_svector_ostream OSE(Data);
761 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
763 return OldSize != Data.size();
766 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
767 MCDwarfCallFrameFragment &DF) {
768 int64_t AddrDelta = 0;
769 uint64_t OldSize = DF.getContents().size();
770 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
773 SmallString<8> &Data = DF.getContents();
775 raw_svector_ostream OSE(Data);
776 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
778 return OldSize != Data.size();
781 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD) {
782 // Holds the first fragment which needed relaxing during this layout. It will
783 // remain NULL if none were relaxed.
784 // When a fragment is relaxed, all the fragments following it should get
785 // invalidated because their offset is going to change.
786 MCFragment *FirstRelaxedFragment = NULL;
788 // Attempt to relax all the fragments in the section.
789 for (MCSectionData::iterator I = SD.begin(), IE = SD.end(); I != IE; ++I) {
790 // Check if this is a fragment that needs relaxation.
791 bool RelaxedFrag = false;
792 switch(I->getKind()) {
795 case MCFragment::FT_Inst:
796 assert(!getRelaxAll() &&
797 "Did not expect a MCInstFragment in RelaxAll mode");
798 RelaxedFrag = relaxInstruction(Layout, *cast<MCInstFragment>(I));
800 case MCFragment::FT_Dwarf:
801 RelaxedFrag = relaxDwarfLineAddr(Layout,
802 *cast<MCDwarfLineAddrFragment>(I));
804 case MCFragment::FT_DwarfFrame:
806 relaxDwarfCallFrameFragment(Layout,
807 *cast<MCDwarfCallFrameFragment>(I));
809 case MCFragment::FT_LEB:
810 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
813 if (RelaxedFrag && !FirstRelaxedFragment)
814 FirstRelaxedFragment = I;
816 if (FirstRelaxedFragment) {
817 Layout.invalidateFragmentsAfter(FirstRelaxedFragment);
823 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
824 ++stats::RelaxationSteps;
826 bool WasRelaxed = false;
827 for (iterator it = begin(), ie = end(); it != ie; ++it) {
828 MCSectionData &SD = *it;
829 while (layoutSectionOnce(Layout, SD))
836 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
837 // The layout is done. Mark every fragment as valid.
838 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
839 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
847 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
848 OS << "<MCFixup" << " Offset:" << AF.getOffset()
849 << " Value:" << *AF.getValue()
850 << " Kind:" << AF.getKind() << ">";
856 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
857 void MCFragment::dump() {
858 raw_ostream &OS = llvm::errs();
862 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
863 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
864 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
865 case MCFragment::FT_Inst: OS << "MCInstFragment"; break;
866 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
867 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
868 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
869 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
872 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
873 << " Offset:" << Offset << ">";
876 case MCFragment::FT_Align: {
877 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
878 if (AF->hasEmitNops())
879 OS << " (emit nops)";
881 OS << " Alignment:" << AF->getAlignment()
882 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
883 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
886 case MCFragment::FT_Data: {
887 const MCDataFragment *DF = cast<MCDataFragment>(this);
890 const SmallVectorImpl<char> &Contents = DF->getContents();
891 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
893 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
895 OS << "] (" << Contents.size() << " bytes)";
897 if (DF->fixup_begin() != DF->fixup_end()) {
900 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
901 ie = DF->fixup_end(); it != ie; ++it) {
902 if (it != DF->fixup_begin()) OS << ",\n ";
909 case MCFragment::FT_Fill: {
910 const MCFillFragment *FF = cast<MCFillFragment>(this);
911 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
912 << " Size:" << FF->getSize();
915 case MCFragment::FT_Inst: {
916 const MCInstFragment *IF = cast<MCInstFragment>(this);
919 IF->getInst().dump_pretty(OS);
922 case MCFragment::FT_Org: {
923 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
925 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
928 case MCFragment::FT_Dwarf: {
929 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
931 OS << " AddrDelta:" << OF->getAddrDelta()
932 << " LineDelta:" << OF->getLineDelta();
935 case MCFragment::FT_DwarfFrame: {
936 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
938 OS << " AddrDelta:" << CF->getAddrDelta();
941 case MCFragment::FT_LEB: {
942 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
944 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
951 void MCSectionData::dump() {
952 raw_ostream &OS = llvm::errs();
954 OS << "<MCSectionData";
955 OS << " Alignment:" << getAlignment() << " Fragments:[\n ";
956 for (iterator it = begin(), ie = end(); it != ie; ++it) {
957 if (it != begin()) OS << ",\n ";
963 void MCSymbolData::dump() {
964 raw_ostream &OS = llvm::errs();
966 OS << "<MCSymbolData Symbol:" << getSymbol()
967 << " Fragment:" << getFragment() << " Offset:" << getOffset()
968 << " Flags:" << getFlags() << " Index:" << getIndex();
970 OS << " (common, size:" << getCommonSize()
971 << " align: " << getCommonAlignment() << ")";
974 if (isPrivateExtern())
975 OS << " (private extern)";
979 void MCAssembler::dump() {
980 raw_ostream &OS = llvm::errs();
982 OS << "<MCAssembler\n";
983 OS << " Sections:[\n ";
984 for (iterator it = begin(), ie = end(); it != ie; ++it) {
985 if (it != begin()) OS << ",\n ";
991 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
992 if (it != symbol_begin()) OS << ",\n ";
999 // anchors for MC*Fragment vtables
1000 void MCEncodedFragment::anchor() { }
1001 void MCDataFragment::anchor() { }
1002 void MCInstFragment::anchor() { }
1003 void MCAlignFragment::anchor() { }
1004 void MCFillFragment::anchor() { }
1005 void MCOrgFragment::anchor() { }
1006 void MCLEBFragment::anchor() { }
1007 void MCDwarfLineAddrFragment::anchor() { }
1008 void MCDwarfCallFrameFragment::anchor() { }