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