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/MCObjectWriter.h"
17 #include "llvm/MC/MCSection.h"
18 #include "llvm/MC/MCSymbol.h"
19 #include "llvm/MC/MCValue.h"
20 #include "llvm/MC/MCDwarf.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Target/TargetRegistry.h"
29 #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 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 assert(SD->getFragment() && "Invalid getOffset() on undefined symbol!");
106 return getFragmentOffset(SD->getFragment()) + SD->getOffset();
109 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
110 // The size is the last fragment's end offset.
111 const MCFragment &F = SD->getFragmentList().back();
112 return getFragmentOffset(&F) + getAssembler().ComputeFragmentSize(*this, F);
115 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
116 // Virtual sections have no file size.
117 if (SD->getSection().isVirtualSection())
120 // Otherwise, the file size is the same as the address space size.
121 return getSectionAddressSize(SD);
126 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
129 MCFragment::~MCFragment() {
132 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
133 : Kind(_Kind), Parent(_Parent), Atom(0), Offset(~UINT64_C(0))
136 Parent->getFragmentList().push_back(this);
141 MCSectionData::MCSectionData() : Section(0) {}
143 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
144 : Section(&_Section),
145 Ordinal(~UINT32_C(0)),
147 HasInstructions(false)
150 A->getSectionList().push_back(this);
155 MCSymbolData::MCSymbolData() : Symbol(0) {}
157 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
158 uint64_t _Offset, MCAssembler *A)
159 : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
160 IsExternal(false), IsPrivateExtern(false),
161 CommonSize(0), SymbolSize(0), CommonAlign(0),
165 A->getSymbolList().push_back(this);
170 MCAssembler::MCAssembler(MCContext &Context_, TargetAsmBackend &Backend_,
171 MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
173 : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
174 OS(OS_), RelaxAll(false), NoExecStack(false), SubsectionsViaSymbols(false)
178 MCAssembler::~MCAssembler() {
181 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
182 // Non-temporary labels should always be visible to the linker.
183 if (!Symbol.isTemporary())
186 // Absolute temporary labels are never visible.
187 if (!Symbol.isInSection())
190 // Otherwise, check if the section requires symbols even for temporary labels.
191 return getBackend().doesSectionRequireSymbols(Symbol.getSection());
194 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
195 // Linker visible symbols define atoms.
196 if (isSymbolLinkerVisible(SD->getSymbol()))
199 // Absolute and undefined symbols have no defining atom.
200 if (!SD->getFragment())
203 // Non-linker visible symbols in sections which can't be atomized have no
205 if (!getBackend().isSectionAtomizable(
206 SD->getFragment()->getParent()->getSection()))
209 // Otherwise, return the atom for the containing fragment.
210 return SD->getFragment()->getAtom();
213 bool MCAssembler::EvaluateFixup(const MCAsmLayout &Layout,
214 const MCFixup &Fixup, const MCFragment *DF,
215 MCValue &Target, uint64_t &Value) const {
216 ++stats::EvaluateFixup;
218 if (!Fixup.getValue()->EvaluateAsRelocatable(Target, Layout))
219 report_fatal_error("expected relocatable expression");
221 bool IsPCRel = Backend.getFixupKindInfo(
222 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
226 if (Target.getSymB()) {
228 } else if (!Target.getSymA()) {
231 const MCSymbolRefExpr *A = Target.getSymA();
232 const MCSymbol &SA = A->getSymbol();
233 if (A->getKind() != MCSymbolRefExpr::VK_None ||
234 SA.AliasedSymbol().isUndefined()) {
237 const MCSymbolData &DataA = getSymbolData(SA);
239 getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
244 IsResolved = Target.isAbsolute();
247 Value = Target.getConstant();
249 bool IsThumb = false;
250 if (const MCSymbolRefExpr *A = Target.getSymA()) {
251 const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
253 Value += Layout.getSymbolOffset(&getSymbolData(Sym));
254 if (isThumbFunc(&Sym))
257 if (const MCSymbolRefExpr *B = Target.getSymB()) {
258 const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
260 Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
264 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
265 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
266 assert((ShouldAlignPC ? IsPCRel : true) &&
267 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
270 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
272 // A number of ARM fixups in Thumb mode require that the effective PC
273 // address be determined as the 32-bit aligned version of the actual offset.
274 if (ShouldAlignPC) Offset &= ~0x3;
278 // ARM fixups based from a thumb function address need to have the low
279 // bit set. The actual value is always at least 16-bit aligned, so the
280 // low bit is normally clear and available for use as an ISA flag for
288 uint64_t MCAssembler::ComputeFragmentSize(const MCAsmLayout &Layout,
289 const MCFragment &F) const {
290 switch (F.getKind()) {
291 case MCFragment::FT_Data:
292 return cast<MCDataFragment>(F).getContents().size();
293 case MCFragment::FT_Fill:
294 return cast<MCFillFragment>(F).getSize();
295 case MCFragment::FT_Inst:
296 return cast<MCInstFragment>(F).getInstSize();
298 case MCFragment::FT_LEB:
299 return cast<MCLEBFragment>(F).getContents().size();
301 case MCFragment::FT_Align: {
302 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
303 unsigned Offset = Layout.getFragmentOffset(&AF);
304 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
305 if (Size > AF.getMaxBytesToEmit())
310 case MCFragment::FT_Org: {
311 MCOrgFragment &OF = cast<MCOrgFragment>(F);
312 int64_t TargetLocation;
313 if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
314 report_fatal_error("expected assembly-time absolute expression");
316 // FIXME: We need a way to communicate this error.
317 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
318 int64_t Size = TargetLocation - FragmentOffset;
319 if (Size < 0 || Size >= 0x40000000)
320 report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
321 "' (at offset '" + Twine(FragmentOffset) + "')");
325 case MCFragment::FT_Dwarf:
326 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
327 case MCFragment::FT_DwarfFrame:
328 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
331 assert(0 && "invalid fragment kind");
335 void MCAsmLayout::LayoutFragment(MCFragment *F) {
336 MCFragment *Prev = F->getPrevNode();
338 // We should never try to recompute something which is up-to-date.
339 assert(!isFragmentUpToDate(F) && "Attempt to recompute up-to-date fragment!");
340 // We should never try to compute the fragment layout if it's predecessor
342 assert((!Prev || isFragmentUpToDate(Prev)) &&
343 "Attempt to compute fragment before it's predecessor!");
345 ++stats::FragmentLayouts;
347 // Compute fragment offset and size.
350 Offset += Prev->Offset + getAssembler().ComputeFragmentSize(*this, *Prev);
353 LastValidFragment[F->getParent()] = F;
356 /// WriteFragmentData - Write the \arg F data to the output file.
357 static void WriteFragmentData(const MCAssembler &Asm, const MCAsmLayout &Layout,
358 const MCFragment &F) {
359 MCObjectWriter *OW = &Asm.getWriter();
360 uint64_t Start = OW->getStream().tell();
363 ++stats::EmittedFragments;
365 // FIXME: Embed in fragments instead?
366 uint64_t FragmentSize = Asm.ComputeFragmentSize(Layout, F);
367 switch (F.getKind()) {
368 case MCFragment::FT_Align: {
369 MCAlignFragment &AF = cast<MCAlignFragment>(F);
370 uint64_t Count = FragmentSize / AF.getValueSize();
372 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
374 // FIXME: This error shouldn't actually occur (the front end should emit
375 // multiple .align directives to enforce the semantics it wants), but is
376 // severe enough that we want to report it. How to handle this?
377 if (Count * AF.getValueSize() != FragmentSize)
378 report_fatal_error("undefined .align directive, value size '" +
379 Twine(AF.getValueSize()) +
380 "' is not a divisor of padding size '" +
381 Twine(FragmentSize) + "'");
383 // See if we are aligning with nops, and if so do that first to try to fill
384 // the Count bytes. Then if that did not fill any bytes or there are any
385 // bytes left to fill use the the Value and ValueSize to fill the rest.
386 // If we are aligning with nops, ask that target to emit the right data.
387 if (AF.hasEmitNops()) {
388 if (!Asm.getBackend().WriteNopData(Count, OW))
389 report_fatal_error("unable to write nop sequence of " +
390 Twine(Count) + " bytes");
394 // Otherwise, write out in multiples of the value size.
395 for (uint64_t i = 0; i != Count; ++i) {
396 switch (AF.getValueSize()) {
398 assert(0 && "Invalid size!");
399 case 1: OW->Write8 (uint8_t (AF.getValue())); break;
400 case 2: OW->Write16(uint16_t(AF.getValue())); break;
401 case 4: OW->Write32(uint32_t(AF.getValue())); break;
402 case 8: OW->Write64(uint64_t(AF.getValue())); break;
408 case MCFragment::FT_Data: {
409 MCDataFragment &DF = cast<MCDataFragment>(F);
410 assert(FragmentSize == DF.getContents().size() && "Invalid size!");
411 OW->WriteBytes(DF.getContents().str());
415 case MCFragment::FT_Fill: {
416 MCFillFragment &FF = cast<MCFillFragment>(F);
418 assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
420 for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
421 switch (FF.getValueSize()) {
423 assert(0 && "Invalid size!");
424 case 1: OW->Write8 (uint8_t (FF.getValue())); break;
425 case 2: OW->Write16(uint16_t(FF.getValue())); break;
426 case 4: OW->Write32(uint32_t(FF.getValue())); break;
427 case 8: OW->Write64(uint64_t(FF.getValue())); break;
433 case MCFragment::FT_Inst: {
434 MCInstFragment &IF = cast<MCInstFragment>(F);
435 OW->WriteBytes(StringRef(IF.getCode().begin(), IF.getCode().size()));
439 case MCFragment::FT_LEB: {
440 MCLEBFragment &LF = cast<MCLEBFragment>(F);
441 OW->WriteBytes(LF.getContents().str());
445 case MCFragment::FT_Org: {
446 MCOrgFragment &OF = cast<MCOrgFragment>(F);
448 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
449 OW->Write8(uint8_t(OF.getValue()));
454 case MCFragment::FT_Dwarf: {
455 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
456 OW->WriteBytes(OF.getContents().str());
459 case MCFragment::FT_DwarfFrame: {
460 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
461 OW->WriteBytes(CF.getContents().str());
466 assert(OW->getStream().tell() - Start == FragmentSize);
469 void MCAssembler::WriteSectionData(const MCSectionData *SD,
470 const MCAsmLayout &Layout) const {
471 // Ignore virtual sections.
472 if (SD->getSection().isVirtualSection()) {
473 assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
475 // Check that contents are only things legal inside a virtual section.
476 for (MCSectionData::const_iterator it = SD->begin(),
477 ie = SD->end(); it != ie; ++it) {
478 switch (it->getKind()) {
480 assert(0 && "Invalid fragment in virtual section!");
481 case MCFragment::FT_Data: {
482 // Check that we aren't trying to write a non-zero contents (or fixups)
483 // into a virtual section. This is to support clients which use standard
484 // directives to fill the contents of virtual sections.
485 MCDataFragment &DF = cast<MCDataFragment>(*it);
486 assert(DF.fixup_begin() == DF.fixup_end() &&
487 "Cannot have fixups in virtual section!");
488 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
489 assert(DF.getContents()[i] == 0 &&
490 "Invalid data value for virtual section!");
493 case MCFragment::FT_Align:
494 // Check that we aren't trying to write a non-zero value into a virtual
496 assert((!cast<MCAlignFragment>(it)->getValueSize() ||
497 !cast<MCAlignFragment>(it)->getValue()) &&
498 "Invalid align in virtual section!");
500 case MCFragment::FT_Fill:
501 assert(!cast<MCFillFragment>(it)->getValueSize() &&
502 "Invalid fill in virtual section!");
510 uint64_t Start = getWriter().getStream().tell();
513 for (MCSectionData::const_iterator it = SD->begin(),
514 ie = SD->end(); it != ie; ++it)
515 WriteFragmentData(*this, Layout, *it);
517 assert(getWriter().getStream().tell() - Start ==
518 Layout.getSectionAddressSize(SD));
522 uint64_t MCAssembler::HandleFixup(const MCAsmLayout &Layout,
524 const MCFixup &Fixup) {
525 // Evaluate the fixup.
528 if (!EvaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
529 // The fixup was unresolved, we need a relocation. Inform the object
530 // writer of the relocation, and give it an opportunity to adjust the
531 // fixup value if need be.
532 getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
537 void MCAssembler::Finish() {
538 DEBUG_WITH_TYPE("mc-dump", {
539 llvm::errs() << "assembler backend - pre-layout\n--\n";
542 // Create the layout object.
543 MCAsmLayout Layout(*this);
545 // Create dummy fragments and assign section ordinals.
546 unsigned SectionIndex = 0;
547 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
548 // Create dummy fragments to eliminate any empty sections, this simplifies
550 if (it->getFragmentList().empty())
551 new MCDataFragment(it);
553 it->setOrdinal(SectionIndex++);
556 // Assign layout order indices to sections and fragments.
557 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
558 MCSectionData *SD = Layout.getSectionOrder()[i];
559 SD->setLayoutOrder(i);
561 unsigned FragmentIndex = 0;
562 for (MCSectionData::iterator it2 = SD->begin(),
563 ie2 = SD->end(); it2 != ie2; ++it2)
564 it2->setLayoutOrder(FragmentIndex++);
567 // Layout until everything fits.
568 while (LayoutOnce(Layout))
571 DEBUG_WITH_TYPE("mc-dump", {
572 llvm::errs() << "assembler backend - post-relaxation\n--\n";
575 // Finalize the layout, including fragment lowering.
576 FinishLayout(Layout);
578 DEBUG_WITH_TYPE("mc-dump", {
579 llvm::errs() << "assembler backend - final-layout\n--\n";
582 uint64_t StartOffset = OS.tell();
584 // Allow the object writer a chance to perform post-layout binding (for
585 // example, to set the index fields in the symbol data).
586 getWriter().ExecutePostLayoutBinding(*this, Layout);
588 // Evaluate and apply the fixups, generating relocation entries as necessary.
589 for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
590 for (MCSectionData::iterator it2 = it->begin(),
591 ie2 = it->end(); it2 != ie2; ++it2) {
592 MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
594 for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
595 ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
596 MCFixup &Fixup = *it3;
597 uint64_t FixedValue = HandleFixup(Layout, *DF, Fixup);
598 getBackend().ApplyFixup(Fixup, DF->getContents().data(),
599 DF->getContents().size(), FixedValue);
602 MCInstFragment *IF = dyn_cast<MCInstFragment>(it2);
604 for (MCInstFragment::fixup_iterator it3 = IF->fixup_begin(),
605 ie3 = IF->fixup_end(); it3 != ie3; ++it3) {
606 MCFixup &Fixup = *it3;
607 uint64_t FixedValue = HandleFixup(Layout, *IF, Fixup);
608 getBackend().ApplyFixup(Fixup, IF->getCode().data(),
609 IF->getCode().size(), FixedValue);
615 // Write the object file.
616 getWriter().WriteObject(*this, Layout);
618 stats::ObjectBytes += OS.tell() - StartOffset;
621 bool MCAssembler::FixupNeedsRelaxation(const MCFixup &Fixup,
622 const MCFragment *DF,
623 const MCAsmLayout &Layout) const {
627 // If we cannot resolve the fixup value, it requires relaxation.
630 if (!EvaluateFixup(Layout, Fixup, DF, Target, Value))
633 // Otherwise, relax if the value is too big for a (signed) i8.
635 // FIXME: This is target dependent!
636 return int64_t(Value) != int64_t(int8_t(Value));
639 bool MCAssembler::FragmentNeedsRelaxation(const MCInstFragment *IF,
640 const MCAsmLayout &Layout) const {
641 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
642 // are intentionally pushing out inst fragments, or because we relaxed a
643 // previous instruction to one that doesn't need relaxation.
644 if (!getBackend().MayNeedRelaxation(IF->getInst()))
647 for (MCInstFragment::const_fixup_iterator it = IF->fixup_begin(),
648 ie = IF->fixup_end(); it != ie; ++it)
649 if (FixupNeedsRelaxation(*it, IF, Layout))
655 bool MCAssembler::RelaxInstruction(MCAsmLayout &Layout,
656 MCInstFragment &IF) {
657 if (!FragmentNeedsRelaxation(&IF, Layout))
660 ++stats::RelaxedInstructions;
662 // FIXME-PERF: We could immediately lower out instructions if we can tell
663 // they are fully resolved, to avoid retesting on later passes.
665 // Relax the fragment.
668 getBackend().RelaxInstruction(IF.getInst(), Relaxed);
670 // Encode the new instruction.
672 // FIXME-PERF: If it matters, we could let the target do this. It can
673 // probably do so more efficiently in many cases.
674 SmallVector<MCFixup, 4> Fixups;
675 SmallString<256> Code;
676 raw_svector_ostream VecOS(Code);
677 getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups);
680 // Update the instruction fragment.
683 IF.getFixups().clear();
684 // FIXME: Eliminate copy.
685 for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
686 IF.getFixups().push_back(Fixups[i]);
691 bool MCAssembler::RelaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
693 uint64_t OldSize = LF.getContents().size();
694 LF.getValue().EvaluateAsAbsolute(Value, Layout);
695 SmallString<8> &Data = LF.getContents();
697 raw_svector_ostream OSE(Data);
699 MCObjectWriter::EncodeSLEB128(Value, OSE);
701 MCObjectWriter::EncodeULEB128(Value, OSE);
703 return OldSize != LF.getContents().size();
706 bool MCAssembler::RelaxDwarfLineAddr(MCAsmLayout &Layout,
707 MCDwarfLineAddrFragment &DF) {
708 int64_t AddrDelta = 0;
709 uint64_t OldSize = DF.getContents().size();
710 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
714 LineDelta = DF.getLineDelta();
715 SmallString<8> &Data = DF.getContents();
717 raw_svector_ostream OSE(Data);
718 MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OSE);
720 return OldSize != Data.size();
723 bool MCAssembler::RelaxDwarfCallFrameFragment(MCAsmLayout &Layout,
724 MCDwarfCallFrameFragment &DF) {
725 int64_t AddrDelta = 0;
726 uint64_t OldSize = DF.getContents().size();
727 bool IsAbs = DF.getAddrDelta().EvaluateAsAbsolute(AddrDelta, Layout);
730 SmallString<8> &Data = DF.getContents();
732 raw_svector_ostream OSE(Data);
733 MCDwarfFrameEmitter::EncodeAdvanceLoc(AddrDelta, OSE);
735 return OldSize != Data.size();
738 bool MCAssembler::LayoutSectionOnce(MCAsmLayout &Layout,
740 MCFragment *FirstInvalidFragment = NULL;
741 // Scan for fragments that need relaxation.
742 for (MCSectionData::iterator it2 = SD.begin(),
743 ie2 = SD.end(); it2 != ie2; ++it2) {
744 // Check if this is an fragment that needs relaxation.
745 bool relaxedFrag = false;
746 switch(it2->getKind()) {
749 case MCFragment::FT_Inst:
750 relaxedFrag = RelaxInstruction(Layout, *cast<MCInstFragment>(it2));
752 case MCFragment::FT_Dwarf:
753 relaxedFrag = RelaxDwarfLineAddr(Layout,
754 *cast<MCDwarfLineAddrFragment>(it2));
756 case MCFragment::FT_DwarfFrame:
758 RelaxDwarfCallFrameFragment(Layout,
759 *cast<MCDwarfCallFrameFragment>(it2));
761 case MCFragment::FT_LEB:
762 relaxedFrag = RelaxLEB(Layout, *cast<MCLEBFragment>(it2));
765 // Update the layout, and remember that we relaxed.
766 if (relaxedFrag && !FirstInvalidFragment)
767 FirstInvalidFragment = it2;
769 if (FirstInvalidFragment) {
770 Layout.Invalidate(FirstInvalidFragment);
776 bool MCAssembler::LayoutOnce(MCAsmLayout &Layout) {
777 ++stats::RelaxationSteps;
779 bool WasRelaxed = false;
780 for (iterator it = begin(), ie = end(); it != ie; ++it) {
781 MCSectionData &SD = *it;
782 while(LayoutSectionOnce(Layout, SD))
789 void MCAssembler::FinishLayout(MCAsmLayout &Layout) {
790 // The layout is done. Mark every fragment as valid.
791 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
792 Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
800 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
801 OS << "<MCFixup" << " Offset:" << AF.getOffset()
802 << " Value:" << *AF.getValue()
803 << " Kind:" << AF.getKind() << ">";
809 void MCFragment::dump() {
810 raw_ostream &OS = llvm::errs();
814 case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
815 case MCFragment::FT_Data: OS << "MCDataFragment"; break;
816 case MCFragment::FT_Fill: OS << "MCFillFragment"; break;
817 case MCFragment::FT_Inst: OS << "MCInstFragment"; break;
818 case MCFragment::FT_Org: OS << "MCOrgFragment"; break;
819 case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
820 case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
821 case MCFragment::FT_LEB: OS << "MCLEBFragment"; break;
824 OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
825 << " Offset:" << Offset << ">";
828 case MCFragment::FT_Align: {
829 const MCAlignFragment *AF = cast<MCAlignFragment>(this);
830 if (AF->hasEmitNops())
831 OS << " (emit nops)";
833 OS << " Alignment:" << AF->getAlignment()
834 << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
835 << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
838 case MCFragment::FT_Data: {
839 const MCDataFragment *DF = cast<MCDataFragment>(this);
842 const SmallVectorImpl<char> &Contents = DF->getContents();
843 for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
845 OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
847 OS << "] (" << Contents.size() << " bytes)";
849 if (!DF->getFixups().empty()) {
852 for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
853 ie = DF->fixup_end(); it != ie; ++it) {
854 if (it != DF->fixup_begin()) OS << ",\n ";
861 case MCFragment::FT_Fill: {
862 const MCFillFragment *FF = cast<MCFillFragment>(this);
863 OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
864 << " Size:" << FF->getSize();
867 case MCFragment::FT_Inst: {
868 const MCInstFragment *IF = cast<MCInstFragment>(this);
871 IF->getInst().dump_pretty(OS);
874 case MCFragment::FT_Org: {
875 const MCOrgFragment *OF = cast<MCOrgFragment>(this);
877 OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
880 case MCFragment::FT_Dwarf: {
881 const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
883 OS << " AddrDelta:" << OF->getAddrDelta()
884 << " LineDelta:" << OF->getLineDelta();
887 case MCFragment::FT_DwarfFrame: {
888 const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
890 OS << " AddrDelta:" << CF->getAddrDelta();
893 case MCFragment::FT_LEB: {
894 const MCLEBFragment *LF = cast<MCLEBFragment>(this);
896 OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
903 void MCSectionData::dump() {
904 raw_ostream &OS = llvm::errs();
906 OS << "<MCSectionData";
907 OS << " Alignment:" << getAlignment() << " Fragments:[\n ";
908 for (iterator it = begin(), ie = end(); it != ie; ++it) {
909 if (it != begin()) OS << ",\n ";
915 void MCSymbolData::dump() {
916 raw_ostream &OS = llvm::errs();
918 OS << "<MCSymbolData Symbol:" << getSymbol()
919 << " Fragment:" << getFragment() << " Offset:" << getOffset()
920 << " Flags:" << getFlags() << " Index:" << getIndex();
922 OS << " (common, size:" << getCommonSize()
923 << " align: " << getCommonAlignment() << ")";
926 if (isPrivateExtern())
927 OS << " (private extern)";
931 void MCAssembler::dump() {
932 raw_ostream &OS = llvm::errs();
934 OS << "<MCAssembler\n";
935 OS << " Sections:[\n ";
936 for (iterator it = begin(), ie = end(); it != ie; ++it) {
937 if (it != begin()) OS << ",\n ";
943 for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
944 if (it != symbol_begin()) OS << ",\n ";