xref: /freebsd/contrib/llvm-project/llvm/lib/MC/MCAssembler.cpp (revision 2e3507c25e42292b45a5482e116d278f5515d04d)
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 
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/MCSymbol.h"
31 #include "llvm/MC/MCValue.h"
32 #include "llvm/Support/Alignment.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/EndianStream.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/LEB128.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <cassert>
40 #include <cstdint>
41 #include <tuple>
42 #include <utility>
43 
44 using namespace llvm;
45 
46 namespace llvm {
47 class MCSubtargetInfo;
48 }
49 
50 #define DEBUG_TYPE "assembler"
51 
52 namespace {
53 namespace stats {
54 
55 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
56 STATISTIC(EmittedRelaxableFragments,
57           "Number of emitted assembler fragments - relaxable");
58 STATISTIC(EmittedDataFragments,
59           "Number of emitted assembler fragments - data");
60 STATISTIC(EmittedCompactEncodedInstFragments,
61           "Number of emitted assembler fragments - compact encoded inst");
62 STATISTIC(EmittedAlignFragments,
63           "Number of emitted assembler fragments - align");
64 STATISTIC(EmittedFillFragments,
65           "Number of emitted assembler fragments - fill");
66 STATISTIC(EmittedNopsFragments, "Number of emitted assembler fragments - nops");
67 STATISTIC(EmittedOrgFragments, "Number of emitted assembler fragments - org");
68 STATISTIC(evaluateFixup, "Number of evaluated fixups");
69 STATISTIC(FragmentLayouts, "Number of fragment layouts");
70 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
71 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
72 STATISTIC(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 
84 MCAssembler::MCAssembler(MCContext &Context,
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 
96 MCAssembler::~MCAssembler() = default;
97 
98 void MCAssembler::reset() {
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();
124   getLOHContainer().reset();
125 }
126 
127 bool MCAssembler::registerSection(MCSection &Section) {
128   if (Section.isRegistered())
129     return false;
130   Sections.push_back(&Section);
131   Section.setIsRegistered(true);
132   return true;
133 }
134 
135 bool 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 
166 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
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 
177 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
178   // Linker visible symbols define atoms.
179   if (isSymbolLinkerVisible(S))
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 
196 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
197                                 const MCFixup &Fixup, const MCFragment *DF,
198                                 MCValue &Target, uint64_t &Value,
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 &
226                   MCFixupKindInfo::FKF_IsTarget;
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 &
234                  MCFixupKindInfo::FKF_IsPCRel;
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 &
271                        MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
272   assert((ShouldAlignPC ? IsPCRel : true) &&
273     "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
274 
275   if (IsPCRel) {
276     uint64_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   // A linker relaxation target may emit ADD/SUB relocations for A-B+C. Let
291   // recordRelocation handle non-VK_None cases like A@plt-B+C.
292   if (!IsResolved && Target.getSymA() && Target.getSymB() &&
293       Target.getSymA()->getKind() == MCSymbolRefExpr::VK_None &&
294       getBackend().handleAddSubRelocations(Layout, *DF, Fixup, Target, Value))
295     return true;
296 
297   return IsResolved;
298 }
299 
300 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
301                                           const MCFragment &F) const {
302   assert(getBackendPtr() && "Requires assembler backend");
303   switch (F.getKind()) {
304   case MCFragment::FT_Data:
305     return cast<MCDataFragment>(F).getContents().size();
306   case MCFragment::FT_Relaxable:
307     return cast<MCRelaxableFragment>(F).getContents().size();
308   case MCFragment::FT_CompactEncodedInst:
309     return cast<MCCompactEncodedInstFragment>(F).getContents().size();
310   case MCFragment::FT_Fill: {
311     auto &FF = cast<MCFillFragment>(F);
312     int64_t NumValues = 0;
313     if (!FF.getNumValues().evaluateKnownAbsolute(NumValues, Layout)) {
314       getContext().reportError(FF.getLoc(),
315                                "expected assembly-time absolute expression");
316       return 0;
317     }
318     int64_t Size = NumValues * FF.getValueSize();
319     if (Size < 0) {
320       getContext().reportError(FF.getLoc(), "invalid number of bytes");
321       return 0;
322     }
323     return Size;
324   }
325 
326   case MCFragment::FT_Nops:
327     return cast<MCNopsFragment>(F).getNumBytes();
328 
329   case MCFragment::FT_LEB:
330     return cast<MCLEBFragment>(F).getContents().size();
331 
332   case MCFragment::FT_BoundaryAlign:
333     return cast<MCBoundaryAlignFragment>(F).getSize();
334 
335   case MCFragment::FT_SymbolId:
336     return 4;
337 
338   case MCFragment::FT_Align: {
339     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
340     unsigned Offset = Layout.getFragmentOffset(&AF);
341     unsigned Size = offsetToAlignment(Offset, AF.getAlignment());
342 
343     // Insert extra Nops for code alignment if the target define
344     // shouldInsertExtraNopBytesForCodeAlign target hook.
345     if (AF.getParent()->useCodeAlign() && AF.hasEmitNops() &&
346         getBackend().shouldInsertExtraNopBytesForCodeAlign(AF, Size))
347       return Size;
348 
349     // If we are padding with nops, force the padding to be larger than the
350     // minimum nop size.
351     if (Size > 0 && AF.hasEmitNops()) {
352       while (Size % getBackend().getMinimumNopSize())
353         Size += AF.getAlignment().value();
354     }
355     if (Size > AF.getMaxBytesToEmit())
356       return 0;
357     return Size;
358   }
359 
360   case MCFragment::FT_Org: {
361     const MCOrgFragment &OF = cast<MCOrgFragment>(F);
362     MCValue Value;
363     if (!OF.getOffset().evaluateAsValue(Value, Layout)) {
364       getContext().reportError(OF.getLoc(),
365                                "expected assembly-time absolute expression");
366         return 0;
367     }
368 
369     uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
370     int64_t TargetLocation = Value.getConstant();
371     if (const MCSymbolRefExpr *A = Value.getSymA()) {
372       uint64_t Val;
373       if (!Layout.getSymbolOffset(A->getSymbol(), Val)) {
374         getContext().reportError(OF.getLoc(), "expected absolute expression");
375         return 0;
376       }
377       TargetLocation += Val;
378     }
379     int64_t Size = TargetLocation - FragmentOffset;
380     if (Size < 0 || Size >= 0x40000000) {
381       getContext().reportError(
382           OF.getLoc(), "invalid .org offset '" + Twine(TargetLocation) +
383                            "' (at offset '" + Twine(FragmentOffset) + "')");
384       return 0;
385     }
386     return Size;
387   }
388 
389   case MCFragment::FT_Dwarf:
390     return cast<MCDwarfLineAddrFragment>(F).getContents().size();
391   case MCFragment::FT_DwarfFrame:
392     return cast<MCDwarfCallFrameFragment>(F).getContents().size();
393   case MCFragment::FT_CVInlineLines:
394     return cast<MCCVInlineLineTableFragment>(F).getContents().size();
395   case MCFragment::FT_CVDefRange:
396     return cast<MCCVDefRangeFragment>(F).getContents().size();
397   case MCFragment::FT_PseudoProbe:
398     return cast<MCPseudoProbeAddrFragment>(F).getContents().size();
399   case MCFragment::FT_Dummy:
400     llvm_unreachable("Should not have been added");
401   }
402 
403   llvm_unreachable("invalid fragment kind");
404 }
405 
406 void MCAsmLayout::layoutFragment(MCFragment *F) {
407   MCFragment *Prev = F->getPrevNode();
408 
409   // We should never try to recompute something which is valid.
410   assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
411   // We should never try to compute the fragment layout if its predecessor
412   // isn't valid.
413   assert((!Prev || isFragmentValid(Prev)) &&
414          "Attempt to compute fragment before its predecessor!");
415 
416   assert(!F->IsBeingLaidOut && "Already being laid out!");
417   F->IsBeingLaidOut = true;
418 
419   ++stats::FragmentLayouts;
420 
421   // Compute fragment offset and size.
422   if (Prev)
423     F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
424   else
425     F->Offset = 0;
426   F->IsBeingLaidOut = false;
427   LastValidFragment[F->getParent()] = F;
428 
429   // If bundling is enabled and this fragment has instructions in it, it has to
430   // obey the bundling restrictions. With padding, we'll have:
431   //
432   //
433   //        BundlePadding
434   //             |||
435   // -------------------------------------
436   //   Prev  |##########|       F        |
437   // -------------------------------------
438   //                    ^
439   //                    |
440   //                    F->Offset
441   //
442   // The fragment's offset will point to after the padding, and its computed
443   // size won't include the padding.
444   //
445   // When the -mc-relax-all flag is used, we optimize bundling by writting the
446   // padding directly into fragments when the instructions are emitted inside
447   // the streamer. When the fragment is larger than the bundle size, we need to
448   // ensure that it's bundle aligned. This means that if we end up with
449   // multiple fragments, we must emit bundle padding between fragments.
450   //
451   // ".align N" is an example of a directive that introduces multiple
452   // fragments. We could add a special case to handle ".align N" by emitting
453   // within-fragment padding (which would produce less padding when N is less
454   // than the bundle size), but for now we don't.
455   //
456   if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
457     assert(isa<MCEncodedFragment>(F) &&
458            "Only MCEncodedFragment implementations have instructions");
459     MCEncodedFragment *EF = cast<MCEncodedFragment>(F);
460     uint64_t FSize = Assembler.computeFragmentSize(*this, *EF);
461 
462     if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
463       report_fatal_error("Fragment can't be larger than a bundle size");
464 
465     uint64_t RequiredBundlePadding =
466         computeBundlePadding(Assembler, EF, EF->Offset, FSize);
467     if (RequiredBundlePadding > UINT8_MAX)
468       report_fatal_error("Padding cannot exceed 255 bytes");
469     EF->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
470     EF->Offset += RequiredBundlePadding;
471   }
472 }
473 
474 bool MCAssembler::registerSymbol(const MCSymbol &Symbol) {
475   bool Changed = !Symbol.isRegistered();
476   if (Changed) {
477     Symbol.setIsRegistered(true);
478     Symbols.push_back(&Symbol);
479   }
480   return Changed;
481 }
482 
483 void MCAssembler::writeFragmentPadding(raw_ostream &OS,
484                                        const MCEncodedFragment &EF,
485                                        uint64_t FSize) const {
486   assert(getBackendPtr() && "Expected assembler backend");
487   // Should NOP padding be written out before this fragment?
488   unsigned BundlePadding = EF.getBundlePadding();
489   if (BundlePadding > 0) {
490     assert(isBundlingEnabled() &&
491            "Writing bundle padding with disabled bundling");
492     assert(EF.hasInstructions() &&
493            "Writing bundle padding for a fragment without instructions");
494 
495     unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
496     const MCSubtargetInfo *STI = EF.getSubtargetInfo();
497     if (EF.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
498       // If the padding itself crosses a bundle boundary, it must be emitted
499       // in 2 pieces, since even nop instructions must not cross boundaries.
500       //             v--------------v   <- BundleAlignSize
501       //        v---------v             <- BundlePadding
502       // ----------------------------
503       // | Prev |####|####|    F    |
504       // ----------------------------
505       //        ^-------------------^   <- TotalLength
506       unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
507       if (!getBackend().writeNopData(OS, DistanceToBoundary, STI))
508         report_fatal_error("unable to write NOP sequence of " +
509                            Twine(DistanceToBoundary) + " bytes");
510       BundlePadding -= DistanceToBoundary;
511     }
512     if (!getBackend().writeNopData(OS, BundlePadding, STI))
513       report_fatal_error("unable to write NOP sequence of " +
514                          Twine(BundlePadding) + " bytes");
515   }
516 }
517 
518 /// Write the fragment \p F to the output file.
519 static void writeFragment(raw_ostream &OS, const MCAssembler &Asm,
520                           const MCAsmLayout &Layout, const MCFragment &F) {
521   // FIXME: Embed in fragments instead?
522   uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
523 
524   support::endianness Endian = Asm.getBackend().Endian;
525 
526   if (const MCEncodedFragment *EF = dyn_cast<MCEncodedFragment>(&F))
527     Asm.writeFragmentPadding(OS, *EF, FragmentSize);
528 
529   // This variable (and its dummy usage) is to participate in the assert at
530   // the end of the function.
531   uint64_t Start = OS.tell();
532   (void) Start;
533 
534   ++stats::EmittedFragments;
535 
536   switch (F.getKind()) {
537   case MCFragment::FT_Align: {
538     ++stats::EmittedAlignFragments;
539     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
540     assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
541 
542     uint64_t Count = FragmentSize / AF.getValueSize();
543 
544     // FIXME: This error shouldn't actually occur (the front end should emit
545     // multiple .align directives to enforce the semantics it wants), but is
546     // severe enough that we want to report it. How to handle this?
547     if (Count * AF.getValueSize() != FragmentSize)
548       report_fatal_error("undefined .align directive, value size '" +
549                         Twine(AF.getValueSize()) +
550                         "' is not a divisor of padding size '" +
551                         Twine(FragmentSize) + "'");
552 
553     // See if we are aligning with nops, and if so do that first to try to fill
554     // the Count bytes.  Then if that did not fill any bytes or there are any
555     // bytes left to fill use the Value and ValueSize to fill the rest.
556     // If we are aligning with nops, ask that target to emit the right data.
557     if (AF.hasEmitNops()) {
558       if (!Asm.getBackend().writeNopData(OS, Count, AF.getSubtargetInfo()))
559         report_fatal_error("unable to write nop sequence of " +
560                           Twine(Count) + " bytes");
561       break;
562     }
563 
564     // Otherwise, write out in multiples of the value size.
565     for (uint64_t i = 0; i != Count; ++i) {
566       switch (AF.getValueSize()) {
567       default: llvm_unreachable("Invalid size!");
568       case 1: OS << char(AF.getValue()); break;
569       case 2:
570         support::endian::write<uint16_t>(OS, AF.getValue(), Endian);
571         break;
572       case 4:
573         support::endian::write<uint32_t>(OS, AF.getValue(), Endian);
574         break;
575       case 8:
576         support::endian::write<uint64_t>(OS, AF.getValue(), Endian);
577         break;
578       }
579     }
580     break;
581   }
582 
583   case MCFragment::FT_Data:
584     ++stats::EmittedDataFragments;
585     OS << cast<MCDataFragment>(F).getContents();
586     break;
587 
588   case MCFragment::FT_Relaxable:
589     ++stats::EmittedRelaxableFragments;
590     OS << cast<MCRelaxableFragment>(F).getContents();
591     break;
592 
593   case MCFragment::FT_CompactEncodedInst:
594     ++stats::EmittedCompactEncodedInstFragments;
595     OS << cast<MCCompactEncodedInstFragment>(F).getContents();
596     break;
597 
598   case MCFragment::FT_Fill: {
599     ++stats::EmittedFillFragments;
600     const MCFillFragment &FF = cast<MCFillFragment>(F);
601     uint64_t V = FF.getValue();
602     unsigned VSize = FF.getValueSize();
603     const unsigned MaxChunkSize = 16;
604     char Data[MaxChunkSize];
605     assert(0 < VSize && VSize <= MaxChunkSize && "Illegal fragment fill size");
606     // Duplicate V into Data as byte vector to reduce number of
607     // writes done. As such, do endian conversion here.
608     for (unsigned I = 0; I != VSize; ++I) {
609       unsigned index = Endian == support::little ? I : (VSize - I - 1);
610       Data[I] = uint8_t(V >> (index * 8));
611     }
612     for (unsigned I = VSize; I < MaxChunkSize; ++I)
613       Data[I] = Data[I - VSize];
614 
615     // Set to largest multiple of VSize in Data.
616     const unsigned NumPerChunk = MaxChunkSize / VSize;
617     // Set ChunkSize to largest multiple of VSize in Data
618     const unsigned ChunkSize = VSize * NumPerChunk;
619 
620     // Do copies by chunk.
621     StringRef Ref(Data, ChunkSize);
622     for (uint64_t I = 0, E = FragmentSize / ChunkSize; I != E; ++I)
623       OS << Ref;
624 
625     // do remainder if needed.
626     unsigned TrailingCount = FragmentSize % ChunkSize;
627     if (TrailingCount)
628       OS.write(Data, TrailingCount);
629     break;
630   }
631 
632   case MCFragment::FT_Nops: {
633     ++stats::EmittedNopsFragments;
634     const MCNopsFragment &NF = cast<MCNopsFragment>(F);
635 
636     int64_t NumBytes = NF.getNumBytes();
637     int64_t ControlledNopLength = NF.getControlledNopLength();
638     int64_t MaximumNopLength =
639         Asm.getBackend().getMaximumNopSize(*NF.getSubtargetInfo());
640 
641     assert(NumBytes > 0 && "Expected positive NOPs fragment size");
642     assert(ControlledNopLength >= 0 && "Expected non-negative NOP size");
643 
644     if (ControlledNopLength > MaximumNopLength) {
645       Asm.getContext().reportError(NF.getLoc(),
646                                    "illegal NOP size " +
647                                        std::to_string(ControlledNopLength) +
648                                        ". (expected within [0, " +
649                                        std::to_string(MaximumNopLength) + "])");
650       // Clamp the NOP length as reportError does not stop the execution
651       // immediately.
652       ControlledNopLength = MaximumNopLength;
653     }
654 
655     // Use maximum value if the size of each NOP is not specified
656     if (!ControlledNopLength)
657       ControlledNopLength = MaximumNopLength;
658 
659     while (NumBytes) {
660       uint64_t NumBytesToEmit =
661           (uint64_t)std::min(NumBytes, ControlledNopLength);
662       assert(NumBytesToEmit && "try to emit empty NOP instruction");
663       if (!Asm.getBackend().writeNopData(OS, NumBytesToEmit,
664                                          NF.getSubtargetInfo())) {
665         report_fatal_error("unable to write nop sequence of the remaining " +
666                            Twine(NumBytesToEmit) + " bytes");
667         break;
668       }
669       NumBytes -= NumBytesToEmit;
670     }
671     break;
672   }
673 
674   case MCFragment::FT_LEB: {
675     const MCLEBFragment &LF = cast<MCLEBFragment>(F);
676     OS << LF.getContents();
677     break;
678   }
679 
680   case MCFragment::FT_BoundaryAlign: {
681     const MCBoundaryAlignFragment &BF = cast<MCBoundaryAlignFragment>(F);
682     if (!Asm.getBackend().writeNopData(OS, FragmentSize, BF.getSubtargetInfo()))
683       report_fatal_error("unable to write nop sequence of " +
684                          Twine(FragmentSize) + " bytes");
685     break;
686   }
687 
688   case MCFragment::FT_SymbolId: {
689     const MCSymbolIdFragment &SF = cast<MCSymbolIdFragment>(F);
690     support::endian::write<uint32_t>(OS, SF.getSymbol()->getIndex(), Endian);
691     break;
692   }
693 
694   case MCFragment::FT_Org: {
695     ++stats::EmittedOrgFragments;
696     const MCOrgFragment &OF = cast<MCOrgFragment>(F);
697 
698     for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
699       OS << char(OF.getValue());
700 
701     break;
702   }
703 
704   case MCFragment::FT_Dwarf: {
705     const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
706     OS << OF.getContents();
707     break;
708   }
709   case MCFragment::FT_DwarfFrame: {
710     const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
711     OS << CF.getContents();
712     break;
713   }
714   case MCFragment::FT_CVInlineLines: {
715     const auto &OF = cast<MCCVInlineLineTableFragment>(F);
716     OS << OF.getContents();
717     break;
718   }
719   case MCFragment::FT_CVDefRange: {
720     const auto &DRF = cast<MCCVDefRangeFragment>(F);
721     OS << DRF.getContents();
722     break;
723   }
724   case MCFragment::FT_PseudoProbe: {
725     const MCPseudoProbeAddrFragment &PF = cast<MCPseudoProbeAddrFragment>(F);
726     OS << PF.getContents();
727     break;
728   }
729   case MCFragment::FT_Dummy:
730     llvm_unreachable("Should not have been added");
731   }
732 
733   assert(OS.tell() - Start == FragmentSize &&
734          "The stream should advance by fragment size");
735 }
736 
737 void MCAssembler::writeSectionData(raw_ostream &OS, const MCSection *Sec,
738                                    const MCAsmLayout &Layout) const {
739   assert(getBackendPtr() && "Expected assembler backend");
740 
741   // Ignore virtual sections.
742   if (Sec->isVirtualSection()) {
743     assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
744 
745     // Check that contents are only things legal inside a virtual section.
746     for (const MCFragment &F : *Sec) {
747       switch (F.getKind()) {
748       default: llvm_unreachable("Invalid fragment in virtual section!");
749       case MCFragment::FT_Data: {
750         // Check that we aren't trying to write a non-zero contents (or fixups)
751         // into a virtual section. This is to support clients which use standard
752         // directives to fill the contents of virtual sections.
753         const MCDataFragment &DF = cast<MCDataFragment>(F);
754         if (DF.fixup_begin() != DF.fixup_end())
755           getContext().reportError(SMLoc(), Sec->getVirtualSectionKind() +
756                                                 " section '" + Sec->getName() +
757                                                 "' cannot have fixups");
758         for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
759           if (DF.getContents()[i]) {
760             getContext().reportError(SMLoc(),
761                                      Sec->getVirtualSectionKind() +
762                                          " section '" + Sec->getName() +
763                                          "' cannot have non-zero initializers");
764             break;
765           }
766         break;
767       }
768       case MCFragment::FT_Align:
769         // Check that we aren't trying to write a non-zero value into a virtual
770         // section.
771         assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
772                 cast<MCAlignFragment>(F).getValue() == 0) &&
773                "Invalid align in virtual section!");
774         break;
775       case MCFragment::FT_Fill:
776         assert((cast<MCFillFragment>(F).getValue() == 0) &&
777                "Invalid fill in virtual section!");
778         break;
779       case MCFragment::FT_Org:
780         break;
781       }
782     }
783 
784     return;
785   }
786 
787   uint64_t Start = OS.tell();
788   (void)Start;
789 
790   for (const MCFragment &F : *Sec)
791     writeFragment(OS, *this, Layout, F);
792 
793   assert(getContext().hadError() ||
794          OS.tell() - Start == Layout.getSectionAddressSize(Sec));
795 }
796 
797 std::tuple<MCValue, uint64_t, bool>
798 MCAssembler::handleFixup(const MCAsmLayout &Layout, MCFragment &F,
799                          const MCFixup &Fixup) {
800   // Evaluate the fixup.
801   MCValue Target;
802   uint64_t FixedValue;
803   bool WasForced;
804   bool IsResolved = evaluateFixup(Layout, Fixup, &F, Target, FixedValue,
805                                   WasForced);
806   if (!IsResolved) {
807     // The fixup was unresolved, we need a relocation. Inform the object
808     // writer of the relocation, and give it an opportunity to adjust the
809     // fixup value if need be.
810     getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, FixedValue);
811   }
812   return std::make_tuple(Target, FixedValue, IsResolved);
813 }
814 
815 void MCAssembler::layout(MCAsmLayout &Layout) {
816   assert(getBackendPtr() && "Expected assembler backend");
817   DEBUG_WITH_TYPE("mc-dump", {
818       errs() << "assembler backend - pre-layout\n--\n";
819       dump(); });
820 
821   // Create dummy fragments and assign section ordinals.
822   unsigned SectionIndex = 0;
823   for (MCSection &Sec : *this) {
824     // Create dummy fragments to eliminate any empty sections, this simplifies
825     // layout.
826     if (Sec.getFragmentList().empty())
827       new MCDataFragment(&Sec);
828 
829     Sec.setOrdinal(SectionIndex++);
830   }
831 
832   // Assign layout order indices to sections and fragments.
833   for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
834     MCSection *Sec = Layout.getSectionOrder()[i];
835     Sec->setLayoutOrder(i);
836 
837     unsigned FragmentIndex = 0;
838     for (MCFragment &Frag : *Sec)
839       Frag.setLayoutOrder(FragmentIndex++);
840   }
841 
842   // Layout until everything fits.
843   while (layoutOnce(Layout)) {
844     if (getContext().hadError())
845       return;
846     // Size of fragments in one section can depend on the size of fragments in
847     // another. If any fragment has changed size, we have to re-layout (and
848     // as a result possibly further relax) all.
849     for (MCSection &Sec : *this)
850       Layout.invalidateFragmentsFrom(&*Sec.begin());
851   }
852 
853   DEBUG_WITH_TYPE("mc-dump", {
854       errs() << "assembler backend - post-relaxation\n--\n";
855       dump(); });
856 
857   // Finalize the layout, including fragment lowering.
858   finishLayout(Layout);
859 
860   DEBUG_WITH_TYPE("mc-dump", {
861       errs() << "assembler backend - final-layout\n--\n";
862       dump(); });
863 
864   // Allow the object writer a chance to perform post-layout binding (for
865   // example, to set the index fields in the symbol data).
866   getWriter().executePostLayoutBinding(*this, Layout);
867 
868   // Evaluate and apply the fixups, generating relocation entries as necessary.
869   for (MCSection &Sec : *this) {
870     for (MCFragment &Frag : Sec) {
871       ArrayRef<MCFixup> Fixups;
872       MutableArrayRef<char> Contents;
873       const MCSubtargetInfo *STI = nullptr;
874 
875       // Process MCAlignFragment and MCEncodedFragmentWithFixups here.
876       switch (Frag.getKind()) {
877       default:
878         continue;
879       case MCFragment::FT_Align: {
880         MCAlignFragment &AF = cast<MCAlignFragment>(Frag);
881         // Insert fixup type for code alignment if the target define
882         // shouldInsertFixupForCodeAlign target hook.
883         if (Sec.useCodeAlign() && AF.hasEmitNops())
884           getBackend().shouldInsertFixupForCodeAlign(*this, Layout, AF);
885         continue;
886       }
887       case MCFragment::FT_Data: {
888         MCDataFragment &DF = cast<MCDataFragment>(Frag);
889         Fixups = DF.getFixups();
890         Contents = DF.getContents();
891         STI = DF.getSubtargetInfo();
892         assert(!DF.hasInstructions() || STI != nullptr);
893         break;
894       }
895       case MCFragment::FT_Relaxable: {
896         MCRelaxableFragment &RF = cast<MCRelaxableFragment>(Frag);
897         Fixups = RF.getFixups();
898         Contents = RF.getContents();
899         STI = RF.getSubtargetInfo();
900         assert(!RF.hasInstructions() || STI != nullptr);
901         break;
902       }
903       case MCFragment::FT_CVDefRange: {
904         MCCVDefRangeFragment &CF = cast<MCCVDefRangeFragment>(Frag);
905         Fixups = CF.getFixups();
906         Contents = CF.getContents();
907         break;
908       }
909       case MCFragment::FT_Dwarf: {
910         MCDwarfLineAddrFragment &DF = cast<MCDwarfLineAddrFragment>(Frag);
911         Fixups = DF.getFixups();
912         Contents = DF.getContents();
913         break;
914       }
915       case MCFragment::FT_DwarfFrame: {
916         MCDwarfCallFrameFragment &DF = cast<MCDwarfCallFrameFragment>(Frag);
917         Fixups = DF.getFixups();
918         Contents = DF.getContents();
919         break;
920       }
921       case MCFragment::FT_PseudoProbe: {
922         MCPseudoProbeAddrFragment &PF = cast<MCPseudoProbeAddrFragment>(Frag);
923         Fixups = PF.getFixups();
924         Contents = PF.getContents();
925         break;
926       }
927       }
928       for (const MCFixup &Fixup : Fixups) {
929         uint64_t FixedValue;
930         bool IsResolved;
931         MCValue Target;
932         std::tie(Target, FixedValue, IsResolved) =
933             handleFixup(Layout, Frag, Fixup);
934         getBackend().applyFixup(*this, Fixup, Target, Contents, FixedValue,
935                                 IsResolved, STI);
936       }
937     }
938   }
939 }
940 
941 void MCAssembler::Finish() {
942   // Create the layout object.
943   MCAsmLayout Layout(*this);
944   layout(Layout);
945 
946   // Write the object file.
947   stats::ObjectBytes += getWriter().writeObject(*this, Layout);
948 }
949 
950 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
951                                        const MCRelaxableFragment *DF,
952                                        const MCAsmLayout &Layout) const {
953   assert(getBackendPtr() && "Expected assembler backend");
954   MCValue Target;
955   uint64_t Value;
956   bool WasForced;
957   bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value, WasForced);
958   if (Target.getSymA() &&
959       Target.getSymA()->getKind() == MCSymbolRefExpr::VK_X86_ABS8 &&
960       Fixup.getKind() == FK_Data_1)
961     return false;
962   return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
963                                                    Layout, WasForced);
964 }
965 
966 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
967                                           const MCAsmLayout &Layout) const {
968   assert(getBackendPtr() && "Expected assembler backend");
969   // If this inst doesn't ever need relaxation, ignore it. This occurs when we
970   // are intentionally pushing out inst fragments, or because we relaxed a
971   // previous instruction to one that doesn't need relaxation.
972   if (!getBackend().mayNeedRelaxation(F->getInst(), *F->getSubtargetInfo()))
973     return false;
974 
975   for (const MCFixup &Fixup : F->getFixups())
976     if (fixupNeedsRelaxation(Fixup, F, Layout))
977       return true;
978 
979   return false;
980 }
981 
982 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
983                                    MCRelaxableFragment &F) {
984   assert(getEmitterPtr() &&
985          "Expected CodeEmitter defined for relaxInstruction");
986   if (!fragmentNeedsRelaxation(&F, Layout))
987     return false;
988 
989   ++stats::RelaxedInstructions;
990 
991   // FIXME-PERF: We could immediately lower out instructions if we can tell
992   // they are fully resolved, to avoid retesting on later passes.
993 
994   // Relax the fragment.
995 
996   MCInst Relaxed = F.getInst();
997   getBackend().relaxInstruction(Relaxed, *F.getSubtargetInfo());
998 
999   // Encode the new instruction.
1000   F.setInst(Relaxed);
1001   F.getFixups().clear();
1002   F.getContents().clear();
1003   getEmitter().encodeInstruction(Relaxed, F.getContents(), F.getFixups(),
1004                                  *F.getSubtargetInfo());
1005   return true;
1006 }
1007 
1008 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
1009   uint64_t OldSize = LF.getContents().size();
1010   int64_t Value;
1011   bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
1012   if (!Abs)
1013     report_fatal_error("sleb128 and uleb128 expressions must be absolute");
1014   SmallString<8> &Data = LF.getContents();
1015   Data.clear();
1016   raw_svector_ostream OSE(Data);
1017   // The compiler can generate EH table assembly that is impossible to assemble
1018   // without either adding padding to an LEB fragment or adding extra padding
1019   // to a later alignment fragment. To accommodate such tables, relaxation can
1020   // only increase an LEB fragment size here, not decrease it. See PR35809.
1021   if (LF.isSigned())
1022     encodeSLEB128(Value, OSE, OldSize);
1023   else
1024     encodeULEB128(Value, OSE, OldSize);
1025   return OldSize != LF.getContents().size();
1026 }
1027 
1028 /// Check if the branch crosses the boundary.
1029 ///
1030 /// \param StartAddr start address of the fused/unfused branch.
1031 /// \param Size size of the fused/unfused branch.
1032 /// \param BoundaryAlignment alignment requirement of the branch.
1033 /// \returns true if the branch cross the boundary.
1034 static bool mayCrossBoundary(uint64_t StartAddr, uint64_t Size,
1035                              Align BoundaryAlignment) {
1036   uint64_t EndAddr = StartAddr + Size;
1037   return (StartAddr >> Log2(BoundaryAlignment)) !=
1038          ((EndAddr - 1) >> Log2(BoundaryAlignment));
1039 }
1040 
1041 /// Check if the branch is against the boundary.
1042 ///
1043 /// \param StartAddr start address of the fused/unfused branch.
1044 /// \param Size size of the fused/unfused branch.
1045 /// \param BoundaryAlignment alignment requirement of the branch.
1046 /// \returns true if the branch is against the boundary.
1047 static bool isAgainstBoundary(uint64_t StartAddr, uint64_t Size,
1048                               Align BoundaryAlignment) {
1049   uint64_t EndAddr = StartAddr + Size;
1050   return (EndAddr & (BoundaryAlignment.value() - 1)) == 0;
1051 }
1052 
1053 /// Check if the branch needs padding.
1054 ///
1055 /// \param StartAddr start address of the fused/unfused branch.
1056 /// \param Size size of the fused/unfused branch.
1057 /// \param BoundaryAlignment alignment requirement of the branch.
1058 /// \returns true if the branch needs padding.
1059 static bool needPadding(uint64_t StartAddr, uint64_t Size,
1060                         Align BoundaryAlignment) {
1061   return mayCrossBoundary(StartAddr, Size, BoundaryAlignment) ||
1062          isAgainstBoundary(StartAddr, Size, BoundaryAlignment);
1063 }
1064 
1065 bool MCAssembler::relaxBoundaryAlign(MCAsmLayout &Layout,
1066                                      MCBoundaryAlignFragment &BF) {
1067   // BoundaryAlignFragment that doesn't need to align any fragment should not be
1068   // relaxed.
1069   if (!BF.getLastFragment())
1070     return false;
1071 
1072   uint64_t AlignedOffset = Layout.getFragmentOffset(&BF);
1073   uint64_t AlignedSize = 0;
1074   for (const MCFragment *F = BF.getLastFragment(); F != &BF;
1075        F = F->getPrevNode())
1076     AlignedSize += computeFragmentSize(Layout, *F);
1077 
1078   Align BoundaryAlignment = BF.getAlignment();
1079   uint64_t NewSize = needPadding(AlignedOffset, AlignedSize, BoundaryAlignment)
1080                          ? offsetToAlignment(AlignedOffset, BoundaryAlignment)
1081                          : 0U;
1082   if (NewSize == BF.getSize())
1083     return false;
1084   BF.setSize(NewSize);
1085   Layout.invalidateFragmentsFrom(&BF);
1086   return true;
1087 }
1088 
1089 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1090                                      MCDwarfLineAddrFragment &DF) {
1091 
1092   bool WasRelaxed;
1093   if (getBackend().relaxDwarfLineAddr(DF, Layout, WasRelaxed))
1094     return WasRelaxed;
1095 
1096   MCContext &Context = Layout.getAssembler().getContext();
1097   uint64_t OldSize = DF.getContents().size();
1098   int64_t AddrDelta;
1099   bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1100   assert(Abs && "We created a line delta with an invalid expression");
1101   (void)Abs;
1102   int64_t LineDelta;
1103   LineDelta = DF.getLineDelta();
1104   SmallVectorImpl<char> &Data = DF.getContents();
1105   Data.clear();
1106   DF.getFixups().clear();
1107 
1108   MCDwarfLineAddr::encode(Context, getDWARFLinetableParams(), LineDelta,
1109                           AddrDelta, Data);
1110   return OldSize != Data.size();
1111 }
1112 
1113 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1114                                               MCDwarfCallFrameFragment &DF) {
1115   bool WasRelaxed;
1116   if (getBackend().relaxDwarfCFA(DF, Layout, WasRelaxed))
1117     return WasRelaxed;
1118 
1119   MCContext &Context = Layout.getAssembler().getContext();
1120   int64_t Value;
1121   bool Abs = DF.getAddrDelta().evaluateAsAbsolute(Value, Layout);
1122   if (!Abs) {
1123     getContext().reportError(DF.getAddrDelta().getLoc(),
1124                              "invalid CFI advance_loc expression");
1125     DF.setAddrDelta(MCConstantExpr::create(0, Context));
1126     return false;
1127   }
1128 
1129   SmallVectorImpl<char> &Data = DF.getContents();
1130   uint64_t OldSize = Data.size();
1131   Data.clear();
1132   DF.getFixups().clear();
1133 
1134   MCDwarfFrameEmitter::encodeAdvanceLoc(Context, Value, Data);
1135   return OldSize != Data.size();
1136 }
1137 
1138 bool MCAssembler::relaxCVInlineLineTable(MCAsmLayout &Layout,
1139                                          MCCVInlineLineTableFragment &F) {
1140   unsigned OldSize = F.getContents().size();
1141   getContext().getCVContext().encodeInlineLineTable(Layout, F);
1142   return OldSize != F.getContents().size();
1143 }
1144 
1145 bool MCAssembler::relaxCVDefRange(MCAsmLayout &Layout,
1146                                   MCCVDefRangeFragment &F) {
1147   unsigned OldSize = F.getContents().size();
1148   getContext().getCVContext().encodeDefRange(Layout, F);
1149   return OldSize != F.getContents().size();
1150 }
1151 
1152 bool MCAssembler::relaxPseudoProbeAddr(MCAsmLayout &Layout,
1153                                        MCPseudoProbeAddrFragment &PF) {
1154   uint64_t OldSize = PF.getContents().size();
1155   int64_t AddrDelta;
1156   bool Abs = PF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1157   assert(Abs && "We created a pseudo probe with an invalid expression");
1158   (void)Abs;
1159   SmallVectorImpl<char> &Data = PF.getContents();
1160   Data.clear();
1161   raw_svector_ostream OSE(Data);
1162   PF.getFixups().clear();
1163 
1164   // AddrDelta is a signed integer
1165   encodeSLEB128(AddrDelta, OSE, OldSize);
1166   return OldSize != Data.size();
1167 }
1168 
1169 bool MCAssembler::relaxFragment(MCAsmLayout &Layout, MCFragment &F) {
1170   switch(F.getKind()) {
1171   default:
1172     return false;
1173   case MCFragment::FT_Relaxable:
1174     assert(!getRelaxAll() &&
1175            "Did not expect a MCRelaxableFragment in RelaxAll mode");
1176     return relaxInstruction(Layout, cast<MCRelaxableFragment>(F));
1177   case MCFragment::FT_Dwarf:
1178     return relaxDwarfLineAddr(Layout, cast<MCDwarfLineAddrFragment>(F));
1179   case MCFragment::FT_DwarfFrame:
1180     return relaxDwarfCallFrameFragment(Layout,
1181                                        cast<MCDwarfCallFrameFragment>(F));
1182   case MCFragment::FT_LEB:
1183     return relaxLEB(Layout, cast<MCLEBFragment>(F));
1184   case MCFragment::FT_BoundaryAlign:
1185     return relaxBoundaryAlign(Layout, cast<MCBoundaryAlignFragment>(F));
1186   case MCFragment::FT_CVInlineLines:
1187     return relaxCVInlineLineTable(Layout, cast<MCCVInlineLineTableFragment>(F));
1188   case MCFragment::FT_CVDefRange:
1189     return relaxCVDefRange(Layout, cast<MCCVDefRangeFragment>(F));
1190   case MCFragment::FT_PseudoProbe:
1191     return relaxPseudoProbeAddr(Layout, cast<MCPseudoProbeAddrFragment>(F));
1192   }
1193 }
1194 
1195 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1196   // Holds the first fragment which needed relaxing during this layout. It will
1197   // remain NULL if none were relaxed.
1198   // When a fragment is relaxed, all the fragments following it should get
1199   // invalidated because their offset is going to change.
1200   MCFragment *FirstRelaxedFragment = nullptr;
1201 
1202   // Attempt to relax all the fragments in the section.
1203   for (MCFragment &Frag : Sec) {
1204     // Check if this is a fragment that needs relaxation.
1205     bool RelaxedFrag = relaxFragment(Layout, Frag);
1206     if (RelaxedFrag && !FirstRelaxedFragment)
1207       FirstRelaxedFragment = &Frag;
1208   }
1209   if (FirstRelaxedFragment) {
1210     Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1211     return true;
1212   }
1213   return false;
1214 }
1215 
1216 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1217   ++stats::RelaxationSteps;
1218 
1219   bool WasRelaxed = false;
1220   for (MCSection &Sec : *this) {
1221     while (layoutSectionOnce(Layout, Sec))
1222       WasRelaxed = true;
1223   }
1224 
1225   return WasRelaxed;
1226 }
1227 
1228 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1229   assert(getBackendPtr() && "Expected assembler backend");
1230   // The layout is done. Mark every fragment as valid.
1231   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1232     MCSection &Section = *Layout.getSectionOrder()[i];
1233     Layout.getFragmentOffset(&*Section.getFragmentList().rbegin());
1234     computeFragmentSize(Layout, *Section.getFragmentList().rbegin());
1235   }
1236   getBackend().finishLayout(*this, Layout);
1237 }
1238 
1239 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1240 LLVM_DUMP_METHOD void MCAssembler::dump() const{
1241   raw_ostream &OS = errs();
1242 
1243   OS << "<MCAssembler\n";
1244   OS << "  Sections:[\n    ";
1245   for (const_iterator it = begin(), ie = end(); it != ie; ++it) {
1246     if (it != begin()) OS << ",\n    ";
1247     it->dump();
1248   }
1249   OS << "],\n";
1250   OS << "  Symbols:[";
1251 
1252   for (const_symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1253     if (it != symbol_begin()) OS << ",\n           ";
1254     OS << "(";
1255     it->dump();
1256     OS << ", Index:" << it->getIndex() << ", ";
1257     OS << ")";
1258   }
1259   OS << "]>\n";
1260 }
1261 #endif
1262