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