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