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