Use range-based for loops. NFC
[oota-llvm.git] / lib / MC / MCAssembler.cpp
1 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/MC/MCAssembler.h"
11 #include "llvm/ADT/Statistic.h"
12 #include "llvm/ADT/StringExtras.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmInfo.h"
16 #include "llvm/MC/MCAsmLayout.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCDwarf.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCFixupKindInfo.h"
22 #include "llvm/MC/MCObjectWriter.h"
23 #include "llvm/MC/MCSection.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/MC/MCValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/LEB128.h"
30 #include "llvm/Support/TargetRegistry.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <tuple>
33 using namespace llvm;
34
35 #define DEBUG_TYPE "assembler"
36
37 namespace {
38 namespace stats {
39 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
40 STATISTIC(EmittedRelaxableFragments,
41           "Number of emitted assembler fragments - relaxable");
42 STATISTIC(EmittedDataFragments,
43           "Number of emitted assembler fragments - data");
44 STATISTIC(EmittedCompactEncodedInstFragments,
45           "Number of emitted assembler fragments - compact encoded inst");
46 STATISTIC(EmittedAlignFragments,
47           "Number of emitted assembler fragments - align");
48 STATISTIC(EmittedFillFragments,
49           "Number of emitted assembler fragments - fill");
50 STATISTIC(EmittedOrgFragments,
51           "Number of emitted assembler fragments - org");
52 STATISTIC(evaluateFixup, "Number of evaluated fixups");
53 STATISTIC(FragmentLayouts, "Number of fragment layouts");
54 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
55 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
56 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
57 }
58 }
59
60 // FIXME FIXME FIXME: There are number of places in this file where we convert
61 // what is a 64-bit assembler value used for computation into a value in the
62 // object file, which may truncate it. We should detect that truncation where
63 // invalid and report errors back.
64
65 /* *** */
66
67 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
68   : Assembler(Asm), LastValidFragment()
69  {
70   // Compute the section layout order. Virtual sections must go last.
71   for (MCSection &Sec : Asm)
72     if (!Sec.isVirtualSection())
73       SectionOrder.push_back(&Sec);
74   for (MCSection &Sec : Asm)
75     if (Sec.isVirtualSection())
76       SectionOrder.push_back(&Sec);
77 }
78
79 bool MCAsmLayout::isFragmentValid(const MCFragment *F) const {
80   const MCSection *Sec = F->getParent();
81   const MCFragment *LastValid = LastValidFragment.lookup(Sec);
82   if (!LastValid)
83     return false;
84   assert(LastValid->getParent() == Sec);
85   return F->getLayoutOrder() <= LastValid->getLayoutOrder();
86 }
87
88 void MCAsmLayout::invalidateFragmentsFrom(MCFragment *F) {
89   // If this fragment wasn't already valid, we don't need to do anything.
90   if (!isFragmentValid(F))
91     return;
92
93   // Otherwise, reset the last valid fragment to the previous fragment
94   // (if this is the first fragment, it will be NULL).
95   LastValidFragment[F->getParent()] = F->getPrevNode();
96 }
97
98 void MCAsmLayout::ensureValid(const MCFragment *F) const {
99   MCSection *Sec = F->getParent();
100   MCSection::iterator I;
101   if (MCFragment *Cur = LastValidFragment[Sec])
102     I = ++MCSection::iterator(Cur);
103   else
104     I = Sec->begin();
105
106   // Advance the layout position until the fragment is valid.
107   while (!isFragmentValid(F)) {
108     assert(I != Sec->end() && "Layout bookkeeping error");
109     const_cast<MCAsmLayout *>(this)->layoutFragment(&*I);
110     ++I;
111   }
112 }
113
114 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
115   ensureValid(F);
116   assert(F->Offset != ~UINT64_C(0) && "Address not set!");
117   return F->Offset;
118 }
119
120 // Simple getSymbolOffset helper for the non-varibale case.
121 static bool getLabelOffset(const MCAsmLayout &Layout, const MCSymbol &S,
122                            bool ReportError, uint64_t &Val) {
123   if (!S.getFragment()) {
124     if (ReportError)
125       report_fatal_error("unable to evaluate offset to undefined symbol '" +
126                          S.getName() + "'");
127     return false;
128   }
129   Val = Layout.getFragmentOffset(S.getFragment()) + S.getOffset();
130   return true;
131 }
132
133 static bool getSymbolOffsetImpl(const MCAsmLayout &Layout, const MCSymbol &S,
134                                 bool ReportError, uint64_t &Val) {
135   if (!S.isVariable())
136     return getLabelOffset(Layout, S, ReportError, Val);
137
138   // If SD is a variable, evaluate it.
139   MCValue Target;
140   if (!S.getVariableValue()->evaluateAsValue(Target, Layout))
141     report_fatal_error("unable to evaluate offset for variable '" +
142                        S.getName() + "'");
143
144   uint64_t Offset = Target.getConstant();
145
146   const MCSymbolRefExpr *A = Target.getSymA();
147   if (A) {
148     uint64_t ValA;
149     if (!getLabelOffset(Layout, A->getSymbol(), ReportError, ValA))
150       return false;
151     Offset += ValA;
152   }
153
154   const MCSymbolRefExpr *B = Target.getSymB();
155   if (B) {
156     uint64_t ValB;
157     if (!getLabelOffset(Layout, B->getSymbol(), ReportError, ValB))
158       return false;
159     Offset -= ValB;
160   }
161
162   Val = Offset;
163   return true;
164 }
165
166 bool MCAsmLayout::getSymbolOffset(const MCSymbol &S, uint64_t &Val) const {
167   return getSymbolOffsetImpl(*this, S, false, Val);
168 }
169
170 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbol &S) const {
171   uint64_t Val;
172   getSymbolOffsetImpl(*this, S, true, Val);
173   return Val;
174 }
175
176 const MCSymbol *MCAsmLayout::getBaseSymbol(const MCSymbol &Symbol) const {
177   if (!Symbol.isVariable())
178     return &Symbol;
179
180   const MCExpr *Expr = Symbol.getVariableValue();
181   MCValue Value;
182   if (!Expr->evaluateAsValue(Value, *this))
183     llvm_unreachable("Invalid Expression");
184
185   const MCSymbolRefExpr *RefB = Value.getSymB();
186   if (RefB)
187     Assembler.getContext().reportFatalError(
188         SMLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
189                      "' could not be evaluated in a subtraction expression");
190
191   const MCSymbolRefExpr *A = Value.getSymA();
192   if (!A)
193     return nullptr;
194
195   const MCSymbol &ASym = A->getSymbol();
196   const MCAssembler &Asm = getAssembler();
197   if (ASym.isCommon()) {
198     // FIXME: we should probably add a SMLoc to MCExpr.
199     Asm.getContext().reportFatalError(SMLoc(),
200                                 "Common symbol " + ASym.getName() +
201                                     " cannot be used in assignment expr");
202   }
203
204   return &ASym;
205 }
206
207 uint64_t MCAsmLayout::getSectionAddressSize(const MCSection *Sec) const {
208   // The size is the last fragment's end offset.
209   const MCFragment &F = Sec->getFragmentList().back();
210   return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
211 }
212
213 uint64_t MCAsmLayout::getSectionFileSize(const MCSection *Sec) const {
214   // Virtual sections have no file size.
215   if (Sec->isVirtualSection())
216     return 0;
217
218   // Otherwise, the file size is the same as the address space size.
219   return getSectionAddressSize(Sec);
220 }
221
222 uint64_t llvm::computeBundlePadding(const MCAssembler &Assembler,
223                                     const MCFragment *F,
224                                     uint64_t FOffset, uint64_t FSize) {
225   uint64_t BundleSize = Assembler.getBundleAlignSize();
226   assert(BundleSize > 0 &&
227          "computeBundlePadding should only be called if bundling is enabled");
228   uint64_t BundleMask = BundleSize - 1;
229   uint64_t OffsetInBundle = FOffset & BundleMask;
230   uint64_t EndOfFragment = OffsetInBundle + FSize;
231
232   // There are two kinds of bundling restrictions:
233   //
234   // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
235   //    *end* on a bundle boundary.
236   // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
237   //    would, add padding until the end of the bundle so that the fragment
238   //    will start in a new one.
239   if (F->alignToBundleEnd()) {
240     // Three possibilities here:
241     //
242     // A) The fragment just happens to end at a bundle boundary, so we're good.
243     // B) The fragment ends before the current bundle boundary: pad it just
244     //    enough to reach the boundary.
245     // C) The fragment ends after the current bundle boundary: pad it until it
246     //    reaches the end of the next bundle boundary.
247     //
248     // Note: this code could be made shorter with some modulo trickery, but it's
249     // intentionally kept in its more explicit form for simplicity.
250     if (EndOfFragment == BundleSize)
251       return 0;
252     else if (EndOfFragment < BundleSize)
253       return BundleSize - EndOfFragment;
254     else { // EndOfFragment > BundleSize
255       return 2 * BundleSize - EndOfFragment;
256     }
257   } else if (OffsetInBundle > 0 && EndOfFragment > BundleSize)
258     return BundleSize - OffsetInBundle;
259   else
260     return 0;
261 }
262
263 /* *** */
264
265 void ilist_node_traits<MCFragment>::deleteNode(MCFragment *V) {
266   V->destroy();
267 }
268
269 MCFragment::MCFragment() : Kind(FragmentType(~0)), HasInstructions(false),
270                            AlignToBundleEnd(false), BundlePadding(0) {
271 }
272
273 MCFragment::~MCFragment() { }
274
275 MCFragment::MCFragment(FragmentType Kind, bool HasInstructions,
276                        uint8_t BundlePadding, MCSection *Parent)
277     : Kind(Kind), HasInstructions(HasInstructions), AlignToBundleEnd(false),
278       BundlePadding(BundlePadding), Parent(Parent), Atom(nullptr),
279       Offset(~UINT64_C(0)) {
280   if (Parent && !isDummy())
281     Parent->getFragmentList().push_back(this);
282 }
283
284 void MCFragment::destroy() {
285   // First check if we are the sentinal.
286   if (Kind == FragmentType(~0)) {
287     delete this;
288     return;
289   }
290
291   switch (Kind) {
292     case FT_Align:
293       delete cast<MCAlignFragment>(this);
294       return;
295     case FT_Data:
296       delete cast<MCDataFragment>(this);
297       return;
298     case FT_CompactEncodedInst:
299       delete cast<MCCompactEncodedInstFragment>(this);
300       return;
301     case FT_Fill:
302       delete cast<MCFillFragment>(this);
303       return;
304     case FT_Relaxable:
305       delete cast<MCRelaxableFragment>(this);
306       return;
307     case FT_Org:
308       delete cast<MCOrgFragment>(this);
309       return;
310     case FT_Dwarf:
311       delete cast<MCDwarfLineAddrFragment>(this);
312       return;
313     case FT_DwarfFrame:
314       delete cast<MCDwarfCallFrameFragment>(this);
315       return;
316     case FT_LEB:
317       delete cast<MCLEBFragment>(this);
318       return;
319     case FT_SafeSEH:
320       delete cast<MCSafeSEHFragment>(this);
321       return;
322     case FT_Dummy:
323       delete cast<MCDummyFragment>(this);
324       return;
325   }
326 }
327
328 /* *** */
329
330 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
331                          MCCodeEmitter &Emitter_, MCObjectWriter &Writer_)
332     : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
333       BundleAlignSize(0), RelaxAll(false), SubsectionsViaSymbols(false),
334       ELFHeaderEFlags(0) {
335   VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
336 }
337
338 MCAssembler::~MCAssembler() {
339 }
340
341 void MCAssembler::reset() {
342   Sections.clear();
343   Symbols.clear();
344   IndirectSymbols.clear();
345   DataRegions.clear();
346   LinkerOptions.clear();
347   FileNames.clear();
348   ThumbFuncs.clear();
349   BundleAlignSize = 0;
350   RelaxAll = false;
351   SubsectionsViaSymbols = false;
352   ELFHeaderEFlags = 0;
353   LOHContainer.reset();
354   VersionMinInfo.Major = 0;
355
356   // reset objects owned by us
357   getBackend().reset();
358   getEmitter().reset();
359   getWriter().reset();
360   getLOHContainer().reset();
361 }
362
363 bool MCAssembler::registerSection(MCSection &Section) {
364   if (Section.isRegistered())
365     return false;
366   Sections.push_back(&Section);
367   Section.setIsRegistered(true);
368   return true;
369 }
370
371 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
372   if (ThumbFuncs.count(Symbol))
373     return true;
374
375   if (!Symbol->isVariable())
376     return false;
377
378   // FIXME: It looks like gas supports some cases of the form "foo + 2". It
379   // is not clear if that is a bug or a feature.
380   const MCExpr *Expr = Symbol->getVariableValue();
381   const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
382   if (!Ref)
383     return false;
384
385   if (Ref->getKind() != MCSymbolRefExpr::VK_None)
386     return false;
387
388   const MCSymbol &Sym = Ref->getSymbol();
389   if (!isThumbFunc(&Sym))
390     return false;
391
392   ThumbFuncs.insert(Symbol); // Cache it.
393   return true;
394 }
395
396 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
397   // Non-temporary labels should always be visible to the linker.
398   if (!Symbol.isTemporary())
399     return true;
400
401   // Absolute temporary labels are never visible.
402   if (!Symbol.isInSection())
403     return false;
404
405   if (Symbol.isUsedInReloc())
406     return true;
407
408   return false;
409 }
410
411 const MCSymbol *MCAssembler::getAtom(const MCSymbol &S) const {
412   // Linker visible symbols define atoms.
413   if (isSymbolLinkerVisible(S))
414     return &S;
415
416   // Absolute and undefined symbols have no defining atom.
417   if (!S.isInSection())
418     return nullptr;
419
420   // Non-linker visible symbols in sections which can't be atomized have no
421   // defining atom.
422   if (!getContext().getAsmInfo()->isSectionAtomizableBySymbols(
423           *S.getFragment()->getParent()))
424     return nullptr;
425
426   // Otherwise, return the atom for the containing fragment.
427   return S.getFragment()->getAtom();
428 }
429
430 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
431                                 const MCFixup &Fixup, const MCFragment *DF,
432                                 MCValue &Target, uint64_t &Value) const {
433   ++stats::evaluateFixup;
434
435   // FIXME: This code has some duplication with recordRelocation. We should
436   // probably merge the two into a single callback that tries to evaluate a
437   // fixup and records a relocation if one is needed.
438   const MCExpr *Expr = Fixup.getValue();
439   if (!Expr->evaluateAsRelocatable(Target, &Layout, &Fixup))
440     getContext().reportFatalError(Fixup.getLoc(), "expected relocatable expression");
441
442   bool IsPCRel = Backend.getFixupKindInfo(
443     Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
444
445   bool IsResolved;
446   if (IsPCRel) {
447     if (Target.getSymB()) {
448       IsResolved = false;
449     } else if (!Target.getSymA()) {
450       IsResolved = false;
451     } else {
452       const MCSymbolRefExpr *A = Target.getSymA();
453       const MCSymbol &SA = A->getSymbol();
454       if (A->getKind() != MCSymbolRefExpr::VK_None || SA.isUndefined()) {
455         IsResolved = false;
456       } else {
457         IsResolved = getWriter().isSymbolRefDifferenceFullyResolvedImpl(
458             *this, SA, *DF, false, true);
459       }
460     }
461   } else {
462     IsResolved = Target.isAbsolute();
463   }
464
465   Value = Target.getConstant();
466
467   if (const MCSymbolRefExpr *A = Target.getSymA()) {
468     const MCSymbol &Sym = A->getSymbol();
469     if (Sym.isDefined())
470       Value += Layout.getSymbolOffset(Sym);
471   }
472   if (const MCSymbolRefExpr *B = Target.getSymB()) {
473     const MCSymbol &Sym = B->getSymbol();
474     if (Sym.isDefined())
475       Value -= Layout.getSymbolOffset(Sym);
476   }
477
478
479   bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
480                          MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
481   assert((ShouldAlignPC ? IsPCRel : true) &&
482     "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
483
484   if (IsPCRel) {
485     uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
486
487     // A number of ARM fixups in Thumb mode require that the effective PC
488     // address be determined as the 32-bit aligned version of the actual offset.
489     if (ShouldAlignPC) Offset &= ~0x3;
490     Value -= Offset;
491   }
492
493   // Let the backend adjust the fixup value if necessary, including whether
494   // we need a relocation.
495   Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
496                             IsResolved);
497
498   return IsResolved;
499 }
500
501 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
502                                           const MCFragment &F) const {
503   switch (F.getKind()) {
504   case MCFragment::FT_Data:
505     return cast<MCDataFragment>(F).getContents().size();
506   case MCFragment::FT_Relaxable:
507     return cast<MCRelaxableFragment>(F).getContents().size();
508   case MCFragment::FT_CompactEncodedInst:
509     return cast<MCCompactEncodedInstFragment>(F).getContents().size();
510   case MCFragment::FT_Fill:
511     return cast<MCFillFragment>(F).getSize();
512
513   case MCFragment::FT_LEB:
514     return cast<MCLEBFragment>(F).getContents().size();
515
516   case MCFragment::FT_SafeSEH:
517     return 4;
518
519   case MCFragment::FT_Align: {
520     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
521     unsigned Offset = Layout.getFragmentOffset(&AF);
522     unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
523     // If we are padding with nops, force the padding to be larger than the
524     // minimum nop size.
525     if (Size > 0 && AF.hasEmitNops()) {
526       while (Size % getBackend().getMinimumNopSize())
527         Size += AF.getAlignment();
528     }
529     if (Size > AF.getMaxBytesToEmit())
530       return 0;
531     return Size;
532   }
533
534   case MCFragment::FT_Org: {
535     const MCOrgFragment &OF = cast<MCOrgFragment>(F);
536     int64_t TargetLocation;
537     if (!OF.getOffset().evaluateAsAbsolute(TargetLocation, Layout))
538       report_fatal_error("expected assembly-time absolute expression");
539
540     // FIXME: We need a way to communicate this error.
541     uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
542     int64_t Size = TargetLocation - FragmentOffset;
543     if (Size < 0 || Size >= 0x40000000)
544       report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
545                          "' (at offset '" + Twine(FragmentOffset) + "')");
546     return Size;
547   }
548
549   case MCFragment::FT_Dwarf:
550     return cast<MCDwarfLineAddrFragment>(F).getContents().size();
551   case MCFragment::FT_DwarfFrame:
552     return cast<MCDwarfCallFrameFragment>(F).getContents().size();
553   case MCFragment::FT_Dummy:
554     llvm_unreachable("Should not have been added");
555   }
556
557   llvm_unreachable("invalid fragment kind");
558 }
559
560 void MCAsmLayout::layoutFragment(MCFragment *F) {
561   MCFragment *Prev = F->getPrevNode();
562
563   // We should never try to recompute something which is valid.
564   assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
565   // We should never try to compute the fragment layout if its predecessor
566   // isn't valid.
567   assert((!Prev || isFragmentValid(Prev)) &&
568          "Attempt to compute fragment before its predecessor!");
569
570   ++stats::FragmentLayouts;
571
572   // Compute fragment offset and size.
573   if (Prev)
574     F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
575   else
576     F->Offset = 0;
577   LastValidFragment[F->getParent()] = F;
578
579   // If bundling is enabled and this fragment has instructions in it, it has to
580   // obey the bundling restrictions. With padding, we'll have:
581   //
582   //
583   //        BundlePadding
584   //             |||
585   // -------------------------------------
586   //   Prev  |##########|       F        |
587   // -------------------------------------
588   //                    ^
589   //                    |
590   //                    F->Offset
591   //
592   // The fragment's offset will point to after the padding, and its computed
593   // size won't include the padding.
594   //
595   // When the -mc-relax-all flag is used, we optimize bundling by writting the
596   // padding directly into fragments when the instructions are emitted inside
597   // the streamer. When the fragment is larger than the bundle size, we need to
598   // ensure that it's bundle aligned. This means that if we end up with
599   // multiple fragments, we must emit bundle padding between fragments.
600   //
601   // ".align N" is an example of a directive that introduces multiple
602   // fragments. We could add a special case to handle ".align N" by emitting
603   // within-fragment padding (which would produce less padding when N is less
604   // than the bundle size), but for now we don't.
605   //
606   if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
607     assert(isa<MCEncodedFragment>(F) &&
608            "Only MCEncodedFragment implementations have instructions");
609     uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
610
611     if (!Assembler.getRelaxAll() && FSize > Assembler.getBundleAlignSize())
612       report_fatal_error("Fragment can't be larger than a bundle size");
613
614     uint64_t RequiredBundlePadding = computeBundlePadding(Assembler, F,
615                                                           F->Offset, FSize);
616     if (RequiredBundlePadding > UINT8_MAX)
617       report_fatal_error("Padding cannot exceed 255 bytes");
618     F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
619     F->Offset += RequiredBundlePadding;
620   }
621 }
622
623 void MCAssembler::registerSymbol(const MCSymbol &Symbol, bool *Created) {
624   bool New = !Symbol.isRegistered();
625   if (Created)
626     *Created = New;
627   if (New) {
628     Symbol.setIsRegistered(true);
629     Symbols.push_back(&Symbol);
630   }
631 }
632
633 void MCAssembler::writeFragmentPadding(const MCFragment &F, uint64_t FSize,
634                                        MCObjectWriter *OW) const {
635   // Should NOP padding be written out before this fragment?
636   unsigned BundlePadding = F.getBundlePadding();
637   if (BundlePadding > 0) {
638     assert(isBundlingEnabled() &&
639            "Writing bundle padding with disabled bundling");
640     assert(F.hasInstructions() &&
641            "Writing bundle padding for a fragment without instructions");
642
643     unsigned TotalLength = BundlePadding + static_cast<unsigned>(FSize);
644     if (F.alignToBundleEnd() && TotalLength > getBundleAlignSize()) {
645       // If the padding itself crosses a bundle boundary, it must be emitted
646       // in 2 pieces, since even nop instructions must not cross boundaries.
647       //             v--------------v   <- BundleAlignSize
648       //        v---------v             <- BundlePadding
649       // ----------------------------
650       // | Prev |####|####|    F    |
651       // ----------------------------
652       //        ^-------------------^   <- TotalLength
653       unsigned DistanceToBoundary = TotalLength - getBundleAlignSize();
654       if (!getBackend().writeNopData(DistanceToBoundary, OW))
655           report_fatal_error("unable to write NOP sequence of " +
656                              Twine(DistanceToBoundary) + " bytes");
657       BundlePadding -= DistanceToBoundary;
658     }
659     if (!getBackend().writeNopData(BundlePadding, OW))
660       report_fatal_error("unable to write NOP sequence of " +
661                          Twine(BundlePadding) + " bytes");
662   }
663 }
664
665 /// \brief Write the fragment \p F to the output file.
666 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
667                           const MCFragment &F) {
668   MCObjectWriter *OW = &Asm.getWriter();
669
670   // FIXME: Embed in fragments instead?
671   uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
672
673   Asm.writeFragmentPadding(F, FragmentSize, OW);
674
675   // This variable (and its dummy usage) is to participate in the assert at
676   // the end of the function.
677   uint64_t Start = OW->getStream().tell();
678   (void) Start;
679
680   ++stats::EmittedFragments;
681
682   switch (F.getKind()) {
683   case MCFragment::FT_Align: {
684     ++stats::EmittedAlignFragments;
685     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
686     assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
687
688     uint64_t Count = FragmentSize / AF.getValueSize();
689
690     // FIXME: This error shouldn't actually occur (the front end should emit
691     // multiple .align directives to enforce the semantics it wants), but is
692     // severe enough that we want to report it. How to handle this?
693     if (Count * AF.getValueSize() != FragmentSize)
694       report_fatal_error("undefined .align directive, value size '" +
695                         Twine(AF.getValueSize()) +
696                         "' is not a divisor of padding size '" +
697                         Twine(FragmentSize) + "'");
698
699     // See if we are aligning with nops, and if so do that first to try to fill
700     // the Count bytes.  Then if that did not fill any bytes or there are any
701     // bytes left to fill use the Value and ValueSize to fill the rest.
702     // If we are aligning with nops, ask that target to emit the right data.
703     if (AF.hasEmitNops()) {
704       if (!Asm.getBackend().writeNopData(Count, OW))
705         report_fatal_error("unable to write nop sequence of " +
706                           Twine(Count) + " bytes");
707       break;
708     }
709
710     // Otherwise, write out in multiples of the value size.
711     for (uint64_t i = 0; i != Count; ++i) {
712       switch (AF.getValueSize()) {
713       default: llvm_unreachable("Invalid size!");
714       case 1: OW->write8 (uint8_t (AF.getValue())); break;
715       case 2: OW->write16(uint16_t(AF.getValue())); break;
716       case 4: OW->write32(uint32_t(AF.getValue())); break;
717       case 8: OW->write64(uint64_t(AF.getValue())); break;
718       }
719     }
720     break;
721   }
722
723   case MCFragment::FT_Data: 
724     ++stats::EmittedDataFragments;
725     OW->writeBytes(cast<MCDataFragment>(F).getContents());
726     break;
727
728   case MCFragment::FT_Relaxable:
729     ++stats::EmittedRelaxableFragments;
730     OW->writeBytes(cast<MCRelaxableFragment>(F).getContents());
731     break;
732
733   case MCFragment::FT_CompactEncodedInst:
734     ++stats::EmittedCompactEncodedInstFragments;
735     OW->writeBytes(cast<MCCompactEncodedInstFragment>(F).getContents());
736     break;
737
738   case MCFragment::FT_Fill: {
739     ++stats::EmittedFillFragments;
740     const MCFillFragment &FF = cast<MCFillFragment>(F);
741
742     assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
743
744     for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
745       switch (FF.getValueSize()) {
746       default: llvm_unreachable("Invalid size!");
747       case 1: OW->write8 (uint8_t (FF.getValue())); break;
748       case 2: OW->write16(uint16_t(FF.getValue())); break;
749       case 4: OW->write32(uint32_t(FF.getValue())); break;
750       case 8: OW->write64(uint64_t(FF.getValue())); break;
751       }
752     }
753     break;
754   }
755
756   case MCFragment::FT_LEB: {
757     const MCLEBFragment &LF = cast<MCLEBFragment>(F);
758     OW->writeBytes(LF.getContents());
759     break;
760   }
761
762   case MCFragment::FT_SafeSEH: {
763     const MCSafeSEHFragment &SF = cast<MCSafeSEHFragment>(F);
764     OW->write32(SF.getSymbol()->getIndex());
765     break;
766   }
767
768   case MCFragment::FT_Org: {
769     ++stats::EmittedOrgFragments;
770     const MCOrgFragment &OF = cast<MCOrgFragment>(F);
771
772     for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
773       OW->write8(uint8_t(OF.getValue()));
774
775     break;
776   }
777
778   case MCFragment::FT_Dwarf: {
779     const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
780     OW->writeBytes(OF.getContents());
781     break;
782   }
783   case MCFragment::FT_DwarfFrame: {
784     const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
785     OW->writeBytes(CF.getContents());
786     break;
787   }
788   case MCFragment::FT_Dummy:
789     llvm_unreachable("Should not have been added");
790   }
791
792   assert(OW->getStream().tell() - Start == FragmentSize &&
793          "The stream should advance by fragment size");
794 }
795
796 void MCAssembler::writeSectionData(const MCSection *Sec,
797                                    const MCAsmLayout &Layout) const {
798   // Ignore virtual sections.
799   if (Sec->isVirtualSection()) {
800     assert(Layout.getSectionFileSize(Sec) == 0 && "Invalid size for section!");
801
802     // Check that contents are only things legal inside a virtual section.
803     for (const MCFragment &F : *Sec) {
804       switch (F.getKind()) {
805       default: llvm_unreachable("Invalid fragment in virtual section!");
806       case MCFragment::FT_Data: {
807         // Check that we aren't trying to write a non-zero contents (or fixups)
808         // into a virtual section. This is to support clients which use standard
809         // directives to fill the contents of virtual sections.
810         const MCDataFragment &DF = cast<MCDataFragment>(F);
811         assert(DF.fixup_begin() == DF.fixup_end() &&
812                "Cannot have fixups in virtual section!");
813         for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
814           if (DF.getContents()[i]) {
815             if (auto *ELFSec = dyn_cast<const MCSectionELF>(Sec))
816               report_fatal_error("non-zero initializer found in section '" +
817                   ELFSec->getSectionName() + "'");
818             else
819               report_fatal_error("non-zero initializer found in virtual section");
820           }
821         break;
822       }
823       case MCFragment::FT_Align:
824         // Check that we aren't trying to write a non-zero value into a virtual
825         // section.
826         assert((cast<MCAlignFragment>(F).getValueSize() == 0 ||
827                 cast<MCAlignFragment>(F).getValue() == 0) &&
828                "Invalid align in virtual section!");
829         break;
830       case MCFragment::FT_Fill:
831         assert((cast<MCFillFragment>(F).getValueSize() == 0 ||
832                 cast<MCFillFragment>(F).getValue() == 0) &&
833                "Invalid fill in virtual section!");
834         break;
835       }
836     }
837
838     return;
839   }
840
841   uint64_t Start = getWriter().getStream().tell();
842   (void)Start;
843
844   for (const MCFragment &F : *Sec)
845     writeFragment(*this, Layout, F);
846
847   assert(getWriter().getStream().tell() - Start ==
848          Layout.getSectionAddressSize(Sec));
849 }
850
851 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
852                                                    MCFragment &F,
853                                                    const MCFixup &Fixup) {
854   // Evaluate the fixup.
855   MCValue Target;
856   uint64_t FixedValue;
857   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
858                  MCFixupKindInfo::FKF_IsPCRel;
859   if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
860     // The fixup was unresolved, we need a relocation. Inform the object
861     // writer of the relocation, and give it an opportunity to adjust the
862     // fixup value if need be.
863     getWriter().recordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
864                                  FixedValue);
865   }
866   return std::make_pair(FixedValue, IsPCRel);
867 }
868
869 void MCAssembler::layout(MCAsmLayout &Layout) {
870   DEBUG_WITH_TYPE("mc-dump", {
871       llvm::errs() << "assembler backend - pre-layout\n--\n";
872       dump(); });
873
874   // Create dummy fragments and assign section ordinals.
875   unsigned SectionIndex = 0;
876   for (MCSection &Sec : *this) {
877     // Create dummy fragments to eliminate any empty sections, this simplifies
878     // layout.
879     if (Sec.getFragmentList().empty())
880       new MCDataFragment(&Sec);
881
882     Sec.setOrdinal(SectionIndex++);
883   }
884
885   // Assign layout order indices to sections and fragments.
886   for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
887     MCSection *Sec = Layout.getSectionOrder()[i];
888     Sec->setLayoutOrder(i);
889
890     unsigned FragmentIndex = 0;
891     for (MCFragment &Frag : *Sec)
892       Frag.setLayoutOrder(FragmentIndex++);
893   }
894
895   // Layout until everything fits.
896   while (layoutOnce(Layout))
897     continue;
898
899   DEBUG_WITH_TYPE("mc-dump", {
900       llvm::errs() << "assembler backend - post-relaxation\n--\n";
901       dump(); });
902
903   // Finalize the layout, including fragment lowering.
904   finishLayout(Layout);
905
906   DEBUG_WITH_TYPE("mc-dump", {
907       llvm::errs() << "assembler backend - final-layout\n--\n";
908       dump(); });
909
910   // Allow the object writer a chance to perform post-layout binding (for
911   // example, to set the index fields in the symbol data).
912   getWriter().executePostLayoutBinding(*this, Layout);
913
914   // Evaluate and apply the fixups, generating relocation entries as necessary.
915   for (MCSection &Sec : *this) {
916     for (MCFragment &Frag : Sec) {
917       MCEncodedFragment *F = dyn_cast<MCEncodedFragment>(&Frag);
918       // Data and relaxable fragments both have fixups.  So only process
919       // those here.
920       // FIXME: Is there a better way to do this?  MCEncodedFragmentWithFixups
921       // being templated makes this tricky.
922       if (!F || isa<MCCompactEncodedInstFragment>(F))
923         continue;
924       ArrayRef<MCFixup> Fixups;
925       MutableArrayRef<char> Contents;
926       if (auto *FragWithFixups = dyn_cast<MCDataFragment>(F)) {
927         Fixups = FragWithFixups->getFixups();
928         Contents = FragWithFixups->getContents();
929       } else if (auto *FragWithFixups = dyn_cast<MCRelaxableFragment>(F)) {
930         Fixups = FragWithFixups->getFixups();
931         Contents = FragWithFixups->getContents();
932       } else
933         llvm_unreachable("Unknown fragment with fixups!");
934       for (const MCFixup &Fixup : Fixups) {
935         uint64_t FixedValue;
936         bool IsPCRel;
937         std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
938         getBackend().applyFixup(Fixup, Contents.data(),
939                                 Contents.size(), FixedValue, IsPCRel);
940       }
941     }
942   }
943 }
944
945 void MCAssembler::Finish() {
946   // Create the layout object.
947   MCAsmLayout Layout(*this);
948   layout(Layout);
949
950   raw_ostream &OS = getWriter().getStream();
951   uint64_t StartOffset = OS.tell();
952
953   // Write the object file.
954   getWriter().writeObject(*this, Layout);
955
956   stats::ObjectBytes += OS.tell() - StartOffset;
957 }
958
959 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
960                                        const MCRelaxableFragment *DF,
961                                        const MCAsmLayout &Layout) const {
962   MCValue Target;
963   uint64_t Value;
964   bool Resolved = evaluateFixup(Layout, Fixup, DF, Target, Value);
965   return getBackend().fixupNeedsRelaxationAdvanced(Fixup, Resolved, Value, DF,
966                                                    Layout);
967 }
968
969 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
970                                           const MCAsmLayout &Layout) const {
971   // If this inst doesn't ever need relaxation, ignore it. This occurs when we
972   // are intentionally pushing out inst fragments, or because we relaxed a
973   // previous instruction to one that doesn't need relaxation.
974   if (!getBackend().mayNeedRelaxation(F->getInst()))
975     return false;
976
977   for (const MCFixup &Fixup : F->getFixups())
978     if (fixupNeedsRelaxation(Fixup, F, Layout))
979       return true;
980
981   return false;
982 }
983
984 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
985                                    MCRelaxableFragment &F) {
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;
997   getBackend().relaxInstruction(F.getInst(), Relaxed);
998
999   // Encode the new instruction.
1000   //
1001   // FIXME-PERF: If it matters, we could let the target do this. It can
1002   // probably do so more efficiently in many cases.
1003   SmallVector<MCFixup, 4> Fixups;
1004   SmallString<256> Code;
1005   raw_svector_ostream VecOS(Code);
1006   getEmitter().encodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
1007
1008   // Update the fragment.
1009   F.setInst(Relaxed);
1010   F.getContents() = Code;
1011   F.getFixups() = Fixups;
1012
1013   return true;
1014 }
1015
1016 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
1017   uint64_t OldSize = LF.getContents().size();
1018   int64_t Value;
1019   bool Abs = LF.getValue().evaluateKnownAbsolute(Value, Layout);
1020   if (!Abs)
1021     report_fatal_error("sleb128 and uleb128 expressions must be absolute");
1022   SmallString<8> &Data = LF.getContents();
1023   Data.clear();
1024   raw_svector_ostream OSE(Data);
1025   if (LF.isSigned())
1026     encodeSLEB128(Value, OSE);
1027   else
1028     encodeULEB128(Value, OSE);
1029   return OldSize != LF.getContents().size();
1030 }
1031
1032 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
1033                                      MCDwarfLineAddrFragment &DF) {
1034   MCContext &Context = Layout.getAssembler().getContext();
1035   uint64_t OldSize = DF.getContents().size();
1036   int64_t AddrDelta;
1037   bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1038   assert(Abs && "We created a line delta with an invalid expression");
1039   (void) Abs;
1040   int64_t LineDelta;
1041   LineDelta = DF.getLineDelta();
1042   SmallString<8> &Data = DF.getContents();
1043   Data.clear();
1044   raw_svector_ostream OSE(Data);
1045   MCDwarfLineAddr::Encode(Context, getDWARFLinetableParams(), LineDelta,
1046                           AddrDelta, OSE);
1047   return OldSize != Data.size();
1048 }
1049
1050 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
1051                                               MCDwarfCallFrameFragment &DF) {
1052   MCContext &Context = Layout.getAssembler().getContext();
1053   uint64_t OldSize = DF.getContents().size();
1054   int64_t AddrDelta;
1055   bool Abs = DF.getAddrDelta().evaluateKnownAbsolute(AddrDelta, Layout);
1056   assert(Abs && "We created call frame with an invalid expression");
1057   (void) Abs;
1058   SmallString<8> &Data = DF.getContents();
1059   Data.clear();
1060   raw_svector_ostream OSE(Data);
1061   MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
1062   return OldSize != Data.size();
1063 }
1064
1065 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec) {
1066   // Holds the first fragment which needed relaxing during this layout. It will
1067   // remain NULL if none were relaxed.
1068   // When a fragment is relaxed, all the fragments following it should get
1069   // invalidated because their offset is going to change.
1070   MCFragment *FirstRelaxedFragment = nullptr;
1071
1072   // Attempt to relax all the fragments in the section.
1073   for (MCSection::iterator I = Sec.begin(), IE = Sec.end(); I != IE; ++I) {
1074     // Check if this is a fragment that needs relaxation.
1075     bool RelaxedFrag = false;
1076     switch(I->getKind()) {
1077     default:
1078       break;
1079     case MCFragment::FT_Relaxable:
1080       assert(!getRelaxAll() &&
1081              "Did not expect a MCRelaxableFragment in RelaxAll mode");
1082       RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
1083       break;
1084     case MCFragment::FT_Dwarf:
1085       RelaxedFrag = relaxDwarfLineAddr(Layout,
1086                                        *cast<MCDwarfLineAddrFragment>(I));
1087       break;
1088     case MCFragment::FT_DwarfFrame:
1089       RelaxedFrag =
1090         relaxDwarfCallFrameFragment(Layout,
1091                                     *cast<MCDwarfCallFrameFragment>(I));
1092       break;
1093     case MCFragment::FT_LEB:
1094       RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
1095       break;
1096     }
1097     if (RelaxedFrag && !FirstRelaxedFragment)
1098       FirstRelaxedFragment = &*I;
1099   }
1100   if (FirstRelaxedFragment) {
1101     Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
1102     return true;
1103   }
1104   return false;
1105 }
1106
1107 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
1108   ++stats::RelaxationSteps;
1109
1110   bool WasRelaxed = false;
1111   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1112     MCSection &Sec = *it;
1113     while (layoutSectionOnce(Layout, Sec))
1114       WasRelaxed = true;
1115   }
1116
1117   return WasRelaxed;
1118 }
1119
1120 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
1121   // The layout is done. Mark every fragment as valid.
1122   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
1123     Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
1124   }
1125 }
1126
1127 // Debugging methods
1128
1129 namespace llvm {
1130
1131 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
1132   OS << "<MCFixup" << " Offset:" << AF.getOffset()
1133      << " Value:" << *AF.getValue()
1134      << " Kind:" << AF.getKind() << ">";
1135   return OS;
1136 }
1137
1138 }
1139
1140 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1141 void MCFragment::dump() {
1142   raw_ostream &OS = llvm::errs();
1143
1144   OS << "<";
1145   switch (getKind()) {
1146   case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
1147   case MCFragment::FT_Data:  OS << "MCDataFragment"; break;
1148   case MCFragment::FT_CompactEncodedInst:
1149     OS << "MCCompactEncodedInstFragment"; break;
1150   case MCFragment::FT_Fill:  OS << "MCFillFragment"; break;
1151   case MCFragment::FT_Relaxable:  OS << "MCRelaxableFragment"; break;
1152   case MCFragment::FT_Org:   OS << "MCOrgFragment"; break;
1153   case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
1154   case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
1155   case MCFragment::FT_LEB:   OS << "MCLEBFragment"; break;
1156   case MCFragment::FT_SafeSEH:    OS << "MCSafeSEHFragment"; break;
1157   case MCFragment::FT_Dummy:
1158     OS << "MCDummyFragment";
1159     break;
1160   }
1161
1162   OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
1163      << " Offset:" << Offset
1164      << " HasInstructions:" << hasInstructions() 
1165      << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
1166
1167   switch (getKind()) {
1168   case MCFragment::FT_Align: {
1169     const MCAlignFragment *AF = cast<MCAlignFragment>(this);
1170     if (AF->hasEmitNops())
1171       OS << " (emit nops)";
1172     OS << "\n       ";
1173     OS << " Alignment:" << AF->getAlignment()
1174        << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
1175        << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
1176     break;
1177   }
1178   case MCFragment::FT_Data:  {
1179     const MCDataFragment *DF = cast<MCDataFragment>(this);
1180     OS << "\n       ";
1181     OS << " Contents:[";
1182     const SmallVectorImpl<char> &Contents = DF->getContents();
1183     for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1184       if (i) OS << ",";
1185       OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1186     }
1187     OS << "] (" << Contents.size() << " bytes)";
1188
1189     if (DF->fixup_begin() != DF->fixup_end()) {
1190       OS << ",\n       ";
1191       OS << " Fixups:[";
1192       for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
1193              ie = DF->fixup_end(); it != ie; ++it) {
1194         if (it != DF->fixup_begin()) OS << ",\n                ";
1195         OS << *it;
1196       }
1197       OS << "]";
1198     }
1199     break;
1200   }
1201   case MCFragment::FT_CompactEncodedInst: {
1202     const MCCompactEncodedInstFragment *CEIF =
1203       cast<MCCompactEncodedInstFragment>(this);
1204     OS << "\n       ";
1205     OS << " Contents:[";
1206     const SmallVectorImpl<char> &Contents = CEIF->getContents();
1207     for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
1208       if (i) OS << ",";
1209       OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1210     }
1211     OS << "] (" << Contents.size() << " bytes)";
1212     break;
1213   }
1214   case MCFragment::FT_Fill:  {
1215     const MCFillFragment *FF = cast<MCFillFragment>(this);
1216     OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
1217        << " Size:" << FF->getSize();
1218     break;
1219   }
1220   case MCFragment::FT_Relaxable:  {
1221     const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
1222     OS << "\n       ";
1223     OS << " Inst:";
1224     F->getInst().dump_pretty(OS);
1225     break;
1226   }
1227   case MCFragment::FT_Org:  {
1228     const MCOrgFragment *OF = cast<MCOrgFragment>(this);
1229     OS << "\n       ";
1230     OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
1231     break;
1232   }
1233   case MCFragment::FT_Dwarf:  {
1234     const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
1235     OS << "\n       ";
1236     OS << " AddrDelta:" << OF->getAddrDelta()
1237        << " LineDelta:" << OF->getLineDelta();
1238     break;
1239   }
1240   case MCFragment::FT_DwarfFrame:  {
1241     const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
1242     OS << "\n       ";
1243     OS << " AddrDelta:" << CF->getAddrDelta();
1244     break;
1245   }
1246   case MCFragment::FT_LEB: {
1247     const MCLEBFragment *LF = cast<MCLEBFragment>(this);
1248     OS << "\n       ";
1249     OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
1250     break;
1251   }
1252   case MCFragment::FT_SafeSEH: {
1253     const MCSafeSEHFragment *F = cast<MCSafeSEHFragment>(this);
1254     OS << "\n       ";
1255     OS << " Sym:" << F->getSymbol();
1256     break;
1257   }
1258   case MCFragment::FT_Dummy:
1259     break;
1260   }
1261   OS << ">";
1262 }
1263
1264 void MCAssembler::dump() {
1265   raw_ostream &OS = llvm::errs();
1266
1267   OS << "<MCAssembler\n";
1268   OS << "  Sections:[\n    ";
1269   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1270     if (it != begin()) OS << ",\n    ";
1271     it->dump();
1272   }
1273   OS << "],\n";
1274   OS << "  Symbols:[";
1275
1276   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1277     if (it != symbol_begin()) OS << ",\n           ";
1278     OS << "(";
1279     it->dump();
1280     OS << ", Index:" << it->getIndex() << ", ";
1281     OS << ")";
1282   }
1283   OS << "]>\n";
1284 }
1285 #endif