LLVM 17.0.0git
MCAssembler.cpp
Go to the documentation of this file.
1//===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
10#include "llvm/ADT/ArrayRef.h"
13#include "llvm/ADT/Statistic.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/ADT/Twine.h"
17#include "llvm/MC/MCAsmInfo.h"
18#include "llvm/MC/MCAsmLayout.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"
26#include "llvm/MC/MCFragment.h"
27#include "llvm/MC/MCInst.h"
29#include "llvm/MC/MCSection.h"
30#include "llvm/MC/MCSymbol.h"
31#include "llvm/MC/MCValue.h"
34#include "llvm/Support/Debug.h"
37#include "llvm/Support/LEB128.h"
39#include <cassert>
40#include <cstdint>
41#include <tuple>
42#include <utility>
43
44using namespace llvm;
45
46namespace llvm {
47class MCSubtargetInfo;
48}
49
50#define DEBUG_TYPE "assembler"
51
52namespace {
53namespace stats {
54
55STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
56STATISTIC(EmittedRelaxableFragments,
57 "Number of emitted assembler fragments - relaxable");
58STATISTIC(EmittedDataFragments,
59 "Number of emitted assembler fragments - data");
60STATISTIC(EmittedCompactEncodedInstFragments,
61 "Number of emitted assembler fragments - compact encoded inst");
62STATISTIC(EmittedAlignFragments,
63 "Number of emitted assembler fragments - align");
64STATISTIC(EmittedFillFragments,
65 "Number of emitted assembler fragments - fill");
66STATISTIC(EmittedNopsFragments, "Number of emitted assembler fragments - nops");
67STATISTIC(EmittedOrgFragments, "Number of emitted assembler fragments - org");
68STATISTIC(evaluateFixup, "Number of evaluated fixups");
69STATISTIC(FragmentLayouts, "Number of fragment layouts");
70STATISTIC(ObjectBytes, "Number of emitted object file bytes");
71STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
72STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
73
74} // end namespace stats
75} // end anonymous namespace
76
77// FIXME FIXME FIXME: There are number of places in this file where we convert
78// what is a 64-bit assembler value used for computation into a value in the
79// object file, which may truncate it. We should detect that truncation where
80// invalid and report errors back.
81
82/* *** */
83
85 std::unique_ptr<MCAsmBackend> Backend,
86 std::unique_ptr<MCCodeEmitter> Emitter,
87 std::unique_ptr<MCObjectWriter> Writer)
88 : Context(Context), Backend(std::move(Backend)),
89 Emitter(std::move(Emitter)), Writer(std::move(Writer)),
90 BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
91 IncrementalLinkerCompatible(false), ELFHeaderEFlags(0) {
92 VersionInfo.Major = 0; // Major version == 0 for "none specified"
93 DarwinTargetVariantVersionInfo.Major = 0;
94}
95
97
99 Sections.clear();
100 Symbols.clear();
101 IndirectSymbols.clear();
102 DataRegions.clear();
103 LinkerOptions.clear();
104 FileNames.clear();
105 ThumbFuncs.clear();
106 BundleAlignSize = 0;
107 RelaxAll = false;
108 SubsectionsViaSymbols = false;
109 IncrementalLinkerCompatible = false;
110 ELFHeaderEFlags = 0;
111 LOHContainer.reset();
112 VersionInfo.Major = 0;
113 VersionInfo.SDKVersion = VersionTuple();
114 DarwinTargetVariantVersionInfo.Major = 0;
115 DarwinTargetVariantVersionInfo.SDKVersion = VersionTuple();
116
117 // reset objects owned by us
118 if (getBackendPtr())
119 getBackendPtr()->reset();
120 if (getEmitterPtr())
121 getEmitterPtr()->reset();
122 if (getWriterPtr())
123 getWriterPtr()->reset();
125}
126
128 if (Section.isRegistered())
129 return false;
130 Sections.push_back(&Section);
131 Section.setIsRegistered(true);
132 return true;
133}
134
135bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
136 if (ThumbFuncs.count(Symbol))
137 return true;
138
139 if (!Symbol->isVariable())
140 return false;
141
142 const MCExpr *Expr = Symbol->getVariableValue();
143
144 MCValue V;
145 if (!Expr->evaluateAsRelocatable(V, nullptr, nullptr))
146 return false;
147
148 if (V.getSymB() || V.getRefKind() != MCSymbolRefExpr::VK_None)
149 return false;
150
151 const MCSymbolRefExpr *Ref = V.getSymA();
152 if (!Ref)
153 return false;
154
155 if (Ref->getKind() != MCSymbolRefExpr::VK_None)
156 return false;
157
158 const MCSymbol &Sym = Ref->getSymbol();
159 if (!isThumbFunc(&Sym))
160 return false;
161
162 ThumbFuncs.insert(Symbol); // Cache it.
163 return true;
164}
165
167 // Non-temporary labels should always be visible to the linker.
168 if (!Symbol.isTemporary())
169 return true;
170
171 if (Symbol.isUsedInReloc())
172 return true;
173
174 return false;
175}
176
177const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
178 // Linker visible symbols define atoms.
180 return &S;
181
182 // Absolute and undefined symbols have no defining atom.
183 if (!S.isInSection())
184 return nullptr;
185
186 // Non-linker visible symbols in sections which can't be atomized have no
187 // defining atom.
188 if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
189 *S.getFragment()->getParent()))
190 return nullptr;
191
192 // Otherwise, return the atom for the containing fragment.
193 return S.getFragment()->getAtom();
194}
195
196bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
197 const MCFixup &Fixup, const MCFragment *DF,
199 bool &WasForced) const {
200 ++stats::evaluateFixup;
201
202 // FIXME: This code has some duplication with recordRelocation. We should
203 // probably merge the two into a single callback that tries to evaluate a
204 // fixup and records a relocation if one is needed.
205
206 // On error claim to have completely evaluated the fixup, to prevent any
207 // further processing from being done.
208 const MCExpr *Expr = Fixup.getValue();
209 MCContext &Ctx = getContext();
210 Value = 0;
211 WasForced = false;
212 if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup)) {
213 Ctx.reportError(Fixup.getLoc(), "expected relocatable expression");
214 return true;
215 }
216 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
217 if (RefB->getKind() != MCSymbolRefExpr::VK_None) {
218 Ctx.reportError(Fixup.getLoc(),
219 "unsupported subtraction of qualified symbol");
220 return true;
221 }
222 }
223
224 assert(getBackendPtr() && "Expected assembler backend");
225 bool IsTarget = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
227
228 if (IsTarget)
229 return getBackend().evaluateTargetFixup(*this, Layout, Fixup, DF, Target,
230 Value, WasForced);
231
232 unsigned FixupFlags = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags;
233 bool IsPCRel = getBackendPtr()->getFixupKindInfo(Fixup.getKind()).Flags &
235
236 bool IsResolved = false;
237 if (IsPCRel) {
238 if (Target.getSymB()) {
239 IsResolved = false;
240 } else if (!Target.getSymA()) {
241 IsResolved = false;
242 } else {
243 const MCSymbolRefExpr *A = Target.getSymA();
244 const MCSymbol &SA = A->getSymbol();
245 if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
246 IsResolved = false;
247 } else if (auto *Writer = getWriterPtr()) {
248 IsResolved = (FixupFlags & MCFixupKindInfo::FKF_Constant) ||
249 Writer->isSymbolRefDifferenceFullyResolvedImpl(
250 *this, SA, *DF, false, true);
251 }
252 }
253 } else {
254 IsResolved = Target.isAbsolute();
255 }
256
257 Value = Target.getConstant();
258
259 if (const MCSymbolRefExpr *A = Target.getSymA()) {
260 const MCSymbol &Sym = A->getSymbol();
261 if (Sym.isDefined())
262 Value += Layout.getSymbolOffset(Sym);
263 }
264 if (const MCSymbolRefExpr *B = Target.getSymB()) {
265 const MCSymbol &Sym = B->getSymbol();
266 if (Sym.isDefined())
267 Value -= Layout.getSymbolOffset(Sym);
268 }
269
270 bool ShouldAlignPC = getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
272 assert((ShouldAlignPC ? IsPCRel : true) &&
273 "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
274
275 if (IsPCRel) {
276 uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
277
278 // A number of ARM fixups in Thumb mode require that the effective PC
279 // address be determined as the 32-bit aligned version of the actual offset.
280 if (ShouldAlignPC) Offset &= ~0x3;
281 Value -= Offset;
282 }
283
284 // Let the backend force a relocation if needed.
285 if (IsResolved && getBackend().shouldForceRelocation(*this, Fixup, Target)) {
286 IsResolved = false;
287 WasForced = true;
288 }
289
290 return IsResolved;
291}
292
294 const MCFragment &F) const {
295 assert(getBackendPtr() && "Requires assembler backend");
296 switch (F.getKind()) {
298 return cast<MCDataFragment>(F).getContents().size();
300 return cast<MCRelaxableFragment>(F).getContents().size();
302 return cast<MCCompactEncodedInstFragment>(F).getContents().size();
303 case MCFragment::FT_Fill: {
304 auto &FF = cast<MCFillFragment>(F);
305 int64_t NumValues = 0;
306 if (!FF.getNumValues().evaluateAsAbsolute(NumValues, Layout)) {
307 getContext().reportError(FF.getLoc(),
308 "expected assembly-time absolute expression");
309 return 0;
310 }
311 int64_t Size = NumValues * FF.getValueSize();
312 if (Size < 0) {
313 getContext().reportError(FF.getLoc(), "invalid number of bytes");
314 return 0;
315 }
316 return Size;
317 }
318
320 return cast<MCNopsFragment>(F).getNumBytes();
321
323 return cast<MCLEBFragment>(F).getContents().size();
324
326 return cast<MCBoundaryAlignFragment>(F).getSize();
327
329 return 4;
330
332 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
333 unsigned Offset = Layout.getFragmentOffset(&AF);
334 unsigned Size = offsetToAlignment(Offset, AF.getAlignment());
335
336 // Insert extra Nops for code alignment if the target define
337 // shouldInsertExtraNopBytesForCodeAlign target hook.
338 if (AF.getParent()->useCodeAlign() && AF.hasEmitNops() &&
339 getBackend().shouldInsertExtraNopBytesForCodeAlign(AF, Size))
340 return Size;
341
342 // If we are padding with nops, force the padding to be larger than the
343 // minimum nop size.
344 if (Size > 0 && AF.hasEmitNops()) {
345 while (Size % getBackend().getMinimumNopSize())
346 Size += AF.getAlignment().value();
347 }
348 if (Size > AF.getMaxBytesToEmit())
349 return 0;
350 return Size;
351 }
352
353 case MCFragment::FT_Org: {
354 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
356 if (!OF.getOffset().evaluateAsValue(Value, Layout)) {
358 "expected assembly-time absolute expression");
359 return 0;
360 }
361
362 uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
363 int64_t TargetLocation = Value.getConstant();
364 if (const MCSymbolRefExpr *A = Value.getSymA()) {
365 uint64_t Val;
366 if (!Layout.getSymbolOffset(A->getSymbol(), Val)) {
367 getContext().reportError(OF.getLoc(), "expected absolute expression");
368 return 0;
369 }
370 TargetLocation += Val;
371 }
372 int64_t Size = TargetLocation - FragmentOffset;
373 if (Size < 0 || Size >= 0x40000000) {
375 OF.getLoc(), "invalid .org offset '" + Twine(TargetLocation) +
376 "' (at offset '" + Twine(FragmentOffset) + "')");
377 return 0;
378 }
379 return Size;
380 }
381
383 return cast<MCDwarfLineAddrFragment>(F).getContents().size();
385 return cast<MCDwarfCallFrameFragment>(F).getContents().size();
387 return cast<MCCVInlineLineTableFragment>(F).getContents().size();
389 return cast<MCCVDefRangeFragment>(F).getContents().size();
391 return cast<MCPseudoProbeAddrFragment>(F).getContents().size();
393 llvm_unreachable("Should not have been added");
394 }
395
396 llvm_unreachable("invalid fragment kind");
397}
398
400 MCFragment *Prev = F->getPrevNode();
401
402 // We should never try to recompute something which is valid.
403 assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
404 // We should never try to compute the fragment layout if its predecessor
405 // isn't valid.
406 assert((!Prev || isFragmentValid(Prev)) &&
407 "Attempt to compute fragment before its predecessor!");
408
409 assert(!F->IsBeingLaidOut && "Already being laid out!");
410 F->IsBeingLaidOut = true;
411
412 ++stats::FragmentLayouts;
413
414 // Compute fragment offset and size.
415 if (Prev)
416 F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
417 else
418 F->Offset = 0;
419 F->IsBeingLaidOut = false;
420 LastValidFragment[F->getParent()] = F;
421
422 // If bundling is enabled and this fragment has instructions in it, it has to
423 // obey the bundling restrictions. With padding, we'll have:
424 //
425 //
426 // BundlePadding
427 // |||
428 // -------------------------------------
429 // Prev |##########| F |
430 // -------------------------------------
431 // ^
432 // |
433 // F->Offset
434 //
435 // The fragment's offset will point to after the padding, and its computed
436 // size won't include the padding.
437 //
438 // When the -mc-relax-all flag is used, we optimize bundling by writting the
439 // padding directly into fragments when the instructions are emitted inside
440 // the streamer. When the fragment is larger than the bundle size, we need to
441 // ensure that it's bundle aligned. This means that if we end up with
442 // multiple fragments, we must emit bundle padding between fragments.
443 //
444 // ".align N" is an example of a directive that introduces multiple
445 // fragments. We could add a special case to handle ".align N" by emitting
446 // within-fragment padding (which would produce less padding when N is less
447 // than the bundle size), but for now we don't.
448 //
449 if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
450 assert(isa<MCEncodedFragment>(F) &&
451 "Only MCEncodedFragment implementations have instructions");
452 MCEncodedFragment *EF = cast<MCEncodedFragment>(F);
453 uint64_t FSize = Assembler.computeFragmentSize(*this, *EF);
454
455 if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
456 report_fatal_error("Fragment can't be larger than a bundle size");
457
458 uint64_t RequiredBundlePadding =
459 computeBundlePadding(Assembler, EF, EF->Offset, FSize);
460 if (RequiredBundlePadding > UINT8_MAX)
461 report_fatal_error("Padding cannot exceed 255 bytes");
462 EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
463 EF->Offset += RequiredBundlePadding;
464 }
465}
466
468 bool Changed = !Symbol.isRegistered();
469 if (Changed) {
470 Symbol.setIsRegistered(true);
471 Symbols.push_back(&Symbol);
472 }
473 return Changed;
474}
475
477 const MCEncodedFragment &EF,
478 uint64_t FSize) const {
479 assert(getBackendPtr() && "Expected assembler backend");
480 // Should NOP padding be written out before this fragment?
481 unsigned BundlePadding = EF.getBundlePadding();
482 if (BundlePadding > 0) {
484 "Writing bundle padding with disabled bundling");
485 assert(EF.hasInstructions() &&
486 "Writing bundle padding for a fragment without instructions");
487
488 unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
489 const MCSubtargetInfo *STI = EF.getSubtargetInfo();
490 if (EF.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
491 // If the padding itself crosses a bundle boundary, it must be emitted
492 // in 2 pieces, since even nop instructions must not cross boundaries.
493 // v--------------v <- BundleAlignSize
494 // v---------v <- BundlePadding
495 // ----------------------------
496 // | Prev |####|####| F |
497 // ----------------------------
498 // ^-------------------^ <- TotalLength
499 unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
500 if (!getBackend().writeNopData(OS, DistanceToBoundary, STI))
501 report_fatal_error("unable to write NOP sequence of " +
502 Twine(DistanceToBoundary) + " bytes");
503 BundlePadding -= DistanceToBoundary;
504 }
505 if (!getBackend().writeNopData(OS, BundlePadding, STI))
506 report_fatal_error("unable to write NOP sequence of " +
507 Twine(BundlePadding) + " bytes");
508 }
509}
510
511/// Write the fragment \p F to the output file.
512static void writeFragment(raw_ostream &OS, const MCAssembler &Asm,
513 const MCAsmLayout &Layout, const MCFragment &F) {
514 // FIXME: Embed in fragments instead?
515 uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
516
517 support::endianness Endian = Asm.getBackend().Endian;
518
519 if (const MCEncodedFragment *EF = dyn_cast<MCEncodedFragment>(&F))
520 Asm.writeFragmentPadding(OS, *EF, FragmentSize);
521
522 // This variable (and its dummy usage) is to participate in the assert at
523 // the end of the function.
524 uint64_t Start = OS.tell();
525 (void) Start;
526
527 ++stats::EmittedFragments;
528
529 switch (F.getKind()) {
531 ++stats::EmittedAlignFragments;
532 const MCAlignFragment &AF = cast<MCAlignFragment>(F);
533 assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
534
535 uint64_t Count = FragmentSize / AF.getValueSize();
536
537 // FIXME: This error shouldn't actually occur (the front end should emit
538 // multiple .align directives to enforce the semantics it wants), but is
539 // severe enough that we want to report it. How to handle this?
540 if (Count * AF.getValueSize() != FragmentSize)
541 report_fatal_error("undefined .align directive, value size '" +
542 Twine(AF.getValueSize()) +
543 "' is not a divisor of padding size '" +
544 Twine(FragmentSize) + "'");
545
546 // See if we are aligning with nops, and if so do that first to try to fill
547 // the Count bytes. Then if that did not fill any bytes or there are any
548 // bytes left to fill use the Value and ValueSize to fill the rest.
549 // If we are aligning with nops, ask that target to emit the right data.
550 if (AF.hasEmitNops()) {
551 if (!Asm.getBackend().writeNopData(OS, Count, AF.getSubtargetInfo()))
552 report_fatal_error("unable to write nop sequence of " +
553 Twine(Count) + " bytes");
554 break;
555 }
556
557 // Otherwise, write out in multiples of the value size.
558 for (uint64_t i = 0; i != Count; ++i) {
559 switch (AF.getValueSize()) {
560 default: llvm_unreachable("Invalid size!");
561 case 1: OS << char(AF.getValue()); break;
562 case 2:
563 support::endian::write<uint16_t>(OS, AF.getValue(), Endian);
564 break;
565 case 4:
566 support::endian::write<uint32_t>(OS, AF.getValue(), Endian);
567 break;
568 case 8:
569 support::endian::write<uint64_t>(OS, AF.getValue(), Endian);
570 break;
571 }
572 }
573 break;
574 }
575
577 ++stats::EmittedDataFragments;
578 OS << cast<MCDataFragment>(F).getContents();
579 break;
580
582 ++stats::EmittedRelaxableFragments;
583 OS << cast<MCRelaxableFragment>(F).getContents();
584 break;
585
587 ++stats::EmittedCompactEncodedInstFragments;
588 OS << cast<MCCompactEncodedInstFragment>(F).getContents();
589 break;
590
591 case MCFragment::FT_Fill: {
592 ++stats::EmittedFillFragments;
593 const MCFillFragment &FF = cast<MCFillFragment>(F);
594 uint64_t V = FF.getValue();
595 unsigned VSize = FF.getValueSize();
596 const unsigned MaxChunkSize = 16;
597 char Data[MaxChunkSize];
598 assert(0 < VSize && VSize <= MaxChunkSize && "Illegal fragment fill size");
599 // Duplicate V into Data as byte vector to reduce number of
600 // writes done. As such, do endian conversion here.
601 for (unsigned I = 0; I != VSize; ++I) {
602 unsigned index = Endian == support::little ? I : (VSize - I - 1);
603 Data[I] = uint8_t(V >> (index * 8));
604 }
605 for (unsigned I = VSize; I < MaxChunkSize; ++I)
606 Data[I] = Data[I - VSize];
607
608 // Set to largest multiple of VSize in Data.
609 const unsigned NumPerChunk = MaxChunkSize / VSize;
610 // Set ChunkSize to largest multiple of VSize in Data
611 const unsigned ChunkSize = VSize * NumPerChunk;
612
613 // Do copies by chunk.
614 StringRef Ref(Data, ChunkSize);
615 for (uint64_t I = 0, E = FragmentSize / ChunkSize; I != E; ++I)
616 OS << Ref;
617
618 // do remainder if needed.
619 unsigned TrailingCount = FragmentSize % ChunkSize;
620 if (TrailingCount)
621 OS.write(Data, TrailingCount);
622 break;
623 }
624
625 case MCFragment::FT_Nops: {
626 ++stats::EmittedNopsFragments;
627 const MCNopsFragment &NF = cast<MCNopsFragment>(F);
628
629 int64_t NumBytes = NF.getNumBytes();
630 int64_t ControlledNopLength = NF.getControlledNopLength();
631 int64_t MaximumNopLength =
632 Asm.getBackend().getMaximumNopSize(*NF.getSubtargetInfo());
633
634 assert(NumBytes > 0 && "Expected positive NOPs fragment size");
635 assert(ControlledNopLength >= 0 && "Expected non-negative NOP size");
636
637 if (ControlledNopLength > MaximumNopLength) {
638 Asm.getContext().reportError(NF.getLoc(),
639 "illegal NOP size " +
640 std::to_string(ControlledNopLength) +
641 ". (expected within [0, " +
642 std::to_string(MaximumNopLength) + "])");
643 // Clamp the NOP length as reportError does not stop the execution
644 // immediately.
645 ControlledNopLength = MaximumNopLength;
646 }
647
648 // Use maximum value if the size of each NOP is not specified
649 if (!ControlledNopLength)
650 ControlledNopLength = MaximumNopLength;
651
652 while (NumBytes) {
653 uint64_t NumBytesToEmit =
654 (uint64_t)std::min(NumBytes, ControlledNopLength);
655 assert(NumBytesToEmit && "try to emit empty NOP instruction");
656 if (!Asm.getBackend().writeNopData(OS, NumBytesToEmit,
657 NF.getSubtargetInfo())) {
658 report_fatal_error("unable to write nop sequence of the remaining " +
659 Twine(NumBytesToEmit) + " bytes");
660 break;
661 }
662 NumBytes -= NumBytesToEmit;
663 }
664 break;
665 }
666
667 case MCFragment::FT_LEB: {
668 const MCLEBFragment &LF = cast<MCLEBFragment>(F);
669 OS << LF.getContents();
670 break;
671 }
672
674 const MCBoundaryAlignFragment &BF = cast<MCBoundaryAlignFragment>(F);
675 if (!Asm.getBackend().writeNopData(OS, FragmentSize, BF.getSubtargetInfo()))
676 report_fatal_error("unable to write nop sequence of " +
677 Twine(FragmentSize) + " bytes");
678 break;
679 }
680
682 const MCSymbolIdFragment &SF = cast<MCSymbolIdFragment>(F);
683 support::endian::write<uint32_t>(OS, SF.getSymbol()->getIndex(), Endian);
684 break;
685 }
686
687 case MCFragment::FT_Org: {
688 ++stats::EmittedOrgFragments;
689 const MCOrgFragment &OF = cast<MCOrgFragment>(F);
690
691 for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
692 OS << char(OF.getValue());
693
694 break;
695 }
696
698 const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
699 OS << OF.getContents();
700 break;
701 }
703 const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
704 OS << CF.getContents();
705 break;
706 }
708 const auto &OF = cast<MCCVInlineLineTableFragment>(F);
709 OS << OF.getContents();
710 break;
711 }
713 const auto &DRF = cast<MCCVDefRangeFragment>(F);
714 OS << DRF.getContents();
715 break;
716 }
718 const MCPseudoProbeAddrFragment &PF = cast<MCPseudoProbeAddrFragment>(F);
719 OS << PF.getContents();
720 break;
721 }
723 llvm_unreachable("Should not have been added");
724 }
725
726 assert(OS.tell() - Start == FragmentSize &&
727 "The stream should advance by fragment size");
728}
729
731 const MCAsmLayout &Layout) const {
732 assert(getBackendPtr() && "Expected assembler backend");
733
734 // Ignore virtual sections.
735 if (Sec->isVirtualSection()) {
736 assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
737
738 // Check that contents are only things legal inside a virtual section.
739 for (const MCFragment &F : *Sec) {
740 switch (F.getKind()) {
741 default: llvm_unreachable("Invalid fragment in virtual section!");
742 case MCFragment::FT_Data: {
743 // Check that we aren't trying to write a non-zero contents (or fixups)
744 // into a virtual section. This is to support clients which use standard
745 // directives to fill the contents of virtual sections.
746 const MCDataFragment &DF = cast<MCDataFragment>(F);
747 if (DF.fixup_begin() != DF.fixup_end())
748 getContext().reportError(SMLoc(), Sec->getVirtualSectionKind() +
749 " section '" + Sec->getName() +
750 "' cannot have fixups");
751 for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
752 if (DF.getContents()[i]) {
754 Sec->getVirtualSectionKind() +
755 " section '" + Sec->getName() +
756 "' cannot have non-zero initializers");
757 break;
758 }
759 break;
760 }
762 // Check that we aren't trying to write a non-zero value into a virtual
763 // section.
764 assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
765 cast<MCAlignFragment>(F).getValue() == 0) &&
766 "Invalid align in virtual section!");
767 break;
769 assert((cast<MCFillFragment>(F).getValue() == 0) &&
770 "Invalid fill in virtual section!");
771 break;
773 break;
774 }
775 }
776
777 return;
778 }
779
780 uint64_t Start = OS.tell();
781 (void)Start;
782
783 for (const MCFragment &F : *Sec)
784 writeFragment(OS, *this, Layout, F);
785
786 assert(getContext().hadError() ||
787 OS.tell() - Start == Layout.getSectionAddressSize(Sec));
788}
789
790std::tuple<MCValue, uint64_t, bool>
791MCAssembler::handleFixup(const MCAsmLayout &Layout, MCFragment &F,
792 const MCFixup &Fixup) {
793 // Evaluate the fixup.
795 uint64_t FixedValue;
796 bool WasForced;
797 bool IsResolved = evaluateFixup(Layout, Fixup, &F, Target, FixedValue,
798 WasForced);
799 if (!IsResolved) {
800 // The fixup was unresolved, we need a relocation. Inform the object
801 // writer of the relocation, and give it an opportunity to adjust the
802 // fixup value if need be.
803 getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
804 }
805 return std::make_tuple(Target, FixedValue, IsResolved);
806}
807
809 assert(getBackendPtr() && "Expected assembler backend");
810 DEBUG_WITH_TYPE("mc-dump", {
811 errs() << "assembler backend - pre-layout\n--\n";
812 dump(); });
813
814 // Create dummy fragments and assign section ordinals.
815 unsigned SectionIndex = 0;
816 for (MCSection &Sec : *this) {
817 // Create dummy fragments to eliminate any empty sections, this simplifies
818 // layout.
819 if (Sec.getFragmentList().empty())
820 new MCDataFragment(&Sec);
821
822 Sec.setOrdinal(SectionIndex++);
823 }
824
825 // Assign layout order indices to sections and fragments.
826 for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
827 MCSection *Sec = Layout.getSectionOrder()[i];
828 Sec->setLayoutOrder(i);
829
830 unsigned FragmentIndex = 0;
831 for (MCFragment &Frag : *Sec)
832 Frag.setLayoutOrder(FragmentIndex++);
833 }
834
835 // Layout until everything fits.
836 while (layoutOnce(Layout)) {
837 if (getContext().hadError())
838 return;
839 // Size of fragments in one section can depend on the size of fragments in
840 // another. If any fragment has changed size, we have to re-layout (and
841 // as a result possibly further relax) all.
842 for (MCSection &Sec : *this)
843 Layout.invalidateFragmentsFrom(&*Sec.begin());
844 }
845
846 DEBUG_WITH_TYPE("mc-dump", {
847 errs() << "assembler backend - post-relaxation\n--\n";
848 dump(); });
849
850 // Finalize the layout, including fragment lowering.
851 finishLayout(Layout);
852
853 DEBUG_WITH_TYPE("mc-dump", {
854 errs() << "assembler backend - final-layout\n--\n";
855 dump(); });
856
857 // Allow the object writer a chance to perform post-layout binding (for
858 // example, to set the index fields in the symbol data).
859 getWriter().executePostLayoutBinding(*this, Layout);
860
861 // Evaluate and apply the fixups, generating relocation entries as necessary.
862 for (MCSection &Sec : *this) {
863 for (MCFragment &Frag : Sec) {
864 ArrayRef<MCFixup> Fixups;
865 MutableArrayRef<char> Contents;
866 const MCSubtargetInfo *STI = nullptr;
867
868 // Process MCAlignFragment and MCEncodedFragmentWithFixups here.
869 switch (Frag.getKind()) {
870 default:
871 continue;
873 MCAlignFragment &AF = cast<MCAlignFragment>(Frag);
874 // Insert fixup type for code alignment if the target define
875 // shouldInsertFixupForCodeAlign target hook.
876 if (Sec.useCodeAlign() && AF.hasEmitNops())
877 getBackend().shouldInsertFixupForCodeAlign(*this, Layout, AF);
878 continue;
879 }
880 case MCFragment::FT_Data: {
881 MCDataFragment &DF = cast<MCDataFragment>(Frag);
882 Fixups = DF.getFixups();
883 Contents = DF.getContents();
884 STI = DF.getSubtargetInfo();
885 assert(!DF.hasInstructions() || STI != nullptr);
886 break;
887 }
889 MCRelaxableFragment &RF = cast<MCRelaxableFragment>(Frag);
890 Fixups = RF.getFixups();
891 Contents = RF.getContents();
892 STI = RF.getSubtargetInfo();
893 assert(!RF.hasInstructions() || STI != nullptr);
894 break;
895 }
897 MCCVDefRangeFragment &CF = cast<MCCVDefRangeFragment>(Frag);
898 Fixups = CF.getFixups();
899 Contents = CF.getContents();
900 break;
901 }
903 MCDwarfLineAddrFragment &DF = cast<MCDwarfLineAddrFragment>(Frag);
904 Fixups = DF.getFixups();
905 Contents = DF.getContents();
906 break;
907 }
909 MCDwarfCallFrameFragment &DF = cast<MCDwarfCallFrameFragment>(Frag);
910 Fixups = DF.getFixups();
911 Contents = DF.getContents();
912 break;
913 }
915 MCPseudoProbeAddrFragment &PF = cast<MCPseudoProbeAddrFragment>(Frag);
916 Fixups = PF.getFixups();
917 Contents = PF.getContents();
918 break;
919 }
920 }
921 for (const MCFixup &Fixup : Fixups) {
922 uint64_t FixedValue;
923 bool IsResolved;
925 std::tie(Target, FixedValue, IsResolved) =
926 handleFixup(Layout, Frag, Fixup);
927 getBackend().applyFixup(*this, Fixup, Target, Contents, FixedValue,
928 IsResolved, STI);
929 }
930 }
931 }
932}
933
935 // Create the layout object.
936 MCAsmLayout Layout(*this);
937 layout(Layout);
938
939 // Write the object file.
940 stats::ObjectBytes += getWriter().writeObject(*this, Layout);
941}
942
943bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
944 const MCRelaxableFragment *DF,
945 const MCAsmLayout &Layout) const {
946 assert(getBackendPtr() && "Expected assembler backend");
949 bool WasForced;
950 bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value, WasForced);
951 if (Target.getSymA() &&
952 Target.getSymA()->getKind() == MCSymbolRefExpr::VK_X86_ABS8 &&
953 Fixup.getKind() == FK_Data_1)
954 return false;
956 Layout, WasForced);
957}
958
959bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
960 const MCAsmLayout &Layout) const {
961 assert(getBackendPtr() && "Expected assembler backend");
962 // If this inst doesn't ever need relaxation, ignore it. This occurs when we
963 // are intentionally pushing out inst fragments, or because we relaxed a
964 // previous instruction to one that doesn't need relaxation.
965 if (!getBackend().mayNeedRelaxation(F->getInst(), *F->getSubtargetInfo()))
966 return false;
967
968 for (const MCFixup &Fixup : F->getFixups())
969 if (fixupNeedsRelaxation(Fixup, F, Layout))
970 return true;
971
972 return false;
973}
974
975bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
978 "Expected CodeEmitter defined for relaxInstruction");
979 if (!fragmentNeedsRelaxation(&F, Layout))
980 return false;
981
982 ++stats::RelaxedInstructions;
983
984 // FIXME-PERF: We could immediately lower out instructions if we can tell
985 // they are fully resolved, to avoid retesting on later passes.
986
987 // Relax the fragment.
988
989 MCInst Relaxed = F.getInst();
990 getBackend().relaxInstruction(Relaxed, *F.getSubtargetInfo());
991
992 // Encode the new instruction.
993 F.setInst(Relaxed);
994 F.getFixups().clear();
995 F.getContents().clear();
996 getEmitter().encodeInstruction(Relaxed, F.getContents(), F.getFixups(),
997 *F.getSubtargetInfo());
998 return true;
999}
1000
1001bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
1002 uint64_t OldSize = LF.getContents().size();
1003 int64_t Value;
1004 bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
1005 if (!Abs)
1006 report_fatal_error("sleb128 and uleb128 expressions must be absolute");
1008 Data.clear();
1010 // The compiler can generate EH table assembly that is impossible to assemble
1011 // without either adding padding to an LEB fragment or adding extra padding
1012 // to a later alignment fragment. To accommodate such tables, relaxation can
1013 // only increase an LEB fragment size here, not decrease it. See PR35809.
1014 if (LF.isSigned())
1015 encodeSLEB128(Value, OSE, OldSize);
1016 else
1017 encodeULEB128(Value, OSE, OldSize);
1018 return OldSize != LF.getContents().size();
1019}
1020
1021/// Check if the branch crosses the boundary.
1022///
1023/// \param StartAddr start address of the fused/unfused branch.
1024/// \param Size size of the fused/unfused branch.
1025/// \param BoundaryAlignment alignment requirement of the branch.
1026/// \returns true if the branch cross the boundary.
1028 Align BoundaryAlignment) {
1029 uint64_t EndAddr = StartAddr + Size;
1030 return (StartAddr >> Log2(BoundaryAlignment)) !=
1031 ((EndAddr - 1) >> Log2(BoundaryAlignment));
1032}
1033
1034/// Check if the branch is against the boundary.
1035///
1036/// \param StartAddr start address of the fused/unfused branch.
1037/// \param Size size of the fused/unfused branch.
1038/// \param BoundaryAlignment alignment requirement of the branch.
1039/// \returns true if the branch is against the boundary.
1041 Align BoundaryAlignment) {
1042 uint64_t EndAddr = StartAddr + Size;
1043 return (EndAddr & (BoundaryAlignment.value() - 1)) == 0;
1044}
1045
1046/// Check if the branch needs padding.
1047///
1048/// \param StartAddr start address of the fused/unfused branch.
1049/// \param Size size of the fused/unfused branch.
1050/// \param BoundaryAlignment alignment requirement of the branch.
1051/// \returns true if the branch needs padding.
1052static bool needPadding(uint64_t StartAddr, uint64_t Size,
1053 Align BoundaryAlignment) {
1054 return mayCrossBoundary(StartAddr, Size, BoundaryAlignment) ||
1055 isAgainstBoundary(StartAddr, Size, BoundaryAlignment);
1056}
1057
1058bool MCAssembler::relaxBoundaryAlign(MCAsmLayout &Layout,
1060 // BoundaryAlignFragment that doesn't need to align any fragment should not be
1061 // relaxed.
1062 if (!BF.getLastFragment())
1063 return false;
1064
1065 uint64_t AlignedOffset = Layout.getFragmentOffset(&BF);
1066 uint64_t AlignedSize = 0;
1067 for (const MCFragment *F = BF.getLastFragment(); F != &BF;
1068 F = F->getPrevNode())
1069 AlignedSize += computeFragmentSize(Layout, *F);
1070
1071 Align BoundaryAlignment = BF.getAlignment();
1072 uint64_t NewSize = needPadding(AlignedOffset, AlignedSize, BoundaryAlignment)
1073 ? offsetToAlignment(AlignedOffset, BoundaryAlignment)
1074 : 0U;
1075 if (NewSize == BF.getSize())
1076 return false;
1077 BF.setSize(NewSize);
1078 Layout.invalidateFragmentsFrom(&BF);
1079 return true;
1080}
1081
1082bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1084
1085 bool WasRelaxed;
1086 if (getBackend().relaxDwarfLineAddr(DF, Layout, WasRelaxed))
1087 return WasRelaxed;
1088
1089 MCContext &Context = Layout.getAssembler().getContext();
1090 uint64_t OldSize = DF.getContents().size();
1091 int64_t AddrDelta;
1092 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1093 assert(Abs && "We created a line delta with an invalid expression");
1094 (void)Abs;
1095 int64_t LineDelta;
1096 LineDelta = DF.getLineDelta();
1097 SmallVectorImpl<char> &Data = DF.getContents();
1098 Data.clear();
1099 DF.getFixups().clear();
1100
1102 AddrDelta, Data);
1103 return OldSize != Data.size();
1104}
1105
1106bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1108 bool WasRelaxed;
1109 if (getBackend().relaxDwarfCFA(DF, Layout, WasRelaxed))
1110 return WasRelaxed;
1111
1113 uint64_t OldSize = DF.getContents().size();
1114 int64_t AddrDelta;
1115 bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1116 assert(Abs && "We created call frame with an invalid expression");
1117 (void) Abs;
1118 SmallVectorImpl<char> &Data = DF.getContents();
1119 Data.clear();
1120 DF.getFixups().clear();
1121
1122 MCDwarfFrameEmitter::encodeAdvanceLoc(Context, AddrDelta, Data);
1123 return OldSize != Data.size();
1124}
1125
1126bool MCAssembler::relaxCVInlineLineTable(MCAsmLayout &Layout,
1128 unsigned OldSize = F.getContents().size();
1130 return OldSize != F.getContents().size();
1131}
1132
1133bool MCAssembler::relaxCVDefRange(MCAsmLayout &Layout,
1135 unsigned OldSize = F.getContents().size();
1137 return OldSize != F.getContents().size();
1138}
1139
1140bool MCAssembler::relaxPseudoProbeAddr(MCAsmLayout &Layout,
1142 uint64_t OldSize = PF.getContents().size();
1143 int64_t AddrDelta;
1144 bool Abs = PF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1145 assert(Abs && "We created a pseudo probe with an invalid expression");
1146 (void)Abs;
1148 Data.clear();
1150 PF.getFixups().clear();
1151
1152 // AddrDelta is a signed integer
1153 encodeSLEB128(AddrDelta, OSE, OldSize);
1154 return OldSize != Data.size();
1155}
1156
1157bool MCAssembler::relaxFragment(MCAsmLayout &Layout, MCFragment &F) {
1158 switch(F.getKind()) {
1159 default:
1160 return false;
1162 assert(!getRelaxAll() &&
1163 "Did not expect a MCRelaxableFragment in RelaxAll mode");
1164 return relaxInstruction(Layout, cast<MCRelaxableFragment>(F));
1166 return relaxDwarfLineAddr(Layout, cast<MCDwarfLineAddrFragment>(F));
1168 return relaxDwarfCallFrameFragment(Layout,
1169 cast<MCDwarfCallFrameFragment>(F));
1170 case MCFragment::FT_LEB:
1171 return relaxLEB(Layout, cast<MCLEBFragment>(F));
1173 return relaxBoundaryAlign(Layout, cast<MCBoundaryAlignFragment>(F));
1175 return relaxCVInlineLineTable(Layout, cast<MCCVInlineLineTableFragment>(F));
1177 return relaxCVDefRange(Layout, cast<MCCVDefRangeFragment>(F));
1179 return relaxPseudoProbeAddr(Layout, cast<MCPseudoProbeAddrFragment>(F));
1180 }
1181}
1182
1183bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1184 // Holds the first fragment which needed relaxing during this layout. It will
1185 // remain NULL if none were relaxed.
1186 // When a fragment is relaxed, all the fragments following it should get
1187 // invalidated because their offset is going to change.
1188 MCFragment *FirstRelaxedFragment = nullptr;
1189
1190 // Attempt to relax all the fragments in the section.
1191 for (MCFragment &Frag : Sec) {
1192 // Check if this is a fragment that needs relaxation.
1193 bool RelaxedFrag = relaxFragment(Layout, Frag);
1194 if (RelaxedFrag && !FirstRelaxedFragment)
1195 FirstRelaxedFragment = &Frag;
1196 }
1197 if (FirstRelaxedFragment) {
1198 Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1199 return true;
1200 }
1201 return false;
1202}
1203
1204bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1205 ++stats::RelaxationSteps;
1206
1207 bool WasRelaxed = false;
1208 for (MCSection &Sec : *this) {
1209 while (layoutSectionOnce(Layout, Sec))
1210 WasRelaxed = true;
1211 }
1212
1213 return WasRelaxed;
1214}
1215
1216void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1217 assert(getBackendPtr() && "Expected assembler backend");
1218 // The layout is done. Mark every fragment as valid.
1219 for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1220 MCSection &Section = *Layout.getSectionOrder()[i];
1221 Layout.getFragmentOffset(&*Section.getFragmentList().rbegin());
1222 computeFragmentSize(Layout, *Section.getFragmentList().rbegin());
1223 }
1224 getBackend().finishLayout(*this, Layout);
1225}
1226
1227#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1229 raw_ostream &OS = errs();
1230
1231 OS << "<MCAssembler\n";
1232 OS << " Sections:[\n ";
1233 for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
1234 if (it != begin()) OS << ",\n ";
1235 it->dump();
1236 }
1237 OS << "],\n";
1238 OS << " Symbols:[";
1239
1240 for (const_symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1241 if (it != symbol_begin()) OS << ",\n ";
1242 OS << "(";
1243 it->dump();
1244 OS << ", Index:" << it->getIndex() << ", ";
1245 OS << ")";
1246 }
1247 OS << "]>\n";
1248}
1249#endif
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:492
dxil DXContainer Global Emitter
#define DEBUG_WITH_TYPE(TYPE, X)
DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug information.
Definition: Debug.h:64
static RegisterPass< DebugifyFunctionPass > DF("debugify-function", "Attach debug info to a function")
uint64_t Size
Symbol * Sym
Definition: ELF_riscv.cpp:463
static void writeFragment(raw_ostream &OS, const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment &F)
Write the fragment F to the output file.
static bool needPadding(uint64_t StartAddr, uint64_t Size, Align BoundaryAlignment)
Check if the branch needs padding.
static bool mayCrossBoundary(uint64_t StartAddr, uint64_t Size, Align BoundaryAlignment)
Check if the branch crosses the boundary.
static bool isAgainstBoundary(uint64_t StartAddr, uint64_t Size, Align BoundaryAlignment)
Check if the branch is against the boundary.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
LLVMContext & Context
PowerPC TLS Dynamic Call Fixup
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
endianness Endian
raw_pwrite_stream & OS
This file defines the SmallString class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
void encodeInlineLineTable(MCAsmLayout &Layout, MCCVInlineLineTableFragment &F)
Encodes the binary annotations once we have a layout.
Definition: MCCodeView.cpp:462
void encodeDefRange(MCAsmLayout &Layout, MCCVDefRangeFragment &F)
Definition: MCCodeView.cpp:606
int64_t getValue() const
Definition: MCFragment.h:324
Align getAlignment() const
Definition: MCFragment.h:322
unsigned getMaxBytesToEmit() const
Definition: MCFragment.h:328
bool hasEmitNops() const
Definition: MCFragment.h:330
unsigned getValueSize() const
Definition: MCFragment.h:326
const MCSubtargetInfo * getSubtargetInfo() const
Definition: MCFragment.h:336
virtual bool fixupNeedsRelaxationAdvanced(const MCFixup &Fixup, bool Resolved, uint64_t Value, const MCRelaxableFragment *DF, const MCAsmLayout &Layout, const bool WasForced) const
Target specific predicate for whether a given fixup requires the associated instruction to be relaxed...
virtual bool evaluateTargetFixup(const MCAssembler &Asm, const MCAsmLayout &Layout, const MCFixup &Fixup, const MCFragment *DF, const MCValue &Target, uint64_t &Value, bool &WasForced)
Definition: MCAsmBackend.h:119
virtual bool shouldInsertFixupForCodeAlign(MCAssembler &Asm, const MCAsmLayout &Layout, MCAlignFragment &AF)
Hook which indicates if the target requires a fixup to be generated when handling an align directive ...
Definition: MCAsmBackend.h:113
virtual void relaxInstruction(MCInst &Inst, const MCSubtargetInfo &STI) const
Relax the instruction in the given fragment to the next wider instruction.
Definition: MCAsmBackend.h:171
virtual void finishLayout(MCAssembler const &Asm, MCAsmLayout &Layout) const
Give backend an opportunity to finish layout after relaxation.
Definition: MCAsmBackend.h:206
virtual void reset()
lifetime management
Definition: MCAsmBackend.h:68
virtual const MCFixupKindInfo & getFixupKindInfo(MCFixupKind Kind) const
Get information on a fixup kind.
virtual void applyFixup(const MCAssembler &Asm, const MCFixup &Fixup, const MCValue &Target, MutableArrayRef< char > Data, uint64_t Value, bool IsResolved, const MCSubtargetInfo *STI) const =0
Apply the Value for given Fixup into the provided data fragment, at the offset specified by the fixup...
Encapsulates the layout of an assembly file at a particular point in time.
Definition: MCAsmLayout.h:28
void invalidateFragmentsFrom(MCFragment *F)
Invalidate the fragments starting with F because it has been resized.
Definition: MCFragment.cpp:70
uint64_t getSectionAddressSize(const MCSection *Sec) const
Get the address space size of the given section, as it effects layout.
Definition: MCFragment.cpp:198
llvm::SmallVectorImpl< MCSection * > & getSectionOrder()
Definition: MCAsmLayout.h:69
uint64_t getSectionFileSize(const MCSection *Sec) const
Get the data size of the given section, as emitted to the object file.
Definition: MCFragment.cpp:204
bool getSymbolOffset(const MCSymbol &S, uint64_t &Val) const
Get the offset of the given symbol, as computed in the current layout.
Definition: MCFragment.cpp:152
void layoutFragment(MCFragment *Fragment)
Perform layout for a single fragment, assuming that the previous fragment has already been laid out c...
uint64_t getFragmentOffset(const MCFragment *F) const
Get the offset of the given fragment inside its containing section.
Definition: MCFragment.cpp:96
MCAssembler & getAssembler() const
Get the assembler object this is a layout for.
Definition: MCAsmLayout.h:50
MCContext & getContext() const
Definition: MCAssembler.h:321
void Finish()
Finish - Do final processing and write the object to the output stream.
void writeSectionData(raw_ostream &OS, const MCSection *Section, const MCAsmLayout &Layout) const
Emit the section contents to OS.
unsigned getBundleAlignSize() const
Definition: MCAssembler.h:362
bool isBundlingEnabled() const
Definition: MCAssembler.h:360
symbol_iterator symbol_begin()
Definition: MCAssembler.h:384
void dump() const
void layout(MCAsmLayout &Layout)
MCObjectWriter * getWriterPtr() const
Definition: MCAssembler.h:327
MCObjectWriter & getWriter() const
Definition: MCAssembler.h:333
uint64_t computeFragmentSize(const MCAsmLayout &Layout, const MCFragment &F) const
Compute the effective fragment size assuming it is laid out at the given SectionAddress and FragmentO...
MCCodeEmitter * getEmitterPtr() const
Definition: MCAssembler.h:325
bool getRelaxAll() const
Definition: MCAssembler.h:357
MCCodeEmitter & getEmitter() const
Definition: MCAssembler.h:331
iterator end()
Definition: MCAssembler.h:376
MCAssembler(MCContext &Context, std::unique_ptr< MCAsmBackend > Backend, std::unique_ptr< MCCodeEmitter > Emitter, std::unique_ptr< MCObjectWriter > Writer)
Construct a new assembler instance.
Definition: MCAssembler.cpp:84
iterator begin()
Definition: MCAssembler.h:373
bool isThumbFunc(const MCSymbol *Func) const
Check whether a given symbol has been flagged with .thumb_func.
MCAsmBackend & getBackend() const
Definition: MCAssembler.h:329
bool registerSection(MCSection &Section)
const MCSymbol * getAtom(const MCSymbol &S) const
Find the symbol which defines the atom containing the given symbol, or null if there is no such symbo...
MCAsmBackend * getBackendPtr() const
Definition: MCAssembler.h:323
bool isSymbolLinkerVisible(const MCSymbol &SD) const
Check whether a particular symbol is visible to the linker and is required in the symbol table,...
MCLOHContainer & getLOHContainer()
Definition: MCAssembler.h:460
symbol_iterator symbol_end()
Definition: MCAssembler.h:387
void reset()
Reuse an assembler instance.
Definition: MCAssembler.cpp:98
bool registerSymbol(const MCSymbol &Symbol)
MCDwarfLineTableParams getDWARFLinetableParams() const
Definition: MCAssembler.h:335
void writeFragmentPadding(raw_ostream &OS, const MCEncodedFragment &F, uint64_t FSize) const
Write the necessary bundle padding to OS.
Represents required padding such that a particular other set of fragments does not cross a particular...
Definition: MCFragment.h:578
uint64_t getSize() const
Definition: MCFragment.h:596
void setSize(uint64_t Value)
Definition: MCFragment.h:597
const MCFragment * getLastFragment() const
Definition: MCFragment.h:602
const MCSubtargetInfo * getSubtargetInfo() const
Definition: MCFragment.h:608
Fragment representing the .cv_def_range directive.
Definition: MCFragment.h:548
Fragment representing the binary annotations produced by the .cv_inline_linetable directive.
Definition: MCFragment.h:515
virtual void reset()
Lifetime management.
Definition: MCCodeEmitter.h:38
virtual void encodeInstruction(const MCInst &Inst, raw_ostream &OS, SmallVectorImpl< MCFixup > &Fixups, const MCSubtargetInfo &STI) const
EncodeInstruction - Encode the given Inst to bytes on the output stream OS.
Definition: MCCodeEmitter.h:28
Context object for machine code objects.
Definition: MCContext.h:76
bool hadError()
Definition: MCContext.h:848
CodeViewContext & getCVContext()
Definition: MCContext.cpp:994
void reportError(SMLoc L, const Twine &Msg)
Definition: MCContext.cpp:1049
Fragment for data and encoded instructions.
Definition: MCFragment.h:241
static void encodeAdvanceLoc(MCContext &Context, uint64_t AddrDelta, SmallVectorImpl< char > &OS)
Definition: MCDwarf.cpp:1931
static void encode(MCContext &Context, MCDwarfLineTableParams Params, int64_t LineDelta, uint64_t AddrDelta, SmallVectorImpl< char > &OS)
Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
Definition: MCDwarf.cpp:684
SmallVectorImpl< char > & getContents()
Definition: MCFragment.h:196
SmallVectorImpl< MCFixup > & getFixups()
Definition: MCFragment.h:222
Interface implemented by fragments that contain encoded instructions and/or data.
Definition: MCFragment.h:124
const MCSubtargetInfo * getSubtargetInfo() const
Retrieve the MCSubTargetInfo in effect when the instruction was encoded.
Definition: MCFragment.h:172
void setBundlePadding(uint8_t N)
Set the padding size for this fragment.
Definition: MCFragment.h:168
uint8_t getBundlePadding() const
Get the padding size that must be inserted before this fragment.
Definition: MCFragment.h:164
bool alignToBundleEnd() const
Should this fragment be placed at the end of an aligned bundle?
Definition: MCFragment.h:156
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
bool evaluateKnownAbsolute(int64_t &Res, const MCAsmLayout &Layout) const
Definition: MCExpr.cpp:561
bool evaluateAsRelocatable(MCValue &Res, const MCAsmLayout *Layout, const MCFixup *Fixup) const
Try to evaluate the expression to a relocatable value, i.e.
Definition: MCExpr.cpp:749
bool evaluateAsValue(MCValue &Res, const MCAsmLayout &Layout) const
Try to evaluate the expression to the form (a - b + constant) where neither a nor b are variables.
Definition: MCExpr.cpp:757
uint8_t getValueSize() const
Definition: MCFragment.h:360
uint64_t getValue() const
Definition: MCFragment.h:359
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:71
const MCSymbol * getAtom() const
Definition: MCFragment.h:98
MCSection * getParent() const
Definition: MCFragment.h:95
bool hasInstructions() const
Does this fragment have instructions emitted into it? By default this is false, but specific fragment...
Definition: MCFragment.h:106
Instances of this class represent a single low-level machine instruction.
Definition: MCInst.h:184
bool isSigned() const
Definition: MCFragment.h:444
const MCExpr & getValue() const
Definition: MCFragment.h:442
SmallString< 8 > & getContents()
Definition: MCFragment.h:446
int64_t getControlledNopLength() const
Definition: MCFragment.h:389
int64_t getNumBytes() const
Definition: MCFragment.h:388
const MCSubtargetInfo * getSubtargetInfo() const
Definition: MCFragment.h:393
SMLoc getLoc() const
Definition: MCFragment.h:391
virtual uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout)=0
Write the object file and returns the number of bytes written.
virtual void executePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout)=0
Perform any late binding of symbols (for example, to assign symbol indices for use when generating re...
virtual void reset()
lifetime management
virtual void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target, uint64_t &FixedValue)=0
Record a relocation entry.
SMLoc getLoc() const
Definition: MCFragment.h:420
uint8_t getValue() const
Definition: MCFragment.h:418
const MCExpr & getOffset() const
Definition: MCFragment.h:416
const MCExpr & getAddrDelta() const
Definition: MCFragment.h:625
A relaxable fragment holds on to its MCInst, since it may need to be relaxed during the assembler lay...
Definition: MCFragment.h:270
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:39
void setLayoutOrder(unsigned Value)
Definition: MCSection.h:153
MCSection::FragmentListType & getFragmentList()
Definition: MCSection.h:172
virtual bool isVirtualSection() const =0
Check whether this section is "virtual", that is has no actual object file contents.
void setOrdinal(unsigned Value)
Definition: MCSection.h:150
virtual bool useCodeAlign() const =0
Return true if a .align directive should use "optimized nops" to fill instead of 0s.
iterator begin()
Definition: MCSection.h:185
Generic base class for all target subtargets.
Represents a symbol table index fragment.
Definition: MCFragment.h:498
const MCSymbol * getSymbol()
Definition: MCFragment.h:505
Represent a reference to a symbol from inside an expression.
Definition: MCExpr.h:192
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute).
Definition: MCSymbol.h:252
bool isUndefined(bool SetUsed=true) const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition: MCSymbol.h:257
uint32_t getIndex() const
Get the (implementation defined) index.
Definition: MCSymbol.h:314
MCFragment * getFragment(bool SetUsed=true) const
Definition: MCSymbol.h:395
This represents an "assembler immediate".
Definition: MCValue.h:36
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:305
Represents a location in source code.
Definition: SMLoc.h:23
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
size_t size() const
Definition: SmallVector.h:91
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:577
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
LLVM Value Representation.
Definition: Value.h:74
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:31
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
uint64_t tell() const
tell - Return the current offset with the file.
Definition: raw_ostream.h:134
raw_ostream & write(unsigned char C)
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:672
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:440
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:145
@ FK_Data_1
A one-byte fixup.
Definition: MCFixup.h:23
uint64_t computeBundlePadding(const MCAssembler &Assembler, const MCEncodedFragment *F, uint64_t FOffset, uint64_t FSize)
Compute the amount of padding required before the fragment F to obey bundling restrictions,...
Definition: MCFragment.cpp:213
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition: Alignment.h:197
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Ref
The access may reference the value stored in memory.
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1946
unsigned encodeSLEB128(int64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a SLEB128 value to an output stream.
Definition: LEB128.h:23
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition: LEB128.h:80
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition: Alignment.h:208
Definition: BitVector.h:858
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
@ FKF_IsTarget
Should this fixup be evaluated in a target dependent manner?
@ FKF_IsAlignedDownTo32Bits
Should this fixup kind force a 4-byte aligned effective PC value?
@ FKF_Constant
This fixup kind should be resolved if defined.
@ FKF_IsPCRel
Is this fixup kind PCrelative? This is used by the assembler backend to evaluate fixup values in a ta...
unsigned Flags
Flags describing additional information on this fixup kind.
An iterator type that allows iterating over the pointees via some other iterator.
Definition: iterator.h:324