1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "llvm/MC/MCAssembler.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/Statistic.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/MC/MCAsmBackend.h"
17 #include "llvm/MC/MCAsmInfo.h"
18 #include "llvm/MC/MCAsmLayout.h"
19 #include "llvm/MC/MCCodeEmitter.h"
20 #include "llvm/MC/MCCodeView.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCDwarf.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCFixup.h"
25 #include "llvm/MC/MCFixupKindInfo.h"
26 #include "llvm/MC/MCFragment.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCObjectWriter.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCSectionELF.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/MC/MCValue.h"
33 #include "llvm/Support/Alignment.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/EndianStream.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/LEB128.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
49 #define DEBUG_TYPE "assembler"
54 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
55 STATISTIC(EmittedRelaxableFragments,
56 "Number of emitted assembler fragments - relaxable");
57 STATISTIC(EmittedDataFragments,
58 "Number of emitted assembler fragments - data");
59 STATISTIC(EmittedCompactEncodedInstFragments,
60 "Number of emitted assembler fragments - compact encoded inst");
61 STATISTIC(EmittedAlignFragments,
62 "Number of emitted assembler fragments - align");
63 STATISTIC(EmittedFillFragments,
64 "Number of emitted assembler fragments - fill");
65 STATISTIC(EmittedOrgFragments,
66 "Number of emitted assembler fragments - org");
67 STATISTIC(evaluateFixup, "Number of evaluated fixups");
68 STATISTIC(FragmentLayouts, "Number of fragment layouts");
69 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
70 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
71 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
73 } // end namespace stats
74 } // end anonymous namespace
76 // FIXME FIXME FIXME: There are number of places in this file where we convert
77 // what is a 64-bit assembler value used for computation into a value in the
78 // object file, which may truncate it. We should detect that truncation where
79 // invalid and report errors back.
83 MCAssembler::MCAssembler(MCContext &Context,
84 std::unique_ptr<MCAsmBackend> Backend,
85 std::unique_ptr<MCCodeEmitter> Emitter,
86 std::unique_ptr<MCObjectWriter> Writer)
87 : Context(Context), Backend(std::move(Backend)),
88 Emitter(std::move(Emitter)), Writer(std::move(Writer)),
89 BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
90 IncrementalLinkerCompatible(false), ELFHeaderEFlags(0) {
91 VersionInfo.Major = 0; // Major version == 0 for "none specified"
94 MCAssembler::~MCAssembler() = default;
96 void MCAssembler::reset() {
99 IndirectSymbols.clear();
101 LinkerOptions.clear();
106 SubsectionsViaSymbols = false;
107 IncrementalLinkerCompatible = false;
109 LOHContainer.reset();
110 VersionInfo.Major = 0;
111 VersionInfo.SDKVersion = VersionTuple();
113 // reset objects owned by us
115 getBackendPtr()->reset();
117 getEmitterPtr()->reset();
119 getWriterPtr()->reset();
120 getLOHContainer().reset();
123 bool MCAssembler::registerSection(MCSection &Section) {
124 if (Section.isRegistered())
126 Sections.push_back(&Section);
127 Section.setIsRegistered(true);
131 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
132 if (ThumbFuncs.count(Symbol))
135 if (!Symbol->isVariable())
138 const MCExpr *Expr = Symbol->getVariableValue();
141 if (!Expr->evaluateAsRelocatable(V, nullptr, nullptr))
144 if (V.getSymB() || V.getRefKind() != MCSymbolRefExpr::VK_None)
147 const MCSymbolRefExpr *Ref = V.getSymA();
151 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
154 const MCSymbol &Sym = Ref->getSymbol();
155 if (!isThumbFunc(&Sym))
158 ThumbFuncs.insert(Symbol); // Cache it.
162 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
163 // Non-temporary labels should always be visible to the linker.
164 if (!Symbol.isTemporary())
167 if (Symbol.isUsedInReloc())
173 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
174 // Linker visible symbols define atoms.
175 if (isSymbolLinkerVisible(S))
178 // Absolute and undefined symbols have no defining atom.
179 if (!S.isInSection())
182 // Non-linker visible symbols in sections which can't be atomized have no
184 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
185 *S.getFragment()->getParent()))
188 // Otherwise, return the atom for the containing fragment.
189 return S.getFragment()->getAtom();
192 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
193 const MCFixup &Fixup, const MCFragment *DF,
194 MCValue &Target, uint64_t &Value,
195 bool &WasForced) const {
196 ++stats::evaluateFixup;
198 // FIXME: This code has some duplication with recordRelocation. We should
199 // probably merge the two into a single callback that tries to evaluate a
200 // fixup and records a relocation if one is needed.
202 // On error claim to have completely evaluated the fixup, to prevent any
203 // further processing from being done.
204 const MCExpr *Expr = Fixup.getValue();
205 MCContext &Ctx = getContext();
208 if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) {
209 Ctx.reportError(Fixup.getLoc(), "expected relocatable expression");
212 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
213 if (RefB->getKind() != MCSymbolRefExpr::VK_None) {
214 Ctx.reportError(Fixup.getLoc(),
215 "unsupported subtraction of qualified symbol");
220 assert(getBackendPtr() && "Expected assembler backend");
221 bool IsTarget = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
222 MCFixupKindInfo::FKF_IsTarget;
225 return getBackend().evaluateTargetFixup(*this, Layout, Fixup, DF, Target,
228 unsigned FixupFlags = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags;
229 bool IsPCRel = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
230 MCFixupKindInfo::FKF_IsPCRel;
232 bool IsResolved = false;
234 if (Target.getSymB()) {
236 } else if (!Target.getSymA()) {
239 const MCSymbolRefExpr *A = Target.getSymA();
240 const MCSymbol &SA = A->getSymbol();
241 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
243 } else if (auto *Writer = getWriterPtr()) {
244 IsResolved = (FixupFlags & MCFixupKindInfo::FKF_Constant) ||
245 Writer->isSymbolRefDifferenceFullyResolvedImpl(
246 *this, SA, *DF, false, true);
250 IsResolved = Target.isAbsolute();
253 Value = Target.getConstant();
255 if (const MCSymbolRefExpr *A = Target.getSymA()) {
256 const MCSymbol &Sym = A->getSymbol();
258 Value += Layout.getSymbolOffset(Sym);
260 if (const MCSymbolRefExpr *B = Target.getSymB()) {
261 const MCSymbol &Sym = B->getSymbol();
263 Value -= Layout.getSymbolOffset(Sym);
266 bool ShouldAlignPC = getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
267 MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
268 assert((ShouldAlignPC ? IsPCRel : true) &&
269 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
272 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
274 // A number of ARM fixups in Thumb mode require that the effective PC
275 // address be determined as the 32-bit aligned version of the actual offset.
276 if (ShouldAlignPC) Offset &= ~0x3;
280 // Let the backend force a relocation if needed.
281 if (IsResolved && getBackend().shouldForceRelocation(*this, Fixup, Target)) {
289 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
290 const MCFragment &F) const {
291 assert(getBackendPtr() && "Requires assembler backend");
292 switch (F.getKind()) {
293 case MCFragment::FT_Data:
294 return cast<MCDataFragment>(F).getContents().size();
295 case MCFragment::FT_Relaxable:
296 return cast<MCRelaxableFragment>(F).getContents().size();
297 case MCFragment::FT_CompactEncodedInst:
298 return cast<MCCompactEncodedInstFragment>(F).getContents().size();
299 case MCFragment::FT_Fill: {
300 auto &FF = cast<MCFillFragment>(F);
301 int64_t NumValues = 0;
302 if (!FF.getNumValues().evaluateAsAbsolute(NumValues, Layout)) {
303 getContext().reportError(FF.getLoc(),
304 "expected assembly-time absolute expression");
307 int64_t Size = NumValues * FF.getValueSize();
309 getContext().reportError(FF.getLoc(), "invalid number of bytes");
315 case MCFragment::FT_LEB:
316 return cast<MCLEBFragment>(F).getContents().size();
318 case MCFragment::FT_BoundaryAlign:
319 return cast<MCBoundaryAlignFragment>(F).getSize();
321 case MCFragment::FT_SymbolId:
324 case MCFragment::FT_Align: {
325 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
326 unsigned Offset = Layout.getFragmentOffset(&AF);
327 unsigned Size = offsetToAlignment(Offset, Align(AF.getAlignment()));
329 // Insert extra Nops for code alignment if the target define
330 // shouldInsertExtraNopBytesForCodeAlign target hook.
331 if (AF.getParent()->UseCodeAlign() && AF.hasEmitNops() &&
332 getBackend().shouldInsertExtraNopBytesForCodeAlign(AF, Size))
335 // If we are padding with nops, force the padding to be larger than the
337 if (Size > 0 && AF.hasEmitNops()) {
338 while (Size % getBackend().getMinimumNopSize())
339 Size += AF.getAlignment();
341 if (Size > AF.getMaxBytesToEmit())
346 case MCFragment::FT_Org: {
347 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
349 if (!OF.getOffset().evaluateAsValue(Value, Layout)) {
350 getContext().reportError(OF.getLoc(),
351 "expected assembly-time absolute expression");
355 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
356 int64_t TargetLocation = Value.getConstant();
357 if (const MCSymbolRefExpr *A = Value.getSymA()) {
359 if (!Layout.getSymbolOffset(A->getSymbol(), Val)) {
360 getContext().reportError(OF.getLoc(), "expected absolute expression");
363 TargetLocation += Val;
365 int64_t Size = TargetLocation - FragmentOffset;
366 if (Size < 0 || Size >= 0x40000000) {
367 getContext().reportError(
368 OF.getLoc(), "invalid .org offset '" + Twine(TargetLocation) +
369 "' (at offset '" + Twine(FragmentOffset) + "')");
375 case MCFragment::FT_Dwarf:
376 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
377 case MCFragment::FT_DwarfFrame:
378 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
379 case MCFragment::FT_CVInlineLines:
380 return cast<MCCVInlineLineTableFragment>(F).getContents().size();
381 case MCFragment::FT_CVDefRange:
382 return cast<MCCVDefRangeFragment>(F).getContents().size();
383 case MCFragment::FT_Dummy:
384 llvm_unreachable("Should not have been added");
387 llvm_unreachable("invalid fragment kind");
390 void MCAsmLayout::layoutFragment(MCFragment *F) {
391 MCFragment *Prev = F->getPrevNode();
393 // We should never try to recompute something which is valid.
394 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
395 // We should never try to compute the fragment layout if its predecessor
397 assert((!Prev || isFragmentValid(Prev)) &&
398 "Attempt to compute fragment before its predecessor!");
400 assert(!F->IsBeingLaidOut && "Already being laid out!");
401 F->IsBeingLaidOut = true;
403 ++stats::FragmentLayouts;
405 // Compute fragment offset and size.
407 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
410 F->IsBeingLaidOut = false;
411 LastValidFragment[F->getParent()] = F;
413 // If bundling is enabled and this fragment has instructions in it, it has to
414 // obey the bundling restrictions. With padding, we'll have:
419 // -------------------------------------
420 // Prev |##########| F |
421 // -------------------------------------
426 // The fragment's offset will point to after the padding, and its computed
427 // size won't include the padding.
429 // When the -mc-relax-all flag is used, we optimize bundling by writting the
430 // padding directly into fragments when the instructions are emitted inside
431 // the streamer. When the fragment is larger than the bundle size, we need to
432 // ensure that it's bundle aligned. This means that if we end up with
433 // multiple fragments, we must emit bundle padding between fragments.
435 // ".align N" is an example of a directive that introduces multiple
436 // fragments. We could add a special case to handle ".align N" by emitting
437 // within-fragment padding (which would produce less padding when N is less
438 // than the bundle size), but for now we don't.
440 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
441 assert(isa<MCEncodedFragment>(F) &&
442 "Only MCEncodedFragment implementations have instructions");
443 MCEncodedFragment *EF = cast<MCEncodedFragment>(F);
444 uint64_t FSize = Assembler.computeFragmentSize(*this, *EF);
446 if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
447 report_fatal_error("Fragment can't be larger than a bundle size");
449 uint64_t RequiredBundlePadding =
450 computeBundlePadding(Assembler, EF, EF->Offset, FSize);
451 if (RequiredBundlePadding > UINT8_MAX)
452 report_fatal_error("Padding cannot exceed 255 bytes");
453 EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
454 EF->Offset += RequiredBundlePadding;
458 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
459 bool New = !Symbol.isRegistered();
463 Symbol.setIsRegistered(true);
464 Symbols.push_back(&Symbol);
468 void MCAssembler::writeFragmentPadding(raw_ostream &OS,
469 const MCEncodedFragment &EF,
470 uint64_t FSize) const {
471 assert(getBackendPtr() && "Expected assembler backend");
472 // Should NOP padding be written out before this fragment?
473 unsigned BundlePadding = EF.getBundlePadding();
474 if (BundlePadding > 0) {
475 assert(isBundlingEnabled() &&
476 "Writing bundle padding with disabled bundling");
477 assert(EF.hasInstructions() &&
478 "Writing bundle padding for a fragment without instructions");
480 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
481 if (EF.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
482 // If the padding itself crosses a bundle boundary, it must be emitted
483 // in 2 pieces, since even nop instructions must not cross boundaries.
484 // v--------------v <- BundleAlignSize
485 // v---------v <- BundlePadding
486 // ----------------------------
487 // | Prev |####|####| F |
488 // ----------------------------
489 // ^-------------------^ <- TotalLength
490 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
491 if (!getBackend().writeNopData(OS, DistanceToBoundary))
492 report_fatal_error("unable to write NOP sequence of " +
493 Twine(DistanceToBoundary) + " bytes");
494 BundlePadding -= DistanceToBoundary;
496 if (!getBackend().writeNopData(OS, BundlePadding))
497 report_fatal_error("unable to write NOP sequence of " +
498 Twine(BundlePadding) + " bytes");
502 /// Write the fragment \p F to the output file.
503 static void writeFragment(raw_ostream &OS, const MCAssembler &Asm,
504 const MCAsmLayout &Layout, const MCFragment &F) {
505 // FIXME: Embed in fragments instead?
506 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
508 support::endianness Endian = Asm.getBackend().Endian;
510 if (const MCEncodedFragment *EF = dyn_cast<MCEncodedFragment>(&F))
511 Asm.writeFragmentPadding(OS, *EF, FragmentSize);
513 // This variable (and its dummy usage) is to participate in the assert at
514 // the end of the function.
515 uint64_t Start = OS.tell();
518 ++stats::EmittedFragments;
520 switch (F.getKind()) {
521 case MCFragment::FT_Align: {
522 ++stats::EmittedAlignFragments;
523 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
524 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
526 uint64_t Count = FragmentSize / AF.getValueSize();
528 // FIXME: This error shouldn't actually occur (the front end should emit
529 // multiple .align directives to enforce the semantics it wants), but is
530 // severe enough that we want to report it. How to handle this?
531 if (Count * AF.getValueSize() != FragmentSize)
532 report_fatal_error("undefined .align directive, value size '" +
533 Twine(AF.getValueSize()) +
534 "' is not a divisor of padding size '" +
535 Twine(FragmentSize) + "'");
537 // See if we are aligning with nops, and if so do that first to try to fill
538 // the Count bytes. Then if that did not fill any bytes or there are any
539 // bytes left to fill use the Value and ValueSize to fill the rest.
540 // If we are aligning with nops, ask that target to emit the right data.
541 if (AF.hasEmitNops()) {
542 if (!Asm.getBackend().writeNopData(OS, Count))
543 report_fatal_error("unable to write nop sequence of " +
544 Twine(Count) + " bytes");
548 // Otherwise, write out in multiples of the value size.
549 for (uint64_t i = 0; i != Count; ++i) {
550 switch (AF.getValueSize()) {
551 default: llvm_unreachable("Invalid size!");
552 case 1: OS << char(AF.getValue()); break;
554 support::endian::write<uint16_t>(OS, AF.getValue(), Endian);
557 support::endian::write<uint32_t>(OS, AF.getValue(), Endian);
560 support::endian::write<uint64_t>(OS, AF.getValue(), Endian);
567 case MCFragment::FT_Data:
568 ++stats::EmittedDataFragments;
569 OS << cast<MCDataFragment>(F).getContents();
572 case MCFragment::FT_Relaxable:
573 ++stats::EmittedRelaxableFragments;
574 OS << cast<MCRelaxableFragment>(F).getContents();
577 case MCFragment::FT_CompactEncodedInst:
578 ++stats::EmittedCompactEncodedInstFragments;
579 OS << cast<MCCompactEncodedInstFragment>(F).getContents();
582 case MCFragment::FT_Fill: {
583 ++stats::EmittedFillFragments;
584 const MCFillFragment &FF = cast<MCFillFragment>(F);
585 uint64_t V = FF.getValue();
586 unsigned VSize = FF.getValueSize();
587 const unsigned MaxChunkSize = 16;
588 char Data[MaxChunkSize];
589 assert(0 < VSize && VSize <= MaxChunkSize && "Illegal fragment fill size");
590 // Duplicate V into Data as byte vector to reduce number of
591 // writes done. As such, do endian conversion here.
592 for (unsigned I = 0; I != VSize; ++I) {
593 unsigned index = Endian == support::little ? I : (VSize - I - 1);
594 Data[I] = uint8_t(V >> (index * 8));
596 for (unsigned I = VSize; I < MaxChunkSize; ++I)
597 Data[I] = Data[I - VSize];
599 // Set to largest multiple of VSize in Data.
600 const unsigned NumPerChunk = MaxChunkSize / VSize;
601 // Set ChunkSize to largest multiple of VSize in Data
602 const unsigned ChunkSize = VSize * NumPerChunk;
604 // Do copies by chunk.
605 StringRef Ref(Data, ChunkSize);
606 for (uint64_t I = 0, E = FragmentSize / ChunkSize; I != E; ++I)
609 // do remainder if needed.
610 unsigned TrailingCount = FragmentSize % ChunkSize;
612 OS.write(Data, TrailingCount);
616 case MCFragment::FT_LEB: {
617 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
618 OS << LF.getContents();
622 case MCFragment::FT_BoundaryAlign: {
623 if (!Asm.getBackend().writeNopData(OS, FragmentSize))
624 report_fatal_error("unable to write nop sequence of " +
625 Twine(FragmentSize) + " bytes");
629 case MCFragment::FT_SymbolId: {
630 const MCSymbolIdFragment &SF = cast<MCSymbolIdFragment>(F);
631 support::endian::write<uint32_t>(OS, SF.getSymbol()->getIndex(), Endian);
635 case MCFragment::FT_Org: {
636 ++stats::EmittedOrgFragments;
637 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
639 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
640 OS << char(OF.getValue());
645 case MCFragment::FT_Dwarf: {
646 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
647 OS << OF.getContents();
650 case MCFragment::FT_DwarfFrame: {
651 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
652 OS << CF.getContents();
655 case MCFragment::FT_CVInlineLines: {
656 const auto &OF = cast<MCCVInlineLineTableFragment>(F);
657 OS << OF.getContents();
660 case MCFragment::FT_CVDefRange: {
661 const auto &DRF = cast<MCCVDefRangeFragment>(F);
662 OS << DRF.getContents();
665 case MCFragment::FT_Dummy:
666 llvm_unreachable("Should not have been added");
669 assert(OS.tell() - Start == FragmentSize &&
670 "The stream should advance by fragment size");
673 void MCAssembler::writeSectionData(raw_ostream &OS, const MCSection *Sec,
674 const MCAsmLayout &Layout) const {
675 assert(getBackendPtr() && "Expected assembler backend");
677 // Ignore virtual sections.
678 if (Sec->isVirtualSection()) {
679 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
681 // Check that contents are only things legal inside a virtual section.
682 for (const MCFragment &F : *Sec) {
683 switch (F.getKind()) {
684 default: llvm_unreachable("Invalid fragment in virtual section!");
685 case MCFragment::FT_Data: {
686 // Check that we aren't trying to write a non-zero contents (or fixups)
687 // into a virtual section. This is to support clients which use standard
688 // directives to fill the contents of virtual sections.
689 const MCDataFragment &DF = cast<MCDataFragment>(F);
690 if (DF.fixup_begin() != DF.fixup_end())
691 getContext().reportError(SMLoc(), Sec->getVirtualSectionKind() +
692 " section '" + Sec->getName() +
693 "' cannot have fixups");
694 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
695 if (DF.getContents()[i]) {
696 getContext().reportError(SMLoc(),
697 Sec->getVirtualSectionKind() +
698 " section '" + Sec->getName() +
699 "' cannot have non-zero initializers");
704 case MCFragment::FT_Align:
705 // Check that we aren't trying to write a non-zero value into a virtual
707 assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
708 cast<MCAlignFragment>(F).getValue() == 0) &&
709 "Invalid align in virtual section!");
711 case MCFragment::FT_Fill:
712 assert((cast<MCFillFragment>(F).getValue() == 0) &&
713 "Invalid fill in virtual section!");
721 uint64_t Start = OS.tell();
724 for (const MCFragment &F : *Sec)
725 writeFragment(OS, *this, Layout, F);
727 assert(OS.tell() - Start == Layout.getSectionAddressSize(Sec));
730 std::tuple<MCValue, uint64_t, bool>
731 MCAssembler::handleFixup(const MCAsmLayout &Layout, MCFragment &F,
732 const MCFixup &Fixup) {
733 // Evaluate the fixup.
737 bool IsResolved = evaluateFixup(Layout, Fixup, &F, Target, FixedValue,
740 // The fixup was unresolved, we need a relocation. Inform the object
741 // writer of the relocation, and give it an opportunity to adjust the
742 // fixup value if need be.
743 if (Target.getSymA() && Target.getSymB() &&
744 getBackend().requiresDiffExpressionRelocations()) {
745 // The fixup represents the difference between two symbols, which the
746 // backend has indicated must be resolved at link time. Split up the fixup
747 // into two relocations, one for the add, and one for the sub, and emit
748 // both of these. The constant will be associated with the add half of the
750 MCFixup FixupAdd = MCFixup::createAddFor(Fixup);
752 MCValue::get(Target.getSymA(), nullptr, Target.getConstant());
753 getWriter().recordRelocation(*this, Layout, &F, FixupAdd, TargetAdd,
755 MCFixup FixupSub = MCFixup::createSubFor(Fixup);
756 MCValue TargetSub = MCValue::get(Target.getSymB());
757 getWriter().recordRelocation(*this, Layout, &F, FixupSub, TargetSub,
760 getWriter().recordRelocation(*this, Layout, &F, Fixup, Target,
764 return std::make_tuple(Target, FixedValue, IsResolved);
767 void MCAssembler::layout(MCAsmLayout &Layout) {
768 assert(getBackendPtr() && "Expected assembler backend");
769 DEBUG_WITH_TYPE("mc-dump", {
770 errs() << "assembler backend - pre-layout\n--\n";
773 // Create dummy fragments and assign section ordinals.
774 unsigned SectionIndex = 0;
775 for (MCSection &Sec : *this) {
776 // Create dummy fragments to eliminate any empty sections, this simplifies
778 if (Sec.getFragmentList().empty())
779 new MCDataFragment(&Sec);
781 Sec.setOrdinal(SectionIndex++);
784 // Assign layout order indices to sections and fragments.
785 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
786 MCSection *Sec = Layout.getSectionOrder()[i];
787 Sec->setLayoutOrder(i);
789 unsigned FragmentIndex = 0;
790 for (MCFragment &Frag : *Sec)
791 Frag.setLayoutOrder(FragmentIndex++);
794 // Layout until everything fits.
795 while (layoutOnce(Layout)) {
796 if (getContext().hadError())
798 // Size of fragments in one section can depend on the size of fragments in
799 // another. If any fragment has changed size, we have to re-layout (and
800 // as a result possibly further relax) all.
801 for (MCSection &Sec : *this)
802 Layout.invalidateFragmentsFrom(&*Sec.begin());
805 DEBUG_WITH_TYPE("mc-dump", {
806 errs() << "assembler backend - post-relaxation\n--\n";
809 // Finalize the layout, including fragment lowering.
810 finishLayout(Layout);
812 DEBUG_WITH_TYPE("mc-dump", {
813 errs() << "assembler backend - final-layout\n--\n";
816 // Allow the object writer a chance to perform post-layout binding (for
817 // example, to set the index fields in the symbol data).
818 getWriter().executePostLayoutBinding(*this, Layout);
820 // Evaluate and apply the fixups, generating relocation entries as necessary.
821 for (MCSection &Sec : *this) {
822 for (MCFragment &Frag : Sec) {
823 ArrayRef<MCFixup> Fixups;
824 MutableArrayRef<char> Contents;
825 const MCSubtargetInfo *STI = nullptr;
827 // Process MCAlignFragment and MCEncodedFragmentWithFixups here.
828 switch (Frag.getKind()) {
831 case MCFragment::FT_Align: {
832 MCAlignFragment &AF = cast<MCAlignFragment>(Frag);
833 // Insert fixup type for code alignment if the target define
834 // shouldInsertFixupForCodeAlign target hook.
835 if (Sec.UseCodeAlign() && AF.hasEmitNops())
836 getBackend().shouldInsertFixupForCodeAlign(*this, Layout, AF);
839 case MCFragment::FT_Data: {
840 MCDataFragment &DF = cast<MCDataFragment>(Frag);
841 Fixups = DF.getFixups();
842 Contents = DF.getContents();
843 STI = DF.getSubtargetInfo();
844 assert(!DF.hasInstructions() || STI != nullptr);
847 case MCFragment::FT_Relaxable: {
848 MCRelaxableFragment &RF = cast<MCRelaxableFragment>(Frag);
849 Fixups = RF.getFixups();
850 Contents = RF.getContents();
851 STI = RF.getSubtargetInfo();
852 assert(!RF.hasInstructions() || STI != nullptr);
855 case MCFragment::FT_CVDefRange: {
856 MCCVDefRangeFragment &CF = cast<MCCVDefRangeFragment>(Frag);
857 Fixups = CF.getFixups();
858 Contents = CF.getContents();
861 case MCFragment::FT_Dwarf: {
862 MCDwarfLineAddrFragment &DF = cast<MCDwarfLineAddrFragment>(Frag);
863 Fixups = DF.getFixups();
864 Contents = DF.getContents();
867 case MCFragment::FT_DwarfFrame: {
868 MCDwarfCallFrameFragment &DF = cast<MCDwarfCallFrameFragment>(Frag);
869 Fixups = DF.getFixups();
870 Contents = DF.getContents();
874 for (const MCFixup &Fixup : Fixups) {
878 std::tie(Target, FixedValue, IsResolved) =
879 handleFixup(Layout, Frag, Fixup);
880 getBackend().applyFixup(*this, Fixup, Target, Contents, FixedValue,
887 void MCAssembler::Finish() {
888 // Create the layout object.
889 MCAsmLayout Layout(*this);
892 // Write the object file.
893 stats::ObjectBytes += getWriter().writeObject(*this, Layout);
896 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
897 const MCRelaxableFragment *DF,
898 const MCAsmLayout &Layout) const {
899 assert(getBackendPtr() && "Expected assembler backend");
903 bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value, WasForced);
904 if (Target.getSymA() &&
905 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_X86_ABS8 &&
906 Fixup.getKind() == FK_Data_1)
908 return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
912 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
913 const MCAsmLayout &Layout) const {
914 assert(getBackendPtr() && "Expected assembler backend");
915 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
916 // are intentionally pushing out inst fragments, or because we relaxed a
917 // previous instruction to one that doesn't need relaxation.
918 if (!getBackend().mayNeedRelaxation(F->getInst(), *F->getSubtargetInfo()))
921 for (const MCFixup &Fixup : F->getFixups())
922 if (fixupNeedsRelaxation(Fixup, F, Layout))
928 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
929 MCRelaxableFragment &F) {
930 assert(getEmitterPtr() &&
931 "Expected CodeEmitter defined for relaxInstruction");
932 if (!fragmentNeedsRelaxation(&F, Layout))
935 ++stats::RelaxedInstructions;
937 // FIXME-PERF: We could immediately lower out instructions if we can tell
938 // they are fully resolved, to avoid retesting on later passes.
940 // Relax the fragment.
942 MCInst Relaxed = F.getInst();
943 getBackend().relaxInstruction(Relaxed, *F.getSubtargetInfo());
945 // Encode the new instruction.
947 // FIXME-PERF: If it matters, we could let the target do this. It can
948 // probably do so more efficiently in many cases.
949 SmallVector<MCFixup, 4> Fixups;
950 SmallString<256> Code;
951 raw_svector_ostream VecOS(Code);
952 getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, *F.getSubtargetInfo());
954 // Update the fragment.
956 F.getContents() = Code;
957 F.getFixups() = Fixups;
962 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
963 uint64_t OldSize = LF.getContents().size();
965 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
967 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
968 SmallString<8> &Data = LF.getContents();
970 raw_svector_ostream OSE(Data);
971 // The compiler can generate EH table assembly that is impossible to assemble
972 // without either adding padding to an LEB fragment or adding extra padding
973 // to a later alignment fragment. To accommodate such tables, relaxation can
974 // only increase an LEB fragment size here, not decrease it. See PR35809.
976 encodeSLEB128(Value, OSE, OldSize);
978 encodeULEB128(Value, OSE, OldSize);
979 return OldSize != LF.getContents().size();
982 /// Check if the branch crosses the boundary.
984 /// \param StartAddr start address of the fused/unfused branch.
985 /// \param Size size of the fused/unfused branch.
986 /// \param BoundaryAlignment alignment requirement of the branch.
987 /// \returns true if the branch cross the boundary.
988 static bool mayCrossBoundary(uint64_t StartAddr, uint64_t Size,
989 Align BoundaryAlignment) {
990 uint64_t EndAddr = StartAddr + Size;
991 return (StartAddr >> Log2(BoundaryAlignment)) !=
992 ((EndAddr - 1) >> Log2(BoundaryAlignment));
995 /// Check if the branch is against the boundary.
997 /// \param StartAddr start address of the fused/unfused branch.
998 /// \param Size size of the fused/unfused branch.
999 /// \param BoundaryAlignment alignment requirement of the branch.
1000 /// \returns true if the branch is against the boundary.
1001 static bool isAgainstBoundary(uint64_t StartAddr, uint64_t Size,
1002 Align BoundaryAlignment) {
1003 uint64_t EndAddr = StartAddr + Size;
1004 return (EndAddr & (BoundaryAlignment.value() - 1)) == 0;
1007 /// Check if the branch needs padding.
1009 /// \param StartAddr start address of the fused/unfused branch.
1010 /// \param Size size of the fused/unfused branch.
1011 /// \param BoundaryAlignment alignment requirement of the branch.
1012 /// \returns true if the branch needs padding.
1013 static bool needPadding(uint64_t StartAddr, uint64_t Size,
1014 Align BoundaryAlignment) {
1015 return mayCrossBoundary(StartAddr, Size, BoundaryAlignment) ||
1016 isAgainstBoundary(StartAddr, Size, BoundaryAlignment);
1019 bool MCAssembler::relaxBoundaryAlign(MCAsmLayout &Layout,
1020 MCBoundaryAlignFragment &BF) {
1021 // BoundaryAlignFragment that doesn't need to align any fragment should not be
1023 if (!BF.getLastFragment())
1026 uint64_t AlignedOffset = Layout.getFragmentOffset(&BF);
1027 uint64_t AlignedSize = 0;
1028 for (const MCFragment *F = BF.getLastFragment(); F != &BF;
1029 F = F->getPrevNode())
1030 AlignedSize += computeFragmentSize(Layout, *F);
1032 Align BoundaryAlignment = BF.getAlignment();
1033 uint64_t NewSize = needPadding(AlignedOffset, AlignedSize, BoundaryAlignment)
1034 ? offsetToAlignment(AlignedOffset, BoundaryAlignment)
1036 if (NewSize == BF.getSize())
1038 BF.setSize(NewSize);
1039 Layout.invalidateFragmentsFrom(&BF);
1043 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1044 MCDwarfLineAddrFragment &DF) {
1045 MCContext &Context = Layout.getAssembler().getContext();
1046 uint64_t OldSize = DF.getContents().size();
1048 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1049 assert(Abs && "We created a line delta with an invalid expression");
1052 LineDelta = DF.getLineDelta();
1053 SmallVectorImpl<char> &Data = DF.getContents();
1055 raw_svector_ostream OSE(Data);
1056 DF.getFixups().clear();
1058 if (!getBackend().requiresDiffExpressionRelocations()) {
1059 MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
1064 bool SetDelta = MCDwarfLineAddr::FixedEncode(Context,
1065 getDWARFLinetableParams(),
1066 LineDelta, AddrDelta,
1067 OSE, &Offset, &Size);
1068 // Add Fixups for address delta or new address.
1069 const MCExpr *FixupExpr;
1071 FixupExpr = &DF.getAddrDelta();
1073 const MCBinaryExpr *ABE = cast<MCBinaryExpr>(&DF.getAddrDelta());
1074 FixupExpr = ABE->getLHS();
1076 DF.getFixups().push_back(
1077 MCFixup::create(Offset, FixupExpr,
1078 MCFixup::getKindForSize(Size, false /*isPCRel*/)));
1081 return OldSize != Data.size();
1084 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1085 MCDwarfCallFrameFragment &DF) {
1086 MCContext &Context = Layout.getAssembler().getContext();
1087 uint64_t OldSize = DF.getContents().size();
1089 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1090 assert(Abs && "We created call frame with an invalid expression");
1092 SmallVectorImpl<char> &Data = DF.getContents();
1094 raw_svector_ostream OSE(Data);
1095 DF.getFixups().clear();
1097 if (getBackend().requiresDiffExpressionRelocations()) {
1100 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE, &Offset,
1103 DF.getFixups().push_back(MCFixup::create(
1104 Offset, &DF.getAddrDelta(),
1105 MCFixup::getKindForSizeInBits(Size /*In bits.*/, false /*isPCRel*/)));
1108 MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
1111 return OldSize != Data.size();
1114 bool MCAssembler::relaxCVInlineLineTable(MCAsmLayout &Layout,
1115 MCCVInlineLineTableFragment &F) {
1116 unsigned OldSize = F.getContents().size();
1117 getContext().getCVContext().encodeInlineLineTable(Layout, F);
1118 return OldSize != F.getContents().size();
1121 bool MCAssembler::relaxCVDefRange(MCAsmLayout &Layout,
1122 MCCVDefRangeFragment &F) {
1123 unsigned OldSize = F.getContents().size();
1124 getContext().getCVContext().encodeDefRange(Layout, F);
1125 return OldSize != F.getContents().size();
1128 bool MCAssembler::relaxFragment(MCAsmLayout &Layout, MCFragment &F) {
1129 switch(F.getKind()) {
1132 case MCFragment::FT_Relaxable:
1133 assert(!getRelaxAll() &&
1134 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1135 return relaxInstruction(Layout, cast<MCRelaxableFragment>(F));
1136 case MCFragment::FT_Dwarf:
1137 return relaxDwarfLineAddr(Layout, cast<MCDwarfLineAddrFragment>(F));
1138 case MCFragment::FT_DwarfFrame:
1139 return relaxDwarfCallFrameFragment(Layout,
1140 cast<MCDwarfCallFrameFragment>(F));
1141 case MCFragment::FT_LEB:
1142 return relaxLEB(Layout, cast<MCLEBFragment>(F));
1143 case MCFragment::FT_BoundaryAlign:
1144 return relaxBoundaryAlign(Layout, cast<MCBoundaryAlignFragment>(F));
1145 case MCFragment::FT_CVInlineLines:
1146 return relaxCVInlineLineTable(Layout, cast<MCCVInlineLineTableFragment>(F));
1147 case MCFragment::FT_CVDefRange:
1148 return relaxCVDefRange(Layout, cast<MCCVDefRangeFragment>(F));
1152 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1153 // Holds the first fragment which needed relaxing during this layout. It will
1154 // remain NULL if none were relaxed.
1155 // When a fragment is relaxed, all the fragments following it should get
1156 // invalidated because their offset is going to change.
1157 MCFragment *FirstRelaxedFragment = nullptr;
1159 // Attempt to relax all the fragments in the section.
1160 for (MCFragment &Frag : Sec) {
1161 // Check if this is a fragment that needs relaxation.
1162 bool RelaxedFrag = relaxFragment(Layout, Frag);
1163 if (RelaxedFrag && !FirstRelaxedFragment)
1164 FirstRelaxedFragment = &Frag;
1166 if (FirstRelaxedFragment) {
1167 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1173 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1174 ++stats::RelaxationSteps;
1176 bool WasRelaxed = false;
1177 for (MCSection &Sec : *this) {
1178 while (layoutSectionOnce(Layout, Sec))
1185 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1186 assert(getBackendPtr() && "Expected assembler backend");
1187 // The layout is done. Mark every fragment as valid.
1188 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1189 MCSection &Section = *Layout.getSectionOrder()[i];
1190 Layout.getFragmentOffset(&*Section.getFragmentList().rbegin());
1191 computeFragmentSize(Layout, *Section.getFragmentList().rbegin());
1193 getBackend().finishLayout(*this, Layout);
1196 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1197 LLVM_DUMP_METHOD void MCAssembler::dump() const{
1198 raw_ostream &OS = errs();
1200 OS << "<MCAssembler\n";
1201 OS << " Sections:[\n ";
1202 for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
1203 if (it != begin()) OS << ",\n ";
1209 for (const_symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1210 if (it != symbol_begin()) OS << ",\n ";
1213 OS << ", Index:" << it->getIndex() << ", ";