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