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 #include "llvm/MC/MCAssembler.h"
11 #include "llvm/ADT/Statistic.h"
12 #include "llvm/ADT/StringExtras.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCAsmLayout.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCCodeView.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCDwarf.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCFixupKindInfo.h"
23 #include "llvm/MC/MCObjectWriter.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/MC/MCSectionELF.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/MC/MCValue.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/LEB128.h"
31 #include "llvm/Support/TargetRegistry.h"
32 #include "llvm/Support/raw_ostream.h"
36 #define DEBUG_TYPE "assembler"
40 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
41 STATISTIC(EmittedRelaxableFragments,
42 "Number of emitted assembler fragments - relaxable");
43 STATISTIC(EmittedDataFragments,
44 "Number of emitted assembler fragments - data");
45 STATISTIC(EmittedCompactEncodedInstFragments,
46 "Number of emitted assembler fragments - compact encoded inst");
47 STATISTIC(EmittedAlignFragments,
48 "Number of emitted assembler fragments - align");
49 STATISTIC(EmittedFillFragments,
50 "Number of emitted assembler fragments - fill");
51 STATISTIC(EmittedOrgFragments,
52 "Number of emitted assembler fragments - org");
53 STATISTIC(evaluateFixup, "Number of evaluated fixups");
54 STATISTIC(FragmentLayouts, "Number of fragment layouts");
55 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
56 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
57 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
61 // FIXME FIXME FIXME: There are number of places in this file where we convert
62 // what is a 64-bit assembler value used for computation into a value in the
63 // object file, which may truncate it. We should detect that truncation where
64 // invalid and report errors back.
68 MCAssembler::MCAssembler(MCContext &Context, MCAsmBackend &Backend,
69 MCCodeEmitter &Emitter, MCObjectWriter &Writer)
70 : Context(Context), Backend(Backend), Emitter(Emitter), Writer(Writer),
71 BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
72 IncrementalLinkerCompatible(false), ELFHeaderEFlags(0) {
73 VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
76 MCAssembler::~MCAssembler() {
79 void MCAssembler::reset() {
82 IndirectSymbols.clear();
84 LinkerOptions.clear();
89 SubsectionsViaSymbols = false;
90 IncrementalLinkerCompatible = false;
93 VersionMinInfo.Major = 0;
95 // reset objects owned by us
99 getLOHContainer().reset();
102 bool MCAssembler::registerSection(MCSection &Section) {
103 if (Section.isRegistered())
105 Sections.push_back(&Section);
106 Section.setIsRegistered(true);
110 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
111 if (ThumbFuncs.count(Symbol))
114 if (!Symbol->isVariable())
117 // FIXME: It looks like gas supports some cases of the form "foo + 2". It
118 // is not clear if that is a bug or a feature.
119 const MCExpr *Expr = Symbol->getVariableValue();
120 const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
124 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
127 const MCSymbol &Sym = Ref->getSymbol();
128 if (!isThumbFunc(&Sym))
131 ThumbFuncs.insert(Symbol); // Cache it.
135 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
136 // Non-temporary labels should always be visible to the linker.
137 if (!Symbol.isTemporary())
140 // Absolute temporary labels are never visible.
141 if (!Symbol.isInSection())
144 if (Symbol.isUsedInReloc())
150 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
151 // Linker visible symbols define atoms.
152 if (isSymbolLinkerVisible(S))
155 // Absolute and undefined symbols have no defining atom.
156 if (!S.isInSection())
159 // Non-linker visible symbols in sections which can't be atomized have no
161 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
162 *S.getFragment()->getParent()))
165 // Otherwise, return the atom for the containing fragment.
166 return S.getFragment()->getAtom();
169 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
170 const MCFixup &Fixup, const MCFragment *DF,
171 MCValue &Target, uint64_t &Value) const {
172 ++stats::evaluateFixup;
174 // FIXME: This code has some duplication with recordRelocation. We should
175 // probably merge the two into a single callback that tries to evaluate a
176 // fixup and records a relocation if one is needed.
177 const MCExpr *Expr = Fixup.getValue();
178 if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) {
179 getContext().reportError(Fixup.getLoc(), "expected relocatable expression");
180 // Claim to have completely evaluated the fixup, to prevent any further
181 // processing from being done.
186 bool IsPCRel = Backend.getFixupKindInfo(
187 Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
191 if (Target.getSymB()) {
193 } else if (!Target.getSymA()) {
196 const MCSymbolRefExpr *A = Target.getSymA();
197 const MCSymbol &SA = A->getSymbol();
198 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
201 IsResolved = getWriter().isSymbolRefDifferenceFullyResolvedImpl(
202 *this, SA, *DF, false, true);
206 IsResolved = Target.isAbsolute();
209 Value = Target.getConstant();
211 if (const MCSymbolRefExpr *A = Target.getSymA()) {
212 const MCSymbol &Sym = A->getSymbol();
214 Value += Layout.getSymbolOffset(Sym);
216 if (const MCSymbolRefExpr *B = Target.getSymB()) {
217 const MCSymbol &Sym = B->getSymbol();
219 Value -= Layout.getSymbolOffset(Sym);
223 bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
224 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
225 assert((ShouldAlignPC ? IsPCRel : true) &&
226 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
229 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
231 // A number of ARM fixups in Thumb mode require that the effective PC
232 // address be determined as the 32-bit aligned version of the actual offset.
233 if (ShouldAlignPC) Offset &= ~0x3;
237 // Let the backend adjust the fixup value if necessary, including whether
238 // we need a relocation.
239 Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
245 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
246 const MCFragment &F) const {
247 switch (F.getKind()) {
248 case MCFragment::FT_Data:
249 return cast<MCDataFragment>(F).getContents().size();
250 case MCFragment::FT_Relaxable:
251 return cast<MCRelaxableFragment>(F).getContents().size();
252 case MCFragment::FT_CompactEncodedInst:
253 return cast<MCCompactEncodedInstFragment>(F).getContents().size();
254 case MCFragment::FT_Fill:
255 return cast<MCFillFragment>(F).getSize();
257 case MCFragment::FT_LEB:
258 return cast<MCLEBFragment>(F).getContents().size();
260 case MCFragment::FT_SafeSEH:
263 case MCFragment::FT_Align: {
264 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
265 unsigned Offset = Layout.getFragmentOffset(&AF);
266 unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
267 // If we are padding with nops, force the padding to be larger than the
269 if (Size > 0 && AF.hasEmitNops()) {
270 while (Size % getBackend().getMinimumNopSize())
271 Size += AF.getAlignment();
273 if (Size > AF.getMaxBytesToEmit())
278 case MCFragment::FT_Org: {
279 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
281 if (!OF.getOffset().evaluateAsValue(Value, Layout)) {
282 getContext().reportError(OF.getLoc(),
283 "expected assembly-time absolute expression");
287 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
288 int64_t TargetLocation = Value.getConstant();
289 if (const MCSymbolRefExpr *A = Value.getSymA()) {
291 if (!Layout.getSymbolOffset(A->getSymbol(), Val)) {
292 getContext().reportError(OF.getLoc(), "expected absolute expression");
295 TargetLocation += Val;
297 int64_t Size = TargetLocation - FragmentOffset;
298 if (Size < 0 || Size >= 0x40000000) {
299 getContext().reportError(
300 OF.getLoc(), "invalid .org offset '" + Twine(TargetLocation) +
301 "' (at offset '" + Twine(FragmentOffset) + "')");
307 case MCFragment::FT_Dwarf:
308 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
309 case MCFragment::FT_DwarfFrame:
310 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
311 case MCFragment::FT_CVInlineLines:
312 return cast<MCCVInlineLineTableFragment>(F).getContents().size();
313 case MCFragment::FT_CVDefRange:
314 return cast<MCCVDefRangeFragment>(F).getContents().size();
315 case MCFragment::FT_Dummy:
316 llvm_unreachable("Should not have been added");
319 llvm_unreachable("invalid fragment kind");
322 void MCAsmLayout::layoutFragment(MCFragment *F) {
323 MCFragment *Prev = F->getPrevNode();
325 // We should never try to recompute something which is valid.
326 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
327 // We should never try to compute the fragment layout if its predecessor
329 assert((!Prev || isFragmentValid(Prev)) &&
330 "Attempt to compute fragment before its predecessor!");
332 ++stats::FragmentLayouts;
334 // Compute fragment offset and size.
336 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
339 LastValidFragment[F->getParent()] = F;
341 // If bundling is enabled and this fragment has instructions in it, it has to
342 // obey the bundling restrictions. With padding, we'll have:
347 // -------------------------------------
348 // Prev |##########| F |
349 // -------------------------------------
354 // The fragment's offset will point to after the padding, and its computed
355 // size won't include the padding.
357 // When the -mc-relax-all flag is used, we optimize bundling by writting the
358 // padding directly into fragments when the instructions are emitted inside
359 // the streamer. When the fragment is larger than the bundle size, we need to
360 // ensure that it's bundle aligned. This means that if we end up with
361 // multiple fragments, we must emit bundle padding between fragments.
363 // ".align N" is an example of a directive that introduces multiple
364 // fragments. We could add a special case to handle ".align N" by emitting
365 // within-fragment padding (which would produce less padding when N is less
366 // than the bundle size), but for now we don't.
368 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
369 assert(isa<MCEncodedFragment>(F) &&
370 "Only MCEncodedFragment implementations have instructions");
371 uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
373 if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
374 report_fatal_error("Fragment can't be larger than a bundle size");
376 uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
378 if (RequiredBundlePadding > UINT8_MAX)
379 report_fatal_error("Padding cannot exceed 255 bytes");
380 F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
381 F->Offset += RequiredBundlePadding;
385 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
386 bool New = !Symbol.isRegistered();
390 Symbol.setIsRegistered(true);
391 Symbols.push_back(&Symbol);
395 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
396 MCObjectWriter *OW) const {
397 // Should NOP padding be written out before this fragment?
398 unsigned BundlePadding = F.getBundlePadding();
399 if (BundlePadding > 0) {
400 assert(isBundlingEnabled() &&
401 "Writing bundle padding with disabled bundling");
402 assert(F.hasInstructions() &&
403 "Writing bundle padding for a fragment without instructions");
405 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
406 if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
407 // If the padding itself crosses a bundle boundary, it must be emitted
408 // in 2 pieces, since even nop instructions must not cross boundaries.
409 // v--------------v <- BundleAlignSize
410 // v---------v <- BundlePadding
411 // ----------------------------
412 // | Prev |####|####| F |
413 // ----------------------------
414 // ^-------------------^ <- TotalLength
415 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
416 if (!getBackend().writeNopData(DistanceToBoundary, OW))
417 report_fatal_error("unable to write NOP sequence of " +
418 Twine(DistanceToBoundary) + " bytes");
419 BundlePadding -= DistanceToBoundary;
421 if (!getBackend().writeNopData(BundlePadding, OW))
422 report_fatal_error("unable to write NOP sequence of " +
423 Twine(BundlePadding) + " bytes");
427 /// \brief Write the fragment \p F to the output file.
428 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
429 const MCFragment &F) {
430 MCObjectWriter *OW = &Asm.getWriter();
432 // FIXME: Embed in fragments instead?
433 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
435 Asm.writeFragmentPadding(F, FragmentSize, OW);
437 // This variable (and its dummy usage) is to participate in the assert at
438 // the end of the function.
439 uint64_t Start = OW->getStream().tell();
442 ++stats::EmittedFragments;
444 switch (F.getKind()) {
445 case MCFragment::FT_Align: {
446 ++stats::EmittedAlignFragments;
447 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
448 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
450 uint64_t Count = FragmentSize / AF.getValueSize();
452 // FIXME: This error shouldn't actually occur (the front end should emit
453 // multiple .align directives to enforce the semantics it wants), but is
454 // severe enough that we want to report it. How to handle this?
455 if (Count * AF.getValueSize() != FragmentSize)
456 report_fatal_error("undefined .align directive, value size '" +
457 Twine(AF.getValueSize()) +
458 "' is not a divisor of padding size '" +
459 Twine(FragmentSize) + "'");
461 // See if we are aligning with nops, and if so do that first to try to fill
462 // the Count bytes. Then if that did not fill any bytes or there are any
463 // bytes left to fill use the Value and ValueSize to fill the rest.
464 // If we are aligning with nops, ask that target to emit the right data.
465 if (AF.hasEmitNops()) {
466 if (!Asm.getBackend().writeNopData(Count, OW))
467 report_fatal_error("unable to write nop sequence of " +
468 Twine(Count) + " bytes");
472 // Otherwise, write out in multiples of the value size.
473 for (uint64_t i = 0; i != Count; ++i) {
474 switch (AF.getValueSize()) {
475 default: llvm_unreachable("Invalid size!");
476 case 1: OW->write8 (uint8_t (AF.getValue())); break;
477 case 2: OW->write16(uint16_t(AF.getValue())); break;
478 case 4: OW->write32(uint32_t(AF.getValue())); break;
479 case 8: OW->write64(uint64_t(AF.getValue())); break;
485 case MCFragment::FT_Data:
486 ++stats::EmittedDataFragments;
487 OW->writeBytes(cast<MCDataFragment>(F).getContents());
490 case MCFragment::FT_Relaxable:
491 ++stats::EmittedRelaxableFragments;
492 OW->writeBytes(cast<MCRelaxableFragment>(F).getContents());
495 case MCFragment::FT_CompactEncodedInst:
496 ++stats::EmittedCompactEncodedInstFragments;
497 OW->writeBytes(cast<MCCompactEncodedInstFragment>(F).getContents());
500 case MCFragment::FT_Fill: {
501 ++stats::EmittedFillFragments;
502 const MCFillFragment &FF = cast<MCFillFragment>(F);
503 uint8_t V = FF.getValue();
504 const unsigned MaxChunkSize = 16;
505 char Data[MaxChunkSize];
507 for (unsigned I = 1; I < MaxChunkSize; ++I)
510 uint64_t Size = FF.getSize();
511 for (unsigned ChunkSize = MaxChunkSize; ChunkSize; ChunkSize /= 2) {
512 StringRef Ref(Data, ChunkSize);
513 for (uint64_t I = 0, E = Size / ChunkSize; I != E; ++I)
515 Size = Size % ChunkSize;
520 case MCFragment::FT_LEB: {
521 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
522 OW->writeBytes(LF.getContents());
526 case MCFragment::FT_SafeSEH: {
527 const MCSafeSEHFragment &SF = cast<MCSafeSEHFragment>(F);
528 OW->write32(SF.getSymbol()->getIndex());
532 case MCFragment::FT_Org: {
533 ++stats::EmittedOrgFragments;
534 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
536 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
537 OW->write8(uint8_t(OF.getValue()));
542 case MCFragment::FT_Dwarf: {
543 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
544 OW->writeBytes(OF.getContents());
547 case MCFragment::FT_DwarfFrame: {
548 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
549 OW->writeBytes(CF.getContents());
552 case MCFragment::FT_CVInlineLines: {
553 const auto &OF = cast<MCCVInlineLineTableFragment>(F);
554 OW->writeBytes(OF.getContents());
557 case MCFragment::FT_CVDefRange: {
558 const auto &DRF = cast<MCCVDefRangeFragment>(F);
559 OW->writeBytes(DRF.getContents());
562 case MCFragment::FT_Dummy:
563 llvm_unreachable("Should not have been added");
566 assert(OW->getStream().tell() - Start == FragmentSize &&
567 "The stream should advance by fragment size");
570 void MCAssembler::writeSectionData(const MCSection *Sec,
571 const MCAsmLayout &Layout) const {
572 // Ignore virtual sections.
573 if (Sec->isVirtualSection()) {
574 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
576 // Check that contents are only things legal inside a virtual section.
577 for (const MCFragment &F : *Sec) {
578 switch (F.getKind()) {
579 default: llvm_unreachable("Invalid fragment in virtual section!");
580 case MCFragment::FT_Data: {
581 // Check that we aren't trying to write a non-zero contents (or fixups)
582 // into a virtual section. This is to support clients which use standard
583 // directives to fill the contents of virtual sections.
584 const MCDataFragment &DF = cast<MCDataFragment>(F);
585 if (DF.fixup_begin() != DF.fixup_end())
586 report_fatal_error("cannot have fixups in virtual section!");
587 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
588 if (DF.getContents()[i]) {
589 if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
590 report_fatal_error("non-zero initializer found in section '" +
591 ELFSec->getSectionName() + "'");
593 report_fatal_error("non-zero initializer found in virtual section");
597 case MCFragment::FT_Align:
598 // Check that we aren't trying to write a non-zero value into a virtual
600 assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
601 cast<MCAlignFragment>(F).getValue() == 0) &&
602 "Invalid align in virtual section!");
604 case MCFragment::FT_Fill:
605 assert((cast<MCFillFragment>(F).getValue() == 0) &&
606 "Invalid fill in virtual section!");
614 uint64_t Start = getWriter().getStream().tell();
617 for (const MCFragment &F : *Sec)
618 writeFragment(*this, Layout, F);
620 assert(getWriter().getStream().tell() - Start ==
621 Layout.getSectionAddressSize(Sec));
624 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
626 const MCFixup &Fixup) {
627 // Evaluate the fixup.
630 bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
631 MCFixupKindInfo::FKF_IsPCRel;
632 if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
633 // The fixup was unresolved, we need a relocation. Inform the object
634 // writer of the relocation, and give it an opportunity to adjust the
635 // fixup value if need be.
636 getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
639 return std::make_pair(FixedValue, IsPCRel);
642 void MCAssembler::layout(MCAsmLayout &Layout) {
643 DEBUG_WITH_TYPE("mc-dump", {
644 llvm::errs() << "assembler backend - pre-layout\n--\n";
647 // Create dummy fragments and assign section ordinals.
648 unsigned SectionIndex = 0;
649 for (MCSection &Sec : *this) {
650 // Create dummy fragments to eliminate any empty sections, this simplifies
652 if (Sec.getFragmentList().empty())
653 new MCDataFragment(&Sec);
655 Sec.setOrdinal(SectionIndex++);
658 // Assign layout order indices to sections and fragments.
659 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
660 MCSection *Sec = Layout.getSectionOrder()[i];
661 Sec->setLayoutOrder(i);
663 unsigned FragmentIndex = 0;
664 for (MCFragment &Frag : *Sec)
665 Frag.setLayoutOrder(FragmentIndex++);
668 // Layout until everything fits.
669 while (layoutOnce(Layout))
670 if (getContext().hadError())
673 DEBUG_WITH_TYPE("mc-dump", {
674 llvm::errs() << "assembler backend - post-relaxation\n--\n";
677 // Finalize the layout, including fragment lowering.
678 finishLayout(Layout);
680 DEBUG_WITH_TYPE("mc-dump", {
681 llvm::errs() << "assembler backend - final-layout\n--\n";
684 // Allow the object writer a chance to perform post-layout binding (for
685 // example, to set the index fields in the symbol data).
686 getWriter().executePostLayoutBinding(*this, Layout);
688 // Evaluate and apply the fixups, generating relocation entries as necessary.
689 for (MCSection &Sec : *this) {
690 for (MCFragment &Frag : Sec) {
691 // Data and relaxable fragments both have fixups. So only process
693 // FIXME: Is there a better way to do this? MCEncodedFragmentWithFixups
694 // being templated makes this tricky.
695 if (isa<MCEncodedFragment>(&Frag) &&
696 isa<MCCompactEncodedInstFragment>(&Frag))
698 if (!isa<MCEncodedFragment>(&Frag) && !isa<MCCVDefRangeFragment>(&Frag))
700 ArrayRef<MCFixup> Fixups;
701 MutableArrayRef<char> Contents;
702 if (auto *FragWithFixups = dyn_cast<MCDataFragment>(&Frag)) {
703 Fixups = FragWithFixups->getFixups();
704 Contents = FragWithFixups->getContents();
705 } else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(&Frag)) {
706 Fixups = FragWithFixups->getFixups();
707 Contents = FragWithFixups->getContents();
708 } else if (auto *FragWithFixups = dyn_cast<MCCVDefRangeFragment>(&Frag)) {
709 Fixups = FragWithFixups->getFixups();
710 Contents = FragWithFixups->getContents();
712 llvm_unreachable("Unknown fragment with fixups!");
713 for (const MCFixup &Fixup : Fixups) {
716 std::tie(FixedValue, IsPCRel) = handleFixup(Layout, Frag, Fixup);
717 getBackend().applyFixup(Fixup, Contents.data(),
718 Contents.size(), FixedValue, IsPCRel);
724 void MCAssembler::Finish() {
725 // Create the layout object.
726 MCAsmLayout Layout(*this);
729 raw_ostream &OS = getWriter().getStream();
730 uint64_t StartOffset = OS.tell();
732 // Write the object file.
733 getWriter().writeObject(*this, Layout);
735 stats::ObjectBytes += OS.tell() - StartOffset;
738 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
739 const MCRelaxableFragment *DF,
740 const MCAsmLayout &Layout) const {
743 bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value);
744 return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
748 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
749 const MCAsmLayout &Layout) const {
750 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
751 // are intentionally pushing out inst fragments, or because we relaxed a
752 // previous instruction to one that doesn't need relaxation.
753 if (!getBackend().mayNeedRelaxation(F->getInst()))
756 for (const MCFixup &Fixup : F->getFixups())
757 if (fixupNeedsRelaxation(Fixup, F, Layout))
763 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
764 MCRelaxableFragment &F) {
765 if (!fragmentNeedsRelaxation(&F, Layout))
768 ++stats::RelaxedInstructions;
770 // FIXME-PERF: We could immediately lower out instructions if we can tell
771 // they are fully resolved, to avoid retesting on later passes.
773 // Relax the fragment.
776 getBackend().relaxInstruction(F.getInst(), F.getSubtargetInfo(), Relaxed);
778 // Encode the new instruction.
780 // FIXME-PERF: If it matters, we could let the target do this. It can
781 // probably do so more efficiently in many cases.
782 SmallVector<MCFixup, 4> Fixups;
783 SmallString<256> Code;
784 raw_svector_ostream VecOS(Code);
785 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
787 // Update the fragment.
789 F.getContents() = Code;
790 F.getFixups() = Fixups;
795 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
796 uint64_t OldSize = LF.getContents().size();
798 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
800 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
801 SmallString<8> &Data = LF.getContents();
803 raw_svector_ostream OSE(Data);
805 encodeSLEB128(Value, OSE);
807 encodeULEB128(Value, OSE);
808 return OldSize != LF.getContents().size();
811 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
812 MCDwarfLineAddrFragment &DF) {
813 MCContext &Context = Layout.getAssembler().getContext();
814 uint64_t OldSize = DF.getContents().size();
816 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
817 assert(Abs && "We created a line delta with an invalid expression");
820 LineDelta = DF.getLineDelta();
821 SmallString<8> &Data = DF.getContents();
823 raw_svector_ostream OSE(Data);
824 MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
826 return OldSize != Data.size();
829 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
830 MCDwarfCallFrameFragment &DF) {
831 MCContext &Context = Layout.getAssembler().getContext();
832 uint64_t OldSize = DF.getContents().size();
834 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
835 assert(Abs && "We created call frame with an invalid expression");
837 SmallString<8> &Data = DF.getContents();
839 raw_svector_ostream OSE(Data);
840 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
841 return OldSize != Data.size();
844 bool MCAssembler::relaxCVInlineLineTable(MCAsmLayout &Layout,
845 MCCVInlineLineTableFragment &F) {
846 unsigned OldSize = F.getContents().size();
847 getContext().getCVContext().encodeInlineLineTable(Layout, F);
848 return OldSize != F.getContents().size();
851 bool MCAssembler::relaxCVDefRange(MCAsmLayout &Layout,
852 MCCVDefRangeFragment &F) {
853 unsigned OldSize = F.getContents().size();
854 getContext().getCVContext().encodeDefRange(Layout, F);
855 return OldSize != F.getContents().size();
858 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
859 // Holds the first fragment which needed relaxing during this layout. It will
860 // remain NULL if none were relaxed.
861 // When a fragment is relaxed, all the fragments following it should get
862 // invalidated because their offset is going to change.
863 MCFragment *FirstRelaxedFragment = nullptr;
865 // Attempt to relax all the fragments in the section.
866 for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
867 // Check if this is a fragment that needs relaxation.
868 bool RelaxedFrag = false;
869 switch(I->getKind()) {
872 case MCFragment::FT_Relaxable:
873 assert(!getRelaxAll() &&
874 "Did not expect a MCRelaxableFragment in RelaxAll mode");
875 RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
877 case MCFragment::FT_Dwarf:
878 RelaxedFrag = relaxDwarfLineAddr(Layout,
879 *cast<MCDwarfLineAddrFragment>(I));
881 case MCFragment::FT_DwarfFrame:
883 relaxDwarfCallFrameFragment(Layout,
884 *cast<MCDwarfCallFrameFragment>(I));
886 case MCFragment::FT_LEB:
887 RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
889 case MCFragment::FT_CVInlineLines:
891 relaxCVInlineLineTable(Layout, *cast<MCCVInlineLineTableFragment>(I));
893 case MCFragment::FT_CVDefRange:
894 RelaxedFrag = relaxCVDefRange(Layout, *cast<MCCVDefRangeFragment>(I));
897 if (RelaxedFrag && !FirstRelaxedFragment)
898 FirstRelaxedFragment = &*I;
900 if (FirstRelaxedFragment) {
901 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
907 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
908 ++stats::RelaxationSteps;
910 bool WasRelaxed = false;
911 for (iterator it = begin(), ie = end(); it != ie; ++it) {
912 MCSection &Sec = *it;
913 while (layoutSectionOnce(Layout, Sec))
920 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
921 // The layout is done. Mark every fragment as valid.
922 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
923 MCSection &Section = *Layout.getSectionOrder()[i];
924 Layout.getFragmentOffset(&*Section.rbegin());
925 computeFragmentSize(Layout, *Section.rbegin());
927 getBackend().finishLayout(*this, Layout);