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, "Number of emitted assembler fragments - instruction");
38 STATISTIC(EmittedDataFragments, "Number of emitted assembler fragments - data");
39 STATISTIC(evaluateFixup, "Number of evaluated fixups");
40 STATISTIC(FragmentLayouts, "Number of fragment layouts");
41 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
42 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
43 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
47 // FIXME FIXME FIXME: There are number of places in this file where we convert
48 // what is a 64-bit assembler value used for computation into a value in the
49 // object file, which may truncate it. We should detect that truncation where
50 // invalid and report errors back.
54 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
55 : Assembler(Asm), LastValidFragment()
57 // Compute the section layout order. Virtual sections must go last.
58 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
59 if (!it->getSection().isVirtualSection())
60 SectionOrder.push_back(&*it);
61 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
62 if (it->getSection().isVirtualSection())
63 SectionOrder.push_back(&*it);
66 bool MCAsmLayout::isFragmentUpToDate(const MCFragment *F) const {
67 const MCSectionData &SD = *F->getParent();
68 const MCFragment *LastValid = LastValidFragment.lookup(&SD);
71 assert(LastValid->getParent() == F->getParent());
72 return F->getLayoutOrder() <= LastValid->getLayoutOrder();
75 void MCAsmLayout::Invalidate(MCFragment *F) {
76 // If this fragment wasn't already up-to-date, we don't need to do anything.
77 if (!isFragmentUpToDate(F))
80 // Otherwise, reset the last valid fragment to this fragment.
81 const MCSectionData &SD = *F->getParent();
82 LastValidFragment[&SD] = F;
85 void MCAsmLayout::EnsureValid(const MCFragment *F) const {
86 MCSectionData &SD = *F->getParent();
88 MCFragment *Cur = LastValidFragment[&SD];
92 Cur = Cur->getNextNode();
94 // Advance the layout position until the fragment is up-to-date.
95 while (!isFragmentUpToDate(F)) {
96 const_cast<MCAsmLayout*>(this)->LayoutFragment(Cur);
97 Cur = Cur->getNextNode();
101 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
103 assert(F->Offset != ~UINT64_C(0) && "Address not set!");
107 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData *SD) const {
108 const MCSymbol &S = SD->getSymbol();
110 // If this is a variable, then recursively evaluate now.
111 if (S.isVariable()) {
113 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, *this))
114 report_fatal_error("unable to evaluate offset for variable '" +
117 // Verify that any used symbols are defined.
118 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
119 report_fatal_error("unable to evaluate offset to undefined symbol '" +
120 Target.getSymA()->getSymbol().getName() + "'");
121 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
122 report_fatal_error("unable to evaluate offset to undefined symbol '" +
123 Target.getSymB()->getSymbol().getName() + "'");
125 uint64_t Offset = Target.getConstant();
126 if (Target.getSymA())
127 Offset += getSymbolOffset(&Assembler.getSymbolData(
128 Target.getSymA()->getSymbol()));
129 if (Target.getSymB())
130 Offset -= getSymbolOffset(&Assembler.getSymbolData(
131 Target.getSymB()->getSymbol()));
135 assert(SD->getFragment() && "Invalid getOffset() on undefined symbol!");
136 return getFragmentOffset(SD->getFragment()) + SD->getOffset();
139 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
140 // The size is the last fragment's end offset.
141 const MCFragment &F = SD->getFragmentList().back();
142 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
145 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
146 // Virtual sections have no file size.
147 if (SD->getSection().isVirtualSection())
150 // Otherwise, the file size is the same as the address space size.
151 return getSectionAddressSize(SD);
156 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
159 MCFragment::~MCFragment() {
162 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
163 : Kind(_Kind), Parent(_Parent), Atom(0), Offset(~UINT64_C(0))
166 Parent->getFragmentList().push_back(this);
171 MCEncodedFragment::~MCEncodedFragment() {
176 MCSectionData::MCSectionData() : Section(0) {}
178 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
179 : Section(&_Section),
180 Ordinal(~UINT32_C(0)),
182 HasInstructions(false)
185 A->getSectionList().push_back(this);
190 MCSymbolData::MCSymbolData() : Symbol(0) {}
192 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
193 uint64_t _Offset, MCAssembler *A)
194 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
195 IsExternal(false), IsPrivateExtern(false),
196 CommonSize(0), SymbolSize(0), CommonAlign(0),
200 A->getSymbolList().push_back(this);
205 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
206 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
208 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
209 OS(OS_), RelaxAll(false), NoExecStack(false), SubsectionsViaSymbols(false) {
212 MCAssembler::~MCAssembler() {
215 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
216 // Non-temporary labels should always be visible to the linker.
217 if (!Symbol.isTemporary())
220 // Absolute temporary labels are never visible.
221 if (!Symbol.isInSection())
224 // Otherwise, check if the section requires symbols even for temporary labels.
225 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
228 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
229 // Linker visible symbols define atoms.
230 if (isSymbolLinkerVisible(SD->getSymbol()))
233 // Absolute and undefined symbols have no defining atom.
234 if (!SD->getFragment())
237 // Non-linker visible symbols in sections which can't be atomized have no
239 if (!getBackend().isSectionAtomizable(
240 SD->getFragment()->getParent()->getSection()))
243 // Otherwise, return the atom for the containing fragment.
244 return SD->getFragment()->getAtom();
247 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
248 const MCFixup &Fixup, const MCFragment *DF,
249 MCValue &Target, uint64_t &Value) const {
250 ++stats::evaluateFixup;
252 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
253 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
255 bool IsPCRel = Backend.getFixupKindInfo(
256 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
260 if (Target.getSymB()) {
262 } else if (!Target.getSymA()) {
265 const MCSymbolRefExpr *A = Target.getSymA();
266 const MCSymbol &SA = A->getSymbol();
267 if (A->getKind() != MCSymbolRefExpr::VK_None ||
268 SA.AliasedSymbol().isUndefined()) {
271 const MCSymbolData &DataA = getSymbolData(SA);
273 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
278 IsResolved = Target.isAbsolute();
281 Value = Target.getConstant();
283 if (const MCSymbolRefExpr *A = Target.getSymA()) {
284 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
286 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
288 if (const MCSymbolRefExpr *B = Target.getSymB()) {
289 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
291 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
295 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
296 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
297 assert((ShouldAlignPC ? IsPCRel : true) &&
298 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
301 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
303 // A number of ARM fixups in Thumb mode require that the effective PC
304 // address be determined as the 32-bit aligned version of the actual offset.
305 if (ShouldAlignPC) Offset &= ~0x3;
309 // Let the backend adjust the fixup value if necessary, including whether
310 // we need a relocation.
311 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
317 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
318 const MCFragment &F) const {
319 switch (F.getKind()) {
320 case MCFragment::FT_Data:
321 return cast<MCDataFragment>(F).getContents().size();
322 case MCFragment::FT_Fill:
323 return cast<MCFillFragment>(F).getSize();
324 case MCFragment::FT_Inst:
325 return cast<MCInstFragment>(F).getInstSize();
327 case MCFragment::FT_LEB:
328 return cast<MCLEBFragment>(F).getContents().size();
330 case MCFragment::FT_Align: {
331 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
332 unsigned Offset = Layout.getFragmentOffset(&AF);
333 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
334 // If we are padding with nops, force the padding to be larger than the
336 if (Size > 0 && AF.hasEmitNops()) {
337 while (Size % getBackend().getMinimumNopSize())
338 Size += AF.getAlignment();
340 if (Size > AF.getMaxBytesToEmit())
345 case MCFragment::FT_Org: {
346 MCOrgFragment &OF = cast<MCOrgFragment>(F);
347 int64_t TargetLocation;
348 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
349 report_fatal_error("expected assembly-time absolute expression");
351 // FIXME: We need a way to communicate this error.
352 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
353 int64_t Size = TargetLocation - FragmentOffset;
354 if (Size < 0 || Size >= 0x40000000)
355 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
356 "' (at offset '" + Twine(FragmentOffset) + "')");
360 case MCFragment::FT_Dwarf:
361 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
362 case MCFragment::FT_DwarfFrame:
363 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
366 llvm_unreachable("invalid fragment kind");
369 void MCAsmLayout::LayoutFragment(MCFragment *F) {
370 MCFragment *Prev = F->getPrevNode();
372 // We should never try to recompute something which is up-to-date.
373 assert(!isFragmentUpToDate(F) && "Attempt to recompute up-to-date fragment!");
374 // We should never try to compute the fragment layout if it's predecessor
376 assert((!Prev || isFragmentUpToDate(Prev)) &&
377 "Attempt to compute fragment before it's predecessor!");
379 ++stats::FragmentLayouts;
381 // Compute fragment offset and size.
384 Offset += Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
387 LastValidFragment[F->getParent()] = F;
390 /// \brief Write the contents of a fragment to the given object writer. Expects
391 /// a MCEncodedFragment.
392 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
393 MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
394 OW->WriteBytes(EF.getContents().str());
397 /// \brief Write the fragment \p F to the output file.
398 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
399 const MCFragment &F) {
400 MCObjectWriter *OW = &Asm.getWriter();
401 uint64_t Start = OW->getStream().tell();
404 ++stats::EmittedFragments;
406 // FIXME: Embed in fragments instead?
407 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
408 switch (F.getKind()) {
409 case MCFragment::FT_Align: {
410 MCAlignFragment &AF = cast<MCAlignFragment>(F);
411 uint64_t Count = FragmentSize / AF.getValueSize();
413 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
415 // FIXME: This error shouldn't actually occur (the front end should emit
416 // multiple .align directives to enforce the semantics it wants), but is
417 // severe enough that we want to report it. How to handle this?
418 if (Count * AF.getValueSize() != FragmentSize)
419 report_fatal_error("undefined .align directive, value size '" +
420 Twine(AF.getValueSize()) +
421 "' is not a divisor of padding size '" +
422 Twine(FragmentSize) + "'");
424 // See if we are aligning with nops, and if so do that first to try to fill
425 // the Count bytes. Then if that did not fill any bytes or there are any
426 // bytes left to fill use the Value and ValueSize to fill the rest.
427 // If we are aligning with nops, ask that target to emit the right data.
428 if (AF.hasEmitNops()) {
429 if (!Asm.getBackend().writeNopData(Count, OW))
430 report_fatal_error("unable to write nop sequence of " +
431 Twine(Count) + " bytes");
435 // Otherwise, write out in multiples of the value size.
436 for (uint64_t i = 0; i != Count; ++i) {
437 switch (AF.getValueSize()) {
438 default: llvm_unreachable("Invalid size!");
439 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
440 case 2: OW->Write16(uint16_t(AF.getValue())); break;
441 case 4: OW->Write32(uint32_t(AF.getValue())); break;
442 case 8: OW->Write64(uint64_t(AF.getValue())); break;
448 case MCFragment::FT_Data:
449 ++stats::EmittedDataFragments;
450 writeFragmentContents(F, OW);
453 case MCFragment::FT_Inst:
454 ++stats::EmittedInstFragments;
455 writeFragmentContents(F, OW);
458 case MCFragment::FT_Fill: {
459 MCFillFragment &FF = cast<MCFillFragment>(F);
461 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
463 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
464 switch (FF.getValueSize()) {
465 default: llvm_unreachable("Invalid size!");
466 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
467 case 2: OW->Write16(uint16_t(FF.getValue())); break;
468 case 4: OW->Write32(uint32_t(FF.getValue())); break;
469 case 8: OW->Write64(uint64_t(FF.getValue())); break;
475 case MCFragment::FT_LEB: {
476 MCLEBFragment &LF = cast<MCLEBFragment>(F);
477 OW->WriteBytes(LF.getContents().str());
481 case MCFragment::FT_Org: {
482 MCOrgFragment &OF = cast<MCOrgFragment>(F);
484 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
485 OW->Write8(uint8_t(OF.getValue()));
490 case MCFragment::FT_Dwarf: {
491 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
492 OW->WriteBytes(OF.getContents().str());
495 case MCFragment::FT_DwarfFrame: {
496 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
497 OW->WriteBytes(CF.getContents().str());
502 assert(OW->getStream().tell() - Start == FragmentSize);
505 void MCAssembler::writeSectionData(const MCSectionData *SD,
506 const MCAsmLayout &Layout) const {
507 // Ignore virtual sections.
508 if (SD->getSection().isVirtualSection()) {
509 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
511 // Check that contents are only things legal inside a virtual section.
512 for (MCSectionData::const_iterator it = SD->begin(),
513 ie = SD->end(); it != ie; ++it) {
514 switch (it->getKind()) {
515 default: llvm_unreachable("Invalid fragment in virtual section!");
516 case MCFragment::FT_Data: {
517 // Check that we aren't trying to write a non-zero contents (or fixups)
518 // into a virtual section. This is to support clients which use standard
519 // directives to fill the contents of virtual sections.
520 MCDataFragment &DF = cast<MCDataFragment>(*it);
521 assert(DF.fixup_begin() == DF.fixup_end() &&
522 "Cannot have fixups in virtual section!");
523 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
524 assert(DF.getContents()[i] == 0 &&
525 "Invalid data value for virtual section!");
528 case MCFragment::FT_Align:
529 // Check that we aren't trying to write a non-zero value into a virtual
531 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
532 !cast<MCAlignFragment>(it)->getValue()) &&
533 "Invalid align in virtual section!");
535 case MCFragment::FT_Fill:
536 assert(!cast<MCFillFragment>(it)->getValueSize() &&
537 "Invalid fill in virtual section!");
545 uint64_t Start = getWriter().getStream().tell();
548 for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
550 writeFragment(*this, Layout, *it);
552 assert(getWriter().getStream().tell() - Start ==
553 Layout.getSectionAddressSize(SD));
557 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
559 const MCFixup &Fixup) {
560 // Evaluate the fixup.
563 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
564 // The fixup was unresolved, we need a relocation. Inform the object
565 // writer of the relocation, and give it an opportunity to adjust the
566 // fixup value if need be.
567 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
572 void MCAssembler::Finish() {
573 DEBUG_WITH_TYPE("mc-dump", {
574 llvm::errs() << "assembler backend - pre-layout\n--\n";
577 // Create the layout object.
578 MCAsmLayout Layout(*this);
580 // Create dummy fragments and assign section ordinals.
581 unsigned SectionIndex = 0;
582 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
583 // Create dummy fragments to eliminate any empty sections, this simplifies
585 if (it->getFragmentList().empty())
586 new MCDataFragment(it);
588 it->setOrdinal(SectionIndex++);
591 // Assign layout order indices to sections and fragments.
592 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
593 MCSectionData *SD = Layout.getSectionOrder()[i];
594 SD->setLayoutOrder(i);
596 unsigned FragmentIndex = 0;
597 for (MCSectionData::iterator it2 = SD->begin(),
598 ie2 = SD->end(); it2 != ie2; ++it2)
599 it2->setLayoutOrder(FragmentIndex++);
602 // Layout until everything fits.
603 while (layoutOnce(Layout))
606 DEBUG_WITH_TYPE("mc-dump", {
607 llvm::errs() << "assembler backend - post-relaxation\n--\n";
610 // Finalize the layout, including fragment lowering.
611 finishLayout(Layout);
613 DEBUG_WITH_TYPE("mc-dump", {
614 llvm::errs() << "assembler backend - final-layout\n--\n";
617 uint64_t StartOffset = OS.tell();
619 // Allow the object writer a chance to perform post-layout binding (for
620 // example, to set the index fields in the symbol data).
621 getWriter().ExecutePostLayoutBinding(*this, Layout);
623 // Evaluate and apply the fixups, generating relocation entries as necessary.
624 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
625 for (MCSectionData::iterator it2 = it->begin(),
626 ie2 = it->end(); it2 != ie2; ++it2) {
627 MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(it2);
629 for (MCEncodedFragment::fixup_iterator it3 = F->fixup_begin(),
630 ie3 = F->fixup_end(); it3 != ie3; ++it3) {
631 MCFixup &Fixup = *it3;
632 uint64_t FixedValue = handleFixup(Layout, *F, Fixup);
633 getBackend().applyFixup(Fixup, F->getContents().data(),
634 F->getContents().size(), FixedValue);
640 // Write the object file.
641 getWriter().WriteObject(*this, Layout);
643 stats::ObjectBytes += OS.tell() - StartOffset;
646 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
647 const MCInstFragment *DF,
648 const MCAsmLayout &Layout) const {
652 // If we cannot resolve the fixup value, it requires relaxation.
655 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
658 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
661 bool MCAssembler::fragmentNeedsRelaxation(const MCInstFragment *IF,
662 const MCAsmLayout &Layout) const {
663 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
664 // are intentionally pushing out inst fragments, or because we relaxed a
665 // previous instruction to one that doesn't need relaxation.
666 if (!getBackend().mayNeedRelaxation(IF->getInst()))
669 for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
670 ie = IF->fixup_end(); it != ie; ++it)
671 if (fixupNeedsRelaxation(*it, IF, Layout))
677 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
678 MCInstFragment &IF) {
679 if (!fragmentNeedsRelaxation(&IF, Layout))
682 ++stats::RelaxedInstructions;
684 // FIXME-PERF: We could immediately lower out instructions if we can tell
685 // they are fully resolved, to avoid retesting on later passes.
687 // Relax the fragment.
690 getBackend().relaxInstruction(IF.getInst(), Relaxed);
692 // Encode the new instruction.
694 // FIXME-PERF: If it matters, we could let the target do this. It can
695 // probably do so more efficiently in many cases.
696 SmallVector<MCFixup, 4> Fixups;
697 SmallString<256> Code;
698 raw_svector_ostream VecOS(Code);
699 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
702 // Update the instruction fragment.
704 IF.getContents() = Code;
705 IF.getFixups() = Fixups;
710 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
712 uint64_t OldSize = LF.getContents().size();
713 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
716 SmallString<8> &Data = LF.getContents();
718 raw_svector_ostream OSE(Data);
720 encodeSLEB128(Value, OSE);
722 encodeULEB128(Value, OSE);
724 return OldSize != LF.getContents().size();
727 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
728 MCDwarfLineAddrFragment &DF) {
729 int64_t AddrDelta = 0;
730 uint64_t OldSize = DF.getContents().size();
731 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
735 LineDelta = DF.getLineDelta();
736 SmallString<8> &Data = DF.getContents();
738 raw_svector_ostream OSE(Data);
739 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
741 return OldSize != Data.size();
744 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
745 MCDwarfCallFrameFragment &DF) {
746 int64_t AddrDelta = 0;
747 uint64_t OldSize = DF.getContents().size();
748 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
751 SmallString<8> &Data = DF.getContents();
753 raw_svector_ostream OSE(Data);
754 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
756 return OldSize != Data.size();
759 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout,
761 MCFragment *FirstInvalidFragment = NULL;
762 // Scan for fragments that need relaxation.
763 for (MCSectionData::iterator it2 = SD.begin(),
764 ie2 = SD.end(); it2 != ie2; ++it2) {
765 // Check if this is an fragment that needs relaxation.
766 bool relaxedFrag = false;
767 switch(it2->getKind()) {
770 case MCFragment::FT_Inst:
771 relaxedFrag = relaxInstruction(Layout, *cast<MCInstFragment>(it2));
773 case MCFragment::FT_Dwarf:
774 relaxedFrag = relaxDwarfLineAddr(Layout,
775 *cast<MCDwarfLineAddrFragment>(it2));
777 case MCFragment::FT_DwarfFrame:
779 relaxDwarfCallFrameFragment(Layout,
780 *cast<MCDwarfCallFrameFragment>(it2));
782 case MCFragment::FT_LEB:
783 relaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(it2));
786 // Update the layout, and remember that we relaxed.
787 if (relaxedFrag && !FirstInvalidFragment)
788 FirstInvalidFragment = it2;
790 if (FirstInvalidFragment) {
791 Layout.Invalidate(FirstInvalidFragment);
797 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
798 ++stats::RelaxationSteps;
800 bool WasRelaxed = false;
801 for (iterator it = begin(), ie = end(); it != ie; ++it) {
802 MCSectionData &SD = *it;
803 while(layoutSectionOnce(Layout, SD))
810 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
811 // The layout is done. Mark every fragment as valid.
812 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
813 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
821 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
822 OS << "<MCFixup" << " Offset:" << AF.getOffset()
823 << " Value:" << *AF.getValue()
824 << " Kind:" << AF.getKind() << ">";
830 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
831 void MCFragment::dump() {
832 raw_ostream &OS = llvm::errs();
836 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
837 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
838 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
839 case MCFragment::FT_Inst: OS << "MCInstFragment"; break;
840 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
841 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
842 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
843 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
846 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
847 << " Offset:" << Offset << ">";
850 case MCFragment::FT_Align: {
851 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
852 if (AF->hasEmitNops())
853 OS << " (emit nops)";
855 OS << " Alignment:" << AF->getAlignment()
856 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
857 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
860 case MCFragment::FT_Data: {
861 const MCDataFragment *DF = cast<MCDataFragment>(this);
864 const SmallVectorImpl<char> &Contents = DF->getContents();
865 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
867 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
869 OS << "] (" << Contents.size() << " bytes)";
871 if (DF->fixup_begin() != DF->fixup_end()) {
874 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
875 ie = DF->fixup_end(); it != ie; ++it) {
876 if (it != DF->fixup_begin()) OS << ",\n ";
883 case MCFragment::FT_Fill: {
884 const MCFillFragment *FF = cast<MCFillFragment>(this);
885 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
886 << " Size:" << FF->getSize();
889 case MCFragment::FT_Inst: {
890 const MCInstFragment *IF = cast<MCInstFragment>(this);
893 IF->getInst().dump_pretty(OS);
896 case MCFragment::FT_Org: {
897 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
899 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
902 case MCFragment::FT_Dwarf: {
903 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
905 OS << " AddrDelta:" << OF->getAddrDelta()
906 << " LineDelta:" << OF->getLineDelta();
909 case MCFragment::FT_DwarfFrame: {
910 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
912 OS << " AddrDelta:" << CF->getAddrDelta();
915 case MCFragment::FT_LEB: {
916 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
918 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
925 void MCSectionData::dump() {
926 raw_ostream &OS = llvm::errs();
928 OS << "<MCSectionData";
929 OS << " Alignment:" << getAlignment() << " Fragments:[\n ";
930 for (iterator it = begin(), ie = end(); it != ie; ++it) {
931 if (it != begin()) OS << ",\n ";
937 void MCSymbolData::dump() {
938 raw_ostream &OS = llvm::errs();
940 OS << "<MCSymbolData Symbol:" << getSymbol()
941 << " Fragment:" << getFragment() << " Offset:" << getOffset()
942 << " Flags:" << getFlags() << " Index:" << getIndex();
944 OS << " (common, size:" << getCommonSize()
945 << " align: " << getCommonAlignment() << ")";
948 if (isPrivateExtern())
949 OS << " (private extern)";
953 void MCAssembler::dump() {
954 raw_ostream &OS = llvm::errs();
956 OS << "<MCAssembler\n";
957 OS << " Sections:[\n ";
958 for (iterator it = begin(), ie = end(); it != ie; ++it) {
959 if (it != begin()) OS << ",\n ";
965 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
966 if (it != symbol_begin()) OS << ",\n ";
973 // anchors for MC*Fragment vtables
974 void MCEncodedFragment::anchor() { }
975 void MCDataFragment::anchor() { }
976 void MCInstFragment::anchor() { }
977 void MCAlignFragment::anchor() { }
978 void MCFillFragment::anchor() { }
979 void MCOrgFragment::anchor() { }
980 void MCLEBFragment::anchor() { }
981 void MCDwarfLineAddrFragment::anchor() { }
982 void MCDwarfCallFrameFragment::anchor() { }