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