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/MC/MCAsmLayout.h"
13 #include "llvm/MC/MCCodeEmitter.h"
14 #include "llvm/MC/MCExpr.h"
15 #include "llvm/MC/MCObjectWriter.h"
16 #include "llvm/MC/MCSection.h"
17 #include "llvm/MC/MCSymbol.h"
18 #include "llvm/MC/MCValue.h"
19 #include "llvm/MC/MCDwarf.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetRegistry.h"
28 #include "llvm/Target/TargetAsmBackend.h"
35 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
36 STATISTIC(EvaluateFixup, "Number of evaluated fixups");
37 STATISTIC(FragmentLayouts, "Number of fragment layouts");
38 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
39 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
40 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
44 // FIXME FIXME FIXME: There are number of places in this file where we convert
45 // what is a 64-bit assembler value used for computation into a value in the
46 // object file, which may truncate it. We should detect that truncation where
47 // invalid and report errors back.
51 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
52 : Assembler(Asm), LastValidFragment()
54 // Compute the section layout order. Virtual sections must go last.
55 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
56 if (!it->getSection().isVirtualSection())
57 SectionOrder.push_back(&*it);
58 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
59 if (it->getSection().isVirtualSection())
60 SectionOrder.push_back(&*it);
63 bool MCAsmLayout::isFragmentUpToDate(const MCFragment *F) const {
64 const MCSectionData &SD = *F->getParent();
65 const MCFragment *LastValid = LastValidFragment.lookup(&SD);
68 assert(LastValid->getParent() == F->getParent());
69 return F->getLayoutOrder() <= LastValid->getLayoutOrder();
72 void MCAsmLayout::Invalidate(MCFragment *F) {
73 // If this fragment wasn't already up-to-date, we don't need to do anything.
74 if (!isFragmentUpToDate(F))
77 // Otherwise, reset the last valid fragment to the predecessor of the
78 // invalidated fragment.
79 const MCSectionData &SD = *F->getParent();
80 LastValidFragment[&SD] = F->getPrevNode();
83 void MCAsmLayout::EnsureValid(const MCFragment *F) const {
84 MCSectionData &SD = *F->getParent();
86 MCFragment *Cur = LastValidFragment[&SD];
90 Cur = Cur->getNextNode();
92 // Advance the layout position until the fragment is up-to-date.
93 while (!isFragmentUpToDate(F)) {
94 const_cast<MCAsmLayout*>(this)->LayoutFragment(Cur);
95 Cur = Cur->getNextNode();
99 uint64_t MCAsmLayout::getFragmentEffectiveSize(const MCFragment *F) const {
101 assert(F->EffectiveSize != ~UINT64_C(0) && "Address not set!");
102 return F->EffectiveSize;
105 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
107 assert(F->Offset != ~UINT64_C(0) && "Address not set!");
111 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData *SD) const {
112 assert(SD->getFragment() && "Invalid getOffset() on undefined symbol!");
113 return getFragmentOffset(SD->getFragment()) + SD->getOffset();
116 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
117 // The size is the last fragment's end offset.
118 const MCFragment &F = SD->getFragmentList().back();
119 return getFragmentOffset(&F) + getFragmentEffectiveSize(&F);
122 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
123 // Virtual sections have no file size.
124 if (SD->getSection().isVirtualSection())
127 // Otherwise, the file size is the same as the address space size.
128 return getSectionAddressSize(SD);
133 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
136 MCFragment::~MCFragment() {
139 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
140 : Kind(_Kind), Parent(_Parent), Atom(0), Offset(~UINT64_C(0)),
141 EffectiveSize(~UINT64_C(0))
144 Parent->getFragmentList().push_back(this);
149 MCSectionData::MCSectionData() : Section(0) {}
151 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
152 : Section(&_Section),
153 Ordinal(~UINT32_C(0)),
155 HasInstructions(false)
158 A->getSectionList().push_back(this);
163 MCSymbolData::MCSymbolData() : Symbol(0) {}
165 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
166 uint64_t _Offset, MCAssembler *A)
167 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
168 IsExternal(false), IsPrivateExtern(false),
169 CommonSize(0), SymbolSize(0), CommonAlign(0),
173 A->getSymbolList().push_back(this);
178 MCAssembler::MCAssembler(MCContext &_Context, TargetAsmBackend &_Backend,
179 MCCodeEmitter &_Emitter, raw_ostream &_OS)
180 : Context(_Context), Backend(_Backend), Emitter(_Emitter),
181 OS(_OS), RelaxAll(false), SubsectionsViaSymbols(false)
185 MCAssembler::~MCAssembler() {
188 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
189 // Non-temporary labels should always be visible to the linker.
190 if (!Symbol.isTemporary())
193 // Absolute temporary labels are never visible.
194 if (!Symbol.isInSection())
197 // Otherwise, check if the section requires symbols even for temporary labels.
198 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
201 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
202 // Linker visible symbols define atoms.
203 if (isSymbolLinkerVisible(SD->getSymbol()))
206 // Absolute and undefined symbols have no defining atom.
207 if (!SD->getFragment())
210 // Non-linker visible symbols in sections which can't be atomized have no
212 if (!getBackend().isSectionAtomizable(
213 SD->getFragment()->getParent()->getSection()))
216 // Otherwise, return the atom for the containing fragment.
217 return SD->getFragment()->getAtom();
220 bool MCAssembler::EvaluateFixup(const MCObjectWriter &Writer,
221 const MCAsmLayout &Layout,
222 const MCFixup &Fixup, const MCFragment *DF,
223 MCValue &Target, uint64_t &Value) const {
224 ++stats::EvaluateFixup;
226 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, &Layout))
227 report_fatal_error("expected relocatable expression");
229 // FIXME: How do non-scattered symbols work in ELF? I presume the linker
230 // doesn't support small relocations, but then under what criteria does the
231 // assembler allow symbol differences?
233 Value = Target.getConstant();
235 bool IsPCRel = Emitter.getFixupKindInfo(
236 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
237 bool IsResolved = true;
238 if (const MCSymbolRefExpr *A = Target.getSymA()) {
239 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
241 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
245 if (const MCSymbolRefExpr *B = Target.getSymB()) {
246 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
248 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
254 IsResolved = Writer.IsFixupFullyResolved(*this, Target, IsPCRel, DF);
257 Value -= Layout.getFragmentOffset(DF) + Fixup.getOffset();
262 uint64_t MCAssembler::ComputeFragmentSize(const MCFragment &F,
263 uint64_t FragmentOffset) const {
264 switch (F.getKind()) {
265 case MCFragment::FT_Data:
266 return cast<MCDataFragment>(F).getContents().size();
267 case MCFragment::FT_Fill:
268 return cast<MCFillFragment>(F).getSize();
269 case MCFragment::FT_Inst:
270 return cast<MCInstFragment>(F).getInstSize();
272 case MCFragment::FT_LEB:
273 return cast<MCLEBFragment>(F).getContents().size();
275 case MCFragment::FT_Align: {
276 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
278 uint64_t Size = OffsetToAlignment(FragmentOffset, AF.getAlignment());
280 // Honor MaxBytesToEmit.
281 if (Size > AF.getMaxBytesToEmit())
287 case MCFragment::FT_Org:
288 return cast<MCOrgFragment>(F).getSize();
290 case MCFragment::FT_Dwarf:
291 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
294 assert(0 && "invalid fragment kind");
298 void MCAsmLayout::LayoutFragment(MCFragment *F) {
299 MCFragment *Prev = F->getPrevNode();
301 // We should never try to recompute something which is up-to-date.
302 assert(!isFragmentUpToDate(F) && "Attempt to recompute up-to-date fragment!");
303 // We should never try to compute the fragment layout if it's predecessor
305 assert((!Prev || isFragmentUpToDate(Prev)) &&
306 "Attempt to compute fragment before it's predecessor!");
308 ++stats::FragmentLayouts;
310 // Compute fragment offset and size.
313 Offset += Prev->Offset + Prev->EffectiveSize;
316 F->EffectiveSize = getAssembler().ComputeFragmentSize(*F, F->Offset);
317 LastValidFragment[F->getParent()] = F;
320 /// WriteFragmentData - Write the \arg F data to the output file.
321 static void WriteFragmentData(const MCAssembler &Asm, const MCAsmLayout &Layout,
322 const MCFragment &F, MCObjectWriter *OW) {
323 uint64_t Start = OW->getStream().tell();
326 ++stats::EmittedFragments;
328 // FIXME: Embed in fragments instead?
329 uint64_t FragmentSize = Layout.getFragmentEffectiveSize(&F);
330 switch (F.getKind()) {
331 case MCFragment::FT_Align: {
332 MCAlignFragment &AF = cast<MCAlignFragment>(F);
333 uint64_t Count = FragmentSize / AF.getValueSize();
335 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
337 // FIXME: This error shouldn't actually occur (the front end should emit
338 // multiple .align directives to enforce the semantics it wants), but is
339 // severe enough that we want to report it. How to handle this?
340 if (Count * AF.getValueSize() != FragmentSize)
341 report_fatal_error("undefined .align directive, value size '" +
342 Twine(AF.getValueSize()) +
343 "' is not a divisor of padding size '" +
344 Twine(FragmentSize) + "'");
346 // See if we are aligning with nops, and if so do that first to try to fill
347 // the Count bytes. Then if that did not fill any bytes or there are any
348 // bytes left to fill use the the Value and ValueSize to fill the rest.
349 // If we are aligning with nops, ask that target to emit the right data.
350 if (AF.hasEmitNops()) {
351 if (!Asm.getBackend().WriteNopData(Count, OW))
352 report_fatal_error("unable to write nop sequence of " +
353 Twine(Count) + " bytes");
357 // Otherwise, write out in multiples of the value size.
358 for (uint64_t i = 0; i != Count; ++i) {
359 switch (AF.getValueSize()) {
361 assert(0 && "Invalid size!");
362 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
363 case 2: OW->Write16(uint16_t(AF.getValue())); break;
364 case 4: OW->Write32(uint32_t(AF.getValue())); break;
365 case 8: OW->Write64(uint64_t(AF.getValue())); break;
371 case MCFragment::FT_Data: {
372 MCDataFragment &DF = cast<MCDataFragment>(F);
373 assert(FragmentSize == DF.getContents().size() && "Invalid size!");
374 OW->WriteBytes(DF.getContents().str());
378 case MCFragment::FT_Fill: {
379 MCFillFragment &FF = cast<MCFillFragment>(F);
381 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
383 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
384 switch (FF.getValueSize()) {
386 assert(0 && "Invalid size!");
387 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
388 case 2: OW->Write16(uint16_t(FF.getValue())); break;
389 case 4: OW->Write32(uint32_t(FF.getValue())); break;
390 case 8: OW->Write64(uint64_t(FF.getValue())); break;
396 case MCFragment::FT_Inst: {
397 MCInstFragment &IF = cast<MCInstFragment>(F);
398 OW->WriteBytes(StringRef(IF.getCode().begin(), IF.getCode().size()));
402 case MCFragment::FT_LEB: {
403 MCLEBFragment &LF = cast<MCLEBFragment>(F);
404 OW->WriteBytes(LF.getContents().str());
408 case MCFragment::FT_Org: {
409 MCOrgFragment &OF = cast<MCOrgFragment>(F);
411 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
412 OW->Write8(uint8_t(OF.getValue()));
417 case MCFragment::FT_Dwarf: {
418 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
419 OW->WriteBytes(OF.getContents().str());
424 assert(OW->getStream().tell() - Start == FragmentSize);
427 void MCAssembler::WriteSectionData(const MCSectionData *SD,
428 const MCAsmLayout &Layout,
429 MCObjectWriter *OW) const {
430 // Ignore virtual sections.
431 if (SD->getSection().isVirtualSection()) {
432 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
434 // Check that contents are only things legal inside a virtual section.
435 for (MCSectionData::const_iterator it = SD->begin(),
436 ie = SD->end(); it != ie; ++it) {
437 switch (it->getKind()) {
439 assert(0 && "Invalid fragment in virtual section!");
440 case MCFragment::FT_Data: {
441 // Check that we aren't trying to write a non-zero contents (or fixups)
442 // into a virtual section. This is to support clients which use standard
443 // directives to fill the contents of virtual sections.
444 MCDataFragment &DF = cast<MCDataFragment>(*it);
445 assert(DF.fixup_begin() == DF.fixup_end() &&
446 "Cannot have fixups in virtual section!");
447 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
448 assert(DF.getContents()[i] == 0 &&
449 "Invalid data value for virtual section!");
452 case MCFragment::FT_Align:
453 // Check that we aren't trying to write a non-zero value into a virtual
455 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
456 !cast<MCAlignFragment>(it)->getValue()) &&
457 "Invalid align in virtual section!");
459 case MCFragment::FT_Fill:
460 assert(!cast<MCFillFragment>(it)->getValueSize() &&
461 "Invalid fill in virtual section!");
469 uint64_t Start = OW->getStream().tell();
472 for (MCSectionData::const_iterator it = SD->begin(),
473 ie = SD->end(); it != ie; ++it)
474 WriteFragmentData(*this, Layout, *it, OW);
476 assert(OW->getStream().tell() - Start == Layout.getSectionAddressSize(SD));
480 uint64_t MCAssembler::HandleFixup(MCObjectWriter &Writer,
481 const MCAsmLayout &Layout,
483 const MCFixup &Fixup) {
484 // Evaluate the fixup.
487 if (!EvaluateFixup(Writer, Layout, Fixup, &F, Target, FixedValue)) {
488 // The fixup was unresolved, we need a relocation. Inform the object
489 // writer of the relocation, and give it an opportunity to adjust the
490 // fixup value if need be.
491 Writer.RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
496 void MCAssembler::Finish(MCObjectWriter *Writer) {
497 DEBUG_WITH_TYPE("mc-dump", {
498 llvm::errs() << "assembler backend - pre-layout\n--\n";
501 // Create the layout object.
502 MCAsmLayout Layout(*this);
506 // Create dummy fragments and assign section ordinals.
507 unsigned SectionIndex = 0;
508 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
509 // Create dummy fragments to eliminate any empty sections, this simplifies
511 if (it->getFragmentList().empty())
512 new MCDataFragment(it);
514 it->setOrdinal(SectionIndex++);
517 // Assign layout order indices to sections and fragments.
518 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
519 MCSectionData *SD = Layout.getSectionOrder()[i];
520 SD->setLayoutOrder(i);
522 unsigned FragmentIndex = 0;
523 for (MCSectionData::iterator it2 = SD->begin(),
524 ie2 = SD->end(); it2 != ie2; ++it2)
525 it2->setLayoutOrder(FragmentIndex++);
528 llvm::OwningPtr<MCObjectWriter> OwnWriter(0);
530 //no custom Writer_ : create the default one life-managed by OwningPtr
531 OwnWriter.reset(getBackend().createObjectWriter(OS));
532 Writer = OwnWriter.get();
534 report_fatal_error("unable to create object writer!");
537 // Layout until everything fits.
538 while (LayoutOnce(*Writer, Layout))
541 DEBUG_WITH_TYPE("mc-dump", {
542 llvm::errs() << "assembler backend - post-relaxation\n--\n";
545 // Finalize the layout, including fragment lowering.
546 FinishLayout(Layout);
548 DEBUG_WITH_TYPE("mc-dump", {
549 llvm::errs() << "assembler backend - final-layout\n--\n";
552 uint64_t StartOffset = OS.tell();
554 // Allow the object writer a chance to perform post-layout binding (for
555 // example, to set the index fields in the symbol data).
556 Writer->ExecutePostLayoutBinding(*this, Layout);
558 // Evaluate and apply the fixups, generating relocation entries as necessary.
559 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
560 for (MCSectionData::iterator it2 = it->begin(),
561 ie2 = it->end(); it2 != ie2; ++it2) {
562 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
564 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
565 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
566 MCFixup &Fixup = *it3;
567 uint64_t FixedValue = HandleFixup(*Writer, Layout, *DF, Fixup);
568 getBackend().ApplyFixup(Fixup, DF->getContents().data(),
569 DF->getContents().size(), FixedValue);
572 MCInstFragment *IF = dyn_cast<MCInstFragment>(it2);
574 for (MCInstFragment::fixup_iterator it3 = IF->fixup_begin(),
575 ie3 = IF->fixup_end(); it3 != ie3; ++it3) {
576 MCFixup &Fixup = *it3;
577 uint64_t FixedValue = HandleFixup(*Writer, Layout, *IF, Fixup);
578 getBackend().ApplyFixup(Fixup, IF->getCode().data(),
579 IF->getCode().size(), FixedValue);
585 // Write the object file.
586 Writer->WriteObject(*this, Layout);
588 stats::ObjectBytes += OS.tell() - StartOffset;
591 bool MCAssembler::FixupNeedsRelaxation(const MCObjectWriter &Writer,
592 const MCFixup &Fixup,
593 const MCFragment *DF,
594 const MCAsmLayout &Layout) const {
598 // If we cannot resolve the fixup value, it requires relaxation.
601 if (!EvaluateFixup(Writer, Layout, Fixup, DF, Target, Value))
604 // Otherwise, relax if the value is too big for a (signed) i8.
606 // FIXME: This is target dependent!
607 return int64_t(Value) != int64_t(int8_t(Value));
610 bool MCAssembler::FragmentNeedsRelaxation(const MCObjectWriter &Writer,
611 const MCInstFragment *IF,
612 const MCAsmLayout &Layout) const {
613 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
614 // are intentionally pushing out inst fragments, or because we relaxed a
615 // previous instruction to one that doesn't need relaxation.
616 if (!getBackend().MayNeedRelaxation(IF->getInst()))
619 for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
620 ie = IF->fixup_end(); it != ie; ++it)
621 if (FixupNeedsRelaxation(Writer, *it, IF, Layout))
627 bool MCAssembler::RelaxInstruction(const MCObjectWriter &Writer,
629 MCInstFragment &IF) {
630 if (!FragmentNeedsRelaxation(Writer, &IF, Layout))
633 ++stats::RelaxedInstructions;
635 // FIXME-PERF: We could immediately lower out instructions if we can tell
636 // they are fully resolved, to avoid retesting on later passes.
638 // Relax the fragment.
641 getBackend().RelaxInstruction(IF.getInst(), Relaxed);
643 // Encode the new instruction.
645 // FIXME-PERF: If it matters, we could let the target do this. It can
646 // probably do so more efficiently in many cases.
647 SmallVector<MCFixup, 4> Fixups;
648 SmallString<256> Code;
649 raw_svector_ostream VecOS(Code);
650 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
653 // Update the instruction fragment.
656 IF.getFixups().clear();
657 // FIXME: Eliminate copy.
658 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
659 IF.getFixups().push_back(Fixups[i]);
664 bool MCAssembler::RelaxOrg(const MCObjectWriter &Writer,
667 int64_t TargetLocation;
668 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
669 report_fatal_error("expected assembly-time absolute expression");
671 // FIXME: We need a way to communicate this error.
672 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
673 int64_t Offset = TargetLocation - FragmentOffset;
674 if (Offset < 0 || Offset >= 0x40000000)
675 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
676 "' (at offset '" + Twine(FragmentOffset) + "')");
678 unsigned OldSize = OF.getSize();
680 return OldSize != OF.getSize();
683 bool MCAssembler::RelaxLEB(const MCObjectWriter &Writer,
687 uint64_t OldSize = LF.getContents().size();
688 LF.getValue().EvaluateAsAbsolute(Value, Layout);
689 SmallString<8> &Data = LF.getContents();
691 raw_svector_ostream OSE(Data);
693 MCObjectWriter::EncodeSLEB128(Value, OSE);
695 MCObjectWriter::EncodeULEB128(Value, OSE);
697 return OldSize != LF.getContents().size();
700 bool MCAssembler::RelaxDwarfLineAddr(const MCObjectWriter &Writer,
702 MCDwarfLineAddrFragment &DF) {
703 int64_t AddrDelta = 0;
704 uint64_t OldSize = DF.getContents().size();
705 DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
707 LineDelta = DF.getLineDelta();
708 SmallString<8> &Data = DF.getContents();
710 raw_svector_ostream OSE(Data);
711 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
713 return OldSize != Data.size();
716 bool MCAssembler::LayoutOnce(const MCObjectWriter &Writer,
717 MCAsmLayout &Layout) {
718 ++stats::RelaxationSteps;
720 // Scan for fragments that need relaxation.
721 bool WasRelaxed = false;
722 for (iterator it = begin(), ie = end(); it != ie; ++it) {
723 MCSectionData &SD = *it;
725 for (MCSectionData::iterator it2 = SD.begin(),
726 ie2 = SD.end(); it2 != ie2; ++it2) {
727 // Check if this is an fragment that needs relaxation.
728 bool relaxedFrag = false;
729 switch(it2->getKind()) {
732 case MCFragment::FT_Inst:
733 relaxedFrag = RelaxInstruction(Writer, Layout,
734 *cast<MCInstFragment>(it2));
736 case MCFragment::FT_Org:
737 relaxedFrag = RelaxOrg(Writer, Layout, *cast<MCOrgFragment>(it2));
739 case MCFragment::FT_Dwarf:
740 relaxedFrag = RelaxDwarfLineAddr(Writer, Layout,
741 *cast<MCDwarfLineAddrFragment>(it2));
743 case MCFragment::FT_LEB:
744 relaxedFrag = RelaxLEB(Writer, Layout, *cast<MCLEBFragment>(it2));
747 // Update the layout, and remember that we relaxed.
749 Layout.Invalidate(it2);
750 WasRelaxed |= relaxedFrag;
757 void MCAssembler::FinishLayout(MCAsmLayout &Layout) {
758 // The layout is done. Mark every fragment as valid.
759 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
760 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
768 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
769 OS << "<MCFixup" << " Offset:" << AF.getOffset()
770 << " Value:" << *AF.getValue()
771 << " Kind:" << AF.getKind() << ">";
777 void MCFragment::dump() {
778 raw_ostream &OS = llvm::errs();
782 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
783 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
784 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
785 case MCFragment::FT_Inst: OS << "MCInstFragment"; break;
786 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
787 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
788 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
791 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
792 << " Offset:" << Offset << " EffectiveSize:" << EffectiveSize << ">";
795 case MCFragment::FT_Align: {
796 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
797 if (AF->hasEmitNops())
798 OS << " (emit nops)";
800 OS << " Alignment:" << AF->getAlignment()
801 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
802 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
805 case MCFragment::FT_Data: {
806 const MCDataFragment *DF = cast<MCDataFragment>(this);
809 const SmallVectorImpl<char> &Contents = DF->getContents();
810 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
812 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
814 OS << "] (" << Contents.size() << " bytes)";
816 if (!DF->getFixups().empty()) {
819 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
820 ie = DF->fixup_end(); it != ie; ++it) {
821 if (it != DF->fixup_begin()) OS << ",\n ";
828 case MCFragment::FT_Fill: {
829 const MCFillFragment *FF = cast<MCFillFragment>(this);
830 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
831 << " Size:" << FF->getSize();
834 case MCFragment::FT_Inst: {
835 const MCInstFragment *IF = cast<MCInstFragment>(this);
838 IF->getInst().dump_pretty(OS);
841 case MCFragment::FT_Org: {
842 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
844 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
847 case MCFragment::FT_Dwarf: {
848 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
850 OS << " AddrDelta:" << OF->getAddrDelta()
851 << " LineDelta:" << OF->getLineDelta();
854 case MCFragment::FT_LEB: {
855 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
857 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
864 void MCSectionData::dump() {
865 raw_ostream &OS = llvm::errs();
867 OS << "<MCSectionData";
868 OS << " Alignment:" << getAlignment() << " Fragments:[\n ";
869 for (iterator it = begin(), ie = end(); it != ie; ++it) {
870 if (it != begin()) OS << ",\n ";
876 void MCSymbolData::dump() {
877 raw_ostream &OS = llvm::errs();
879 OS << "<MCSymbolData Symbol:" << getSymbol()
880 << " Fragment:" << getFragment() << " Offset:" << getOffset()
881 << " Flags:" << getFlags() << " Index:" << getIndex();
883 OS << " (common, size:" << getCommonSize()
884 << " align: " << getCommonAlignment() << ")";
887 if (isPrivateExtern())
888 OS << " (private extern)";
892 void MCAssembler::dump() {
893 raw_ostream &OS = llvm::errs();
895 OS << "<MCAssembler\n";
896 OS << " Sections:[\n ";
897 for (iterator it = begin(), ie = end(); it != ie; ++it) {
898 if (it != begin()) OS << ",\n ";
904 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
905 if (it != symbol_begin()) OS << ",\n ";