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/MCContext.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCFixupKindInfo.h"
17 #include "llvm/MC/MCObjectWriter.h"
18 #include "llvm/MC/MCSection.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/MC/MCValue.h"
21 #include "llvm/MC/MCDwarf.h"
22 #include "llvm/MC/MCAsmBackend.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Support/TargetRegistry.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 this fragment.
78 const MCSectionData &SD = *F->getParent();
79 LastValidFragment[&SD] = F;
82 void MCAsmLayout::EnsureValid(const MCFragment *F) const {
83 MCSectionData &SD = *F->getParent();
85 MCFragment *Cur = LastValidFragment[&SD];
89 Cur = Cur->getNextNode();
91 // Advance the layout position until the fragment is up-to-date.
92 while (!isFragmentUpToDate(F)) {
93 const_cast<MCAsmLayout*>(this)->LayoutFragment(Cur);
94 Cur = Cur->getNextNode();
98 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
100 assert(F->Offset != ~UINT64_C(0) && "Address not set!");
104 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData *SD) const {
105 const MCSymbol &S = SD->getSymbol();
107 // If this is a variable, then recursively evaluate now.
108 if (S.isVariable()) {
110 if (!S.getVariableValue()->EvaluateAsRelocatable(Target, *this))
111 report_fatal_error("unable to evaluate offset for variable '" +
114 // Verify that any used symbols are defined.
115 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
116 report_fatal_error("unable to evaluate offset to undefined symbol '" +
117 Target.getSymA()->getSymbol().getName() + "'");
118 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
119 report_fatal_error("unable to evaluate offset to undefined symbol '" +
120 Target.getSymB()->getSymbol().getName() + "'");
122 uint64_t Offset = Target.getConstant();
123 if (Target.getSymA())
124 Offset += getSymbolOffset(&Assembler.getSymbolData(
125 Target.getSymA()->getSymbol()));
126 if (Target.getSymB())
127 Offset -= getSymbolOffset(&Assembler.getSymbolData(
128 Target.getSymB()->getSymbol()));
132 assert(SD->getFragment() && "Invalid getOffset() on undefined symbol!");
133 return getFragmentOffset(SD->getFragment()) + SD->getOffset();
136 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
137 // The size is the last fragment's end offset.
138 const MCFragment &F = SD->getFragmentList().back();
139 return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
142 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
143 // Virtual sections have no file size.
144 if (SD->getSection().isVirtualSection())
147 // Otherwise, the file size is the same as the address space size.
148 return getSectionAddressSize(SD);
153 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
156 MCFragment::~MCFragment() {
159 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
160 : Kind(_Kind), Parent(_Parent), Atom(0), Offset(~UINT64_C(0))
163 Parent->getFragmentList().push_back(this);
168 MCSectionData::MCSectionData() : Section(0) {}
170 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
171 : Section(&_Section),
172 Ordinal(~UINT32_C(0)),
174 HasInstructions(false)
177 A->getSectionList().push_back(this);
182 MCSymbolData::MCSymbolData() : Symbol(0) {}
184 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
185 uint64_t _Offset, MCAssembler *A)
186 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
187 IsExternal(false), IsPrivateExtern(false),
188 CommonSize(0), SymbolSize(0), CommonAlign(0),
192 A->getSymbolList().push_back(this);
197 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
198 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
200 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
201 OS(OS_), RelaxAll(false), NoExecStack(false), SubsectionsViaSymbols(false)
205 MCAssembler::~MCAssembler() {
208 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
209 // Non-temporary labels should always be visible to the linker.
210 if (!Symbol.isTemporary())
213 // Absolute temporary labels are never visible.
214 if (!Symbol.isInSection())
217 // Otherwise, check if the section requires symbols even for temporary labels.
218 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
221 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
222 // Linker visible symbols define atoms.
223 if (isSymbolLinkerVisible(SD->getSymbol()))
226 // Absolute and undefined symbols have no defining atom.
227 if (!SD->getFragment())
230 // Non-linker visible symbols in sections which can't be atomized have no
232 if (!getBackend().isSectionAtomizable(
233 SD->getFragment()->getParent()->getSection()))
236 // Otherwise, return the atom for the containing fragment.
237 return SD->getFragment()->getAtom();
240 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
241 const MCFixup &Fixup, const MCFragment *DF,
242 MCValue &Target, uint64_t &Value) const {
243 ++stats::evaluateFixup;
245 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
246 getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
248 bool IsPCRel = Backend.getFixupKindInfo(
249 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
253 if (Target.getSymB()) {
255 } else if (!Target.getSymA()) {
258 const MCSymbolRefExpr *A = Target.getSymA();
259 const MCSymbol &SA = A->getSymbol();
260 if (A->getKind() != MCSymbolRefExpr::VK_None ||
261 SA.AliasedSymbol().isUndefined()) {
264 const MCSymbolData &DataA = getSymbolData(SA);
266 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
271 IsResolved = Target.isAbsolute();
274 Value = Target.getConstant();
276 if (const MCSymbolRefExpr *A = Target.getSymA()) {
277 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
279 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
281 if (const MCSymbolRefExpr *B = Target.getSymB()) {
282 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
284 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
288 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
289 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
290 assert((ShouldAlignPC ? IsPCRel : true) &&
291 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
294 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
296 // A number of ARM fixups in Thumb mode require that the effective PC
297 // address be determined as the 32-bit aligned version of the actual offset.
298 if (ShouldAlignPC) Offset &= ~0x3;
302 // Let the backend adjust the fixup value if necessary, including whether
303 // we need a relocation.
304 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
310 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
311 const MCFragment &F) const {
312 switch (F.getKind()) {
313 case MCFragment::FT_Data:
314 return cast<MCDataFragment>(F).getContents().size();
315 case MCFragment::FT_Fill:
316 return cast<MCFillFragment>(F).getSize();
317 case MCFragment::FT_Inst:
318 return cast<MCInstFragment>(F).getInstSize();
320 case MCFragment::FT_LEB:
321 return cast<MCLEBFragment>(F).getContents().size();
323 case MCFragment::FT_Align: {
324 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
325 unsigned Offset = Layout.getFragmentOffset(&AF);
326 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
327 if (Size > AF.getMaxBytesToEmit())
332 case MCFragment::FT_Org: {
333 MCOrgFragment &OF = cast<MCOrgFragment>(F);
334 int64_t TargetLocation;
335 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
336 report_fatal_error("expected assembly-time absolute expression");
338 // FIXME: We need a way to communicate this error.
339 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
340 int64_t Size = TargetLocation - FragmentOffset;
341 if (Size < 0 || Size >= 0x40000000)
342 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
343 "' (at offset '" + Twine(FragmentOffset) + "')");
347 case MCFragment::FT_Dwarf:
348 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
349 case MCFragment::FT_DwarfFrame:
350 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
353 llvm_unreachable("invalid fragment kind");
356 void MCAsmLayout::LayoutFragment(MCFragment *F) {
357 MCFragment *Prev = F->getPrevNode();
359 // We should never try to recompute something which is up-to-date.
360 assert(!isFragmentUpToDate(F) && "Attempt to recompute up-to-date fragment!");
361 // We should never try to compute the fragment layout if it's predecessor
363 assert((!Prev || isFragmentUpToDate(Prev)) &&
364 "Attempt to compute fragment before it's predecessor!");
366 ++stats::FragmentLayouts;
368 // Compute fragment offset and size.
371 Offset += Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
374 LastValidFragment[F->getParent()] = F;
377 /// WriteFragmentData - Write the \arg F data to the output file.
378 static void WriteFragmentData(const MCAssembler &Asm, const MCAsmLayout &Layout,
379 const MCFragment &F) {
380 MCObjectWriter *OW = &Asm.getWriter();
381 uint64_t Start = OW->getStream().tell();
384 ++stats::EmittedFragments;
386 // FIXME: Embed in fragments instead?
387 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
388 switch (F.getKind()) {
389 case MCFragment::FT_Align: {
390 MCAlignFragment &AF = cast<MCAlignFragment>(F);
391 uint64_t Count = FragmentSize / AF.getValueSize();
393 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
395 // FIXME: This error shouldn't actually occur (the front end should emit
396 // multiple .align directives to enforce the semantics it wants), but is
397 // severe enough that we want to report it. How to handle this?
398 if (Count * AF.getValueSize() != FragmentSize)
399 report_fatal_error("undefined .align directive, value size '" +
400 Twine(AF.getValueSize()) +
401 "' is not a divisor of padding size '" +
402 Twine(FragmentSize) + "'");
404 // See if we are aligning with nops, and if so do that first to try to fill
405 // the Count bytes. Then if that did not fill any bytes or there are any
406 // bytes left to fill use the the Value and ValueSize to fill the rest.
407 // If we are aligning with nops, ask that target to emit the right data.
408 if (AF.hasEmitNops()) {
409 if (!Asm.getBackend().writeNopData(Count, OW))
410 report_fatal_error("unable to write nop sequence of " +
411 Twine(Count) + " bytes");
415 // Otherwise, write out in multiples of the value size.
416 for (uint64_t i = 0; i != Count; ++i) {
417 switch (AF.getValueSize()) {
418 default: llvm_unreachable("Invalid size!");
419 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
420 case 2: OW->Write16(uint16_t(AF.getValue())); break;
421 case 4: OW->Write32(uint32_t(AF.getValue())); break;
422 case 8: OW->Write64(uint64_t(AF.getValue())); break;
428 case MCFragment::FT_Data: {
429 MCDataFragment &DF = cast<MCDataFragment>(F);
430 assert(FragmentSize == DF.getContents().size() && "Invalid size!");
431 OW->WriteBytes(DF.getContents().str());
435 case MCFragment::FT_Fill: {
436 MCFillFragment &FF = cast<MCFillFragment>(F);
438 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
440 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
441 switch (FF.getValueSize()) {
442 default: llvm_unreachable("Invalid size!");
443 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
444 case 2: OW->Write16(uint16_t(FF.getValue())); break;
445 case 4: OW->Write32(uint32_t(FF.getValue())); break;
446 case 8: OW->Write64(uint64_t(FF.getValue())); break;
452 case MCFragment::FT_Inst: {
453 MCInstFragment &IF = cast<MCInstFragment>(F);
454 OW->WriteBytes(StringRef(IF.getCode().begin(), IF.getCode().size()));
458 case MCFragment::FT_LEB: {
459 MCLEBFragment &LF = cast<MCLEBFragment>(F);
460 OW->WriteBytes(LF.getContents().str());
464 case MCFragment::FT_Org: {
465 MCOrgFragment &OF = cast<MCOrgFragment>(F);
467 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
468 OW->Write8(uint8_t(OF.getValue()));
473 case MCFragment::FT_Dwarf: {
474 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
475 OW->WriteBytes(OF.getContents().str());
478 case MCFragment::FT_DwarfFrame: {
479 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
480 OW->WriteBytes(CF.getContents().str());
485 assert(OW->getStream().tell() - Start == FragmentSize);
488 void MCAssembler::writeSectionData(const MCSectionData *SD,
489 const MCAsmLayout &Layout) const {
490 // Ignore virtual sections.
491 if (SD->getSection().isVirtualSection()) {
492 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
494 // Check that contents are only things legal inside a virtual section.
495 for (MCSectionData::const_iterator it = SD->begin(),
496 ie = SD->end(); it != ie; ++it) {
497 switch (it->getKind()) {
498 default: llvm_unreachable("Invalid fragment in virtual section!");
499 case MCFragment::FT_Data: {
500 // Check that we aren't trying to write a non-zero contents (or fixups)
501 // into a virtual section. This is to support clients which use standard
502 // directives to fill the contents of virtual sections.
503 MCDataFragment &DF = cast<MCDataFragment>(*it);
504 assert(DF.fixup_begin() == DF.fixup_end() &&
505 "Cannot have fixups in virtual section!");
506 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
507 assert(DF.getContents()[i] == 0 &&
508 "Invalid data value for virtual section!");
511 case MCFragment::FT_Align:
512 // Check that we aren't trying to write a non-zero value into a virtual
514 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
515 !cast<MCAlignFragment>(it)->getValue()) &&
516 "Invalid align in virtual section!");
518 case MCFragment::FT_Fill:
519 assert(!cast<MCFillFragment>(it)->getValueSize() &&
520 "Invalid fill in virtual section!");
528 uint64_t Start = getWriter().getStream().tell();
531 for (MCSectionData::const_iterator it = SD->begin(),
532 ie = SD->end(); it != ie; ++it)
533 WriteFragmentData(*this, Layout, *it);
535 assert(getWriter().getStream().tell() - Start ==
536 Layout.getSectionAddressSize(SD));
540 uint64_t MCAssembler::handleFixup(const MCAsmLayout &Layout,
542 const MCFixup &Fixup) {
543 // Evaluate the fixup.
546 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
547 // The fixup was unresolved, we need a relocation. Inform the object
548 // writer of the relocation, and give it an opportunity to adjust the
549 // fixup value if need be.
550 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
555 void MCAssembler::Finish() {
556 DEBUG_WITH_TYPE("mc-dump", {
557 llvm::errs() << "assembler backend - pre-layout\n--\n";
560 // Create the layout object.
561 MCAsmLayout Layout(*this);
563 // Create dummy fragments and assign section ordinals.
564 unsigned SectionIndex = 0;
565 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
566 // Create dummy fragments to eliminate any empty sections, this simplifies
568 if (it->getFragmentList().empty())
569 new MCDataFragment(it);
571 it->setOrdinal(SectionIndex++);
574 // Assign layout order indices to sections and fragments.
575 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
576 MCSectionData *SD = Layout.getSectionOrder()[i];
577 SD->setLayoutOrder(i);
579 unsigned FragmentIndex = 0;
580 for (MCSectionData::iterator it2 = SD->begin(),
581 ie2 = SD->end(); it2 != ie2; ++it2)
582 it2->setLayoutOrder(FragmentIndex++);
585 // Layout until everything fits.
586 while (layoutOnce(Layout))
589 DEBUG_WITH_TYPE("mc-dump", {
590 llvm::errs() << "assembler backend - post-relaxation\n--\n";
593 // Finalize the layout, including fragment lowering.
594 finishLayout(Layout);
596 DEBUG_WITH_TYPE("mc-dump", {
597 llvm::errs() << "assembler backend - final-layout\n--\n";
600 uint64_t StartOffset = OS.tell();
602 // Allow the object writer a chance to perform post-layout binding (for
603 // example, to set the index fields in the symbol data).
604 getWriter().ExecutePostLayoutBinding(*this, Layout);
606 // Evaluate and apply the fixups, generating relocation entries as necessary.
607 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
608 for (MCSectionData::iterator it2 = it->begin(),
609 ie2 = it->end(); it2 != ie2; ++it2) {
610 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
612 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
613 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
614 MCFixup &Fixup = *it3;
615 uint64_t FixedValue = handleFixup(Layout, *DF, Fixup);
616 getBackend().applyFixup(Fixup, DF->getContents().data(),
617 DF->getContents().size(), FixedValue);
620 MCInstFragment *IF = dyn_cast<MCInstFragment>(it2);
622 for (MCInstFragment::fixup_iterator it3 = IF->fixup_begin(),
623 ie3 = IF->fixup_end(); it3 != ie3; ++it3) {
624 MCFixup &Fixup = *it3;
625 uint64_t FixedValue = handleFixup(Layout, *IF, Fixup);
626 getBackend().applyFixup(Fixup, IF->getCode().data(),
627 IF->getCode().size(), FixedValue);
633 // Write the object file.
634 getWriter().WriteObject(*this, Layout);
636 stats::ObjectBytes += OS.tell() - StartOffset;
639 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
640 const MCInstFragment *DF,
641 const MCAsmLayout &Layout) const {
645 // If we cannot resolve the fixup value, it requires relaxation.
648 if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
651 return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
654 bool MCAssembler::fragmentNeedsRelaxation(const MCInstFragment *IF,
655 const MCAsmLayout &Layout) const {
656 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
657 // are intentionally pushing out inst fragments, or because we relaxed a
658 // previous instruction to one that doesn't need relaxation.
659 if (!getBackend().mayNeedRelaxation(IF->getInst()))
662 for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
663 ie = IF->fixup_end(); it != ie; ++it)
664 if (fixupNeedsRelaxation(*it, IF, Layout))
670 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
671 MCInstFragment &IF) {
672 if (!fragmentNeedsRelaxation(&IF, Layout))
675 ++stats::RelaxedInstructions;
677 // FIXME-PERF: We could immediately lower out instructions if we can tell
678 // they are fully resolved, to avoid retesting on later passes.
680 // Relax the fragment.
683 getBackend().relaxInstruction(IF.getInst(), Relaxed);
685 // Encode the new instruction.
687 // FIXME-PERF: If it matters, we could let the target do this. It can
688 // probably do so more efficiently in many cases.
689 SmallVector<MCFixup, 4> Fixups;
690 SmallString<256> Code;
691 raw_svector_ostream VecOS(Code);
692 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
695 // Update the instruction fragment.
698 IF.getFixups().clear();
699 // FIXME: Eliminate copy.
700 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
701 IF.getFixups().push_back(Fixups[i]);
706 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
708 uint64_t OldSize = LF.getContents().size();
709 bool IsAbs = LF.getValue().EvaluateAsAbsolute(Value, Layout);
712 SmallString<8> &Data = LF.getContents();
714 raw_svector_ostream OSE(Data);
716 MCObjectWriter::EncodeSLEB128(Value, OSE);
718 MCObjectWriter::EncodeULEB128(Value, OSE);
720 return OldSize != LF.getContents().size();
723 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
724 MCDwarfLineAddrFragment &DF) {
725 int64_t AddrDelta = 0;
726 uint64_t OldSize = DF.getContents().size();
727 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
731 LineDelta = DF.getLineDelta();
732 SmallString<8> &Data = DF.getContents();
734 raw_svector_ostream OSE(Data);
735 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
737 return OldSize != Data.size();
740 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
741 MCDwarfCallFrameFragment &DF) {
742 int64_t AddrDelta = 0;
743 uint64_t OldSize = DF.getContents().size();
744 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
747 SmallString<8> &Data = DF.getContents();
749 raw_svector_ostream OSE(Data);
750 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
752 return OldSize != Data.size();
755 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout,
757 MCFragment *FirstInvalidFragment = NULL;
758 // Scan for fragments that need relaxation.
759 for (MCSectionData::iterator it2 = SD.begin(),
760 ie2 = SD.end(); it2 != ie2; ++it2) {
761 // Check if this is an fragment that needs relaxation.
762 bool relaxedFrag = false;
763 switch(it2->getKind()) {
766 case MCFragment::FT_Inst:
767 relaxedFrag = relaxInstruction(Layout, *cast<MCInstFragment>(it2));
769 case MCFragment::FT_Dwarf:
770 relaxedFrag = relaxDwarfLineAddr(Layout,
771 *cast<MCDwarfLineAddrFragment>(it2));
773 case MCFragment::FT_DwarfFrame:
775 relaxDwarfCallFrameFragment(Layout,
776 *cast<MCDwarfCallFrameFragment>(it2));
778 case MCFragment::FT_LEB:
779 relaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(it2));
782 // Update the layout, and remember that we relaxed.
783 if (relaxedFrag && !FirstInvalidFragment)
784 FirstInvalidFragment = it2;
786 if (FirstInvalidFragment) {
787 Layout.Invalidate(FirstInvalidFragment);
793 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
794 ++stats::RelaxationSteps;
796 bool WasRelaxed = false;
797 for (iterator it = begin(), ie = end(); it != ie; ++it) {
798 MCSectionData &SD = *it;
799 while(layoutSectionOnce(Layout, SD))
806 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
807 // The layout is done. Mark every fragment as valid.
808 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
809 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
817 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
818 OS << "<MCFixup" << " Offset:" << AF.getOffset()
819 << " Value:" << *AF.getValue()
820 << " Kind:" << AF.getKind() << ">";
826 void MCFragment::dump() {
827 raw_ostream &OS = llvm::errs();
831 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
832 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
833 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
834 case MCFragment::FT_Inst: OS << "MCInstFragment"; break;
835 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
836 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
837 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
838 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
841 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
842 << " Offset:" << Offset << ">";
845 case MCFragment::FT_Align: {
846 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
847 if (AF->hasEmitNops())
848 OS << " (emit nops)";
850 OS << " Alignment:" << AF->getAlignment()
851 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
852 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
855 case MCFragment::FT_Data: {
856 const MCDataFragment *DF = cast<MCDataFragment>(this);
859 const SmallVectorImpl<char> &Contents = DF->getContents();
860 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
862 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
864 OS << "] (" << Contents.size() << " bytes)";
866 if (!DF->getFixups().empty()) {
869 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
870 ie = DF->fixup_end(); it != ie; ++it) {
871 if (it != DF->fixup_begin()) OS << ",\n ";
878 case MCFragment::FT_Fill: {
879 const MCFillFragment *FF = cast<MCFillFragment>(this);
880 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
881 << " Size:" << FF->getSize();
884 case MCFragment::FT_Inst: {
885 const MCInstFragment *IF = cast<MCInstFragment>(this);
888 IF->getInst().dump_pretty(OS);
891 case MCFragment::FT_Org: {
892 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
894 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
897 case MCFragment::FT_Dwarf: {
898 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
900 OS << " AddrDelta:" << OF->getAddrDelta()
901 << " LineDelta:" << OF->getLineDelta();
904 case MCFragment::FT_DwarfFrame: {
905 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
907 OS << " AddrDelta:" << CF->getAddrDelta();
910 case MCFragment::FT_LEB: {
911 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
913 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
920 void MCSectionData::dump() {
921 raw_ostream &OS = llvm::errs();
923 OS << "<MCSectionData";
924 OS << " Alignment:" << getAlignment() << " Fragments:[\n ";
925 for (iterator it = begin(), ie = end(); it != ie; ++it) {
926 if (it != begin()) OS << ",\n ";
932 void MCSymbolData::dump() {
933 raw_ostream &OS = llvm::errs();
935 OS << "<MCSymbolData Symbol:" << getSymbol()
936 << " Fragment:" << getFragment() << " Offset:" << getOffset()
937 << " Flags:" << getFlags() << " Index:" << getIndex();
939 OS << " (common, size:" << getCommonSize()
940 << " align: " << getCommonAlignment() << ")";
943 if (isPrivateExtern())
944 OS << " (private extern)";
948 void MCAssembler::dump() {
949 raw_ostream &OS = llvm::errs();
951 OS << "<MCAssembler\n";
952 OS << " Sections:[\n ";
953 for (iterator it = begin(), ie = end(); it != ie; ++it) {
954 if (it != begin()) OS << ",\n ";
960 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
961 if (it != symbol_begin()) OS << ",\n ";
967 // anchors for MC*Fragment vtables
968 void MCDataFragment::anchor() { }
969 void MCInstFragment::anchor() { }
970 void MCAlignFragment::anchor() { }
971 void MCFillFragment::anchor() { }
972 void MCOrgFragment::anchor() { }
973 void MCLEBFragment::anchor() { }
974 void MCDwarfLineAddrFragment::anchor() { }
975 void MCDwarfCallFrameFragment::anchor() { }