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