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 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
225 // Non-temporary labels should always be visible to the linker.
226 if (!Symbol.isTemporary())
229 // Absolute temporary labels are never visible.
230 if (!Symbol.isInSection())
233 // Otherwise, check if the section requires symbols even for temporary labels.
234 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
237 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
238 // Linker visible symbols define atoms.
239 if (isSymbolLinkerVisible(SD->getSymbol()))
242 // Absolute and undefined symbols have no defining atom.
243 if (!SD->getFragment())
246 // Non-linker visible symbols in sections which can't be atomized have no
248 if (!getBackend().isSectionAtomizable(
249 SD->getFragment()->getParent()->getSection()))
252 // Otherwise, return the atom for the containing fragment.
253 return SD->getFragment()->getAtom();
256 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
257 const MCFixup &Fixup, const MCFragment *DF,
258 MCValue &Target, uint64_t &Value) const {
259 ++stats::evaluateFixup;
261 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
262 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
264 bool IsPCRel = Backend.getFixupKindInfo(
265 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
269 if (Target.getSymB()) {
271 } else if (!Target.getSymA()) {
274 const MCSymbolRefExpr *A = Target.getSymA();
275 const MCSymbol &SA = A->getSymbol();
276 if (A->getKind() != MCSymbolRefExpr::VK_None ||
277 SA.AliasedSymbol().isUndefined()) {
280 const MCSymbolData &DataA = getSymbolData(SA);
282 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
287 IsResolved = Target.isAbsolute();
290 Value = Target.getConstant();
292 if (const MCSymbolRefExpr *A = Target.getSymA()) {
293 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
295 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
297 if (const MCSymbolRefExpr *B = Target.getSymB()) {
298 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
300 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
304 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
305 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
306 assert((ShouldAlignPC ? IsPCRel : true) &&
307 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
310 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
312 // A number of ARM fixups in Thumb mode require that the effective PC
313 // address be determined as the 32-bit aligned version of the actual offset.
314 if (ShouldAlignPC) Offset &= ~0x3;
318 // Let the backend adjust the fixup value if necessary, including whether
319 // we need a relocation.
320 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
326 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
327 const MCFragment &F) const {
328 switch (F.getKind()) {
329 case MCFragment::FT_Data:
330 return cast<MCDataFragment>(F).getContents().size();
331 case MCFragment::FT_Fill:
332 return cast<MCFillFragment>(F).getSize();
333 case MCFragment::FT_Inst:
334 return cast<MCInstFragment>(F).getInstSize();
336 case MCFragment::FT_LEB:
337 return cast<MCLEBFragment>(F).getContents().size();
339 case MCFragment::FT_Align: {
340 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
341 unsigned Offset = Layout.getFragmentOffset(&AF);
342 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
343 // If we are padding with nops, force the padding to be larger than the
345 if (Size > 0 && AF.hasEmitNops()) {
346 while (Size % getBackend().getMinimumNopSize())
347 Size += AF.getAlignment();
349 if (Size > AF.getMaxBytesToEmit())
354 case MCFragment::FT_Org: {
355 MCOrgFragment &OF = cast<MCOrgFragment>(F);
356 int64_t TargetLocation;
357 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
358 report_fatal_error("expected assembly-time absolute expression");
360 // FIXME: We need a way to communicate this error.
361 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
362 int64_t Size = TargetLocation - FragmentOffset;
363 if (Size < 0 || Size >= 0x40000000)
364 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
365 "' (at offset '" + Twine(FragmentOffset) + "')");
369 case MCFragment::FT_Dwarf:
370 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
371 case MCFragment::FT_DwarfFrame:
372 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
375 llvm_unreachable("invalid fragment kind");
378 void MCAsmLayout::layoutFragment(MCFragment *F) {
379 MCFragment *Prev = F->getPrevNode();
381 // We should never try to recompute something which is valid.
382 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
383 // We should never try to compute the fragment layout if its predecessor
385 assert((!Prev || isFragmentValid(Prev)) &&
386 "Attempt to compute fragment before its predecessor!");
388 ++stats::FragmentLayouts;
390 // Compute fragment offset and size.
393 Offset += Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
396 LastValidFragment[F->getParent()] = F;
399 /// \brief Write the contents of a fragment to the given object writer. Expects
400 /// a MCEncodedFragment.
401 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
402 MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
403 OW->WriteBytes(EF.getContents());
406 /// \brief Write the fragment \p F to the output file.
407 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
408 const MCFragment &F) {
409 MCObjectWriter *OW = &Asm.getWriter();
410 uint64_t Start = OW->getStream().tell();
413 ++stats::EmittedFragments;
415 // FIXME: Embed in fragments instead?
416 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
417 switch (F.getKind()) {
418 case MCFragment::FT_Align: {
419 ++stats::EmittedAlignFragments;
420 MCAlignFragment &AF = cast<MCAlignFragment>(F);
421 uint64_t Count = FragmentSize / AF.getValueSize();
423 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
425 // FIXME: This error shouldn't actually occur (the front end should emit
426 // multiple .align directives to enforce the semantics it wants), but is
427 // severe enough that we want to report it. How to handle this?
428 if (Count * AF.getValueSize() != FragmentSize)
429 report_fatal_error("undefined .align directive, value size '" +
430 Twine(AF.getValueSize()) +
431 "' is not a divisor of padding size '" +
432 Twine(FragmentSize) + "'");
434 // See if we are aligning with nops, and if so do that first to try to fill
435 // the Count bytes. Then if that did not fill any bytes or there are any
436 // bytes left to fill use the Value and ValueSize to fill the rest.
437 // If we are aligning with nops, ask that target to emit the right data.
438 if (AF.hasEmitNops()) {
439 if (!Asm.getBackend().writeNopData(Count, OW))
440 report_fatal_error("unable to write nop sequence of " +
441 Twine(Count) + " bytes");
445 // Otherwise, write out in multiples of the value size.
446 for (uint64_t i = 0; i != Count; ++i) {
447 switch (AF.getValueSize()) {
448 default: llvm_unreachable("Invalid size!");
449 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
450 case 2: OW->Write16(uint16_t(AF.getValue())); break;
451 case 4: OW->Write32(uint32_t(AF.getValue())); break;
452 case 8: OW->Write64(uint64_t(AF.getValue())); break;
458 case MCFragment::FT_Data:
459 ++stats::EmittedDataFragments;
460 writeFragmentContents(F, OW);
463 case MCFragment::FT_Inst:
464 ++stats::EmittedInstFragments;
465 writeFragmentContents(F, OW);
468 case MCFragment::FT_Fill: {
469 ++stats::EmittedFillFragments;
470 MCFillFragment &FF = cast<MCFillFragment>(F);
472 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
474 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
475 switch (FF.getValueSize()) {
476 default: llvm_unreachable("Invalid size!");
477 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
478 case 2: OW->Write16(uint16_t(FF.getValue())); break;
479 case 4: OW->Write32(uint32_t(FF.getValue())); break;
480 case 8: OW->Write64(uint64_t(FF.getValue())); break;
486 case MCFragment::FT_LEB: {
487 MCLEBFragment &LF = cast<MCLEBFragment>(F);
488 OW->WriteBytes(LF.getContents().str());
492 case MCFragment::FT_Org: {
493 ++stats::EmittedOrgFragments;
494 MCOrgFragment &OF = cast<MCOrgFragment>(F);
496 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
497 OW->Write8(uint8_t(OF.getValue()));
502 case MCFragment::FT_Dwarf: {
503 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
504 OW->WriteBytes(OF.getContents().str());
507 case MCFragment::FT_DwarfFrame: {
508 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
509 OW->WriteBytes(CF.getContents().str());
514 assert(OW->getStream().tell() - Start == FragmentSize);
517 void MCAssembler::writeSectionData(const MCSectionData *SD,
518 const MCAsmLayout &Layout) const {
519 // Ignore virtual sections.
520 if (SD->getSection().isVirtualSection()) {
521 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
523 // Check that contents are only things legal inside a virtual section.
524 for (MCSectionData::const_iterator it = SD->begin(),
525 ie = SD->end(); it != ie; ++it) {
526 switch (it->getKind()) {
527 default: llvm_unreachable("Invalid fragment in virtual section!");
528 case MCFragment::FT_Data: {
529 // Check that we aren't trying to write a non-zero contents (or fixups)
530 // into a virtual section. This is to support clients which use standard
531 // directives to fill the contents of virtual sections.
532 MCDataFragment &DF = cast<MCDataFragment>(*it);
533 assert(DF.fixup_begin() == DF.fixup_end() &&
534 "Cannot have fixups in virtual section!");
535 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
536 assert(DF.getContents()[i] == 0 &&
537 "Invalid data value for virtual section!");
540 case MCFragment::FT_Align:
541 // Check that we aren't trying to write a non-zero value into a virtual
543 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
544 !cast<MCAlignFragment>(it)->getValue()) &&
545 "Invalid align in virtual section!");
547 case MCFragment::FT_Fill:
548 assert(!cast<MCFillFragment>(it)->getValueSize() &&
549 "Invalid fill in virtual section!");
557 uint64_t Start = getWriter().getStream().tell();
560 for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
562 writeFragment(*this, Layout, *it);
564 assert(getWriter().getStream().tell() - Start ==
565 Layout.getSectionAddressSize(SD));
569 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
571 const MCFixup &Fixup) {
572 // Evaluate the fixup.
575 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
576 // The fixup was unresolved, we need a relocation. Inform the object
577 // writer of the relocation, and give it an opportunity to adjust the
578 // fixup value if need be.
579 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
584 void MCAssembler::Finish() {
585 DEBUG_WITH_TYPE("mc-dump", {
586 llvm::errs() << "assembler backend - pre-layout\n--\n";
589 // Create the layout object.
590 MCAsmLayout Layout(*this);
592 // Create dummy fragments and assign section ordinals.
593 unsigned SectionIndex = 0;
594 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
595 // Create dummy fragments to eliminate any empty sections, this simplifies
597 if (it->getFragmentList().empty())
598 new MCDataFragment(it);
600 it->setOrdinal(SectionIndex++);
603 // Assign layout order indices to sections and fragments.
604 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
605 MCSectionData *SD = Layout.getSectionOrder()[i];
606 SD->setLayoutOrder(i);
608 unsigned FragmentIndex = 0;
609 for (MCSectionData::iterator iFrag = SD->begin(), iFragEnd = SD->end();
610 iFrag != iFragEnd; ++iFrag)
611 iFrag->setLayoutOrder(FragmentIndex++);
614 // Layout until everything fits.
615 while (layoutOnce(Layout))
618 DEBUG_WITH_TYPE("mc-dump", {
619 llvm::errs() << "assembler backend - post-relaxation\n--\n";
622 // Finalize the layout, including fragment lowering.
623 finishLayout(Layout);
625 DEBUG_WITH_TYPE("mc-dump", {
626 llvm::errs() << "assembler backend - final-layout\n--\n";
629 uint64_t StartOffset = OS.tell();
631 // Allow the object writer a chance to perform post-layout binding (for
632 // example, to set the index fields in the symbol data).
633 getWriter().ExecutePostLayoutBinding(*this, Layout);
635 // Evaluate and apply the fixups, generating relocation entries as necessary.
636 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
637 for (MCSectionData::iterator it2 = it->begin(),
638 ie2 = it->end(); it2 != ie2; ++it2) {
639 MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(it2);
641 for (MCEncodedFragment::fixup_iterator it3 = F->fixup_begin(),
642 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
643 MCFixup &Fixup = *it3;
644 uint64_t FixedValue = handleFixup(Layout, *F, Fixup);
645 getBackend().applyFixup(Fixup, F->getContents().data(),
646 F->getContents().size(), FixedValue);
652 // Write the object file.
653 getWriter().WriteObject(*this, Layout);
655 stats::ObjectBytes += OS.tell() - StartOffset;
658 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
659 const MCInstFragment *DF,
660 const MCAsmLayout &Layout) const {
661 // If we cannot resolve the fixup value, it requires relaxation.
664 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
667 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
670 bool MCAssembler::fragmentNeedsRelaxation(const MCInstFragment *IF,
671 const MCAsmLayout &Layout) const {
672 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
673 // are intentionally pushing out inst fragments, or because we relaxed a
674 // previous instruction to one that doesn't need relaxation.
675 if (!getBackend().mayNeedRelaxation(IF->getInst()))
678 for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
679 ie = IF->fixup_end(); it != ie; ++it)
680 if (fixupNeedsRelaxation(*it, IF, Layout))
686 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
687 MCInstFragment &IF) {
688 if (!fragmentNeedsRelaxation(&IF, Layout))
691 ++stats::RelaxedInstructions;
693 // FIXME-PERF: We could immediately lower out instructions if we can tell
694 // they are fully resolved, to avoid retesting on later passes.
696 // Relax the fragment.
699 getBackend().relaxInstruction(IF.getInst(), Relaxed);
701 // Encode the new instruction.
703 // FIXME-PERF: If it matters, we could let the target do this. It can
704 // probably do so more efficiently in many cases.
705 SmallVector<MCFixup, 4> Fixups;
706 SmallString<256> Code;
707 raw_svector_ostream VecOS(Code);
708 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
711 // Update the instruction fragment.
713 IF.getContents() = Code;
714 IF.getFixups() = Fixups;
719 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
721 uint64_t OldSize = LF.getContents().size();
722 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
725 SmallString<8> &Data = LF.getContents();
727 raw_svector_ostream OSE(Data);
729 encodeSLEB128(Value, OSE);
731 encodeULEB128(Value, OSE);
733 return OldSize != LF.getContents().size();
736 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
737 MCDwarfLineAddrFragment &DF) {
738 int64_t AddrDelta = 0;
739 uint64_t OldSize = DF.getContents().size();
740 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
744 LineDelta = DF.getLineDelta();
745 SmallString<8> &Data = DF.getContents();
747 raw_svector_ostream OSE(Data);
748 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
750 return OldSize != Data.size();
753 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
754 MCDwarfCallFrameFragment &DF) {
755 int64_t AddrDelta = 0;
756 uint64_t OldSize = DF.getContents().size();
757 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
760 SmallString<8> &Data = DF.getContents();
762 raw_svector_ostream OSE(Data);
763 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
765 return OldSize != Data.size();
768 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD) {
769 // Holds the first fragment which needed relaxing during this layout. It will
770 // remain NULL if none were relaxed.
771 // When a fragment is relaxed, all the fragments following it should get
772 // invalidated because their offset is going to change.
773 MCFragment *FirstRelaxedFragment = NULL;
775 // Attempt to relax all the fragments in the section.
776 for (MCSectionData::iterator I = SD.begin(), IE = SD.end(); I != IE; ++I) {
777 // Check if this is a fragment that needs relaxation.
778 bool RelaxedFrag = false;
779 switch(I->getKind()) {
782 case MCFragment::FT_Inst:
783 assert(!getRelaxAll() &&
784 "Did not expect a MCInstFragment in RelaxAll mode");
785 RelaxedFrag = relaxInstruction(Layout, *cast<MCInstFragment>(I));
787 case MCFragment::FT_Dwarf:
788 RelaxedFrag = relaxDwarfLineAddr(Layout,
789 *cast<MCDwarfLineAddrFragment>(I));
791 case MCFragment::FT_DwarfFrame:
793 relaxDwarfCallFrameFragment(Layout,
794 *cast<MCDwarfCallFrameFragment>(I));
796 case MCFragment::FT_LEB:
797 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
800 if (RelaxedFrag && !FirstRelaxedFragment)
801 FirstRelaxedFragment = I;
803 if (FirstRelaxedFragment) {
804 Layout.invalidateFragmentsAfter(FirstRelaxedFragment);
810 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
811 ++stats::RelaxationSteps;
813 bool WasRelaxed = false;
814 for (iterator it = begin(), ie = end(); it != ie; ++it) {
815 MCSectionData &SD = *it;
816 while (layoutSectionOnce(Layout, SD))
823 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
824 // The layout is done. Mark every fragment as valid.
825 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
826 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
834 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
835 OS << "<MCFixup" << " Offset:" << AF.getOffset()
836 << " Value:" << *AF.getValue()
837 << " Kind:" << AF.getKind() << ">";
843 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
844 void MCFragment::dump() {
845 raw_ostream &OS = llvm::errs();
849 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
850 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
851 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
852 case MCFragment::FT_Inst: OS << "MCInstFragment"; break;
853 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
854 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
855 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
856 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
859 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
860 << " Offset:" << Offset << ">";
863 case MCFragment::FT_Align: {
864 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
865 if (AF->hasEmitNops())
866 OS << " (emit nops)";
868 OS << " Alignment:" << AF->getAlignment()
869 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
870 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
873 case MCFragment::FT_Data: {
874 const MCDataFragment *DF = cast<MCDataFragment>(this);
877 const SmallVectorImpl<char> &Contents = DF->getContents();
878 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
880 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
882 OS << "] (" << Contents.size() << " bytes)";
884 if (DF->fixup_begin() != DF->fixup_end()) {
887 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
888 ie = DF->fixup_end(); it != ie; ++it) {
889 if (it != DF->fixup_begin()) OS << ",\n ";
896 case MCFragment::FT_Fill: {
897 const MCFillFragment *FF = cast<MCFillFragment>(this);
898 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
899 << " Size:" << FF->getSize();
902 case MCFragment::FT_Inst: {
903 const MCInstFragment *IF = cast<MCInstFragment>(this);
906 IF->getInst().dump_pretty(OS);
909 case MCFragment::FT_Org: {
910 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
912 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
915 case MCFragment::FT_Dwarf: {
916 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
918 OS << " AddrDelta:" << OF->getAddrDelta()
919 << " LineDelta:" << OF->getLineDelta();
922 case MCFragment::FT_DwarfFrame: {
923 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
925 OS << " AddrDelta:" << CF->getAddrDelta();
928 case MCFragment::FT_LEB: {
929 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
931 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
938 void MCSectionData::dump() {
939 raw_ostream &OS = llvm::errs();
941 OS << "<MCSectionData";
942 OS << " Alignment:" << getAlignment() << " Fragments:[\n ";
943 for (iterator it = begin(), ie = end(); it != ie; ++it) {
944 if (it != begin()) OS << ",\n ";
950 void MCSymbolData::dump() {
951 raw_ostream &OS = llvm::errs();
953 OS << "<MCSymbolData Symbol:" << getSymbol()
954 << " Fragment:" << getFragment() << " Offset:" << getOffset()
955 << " Flags:" << getFlags() << " Index:" << getIndex();
957 OS << " (common, size:" << getCommonSize()
958 << " align: " << getCommonAlignment() << ")";
961 if (isPrivateExtern())
962 OS << " (private extern)";
966 void MCAssembler::dump() {
967 raw_ostream &OS = llvm::errs();
969 OS << "<MCAssembler\n";
970 OS << " Sections:[\n ";
971 for (iterator it = begin(), ie = end(); it != ie; ++it) {
972 if (it != begin()) OS << ",\n ";
978 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
979 if (it != symbol_begin()) OS << ",\n ";
986 // anchors for MC*Fragment vtables
987 void MCEncodedFragment::anchor() { }
988 void MCDataFragment::anchor() { }
989 void MCInstFragment::anchor() { }
990 void MCAlignFragment::anchor() { }
991 void MCFillFragment::anchor() { }
992 void MCOrgFragment::anchor() { }
993 void MCLEBFragment::anchor() { }
994 void MCDwarfLineAddrFragment::anchor() { }
995 void MCDwarfCallFrameFragment::anchor() { }