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