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 MCSectionData::MCSectionData() : Section(0) {}
173 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
174 : Section(&_Section),
175 Ordinal(~UINT32_C(0)),
177 HasInstructions(false)
180 A->getSectionList().push_back(this);
185 MCSymbolData::MCSymbolData() : Symbol(0) {}
187 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
188 uint64_t _Offset, MCAssembler *A)
189 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
190 IsExternal(false), IsPrivateExtern(false),
191 CommonSize(0), SymbolSize(0), CommonAlign(0),
195 A->getSymbolList().push_back(this);
200 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
201 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
203 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
204 OS(OS_), RelaxAll(false), NoExecStack(false), SubsectionsViaSymbols(false) {
207 MCAssembler::~MCAssembler() {
210 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
211 // Non-temporary labels should always be visible to the linker.
212 if (!Symbol.isTemporary())
215 // Absolute temporary labels are never visible.
216 if (!Symbol.isInSection())
219 // Otherwise, check if the section requires symbols even for temporary labels.
220 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
223 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
224 // Linker visible symbols define atoms.
225 if (isSymbolLinkerVisible(SD->getSymbol()))
228 // Absolute and undefined symbols have no defining atom.
229 if (!SD->getFragment())
232 // Non-linker visible symbols in sections which can't be atomized have no
234 if (!getBackend().isSectionAtomizable(
235 SD->getFragment()->getParent()->getSection()))
238 // Otherwise, return the atom for the containing fragment.
239 return SD->getFragment()->getAtom();
242 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
243 const MCFixup &Fixup, const MCFragment *DF,
244 MCValue &Target, uint64_t &Value) const {
245 ++stats::evaluateFixup;
247 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
248 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
250 bool IsPCRel = Backend.getFixupKindInfo(
251 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
255 if (Target.getSymB()) {
257 } else if (!Target.getSymA()) {
260 const MCSymbolRefExpr *A = Target.getSymA();
261 const MCSymbol &SA = A->getSymbol();
262 if (A->getKind() != MCSymbolRefExpr::VK_None ||
263 SA.AliasedSymbol().isUndefined()) {
266 const MCSymbolData &DataA = getSymbolData(SA);
268 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
273 IsResolved = Target.isAbsolute();
276 Value = Target.getConstant();
278 if (const MCSymbolRefExpr *A = Target.getSymA()) {
279 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
281 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
283 if (const MCSymbolRefExpr *B = Target.getSymB()) {
284 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
286 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
290 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
291 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
292 assert((ShouldAlignPC ? IsPCRel : true) &&
293 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
296 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
298 // A number of ARM fixups in Thumb mode require that the effective PC
299 // address be determined as the 32-bit aligned version of the actual offset.
300 if (ShouldAlignPC) Offset &= ~0x3;
304 // Let the backend adjust the fixup value if necessary, including whether
305 // we need a relocation.
306 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
312 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
313 const MCFragment &F) const {
314 switch (F.getKind()) {
315 case MCFragment::FT_Data:
316 return cast<MCDataFragment>(F).getContents().size();
317 case MCFragment::FT_Fill:
318 return cast<MCFillFragment>(F).getSize();
319 case MCFragment::FT_Inst:
320 return cast<MCInstFragment>(F).getInstSize();
322 case MCFragment::FT_LEB:
323 return cast<MCLEBFragment>(F).getContents().size();
325 case MCFragment::FT_Align: {
326 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
327 unsigned Offset = Layout.getFragmentOffset(&AF);
328 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
329 // If we are padding with nops, force the padding to be larger than the
331 if (Size > 0 && AF.hasEmitNops()) {
332 while (Size % getBackend().getMinimumNopSize())
333 Size += AF.getAlignment();
335 if (Size > AF.getMaxBytesToEmit())
340 case MCFragment::FT_Org: {
341 MCOrgFragment &OF = cast<MCOrgFragment>(F);
342 int64_t TargetLocation;
343 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
344 report_fatal_error("expected assembly-time absolute expression");
346 // FIXME: We need a way to communicate this error.
347 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
348 int64_t Size = TargetLocation - FragmentOffset;
349 if (Size < 0 || Size >= 0x40000000)
350 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
351 "' (at offset '" + Twine(FragmentOffset) + "')");
355 case MCFragment::FT_Dwarf:
356 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
357 case MCFragment::FT_DwarfFrame:
358 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
361 llvm_unreachable("invalid fragment kind");
364 void MCAsmLayout::LayoutFragment(MCFragment *F) {
365 MCFragment *Prev = F->getPrevNode();
367 // We should never try to recompute something which is up-to-date.
368 assert(!isFragmentUpToDate(F) && "Attempt to recompute up-to-date fragment!");
369 // We should never try to compute the fragment layout if it's predecessor
371 assert((!Prev || isFragmentUpToDate(Prev)) &&
372 "Attempt to compute fragment before it's predecessor!");
374 ++stats::FragmentLayouts;
376 // Compute fragment offset and size.
379 Offset += Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
382 LastValidFragment[F->getParent()] = F;
385 /// WriteFragmentData - Write the \p F data to the output file.
386 static void WriteFragmentData(const MCAssembler &Asm, const MCAsmLayout &Layout,
387 const MCFragment &F) {
388 MCObjectWriter *OW = &Asm.getWriter();
389 uint64_t Start = OW->getStream().tell();
392 ++stats::EmittedFragments;
394 // FIXME: Embed in fragments instead?
395 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
396 switch (F.getKind()) {
397 case MCFragment::FT_Align: {
398 MCAlignFragment &AF = cast<MCAlignFragment>(F);
399 uint64_t Count = FragmentSize / AF.getValueSize();
401 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
403 // FIXME: This error shouldn't actually occur (the front end should emit
404 // multiple .align directives to enforce the semantics it wants), but is
405 // severe enough that we want to report it. How to handle this?
406 if (Count * AF.getValueSize() != FragmentSize)
407 report_fatal_error("undefined .align directive, value size '" +
408 Twine(AF.getValueSize()) +
409 "' is not a divisor of padding size '" +
410 Twine(FragmentSize) + "'");
412 // See if we are aligning with nops, and if so do that first to try to fill
413 // the Count bytes. Then if that did not fill any bytes or there are any
414 // bytes left to fill use the Value and ValueSize to fill the rest.
415 // If we are aligning with nops, ask that target to emit the right data.
416 if (AF.hasEmitNops()) {
417 if (!Asm.getBackend().writeNopData(Count, OW))
418 report_fatal_error("unable to write nop sequence of " +
419 Twine(Count) + " bytes");
423 // Otherwise, write out in multiples of the value size.
424 for (uint64_t i = 0; i != Count; ++i) {
425 switch (AF.getValueSize()) {
426 default: llvm_unreachable("Invalid size!");
427 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
428 case 2: OW->Write16(uint16_t(AF.getValue())); break;
429 case 4: OW->Write32(uint32_t(AF.getValue())); break;
430 case 8: OW->Write64(uint64_t(AF.getValue())); break;
436 case MCFragment::FT_Data: {
437 ++stats::EmittedDataFragments;
438 MCDataFragment &DF = cast<MCDataFragment>(F);
439 assert(FragmentSize == DF.getContents().size() && "Invalid size!");
440 OW->WriteBytes(DF.getContents().str());
444 case MCFragment::FT_Fill: {
445 MCFillFragment &FF = cast<MCFillFragment>(F);
447 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
449 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
450 switch (FF.getValueSize()) {
451 default: llvm_unreachable("Invalid size!");
452 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
453 case 2: OW->Write16(uint16_t(FF.getValue())); break;
454 case 4: OW->Write32(uint32_t(FF.getValue())); break;
455 case 8: OW->Write64(uint64_t(FF.getValue())); break;
461 case MCFragment::FT_Inst: {
462 ++stats::EmittedInstFragments;
463 MCInstFragment &IF = cast<MCInstFragment>(F);
464 OW->WriteBytes(StringRef(IF.getCode().begin(), IF.getCode().size()));
468 case MCFragment::FT_LEB: {
469 MCLEBFragment &LF = cast<MCLEBFragment>(F);
470 OW->WriteBytes(LF.getContents().str());
474 case MCFragment::FT_Org: {
475 MCOrgFragment &OF = cast<MCOrgFragment>(F);
477 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
478 OW->Write8(uint8_t(OF.getValue()));
483 case MCFragment::FT_Dwarf: {
484 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
485 OW->WriteBytes(OF.getContents().str());
488 case MCFragment::FT_DwarfFrame: {
489 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
490 OW->WriteBytes(CF.getContents().str());
495 assert(OW->getStream().tell() - Start == FragmentSize);
498 void MCAssembler::writeSectionData(const MCSectionData *SD,
499 const MCAsmLayout &Layout) const {
500 // Ignore virtual sections.
501 if (SD->getSection().isVirtualSection()) {
502 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
504 // Check that contents are only things legal inside a virtual section.
505 for (MCSectionData::const_iterator it = SD->begin(),
506 ie = SD->end(); it != ie; ++it) {
507 switch (it->getKind()) {
508 default: llvm_unreachable("Invalid fragment in virtual section!");
509 case MCFragment::FT_Data: {
510 // Check that we aren't trying to write a non-zero contents (or fixups)
511 // into a virtual section. This is to support clients which use standard
512 // directives to fill the contents of virtual sections.
513 MCDataFragment &DF = cast<MCDataFragment>(*it);
514 assert(DF.fixup_begin() == DF.fixup_end() &&
515 "Cannot have fixups in virtual section!");
516 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
517 assert(DF.getContents()[i] == 0 &&
518 "Invalid data value for virtual section!");
521 case MCFragment::FT_Align:
522 // Check that we aren't trying to write a non-zero value into a virtual
524 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
525 !cast<MCAlignFragment>(it)->getValue()) &&
526 "Invalid align in virtual section!");
528 case MCFragment::FT_Fill:
529 assert(!cast<MCFillFragment>(it)->getValueSize() &&
530 "Invalid fill in virtual section!");
538 uint64_t Start = getWriter().getStream().tell();
541 for (MCSectionData::const_iterator it = SD->begin(),
542 ie = SD->end(); it != ie; ++it)
543 WriteFragmentData(*this, Layout, *it);
545 assert(getWriter().getStream().tell() - Start ==
546 Layout.getSectionAddressSize(SD));
550 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
552 const MCFixup &Fixup) {
553 // Evaluate the fixup.
556 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
557 // The fixup was unresolved, we need a relocation. Inform the object
558 // writer of the relocation, and give it an opportunity to adjust the
559 // fixup value if need be.
560 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
565 void MCAssembler::Finish() {
566 DEBUG_WITH_TYPE("mc-dump", {
567 llvm::errs() << "assembler backend - pre-layout\n--\n";
570 // Create the layout object.
571 MCAsmLayout Layout(*this);
573 // Create dummy fragments and assign section ordinals.
574 unsigned SectionIndex = 0;
575 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
576 // Create dummy fragments to eliminate any empty sections, this simplifies
578 if (it->getFragmentList().empty())
579 new MCDataFragment(it);
581 it->setOrdinal(SectionIndex++);
584 // Assign layout order indices to sections and fragments.
585 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
586 MCSectionData *SD = Layout.getSectionOrder()[i];
587 SD->setLayoutOrder(i);
589 unsigned FragmentIndex = 0;
590 for (MCSectionData::iterator it2 = SD->begin(),
591 ie2 = SD->end(); it2 != ie2; ++it2)
592 it2->setLayoutOrder(FragmentIndex++);
595 // Layout until everything fits.
596 while (layoutOnce(Layout))
599 DEBUG_WITH_TYPE("mc-dump", {
600 llvm::errs() << "assembler backend - post-relaxation\n--\n";
603 // Finalize the layout, including fragment lowering.
604 finishLayout(Layout);
606 DEBUG_WITH_TYPE("mc-dump", {
607 llvm::errs() << "assembler backend - final-layout\n--\n";
610 uint64_t StartOffset = OS.tell();
612 // Allow the object writer a chance to perform post-layout binding (for
613 // example, to set the index fields in the symbol data).
614 getWriter().ExecutePostLayoutBinding(*this, Layout);
616 // Evaluate and apply the fixups, generating relocation entries as necessary.
617 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
618 for (MCSectionData::iterator it2 = it->begin(),
619 ie2 = it->end(); it2 != ie2; ++it2) {
620 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
622 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
623 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
624 MCFixup &Fixup = *it3;
625 uint64_t FixedValue = handleFixup(Layout, *DF, Fixup);
626 getBackend().applyFixup(Fixup, DF->getContents().data(),
627 DF->getContents().size(), FixedValue);
630 MCInstFragment *IF = dyn_cast<MCInstFragment>(it2);
632 for (MCInstFragment::fixup_iterator it3 = IF->fixup_begin(),
633 ie3 = IF->fixup_end(); it3 != ie3; ++it3) {
634 MCFixup &Fixup = *it3;
635 uint64_t FixedValue = handleFixup(Layout, *IF, Fixup);
636 getBackend().applyFixup(Fixup, IF->getCode().data(),
637 IF->getCode().size(), FixedValue);
643 // Write the object file.
644 getWriter().WriteObject(*this, Layout);
646 stats::ObjectBytes += OS.tell() - StartOffset;
649 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
650 const MCInstFragment *DF,
651 const MCAsmLayout &Layout) const {
655 // If we cannot resolve the fixup value, it requires relaxation.
658 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
661 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
664 bool MCAssembler::fragmentNeedsRelaxation(const MCInstFragment *IF,
665 const MCAsmLayout &Layout) const {
666 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
667 // are intentionally pushing out inst fragments, or because we relaxed a
668 // previous instruction to one that doesn't need relaxation.
669 if (!getBackend().mayNeedRelaxation(IF->getInst()))
672 for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
673 ie = IF->fixup_end(); it != ie; ++it)
674 if (fixupNeedsRelaxation(*it, IF, Layout))
680 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
681 MCInstFragment &IF) {
682 if (!fragmentNeedsRelaxation(&IF, Layout))
685 ++stats::RelaxedInstructions;
687 // FIXME-PERF: We could immediately lower out instructions if we can tell
688 // they are fully resolved, to avoid retesting on later passes.
690 // Relax the fragment.
693 getBackend().relaxInstruction(IF.getInst(), Relaxed);
695 // Encode the new instruction.
697 // FIXME-PERF: If it matters, we could let the target do this. It can
698 // probably do so more efficiently in many cases.
699 SmallVector<MCFixup, 4> Fixups;
700 SmallString<256> Code;
701 raw_svector_ostream VecOS(Code);
702 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
705 // Update the instruction fragment.
708 IF.getFixups().clear();
709 // FIXME: Eliminate copy.
710 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
711 IF.getFixups().push_back(Fixups[i]);
716 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
718 uint64_t OldSize = LF.getContents().size();
719 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
722 SmallString<8> &Data = LF.getContents();
724 raw_svector_ostream OSE(Data);
726 encodeSLEB128(Value, OSE);
728 encodeULEB128(Value, OSE);
730 return OldSize != LF.getContents().size();
733 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
734 MCDwarfLineAddrFragment &DF) {
735 int64_t AddrDelta = 0;
736 uint64_t OldSize = DF.getContents().size();
737 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
741 LineDelta = DF.getLineDelta();
742 SmallString<8> &Data = DF.getContents();
744 raw_svector_ostream OSE(Data);
745 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
747 return OldSize != Data.size();
750 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
751 MCDwarfCallFrameFragment &DF) {
752 int64_t AddrDelta = 0;
753 uint64_t OldSize = DF.getContents().size();
754 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
757 SmallString<8> &Data = DF.getContents();
759 raw_svector_ostream OSE(Data);
760 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
762 return OldSize != Data.size();
765 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout,
767 MCFragment *FirstInvalidFragment = NULL;
768 // Scan for fragments that need relaxation.
769 for (MCSectionData::iterator it2 = SD.begin(),
770 ie2 = SD.end(); it2 != ie2; ++it2) {
771 // Check if this is an fragment that needs relaxation.
772 bool relaxedFrag = false;
773 switch(it2->getKind()) {
776 case MCFragment::FT_Inst:
777 relaxedFrag = relaxInstruction(Layout, *cast<MCInstFragment>(it2));
779 case MCFragment::FT_Dwarf:
780 relaxedFrag = relaxDwarfLineAddr(Layout,
781 *cast<MCDwarfLineAddrFragment>(it2));
783 case MCFragment::FT_DwarfFrame:
785 relaxDwarfCallFrameFragment(Layout,
786 *cast<MCDwarfCallFrameFragment>(it2));
788 case MCFragment::FT_LEB:
789 relaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(it2));
792 // Update the layout, and remember that we relaxed.
793 if (relaxedFrag && !FirstInvalidFragment)
794 FirstInvalidFragment = it2;
796 if (FirstInvalidFragment) {
797 Layout.Invalidate(FirstInvalidFragment);
803 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
804 ++stats::RelaxationSteps;
806 bool WasRelaxed = false;
807 for (iterator it = begin(), ie = end(); it != ie; ++it) {
808 MCSectionData &SD = *it;
809 while(layoutSectionOnce(Layout, SD))
816 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
817 // The layout is done. Mark every fragment as valid.
818 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
819 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
827 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
828 OS << "<MCFixup" << " Offset:" << AF.getOffset()
829 << " Value:" << *AF.getValue()
830 << " Kind:" << AF.getKind() << ">";
836 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
837 void MCFragment::dump() {
838 raw_ostream &OS = llvm::errs();
842 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
843 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
844 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
845 case MCFragment::FT_Inst: OS << "MCInstFragment"; break;
846 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
847 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
848 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
849 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
852 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
853 << " Offset:" << Offset << ">";
856 case MCFragment::FT_Align: {
857 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
858 if (AF->hasEmitNops())
859 OS << " (emit nops)";
861 OS << " Alignment:" << AF->getAlignment()
862 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
863 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
866 case MCFragment::FT_Data: {
867 const MCDataFragment *DF = cast<MCDataFragment>(this);
870 const SmallVectorImpl<char> &Contents = DF->getContents();
871 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
873 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
875 OS << "] (" << Contents.size() << " bytes)";
877 if (DF->fixup_begin() != DF->fixup_end()) {
880 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
881 ie = DF->fixup_end(); it != ie; ++it) {
882 if (it != DF->fixup_begin()) OS << ",\n ";
889 case MCFragment::FT_Fill: {
890 const MCFillFragment *FF = cast<MCFillFragment>(this);
891 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
892 << " Size:" << FF->getSize();
895 case MCFragment::FT_Inst: {
896 const MCInstFragment *IF = cast<MCInstFragment>(this);
899 IF->getInst().dump_pretty(OS);
902 case MCFragment::FT_Org: {
903 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
905 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
908 case MCFragment::FT_Dwarf: {
909 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
911 OS << " AddrDelta:" << OF->getAddrDelta()
912 << " LineDelta:" << OF->getLineDelta();
915 case MCFragment::FT_DwarfFrame: {
916 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
918 OS << " AddrDelta:" << CF->getAddrDelta();
921 case MCFragment::FT_LEB: {
922 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
924 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
931 void MCSectionData::dump() {
932 raw_ostream &OS = llvm::errs();
934 OS << "<MCSectionData";
935 OS << " Alignment:" << getAlignment() << " Fragments:[\n ";
936 for (iterator it = begin(), ie = end(); it != ie; ++it) {
937 if (it != begin()) OS << ",\n ";
943 void MCSymbolData::dump() {
944 raw_ostream &OS = llvm::errs();
946 OS << "<MCSymbolData Symbol:" << getSymbol()
947 << " Fragment:" << getFragment() << " Offset:" << getOffset()
948 << " Flags:" << getFlags() << " Index:" << getIndex();
950 OS << " (common, size:" << getCommonSize()
951 << " align: " << getCommonAlignment() << ")";
954 if (isPrivateExtern())
955 OS << " (private extern)";
959 void MCAssembler::dump() {
960 raw_ostream &OS = llvm::errs();
962 OS << "<MCAssembler\n";
963 OS << " Sections:[\n ";
964 for (iterator it = begin(), ie = end(); it != ie; ++it) {
965 if (it != begin()) OS << ",\n ";
971 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
972 if (it != symbol_begin()) OS << ",\n ";
979 // anchors for MC*Fragment vtables
980 void MCDataFragment::anchor() { }
981 void MCInstFragment::anchor() { }
982 void MCAlignFragment::anchor() { }
983 void MCFillFragment::anchor() { }
984 void MCOrgFragment::anchor() { }
985 void MCLEBFragment::anchor() { }
986 void MCDwarfLineAddrFragment::anchor() { }
987 void MCDwarfCallFrameFragment::anchor() { }