LLVM API Documentation

MCAssembler.cpp
Go to the documentation of this file.
00001 //===- lib/MC/MCAssembler.cpp - Assembler Backend Implementation ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "llvm/MC/MCAssembler.h"
00011 #include "llvm/ADT/Statistic.h"
00012 #include "llvm/ADT/StringExtras.h"
00013 #include "llvm/ADT/Twine.h"
00014 #include "llvm/MC/MCAsmBackend.h"
00015 #include "llvm/MC/MCAsmLayout.h"
00016 #include "llvm/MC/MCCodeEmitter.h"
00017 #include "llvm/MC/MCContext.h"
00018 #include "llvm/MC/MCDwarf.h"
00019 #include "llvm/MC/MCExpr.h"
00020 #include "llvm/MC/MCFixupKindInfo.h"
00021 #include "llvm/MC/MCObjectWriter.h"
00022 #include "llvm/MC/MCSection.h"
00023 #include "llvm/MC/MCSymbol.h"
00024 #include "llvm/MC/MCValue.h"
00025 #include "llvm/Support/Debug.h"
00026 #include "llvm/Support/ErrorHandling.h"
00027 #include "llvm/Support/LEB128.h"
00028 #include "llvm/Support/TargetRegistry.h"
00029 #include "llvm/Support/raw_ostream.h"
00030 #include "llvm/MC/MCSectionELF.h"
00031 #include <tuple>
00032 using namespace llvm;
00033 
00034 #define DEBUG_TYPE "assembler"
00035 
00036 namespace {
00037 namespace stats {
00038 STATISTIC(EmittedFragments, "Number of emitted assembler fragments - total");
00039 STATISTIC(EmittedRelaxableFragments,
00040           "Number of emitted assembler fragments - relaxable");
00041 STATISTIC(EmittedDataFragments,
00042           "Number of emitted assembler fragments - data");
00043 STATISTIC(EmittedCompactEncodedInstFragments,
00044           "Number of emitted assembler fragments - compact encoded inst");
00045 STATISTIC(EmittedAlignFragments,
00046           "Number of emitted assembler fragments - align");
00047 STATISTIC(EmittedFillFragments,
00048           "Number of emitted assembler fragments - fill");
00049 STATISTIC(EmittedOrgFragments,
00050           "Number of emitted assembler fragments - org");
00051 STATISTIC(evaluateFixup, "Number of evaluated fixups");
00052 STATISTIC(FragmentLayouts, "Number of fragment layouts");
00053 STATISTIC(ObjectBytes, "Number of emitted object file bytes");
00054 STATISTIC(RelaxationSteps, "Number of assembler layout and relaxation steps");
00055 STATISTIC(RelaxedInstructions, "Number of relaxed instructions");
00056 }
00057 }
00058 
00059 // FIXME FIXME FIXME: There are number of places in this file where we convert
00060 // what is a 64-bit assembler value used for computation into a value in the
00061 // object file, which may truncate it. We should detect that truncation where
00062 // invalid and report errors back.
00063 
00064 /* *** */
00065 
00066 MCAsmLayout::MCAsmLayout(MCAssembler &Asm)
00067   : Assembler(Asm), LastValidFragment()
00068  {
00069   // Compute the section layout order. Virtual sections must go last.
00070   for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
00071     if (!it->getSection().isVirtualSection())
00072       SectionOrder.push_back(&*it);
00073   for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
00074     if (it->getSection().isVirtualSection())
00075       SectionOrder.push_back(&*it);
00076 }
00077 
00078 bool MCAsmLayout::isFragmentValid(const MCFragment *F) const {
00079   const MCSectionData &SD = *F->getParent();
00080   const MCFragment *LastValid = LastValidFragment.lookup(&SD);
00081   if (!LastValid)
00082     return false;
00083   assert(LastValid->getParent() == F->getParent());
00084   return F->getLayoutOrder() <= LastValid->getLayoutOrder();
00085 }
00086 
00087 void MCAsmLayout::invalidateFragmentsFrom(MCFragment *F) {
00088   // If this fragment wasn't already valid, we don't need to do anything.
00089   if (!isFragmentValid(F))
00090     return;
00091 
00092   // Otherwise, reset the last valid fragment to the previous fragment
00093   // (if this is the first fragment, it will be NULL).
00094   const MCSectionData &SD = *F->getParent();
00095   LastValidFragment[&SD] = F->getPrevNode();
00096 }
00097 
00098 void MCAsmLayout::ensureValid(const MCFragment *F) const {
00099   MCSectionData &SD = *F->getParent();
00100 
00101   MCFragment *Cur = LastValidFragment[&SD];
00102   if (!Cur)
00103     Cur = &*SD.begin();
00104   else
00105     Cur = Cur->getNextNode();
00106 
00107   // Advance the layout position until the fragment is valid.
00108   while (!isFragmentValid(F)) {
00109     assert(Cur && "Layout bookkeeping error");
00110     const_cast<MCAsmLayout*>(this)->layoutFragment(Cur);
00111     Cur = Cur->getNextNode();
00112   }
00113 }
00114 
00115 uint64_t MCAsmLayout::getFragmentOffset(const MCFragment *F) const {
00116   ensureValid(F);
00117   assert(F->Offset != ~UINT64_C(0) && "Address not set!");
00118   return F->Offset;
00119 }
00120 
00121 // Simple getSymbolOffset helper for the non-varibale case.
00122 static bool getLabelOffset(const MCAsmLayout &Layout, const MCSymbolData &SD,
00123                            bool ReportError, uint64_t &Val) {
00124   if (!SD.getFragment()) {
00125     if (ReportError)
00126       report_fatal_error("unable to evaluate offset to undefined symbol '" +
00127                          SD.getSymbol().getName() + "'");
00128     return false;
00129   }
00130   Val = Layout.getFragmentOffset(SD.getFragment()) + SD.getOffset();
00131   return true;
00132 }
00133 
00134 static bool getSymbolOffsetImpl(const MCAsmLayout &Layout,
00135                                 const MCSymbolData *SD, bool ReportError,
00136                                 uint64_t &Val) {
00137   const MCSymbol &S = SD->getSymbol();
00138 
00139   if (!S.isVariable())
00140     return getLabelOffset(Layout, *SD, ReportError, Val);
00141 
00142   // If SD is a variable, evaluate it.
00143   MCValue Target;
00144   if (!S.getVariableValue()->EvaluateAsValue(Target, &Layout, nullptr))
00145     report_fatal_error("unable to evaluate offset for variable '" +
00146                        S.getName() + "'");
00147 
00148   uint64_t Offset = Target.getConstant();
00149 
00150   const MCAssembler &Asm = Layout.getAssembler();
00151 
00152   const MCSymbolRefExpr *A = Target.getSymA();
00153   if (A) {
00154     uint64_t ValA;
00155     if (!getLabelOffset(Layout, Asm.getSymbolData(A->getSymbol()), ReportError,
00156                         ValA))
00157       return false;
00158     Offset += ValA;
00159   }
00160 
00161   const MCSymbolRefExpr *B = Target.getSymB();
00162   if (B) {
00163     uint64_t ValB;
00164     if (!getLabelOffset(Layout, Asm.getSymbolData(B->getSymbol()), ReportError,
00165                         ValB))
00166       return false;
00167     Offset -= ValB;
00168   }
00169 
00170   Val = Offset;
00171   return true;
00172 }
00173 
00174 bool MCAsmLayout::getSymbolOffset(const MCSymbolData *SD, uint64_t &Val) const {
00175   return getSymbolOffsetImpl(*this, SD, false, Val);
00176 }
00177 
00178 uint64_t MCAsmLayout::getSymbolOffset(const MCSymbolData *SD) const {
00179   uint64_t Val;
00180   getSymbolOffsetImpl(*this, SD, true, Val);
00181   return Val;
00182 }
00183 
00184 const MCSymbol *MCAsmLayout::getBaseSymbol(const MCSymbol &Symbol) const {
00185   if (!Symbol.isVariable())
00186     return &Symbol;
00187 
00188   const MCExpr *Expr = Symbol.getVariableValue();
00189   MCValue Value;
00190   if (!Expr->EvaluateAsValue(Value, this, nullptr))
00191     llvm_unreachable("Invalid Expression");
00192 
00193   const MCSymbolRefExpr *RefB = Value.getSymB();
00194   if (RefB)
00195     Assembler.getContext().FatalError(
00196         SMLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
00197                      "' could not be evaluated in a subtraction expression");
00198 
00199   const MCSymbolRefExpr *A = Value.getSymA();
00200   if (!A)
00201     return nullptr;
00202 
00203   return &A->getSymbol();
00204 }
00205 
00206 uint64_t MCAsmLayout::getSectionAddressSize(const MCSectionData *SD) const {
00207   // The size is the last fragment's end offset.
00208   const MCFragment &F = SD->getFragmentList().back();
00209   return getFragmentOffset(&F) + getAssembler().computeFragmentSize(*this, F);
00210 }
00211 
00212 uint64_t MCAsmLayout::getSectionFileSize(const MCSectionData *SD) const {
00213   // Virtual sections have no file size.
00214   if (SD->getSection().isVirtualSection())
00215     return 0;
00216 
00217   // Otherwise, the file size is the same as the address space size.
00218   return getSectionAddressSize(SD);
00219 }
00220 
00221 uint64_t MCAsmLayout::computeBundlePadding(const MCFragment *F,
00222                                            uint64_t FOffset, uint64_t FSize) {
00223   uint64_t BundleSize = Assembler.getBundleAlignSize();
00224   assert(BundleSize > 0 &&
00225          "computeBundlePadding should only be called if bundling is enabled");
00226   uint64_t BundleMask = BundleSize - 1;
00227   uint64_t OffsetInBundle = FOffset & BundleMask;
00228   uint64_t EndOfFragment = OffsetInBundle + FSize;
00229 
00230   // There are two kinds of bundling restrictions:
00231   //
00232   // 1) For alignToBundleEnd(), add padding to ensure that the fragment will
00233   //    *end* on a bundle boundary.
00234   // 2) Otherwise, check if the fragment would cross a bundle boundary. If it
00235   //    would, add padding until the end of the bundle so that the fragment
00236   //    will start in a new one.
00237   if (F->alignToBundleEnd()) {
00238     // Three possibilities here:
00239     //
00240     // A) The fragment just happens to end at a bundle boundary, so we're good.
00241     // B) The fragment ends before the current bundle boundary: pad it just
00242     //    enough to reach the boundary.
00243     // C) The fragment ends after the current bundle boundary: pad it until it
00244     //    reaches the end of the next bundle boundary.
00245     //
00246     // Note: this code could be made shorter with some modulo trickery, but it's
00247     // intentionally kept in its more explicit form for simplicity.
00248     if (EndOfFragment == BundleSize)
00249       return 0;
00250     else if (EndOfFragment < BundleSize)
00251       return BundleSize - EndOfFragment;
00252     else { // EndOfFragment > BundleSize
00253       return 2 * BundleSize - EndOfFragment;
00254     }
00255   } else if (EndOfFragment > BundleSize)
00256     return BundleSize - OffsetInBundle;
00257   else
00258     return 0;
00259 }
00260 
00261 /* *** */
00262 
00263 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
00264 }
00265 
00266 MCFragment::~MCFragment() {
00267 }
00268 
00269 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
00270   : Kind(_Kind), Parent(_Parent), Atom(nullptr), Offset(~UINT64_C(0))
00271 {
00272   if (Parent)
00273     Parent->getFragmentList().push_back(this);
00274 }
00275 
00276 /* *** */
00277 
00278 MCEncodedFragment::~MCEncodedFragment() {
00279 }
00280 
00281 /* *** */
00282 
00283 MCEncodedFragmentWithFixups::~MCEncodedFragmentWithFixups() {
00284 }
00285 
00286 /* *** */
00287 
00288 MCSectionData::MCSectionData() : Section(nullptr) {}
00289 
00290 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
00291   : Section(&_Section),
00292     Ordinal(~UINT32_C(0)),
00293     Alignment(1),
00294     BundleLockState(NotBundleLocked), BundleGroupBeforeFirstInst(false),
00295     HasInstructions(false)
00296 {
00297   if (A)
00298     A->getSectionList().push_back(this);
00299 }
00300 
00301 MCSectionData::iterator
00302 MCSectionData::getSubsectionInsertionPoint(unsigned Subsection) {
00303   if (Subsection == 0 && SubsectionFragmentMap.empty())
00304     return end();
00305 
00306   SmallVectorImpl<std::pair<unsigned, MCFragment *> >::iterator MI =
00307     std::lower_bound(SubsectionFragmentMap.begin(), SubsectionFragmentMap.end(),
00308                      std::make_pair(Subsection, (MCFragment *)nullptr));
00309   bool ExactMatch = false;
00310   if (MI != SubsectionFragmentMap.end()) {
00311     ExactMatch = MI->first == Subsection;
00312     if (ExactMatch)
00313       ++MI;
00314   }
00315   iterator IP;
00316   if (MI == SubsectionFragmentMap.end())
00317     IP = end();
00318   else
00319     IP = MI->second;
00320   if (!ExactMatch && Subsection != 0) {
00321     // The GNU as documentation claims that subsections have an alignment of 4,
00322     // although this appears not to be the case.
00323     MCFragment *F = new MCDataFragment();
00324     SubsectionFragmentMap.insert(MI, std::make_pair(Subsection, F));
00325     getFragmentList().insert(IP, F);
00326     F->setParent(this);
00327   }
00328   return IP;
00329 }
00330 
00331 /* *** */
00332 
00333 MCSymbolData::MCSymbolData() : Symbol(nullptr) {}
00334 
00335 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
00336                            uint64_t _Offset, MCAssembler *A)
00337   : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
00338     IsExternal(false), IsPrivateExtern(false),
00339     CommonSize(0), SymbolSize(nullptr), CommonAlign(0),
00340     Flags(0), Index(0)
00341 {
00342   if (A)
00343     A->getSymbolList().push_back(this);
00344 }
00345 
00346 /* *** */
00347 
00348 MCAssembler::MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
00349                          MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
00350                          raw_ostream &OS_)
00351   : Context(Context_), Backend(Backend_), Emitter(Emitter_), Writer(Writer_),
00352     OS(OS_), BundleAlignSize(0), RelaxAll(false), NoExecStack(false),
00353     SubsectionsViaSymbols(false), ELFHeaderEFlags(0) {
00354   VersionMinInfo.Major = 0; // Major version == 0 for "none specified"
00355 }
00356 
00357 MCAssembler::~MCAssembler() {
00358 }
00359 
00360 void MCAssembler::reset() {
00361   Sections.clear();
00362   Symbols.clear();
00363   SectionMap.clear();
00364   SymbolMap.clear();
00365   IndirectSymbols.clear();
00366   DataRegions.clear();
00367   LinkerOptions.clear();
00368   FileNames.clear();
00369   ThumbFuncs.clear();
00370   BundleAlignSize = 0;
00371   RelaxAll = false;
00372   NoExecStack = false;
00373   SubsectionsViaSymbols = false;
00374   ELFHeaderEFlags = 0;
00375   LOHContainer.reset();
00376   VersionMinInfo.Major = 0;
00377 
00378   // reset objects owned by us
00379   getBackend().reset();
00380   getEmitter().reset();
00381   getWriter().reset();
00382   getLOHContainer().reset();
00383 }
00384 
00385 bool MCAssembler::isThumbFunc(const MCSymbol *Symbol) const {
00386   if (ThumbFuncs.count(Symbol))
00387     return true;
00388 
00389   if (!Symbol->isVariable())
00390     return false;
00391 
00392   // FIXME: It looks like gas supports some cases of the form "foo + 2". It
00393   // is not clear if that is a bug or a feature.
00394   const MCExpr *Expr = Symbol->getVariableValue();
00395   const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr);
00396   if (!Ref)
00397     return false;
00398 
00399   if (Ref->getKind() != MCSymbolRefExpr::VK_None)
00400     return false;
00401 
00402   const MCSymbol &Sym = Ref->getSymbol();
00403   if (!isThumbFunc(&Sym))
00404     return false;
00405 
00406   ThumbFuncs.insert(Symbol); // Cache it.
00407   return true;
00408 }
00409 
00410 bool MCAssembler::isSymbolLinkerVisible(const MCSymbol &Symbol) const {
00411   // Non-temporary labels should always be visible to the linker.
00412   if (!Symbol.isTemporary())
00413     return true;
00414 
00415   // Absolute temporary labels are never visible.
00416   if (!Symbol.isInSection())
00417     return false;
00418 
00419   // Otherwise, check if the section requires symbols even for temporary labels.
00420   return getBackend().doesSectionRequireSymbols(Symbol.getSection());
00421 }
00422 
00423 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
00424   // Linker visible symbols define atoms.
00425   if (isSymbolLinkerVisible(SD->getSymbol()))
00426     return SD;
00427 
00428   // Absolute and undefined symbols have no defining atom.
00429   if (!SD->getFragment())
00430     return nullptr;
00431 
00432   // Non-linker visible symbols in sections which can't be atomized have no
00433   // defining atom.
00434   if (!getBackend().isSectionAtomizable(
00435         SD->getFragment()->getParent()->getSection()))
00436     return nullptr;
00437 
00438   // Otherwise, return the atom for the containing fragment.
00439   return SD->getFragment()->getAtom();
00440 }
00441 
00442 // Try to fully compute Expr to an absolute value and if that fails produce
00443 // a relocatable expr.
00444 // FIXME: Should this be the behavior of EvaluateAsRelocatable itself?
00445 static bool evaluate(const MCExpr &Expr, const MCAsmLayout &Layout,
00446                      const MCFixup &Fixup, MCValue &Target) {
00447   if (Expr.EvaluateAsValue(Target, &Layout, &Fixup)) {
00448     if (Target.isAbsolute())
00449       return true;
00450   }
00451   return Expr.EvaluateAsRelocatable(Target, &Layout, &Fixup);
00452 }
00453 
00454 bool MCAssembler::evaluateFixup(const MCAsmLayout &Layout,
00455                                 const MCFixup &Fixup, const MCFragment *DF,
00456                                 MCValue &Target, uint64_t &Value) const {
00457   ++stats::evaluateFixup;
00458 
00459   // FIXME: This code has some duplication with RecordRelocation. We should
00460   // probably merge the two into a single callback that tries to evaluate a
00461   // fixup and records a relocation if one is needed.
00462   const MCExpr *Expr = Fixup.getValue();
00463   if (!evaluate(*Expr, Layout, Fixup, Target))
00464     getContext().FatalError(Fixup.getLoc(), "expected relocatable expression");
00465 
00466   bool IsPCRel = Backend.getFixupKindInfo(
00467     Fixup.getKind()).Flags & MCFixupKindInfo::FKF_IsPCRel;
00468 
00469   bool IsResolved;
00470   if (IsPCRel) {
00471     if (Target.getSymB()) {
00472       IsResolved = false;
00473     } else if (!Target.getSymA()) {
00474       IsResolved = false;
00475     } else {
00476       const MCSymbolRefExpr *A = Target.getSymA();
00477       const MCSymbol &SA = A->getSymbol();
00478       if (A->getKind() != MCSymbolRefExpr::VK_None ||
00479           SA.AliasedSymbol().isUndefined()) {
00480         IsResolved = false;
00481       } else {
00482         const MCSymbolData &DataA = getSymbolData(SA);
00483         IsResolved =
00484           getWriter().IsSymbolRefDifferenceFullyResolvedImpl(*this, DataA,
00485                                                              *DF, false, true);
00486       }
00487     }
00488   } else {
00489     IsResolved = Target.isAbsolute();
00490   }
00491 
00492   Value = Target.getConstant();
00493 
00494   if (const MCSymbolRefExpr *A = Target.getSymA()) {
00495     const MCSymbol &Sym = A->getSymbol().AliasedSymbol();
00496     if (Sym.isDefined())
00497       Value += Layout.getSymbolOffset(&getSymbolData(Sym));
00498   }
00499   if (const MCSymbolRefExpr *B = Target.getSymB()) {
00500     const MCSymbol &Sym = B->getSymbol().AliasedSymbol();
00501     if (Sym.isDefined())
00502       Value -= Layout.getSymbolOffset(&getSymbolData(Sym));
00503   }
00504 
00505 
00506   bool ShouldAlignPC = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
00507                          MCFixupKindInfo::FKF_IsAlignedDownTo32Bits;
00508   assert((ShouldAlignPC ? IsPCRel : true) &&
00509     "FKF_IsAlignedDownTo32Bits is only allowed on PC-relative fixups!");
00510 
00511   if (IsPCRel) {
00512     uint32_t Offset = Layout.getFragmentOffset(DF) + Fixup.getOffset();
00513 
00514     // A number of ARM fixups in Thumb mode require that the effective PC
00515     // address be determined as the 32-bit aligned version of the actual offset.
00516     if (ShouldAlignPC) Offset &= ~0x3;
00517     Value -= Offset;
00518   }
00519 
00520   // Let the backend adjust the fixup value if necessary, including whether
00521   // we need a relocation.
00522   Backend.processFixupValue(*this, Layout, Fixup, DF, Target, Value,
00523                             IsResolved);
00524 
00525   return IsResolved;
00526 }
00527 
00528 uint64_t MCAssembler::computeFragmentSize(const MCAsmLayout &Layout,
00529                                           const MCFragment &F) const {
00530   switch (F.getKind()) {
00531   case MCFragment::FT_Data:
00532   case MCFragment::FT_Relaxable:
00533   case MCFragment::FT_CompactEncodedInst:
00534     return cast<MCEncodedFragment>(F).getContents().size();
00535   case MCFragment::FT_Fill:
00536     return cast<MCFillFragment>(F).getSize();
00537 
00538   case MCFragment::FT_LEB:
00539     return cast<MCLEBFragment>(F).getContents().size();
00540 
00541   case MCFragment::FT_Align: {
00542     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
00543     unsigned Offset = Layout.getFragmentOffset(&AF);
00544     unsigned Size = OffsetToAlignment(Offset, AF.getAlignment());
00545     // If we are padding with nops, force the padding to be larger than the
00546     // minimum nop size.
00547     if (Size > 0 && AF.hasEmitNops()) {
00548       while (Size % getBackend().getMinimumNopSize())
00549         Size += AF.getAlignment();
00550     }
00551     if (Size > AF.getMaxBytesToEmit())
00552       return 0;
00553     return Size;
00554   }
00555 
00556   case MCFragment::FT_Org: {
00557     const MCOrgFragment &OF = cast<MCOrgFragment>(F);
00558     int64_t TargetLocation;
00559     if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, Layout))
00560       report_fatal_error("expected assembly-time absolute expression");
00561 
00562     // FIXME: We need a way to communicate this error.
00563     uint64_t FragmentOffset = Layout.getFragmentOffset(&OF);
00564     int64_t Size = TargetLocation - FragmentOffset;
00565     if (Size < 0 || Size >= 0x40000000)
00566       report_fatal_error("invalid .org offset '" + Twine(TargetLocation) +
00567                          "' (at offset '" + Twine(FragmentOffset) + "')");
00568     return Size;
00569   }
00570 
00571   case MCFragment::FT_Dwarf:
00572     return cast<MCDwarfLineAddrFragment>(F).getContents().size();
00573   case MCFragment::FT_DwarfFrame:
00574     return cast<MCDwarfCallFrameFragment>(F).getContents().size();
00575   }
00576 
00577   llvm_unreachable("invalid fragment kind");
00578 }
00579 
00580 void MCAsmLayout::layoutFragment(MCFragment *F) {
00581   MCFragment *Prev = F->getPrevNode();
00582 
00583   // We should never try to recompute something which is valid.
00584   assert(!isFragmentValid(F) && "Attempt to recompute a valid fragment!");
00585   // We should never try to compute the fragment layout if its predecessor
00586   // isn't valid.
00587   assert((!Prev || isFragmentValid(Prev)) &&
00588          "Attempt to compute fragment before its predecessor!");
00589 
00590   ++stats::FragmentLayouts;
00591 
00592   // Compute fragment offset and size.
00593   if (Prev)
00594     F->Offset = Prev->Offset + getAssembler().computeFragmentSize(*this, *Prev);
00595   else
00596     F->Offset = 0;
00597   LastValidFragment[F->getParent()] = F;
00598 
00599   // If bundling is enabled and this fragment has instructions in it, it has to
00600   // obey the bundling restrictions. With padding, we'll have:
00601   //
00602   //
00603   //        BundlePadding
00604   //             |||
00605   // -------------------------------------
00606   //   Prev  |##########|       F        |
00607   // -------------------------------------
00608   //                    ^
00609   //                    |
00610   //                    F->Offset
00611   //
00612   // The fragment's offset will point to after the padding, and its computed
00613   // size won't include the padding.
00614   //
00615   if (Assembler.isBundlingEnabled() && F->hasInstructions()) {
00616     assert(isa<MCEncodedFragment>(F) &&
00617            "Only MCEncodedFragment implementations have instructions");
00618     uint64_t FSize = Assembler.computeFragmentSize(*this, *F);
00619 
00620     if (FSize > Assembler.getBundleAlignSize())
00621       report_fatal_error("Fragment can't be larger than a bundle size");
00622 
00623     uint64_t RequiredBundlePadding = computeBundlePadding(F, F->Offset, FSize);
00624     if (RequiredBundlePadding > UINT8_MAX)
00625       report_fatal_error("Padding cannot exceed 255 bytes");
00626     F->setBundlePadding(static_cast<uint8_t>(RequiredBundlePadding));
00627     F->Offset += RequiredBundlePadding;
00628   }
00629 }
00630 
00631 /// \brief Write the contents of a fragment to the given object writer. Expects
00632 ///        a MCEncodedFragment.
00633 static void writeFragmentContents(const MCFragment &F, MCObjectWriter *OW) {
00634   const MCEncodedFragment &EF = cast<MCEncodedFragment>(F);
00635   OW->WriteBytes(EF.getContents());
00636 }
00637 
00638 /// \brief Write the fragment \p F to the output file.
00639 static void writeFragment(const MCAssembler &Asm, const MCAsmLayout &Layout,
00640                           const MCFragment &F) {
00641   MCObjectWriter *OW = &Asm.getWriter();
00642 
00643   // FIXME: Embed in fragments instead?
00644   uint64_t FragmentSize = Asm.computeFragmentSize(Layout, F);
00645 
00646   // Should NOP padding be written out before this fragment?
00647   unsigned BundlePadding = F.getBundlePadding();
00648   if (BundlePadding > 0) {
00649     assert(Asm.isBundlingEnabled() &&
00650            "Writing bundle padding with disabled bundling");
00651     assert(F.hasInstructions() &&
00652            "Writing bundle padding for a fragment without instructions");
00653 
00654     unsigned TotalLength = BundlePadding + static_cast<unsigned>(FragmentSize);
00655     if (F.alignToBundleEnd() && TotalLength > Asm.getBundleAlignSize()) {
00656       // If the padding itself crosses a bundle boundary, it must be emitted
00657       // in 2 pieces, since even nop instructions must not cross boundaries.
00658       //             v--------------v   <- BundleAlignSize
00659       //        v---------v             <- BundlePadding
00660       // ----------------------------
00661       // | Prev |####|####|    F    |
00662       // ----------------------------
00663       //        ^-------------------^   <- TotalLength
00664       unsigned DistanceToBoundary = TotalLength - Asm.getBundleAlignSize();
00665       if (!Asm.getBackend().writeNopData(DistanceToBoundary, OW))
00666           report_fatal_error("unable to write NOP sequence of " +
00667                              Twine(DistanceToBoundary) + " bytes");
00668       BundlePadding -= DistanceToBoundary;
00669     }
00670     if (!Asm.getBackend().writeNopData(BundlePadding, OW))
00671       report_fatal_error("unable to write NOP sequence of " +
00672                          Twine(BundlePadding) + " bytes");
00673   }
00674 
00675   // This variable (and its dummy usage) is to participate in the assert at
00676   // the end of the function.
00677   uint64_t Start = OW->getStream().tell();
00678   (void) Start;
00679 
00680   ++stats::EmittedFragments;
00681 
00682   switch (F.getKind()) {
00683   case MCFragment::FT_Align: {
00684     ++stats::EmittedAlignFragments;
00685     const MCAlignFragment &AF = cast<MCAlignFragment>(F);
00686     assert(AF.getValueSize() && "Invalid virtual align in concrete fragment!");
00687 
00688     uint64_t Count = FragmentSize / AF.getValueSize();
00689 
00690     // FIXME: This error shouldn't actually occur (the front end should emit
00691     // multiple .align directives to enforce the semantics it wants), but is
00692     // severe enough that we want to report it. How to handle this?
00693     if (Count * AF.getValueSize() != FragmentSize)
00694       report_fatal_error("undefined .align directive, value size '" +
00695                         Twine(AF.getValueSize()) +
00696                         "' is not a divisor of padding size '" +
00697                         Twine(FragmentSize) + "'");
00698 
00699     // See if we are aligning with nops, and if so do that first to try to fill
00700     // the Count bytes.  Then if that did not fill any bytes or there are any
00701     // bytes left to fill use the Value and ValueSize to fill the rest.
00702     // If we are aligning with nops, ask that target to emit the right data.
00703     if (AF.hasEmitNops()) {
00704       if (!Asm.getBackend().writeNopData(Count, OW))
00705         report_fatal_error("unable to write nop sequence of " +
00706                           Twine(Count) + " bytes");
00707       break;
00708     }
00709 
00710     // Otherwise, write out in multiples of the value size.
00711     for (uint64_t i = 0; i != Count; ++i) {
00712       switch (AF.getValueSize()) {
00713       default: llvm_unreachable("Invalid size!");
00714       case 1: OW->Write8 (uint8_t (AF.getValue())); break;
00715       case 2: OW->Write16(uint16_t(AF.getValue())); break;
00716       case 4: OW->Write32(uint32_t(AF.getValue())); break;
00717       case 8: OW->Write64(uint64_t(AF.getValue())); break;
00718       }
00719     }
00720     break;
00721   }
00722 
00723   case MCFragment::FT_Data: 
00724     ++stats::EmittedDataFragments;
00725     writeFragmentContents(F, OW);
00726     break;
00727 
00728   case MCFragment::FT_Relaxable:
00729     ++stats::EmittedRelaxableFragments;
00730     writeFragmentContents(F, OW);
00731     break;
00732 
00733   case MCFragment::FT_CompactEncodedInst:
00734     ++stats::EmittedCompactEncodedInstFragments;
00735     writeFragmentContents(F, OW);
00736     break;
00737 
00738   case MCFragment::FT_Fill: {
00739     ++stats::EmittedFillFragments;
00740     const MCFillFragment &FF = cast<MCFillFragment>(F);
00741 
00742     assert(FF.getValueSize() && "Invalid virtual align in concrete fragment!");
00743 
00744     for (uint64_t i = 0, e = FF.getSize() / FF.getValueSize(); i != e; ++i) {
00745       switch (FF.getValueSize()) {
00746       default: llvm_unreachable("Invalid size!");
00747       case 1: OW->Write8 (uint8_t (FF.getValue())); break;
00748       case 2: OW->Write16(uint16_t(FF.getValue())); break;
00749       case 4: OW->Write32(uint32_t(FF.getValue())); break;
00750       case 8: OW->Write64(uint64_t(FF.getValue())); break;
00751       }
00752     }
00753     break;
00754   }
00755 
00756   case MCFragment::FT_LEB: {
00757     const MCLEBFragment &LF = cast<MCLEBFragment>(F);
00758     OW->WriteBytes(LF.getContents().str());
00759     break;
00760   }
00761 
00762   case MCFragment::FT_Org: {
00763     ++stats::EmittedOrgFragments;
00764     const MCOrgFragment &OF = cast<MCOrgFragment>(F);
00765 
00766     for (uint64_t i = 0, e = FragmentSize; i != e; ++i)
00767       OW->Write8(uint8_t(OF.getValue()));
00768 
00769     break;
00770   }
00771 
00772   case MCFragment::FT_Dwarf: {
00773     const MCDwarfLineAddrFragment &OF = cast<MCDwarfLineAddrFragment>(F);
00774     OW->WriteBytes(OF.getContents().str());
00775     break;
00776   }
00777   case MCFragment::FT_DwarfFrame: {
00778     const MCDwarfCallFrameFragment &CF = cast<MCDwarfCallFrameFragment>(F);
00779     OW->WriteBytes(CF.getContents().str());
00780     break;
00781   }
00782   }
00783 
00784   assert(OW->getStream().tell() - Start == FragmentSize &&
00785          "The stream should advance by fragment size");
00786 }
00787 
00788 void MCAssembler::writeSectionData(const MCSectionData *SD,
00789                                    const MCAsmLayout &Layout) const {
00790   // Ignore virtual sections.
00791   if (SD->getSection().isVirtualSection()) {
00792     assert(Layout.getSectionFileSize(SD) == 0 && "Invalid size for section!");
00793 
00794     // Check that contents are only things legal inside a virtual section.
00795     for (MCSectionData::const_iterator it = SD->begin(),
00796            ie = SD->end(); it != ie; ++it) {
00797       switch (it->getKind()) {
00798       default: llvm_unreachable("Invalid fragment in virtual section!");
00799       case MCFragment::FT_Data: {
00800         // Check that we aren't trying to write a non-zero contents (or fixups)
00801         // into a virtual section. This is to support clients which use standard
00802         // directives to fill the contents of virtual sections.
00803         const MCDataFragment &DF = cast<MCDataFragment>(*it);
00804         assert(DF.fixup_begin() == DF.fixup_end() &&
00805                "Cannot have fixups in virtual section!");
00806         for (unsigned i = 0, e = DF.getContents().size(); i != e; ++i)
00807           if (DF.getContents()[i]) {
00808             if (auto *ELFSec = dyn_cast<const MCSectionELF>(&SD->getSection()))
00809               report_fatal_error("non-zero initializer found in section '" +
00810                   ELFSec->getSectionName() + "'");
00811             else
00812               report_fatal_error("non-zero initializer found in virtual section");
00813           }
00814         break;
00815       }
00816       case MCFragment::FT_Align:
00817         // Check that we aren't trying to write a non-zero value into a virtual
00818         // section.
00819         assert((cast<MCAlignFragment>(it)->getValueSize() == 0 ||
00820                 cast<MCAlignFragment>(it)->getValue() == 0) &&
00821                "Invalid align in virtual section!");
00822         break;
00823       case MCFragment::FT_Fill:
00824         assert((cast<MCFillFragment>(it)->getValueSize() == 0 ||
00825                 cast<MCFillFragment>(it)->getValue() == 0) &&
00826                "Invalid fill in virtual section!");
00827         break;
00828       }
00829     }
00830 
00831     return;
00832   }
00833 
00834   uint64_t Start = getWriter().getStream().tell();
00835   (void)Start;
00836 
00837   for (MCSectionData::const_iterator it = SD->begin(), ie = SD->end();
00838        it != ie; ++it)
00839     writeFragment(*this, Layout, *it);
00840 
00841   assert(getWriter().getStream().tell() - Start ==
00842          Layout.getSectionAddressSize(SD));
00843 }
00844 
00845 std::pair<uint64_t, bool> MCAssembler::handleFixup(const MCAsmLayout &Layout,
00846                                                    MCFragment &F,
00847                                                    const MCFixup &Fixup) {
00848   // Evaluate the fixup.
00849   MCValue Target;
00850   uint64_t FixedValue;
00851   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
00852                  MCFixupKindInfo::FKF_IsPCRel;
00853   if (!evaluateFixup(Layout, Fixup, &F, Target, FixedValue)) {
00854     // The fixup was unresolved, we need a relocation. Inform the object
00855     // writer of the relocation, and give it an opportunity to adjust the
00856     // fixup value if need be.
00857     getWriter().RecordRelocation(*this, Layout, &F, Fixup, Target, IsPCRel,
00858                                  FixedValue);
00859   }
00860   return std::make_pair(FixedValue, IsPCRel);
00861 }
00862 
00863 void MCAssembler::Finish() {
00864   DEBUG_WITH_TYPE("mc-dump", {
00865       llvm::errs() << "assembler backend - pre-layout\n--\n";
00866       dump(); });
00867 
00868   // Create the layout object.
00869   MCAsmLayout Layout(*this);
00870 
00871   // Create dummy fragments and assign section ordinals.
00872   unsigned SectionIndex = 0;
00873   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
00874     // Create dummy fragments to eliminate any empty sections, this simplifies
00875     // layout.
00876     if (it->getFragmentList().empty())
00877       new MCDataFragment(it);
00878 
00879     it->setOrdinal(SectionIndex++);
00880   }
00881 
00882   // Assign layout order indices to sections and fragments.
00883   for (unsigned i = 0, e = Layout.getSectionOrder().size(); i != e; ++i) {
00884     MCSectionData *SD = Layout.getSectionOrder()[i];
00885     SD->setLayoutOrder(i);
00886 
00887     unsigned FragmentIndex = 0;
00888     for (MCSectionData::iterator iFrag = SD->begin(), iFragEnd = SD->end();
00889          iFrag != iFragEnd; ++iFrag)
00890       iFrag->setLayoutOrder(FragmentIndex++);
00891   }
00892 
00893   // Layout until everything fits.
00894   while (layoutOnce(Layout))
00895     continue;
00896 
00897   DEBUG_WITH_TYPE("mc-dump", {
00898       llvm::errs() << "assembler backend - post-relaxation\n--\n";
00899       dump(); });
00900 
00901   // Finalize the layout, including fragment lowering.
00902   finishLayout(Layout);
00903 
00904   DEBUG_WITH_TYPE("mc-dump", {
00905       llvm::errs() << "assembler backend - final-layout\n--\n";
00906       dump(); });
00907 
00908   uint64_t StartOffset = OS.tell();
00909 
00910   // Allow the object writer a chance to perform post-layout binding (for
00911   // example, to set the index fields in the symbol data).
00912   getWriter().ExecutePostLayoutBinding(*this, Layout);
00913 
00914   // Evaluate and apply the fixups, generating relocation entries as necessary.
00915   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
00916     for (MCSectionData::iterator it2 = it->begin(),
00917            ie2 = it->end(); it2 != ie2; ++it2) {
00918       MCEncodedFragmentWithFixups *F =
00919         dyn_cast<MCEncodedFragmentWithFixups>(it2);
00920       if (F) {
00921         for (MCEncodedFragmentWithFixups::fixup_iterator it3 = F->fixup_begin(),
00922              ie3 = F->fixup_end(); it3 != ie3; ++it3) {
00923           MCFixup &Fixup = *it3;
00924           uint64_t FixedValue;
00925           bool IsPCRel;
00926           std::tie(FixedValue, IsPCRel) = handleFixup(Layout, *F, Fixup);
00927           getBackend().applyFixup(Fixup, F->getContents().data(),
00928                                   F->getContents().size(), FixedValue, IsPCRel);
00929         }
00930       }
00931     }
00932   }
00933 
00934   // Write the object file.
00935   getWriter().WriteObject(*this, Layout);
00936 
00937   stats::ObjectBytes += OS.tell() - StartOffset;
00938 }
00939 
00940 bool MCAssembler::fixupNeedsRelaxation(const MCFixup &Fixup,
00941                                        const MCRelaxableFragment *DF,
00942                                        const MCAsmLayout &Layout) const {
00943   // If we cannot resolve the fixup value, it requires relaxation.
00944   MCValue Target;
00945   uint64_t Value;
00946   if (!evaluateFixup(Layout, Fixup, DF, Target, Value))
00947     return true;
00948 
00949   return getBackend().fixupNeedsRelaxation(Fixup, Value, DF, Layout);
00950 }
00951 
00952 bool MCAssembler::fragmentNeedsRelaxation(const MCRelaxableFragment *F,
00953                                           const MCAsmLayout &Layout) const {
00954   // If this inst doesn't ever need relaxation, ignore it. This occurs when we
00955   // are intentionally pushing out inst fragments, or because we relaxed a
00956   // previous instruction to one that doesn't need relaxation.
00957   if (!getBackend().mayNeedRelaxation(F->getInst()))
00958     return false;
00959 
00960   for (MCRelaxableFragment::const_fixup_iterator it = F->fixup_begin(),
00961        ie = F->fixup_end(); it != ie; ++it)
00962     if (fixupNeedsRelaxation(*it, F, Layout))
00963       return true;
00964 
00965   return false;
00966 }
00967 
00968 bool MCAssembler::relaxInstruction(MCAsmLayout &Layout,
00969                                    MCRelaxableFragment &F) {
00970   if (!fragmentNeedsRelaxation(&F, Layout))
00971     return false;
00972 
00973   ++stats::RelaxedInstructions;
00974 
00975   // FIXME-PERF: We could immediately lower out instructions if we can tell
00976   // they are fully resolved, to avoid retesting on later passes.
00977 
00978   // Relax the fragment.
00979 
00980   MCInst Relaxed;
00981   getBackend().relaxInstruction(F.getInst(), Relaxed);
00982 
00983   // Encode the new instruction.
00984   //
00985   // FIXME-PERF: If it matters, we could let the target do this. It can
00986   // probably do so more efficiently in many cases.
00987   SmallVector<MCFixup, 4> Fixups;
00988   SmallString<256> Code;
00989   raw_svector_ostream VecOS(Code);
00990   getEmitter().EncodeInstruction(Relaxed, VecOS, Fixups, F.getSubtargetInfo());
00991   VecOS.flush();
00992 
00993   // Update the fragment.
00994   F.setInst(Relaxed);
00995   F.getContents() = Code;
00996   F.getFixups() = Fixups;
00997 
00998   return true;
00999 }
01000 
01001 bool MCAssembler::relaxLEB(MCAsmLayout &Layout, MCLEBFragment &LF) {
01002   uint64_t OldSize = LF.getContents().size();
01003   int64_t Value = LF.getValue().evaluateKnownAbsolute(Layout);
01004   SmallString<8> &Data = LF.getContents();
01005   Data.clear();
01006   raw_svector_ostream OSE(Data);
01007   if (LF.isSigned())
01008     encodeSLEB128(Value, OSE);
01009   else
01010     encodeULEB128(Value, OSE);
01011   OSE.flush();
01012   return OldSize != LF.getContents().size();
01013 }
01014 
01015 bool MCAssembler::relaxDwarfLineAddr(MCAsmLayout &Layout,
01016                                      MCDwarfLineAddrFragment &DF) {
01017   MCContext &Context = Layout.getAssembler().getContext();
01018   uint64_t OldSize = DF.getContents().size();
01019   int64_t AddrDelta = DF.getAddrDelta().evaluateKnownAbsolute(Layout);
01020   int64_t LineDelta;
01021   LineDelta = DF.getLineDelta();
01022   SmallString<8> &Data = DF.getContents();
01023   Data.clear();
01024   raw_svector_ostream OSE(Data);
01025   MCDwarfLineAddr::Encode(Context, LineDelta, AddrDelta, OSE);
01026   OSE.flush();
01027   return OldSize != Data.size();
01028 }
01029 
01030 bool MCAssembler::relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
01031                                               MCDwarfCallFrameFragment &DF) {
01032   MCContext &Context = Layout.getAssembler().getContext();
01033   uint64_t OldSize = DF.getContents().size();
01034   int64_t AddrDelta = DF.getAddrDelta().evaluateKnownAbsolute(Layout);
01035   SmallString<8> &Data = DF.getContents();
01036   Data.clear();
01037   raw_svector_ostream OSE(Data);
01038   MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OSE);
01039   OSE.flush();
01040   return OldSize != Data.size();
01041 }
01042 
01043 bool MCAssembler::layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD) {
01044   // Holds the first fragment which needed relaxing during this layout. It will
01045   // remain NULL if none were relaxed.
01046   // When a fragment is relaxed, all the fragments following it should get
01047   // invalidated because their offset is going to change.
01048   MCFragment *FirstRelaxedFragment = nullptr;
01049 
01050   // Attempt to relax all the fragments in the section.
01051   for (MCSectionData::iterator I = SD.begin(), IE = SD.end(); I != IE; ++I) {
01052     // Check if this is a fragment that needs relaxation.
01053     bool RelaxedFrag = false;
01054     switch(I->getKind()) {
01055     default:
01056       break;
01057     case MCFragment::FT_Relaxable:
01058       assert(!getRelaxAll() &&
01059              "Did not expect a MCRelaxableFragment in RelaxAll mode");
01060       RelaxedFrag = relaxInstruction(Layout, *cast<MCRelaxableFragment>(I));
01061       break;
01062     case MCFragment::FT_Dwarf:
01063       RelaxedFrag = relaxDwarfLineAddr(Layout,
01064                                        *cast<MCDwarfLineAddrFragment>(I));
01065       break;
01066     case MCFragment::FT_DwarfFrame:
01067       RelaxedFrag =
01068         relaxDwarfCallFrameFragment(Layout,
01069                                     *cast<MCDwarfCallFrameFragment>(I));
01070       break;
01071     case MCFragment::FT_LEB:
01072       RelaxedFrag = relaxLEB(Layout, *cast<MCLEBFragment>(I));
01073       break;
01074     }
01075     if (RelaxedFrag && !FirstRelaxedFragment)
01076       FirstRelaxedFragment = I;
01077   }
01078   if (FirstRelaxedFragment) {
01079     Layout.invalidateFragmentsFrom(FirstRelaxedFragment);
01080     return true;
01081   }
01082   return false;
01083 }
01084 
01085 bool MCAssembler::layoutOnce(MCAsmLayout &Layout) {
01086   ++stats::RelaxationSteps;
01087 
01088   bool WasRelaxed = false;
01089   for (iterator it = begin(), ie = end(); it != ie; ++it) {
01090     MCSectionData &SD = *it;
01091     while (layoutSectionOnce(Layout, SD))
01092       WasRelaxed = true;
01093   }
01094 
01095   return WasRelaxed;
01096 }
01097 
01098 void MCAssembler::finishLayout(MCAsmLayout &Layout) {
01099   // The layout is done. Mark every fragment as valid.
01100   for (unsigned int i = 0, n = Layout.getSectionOrder().size(); i != n; ++i) {
01101     Layout.getFragmentOffset(&*Layout.getSectionOrder()[i]->rbegin());
01102   }
01103 }
01104 
01105 // Debugging methods
01106 
01107 namespace llvm {
01108 
01109 raw_ostream &operator<<(raw_ostream &OS, const MCFixup &AF) {
01110   OS << "<MCFixup" << " Offset:" << AF.getOffset()
01111      << " Value:" << *AF.getValue()
01112      << " Kind:" << AF.getKind() << ">";
01113   return OS;
01114 }
01115 
01116 }
01117 
01118 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01119 void MCFragment::dump() {
01120   raw_ostream &OS = llvm::errs();
01121 
01122   OS << "<";
01123   switch (getKind()) {
01124   case MCFragment::FT_Align: OS << "MCAlignFragment"; break;
01125   case MCFragment::FT_Data:  OS << "MCDataFragment"; break;
01126   case MCFragment::FT_CompactEncodedInst:
01127     OS << "MCCompactEncodedInstFragment"; break;
01128   case MCFragment::FT_Fill:  OS << "MCFillFragment"; break;
01129   case MCFragment::FT_Relaxable:  OS << "MCRelaxableFragment"; break;
01130   case MCFragment::FT_Org:   OS << "MCOrgFragment"; break;
01131   case MCFragment::FT_Dwarf: OS << "MCDwarfFragment"; break;
01132   case MCFragment::FT_DwarfFrame: OS << "MCDwarfCallFrameFragment"; break;
01133   case MCFragment::FT_LEB:   OS << "MCLEBFragment"; break;
01134   }
01135 
01136   OS << "<MCFragment " << (void*) this << " LayoutOrder:" << LayoutOrder
01137      << " Offset:" << Offset
01138      << " HasInstructions:" << hasInstructions() 
01139      << " BundlePadding:" << static_cast<unsigned>(getBundlePadding()) << ">";
01140 
01141   switch (getKind()) {
01142   case MCFragment::FT_Align: {
01143     const MCAlignFragment *AF = cast<MCAlignFragment>(this);
01144     if (AF->hasEmitNops())
01145       OS << " (emit nops)";
01146     OS << "\n       ";
01147     OS << " Alignment:" << AF->getAlignment()
01148        << " Value:" << AF->getValue() << " ValueSize:" << AF->getValueSize()
01149        << " MaxBytesToEmit:" << AF->getMaxBytesToEmit() << ">";
01150     break;
01151   }
01152   case MCFragment::FT_Data:  {
01153     const MCDataFragment *DF = cast<MCDataFragment>(this);
01154     OS << "\n       ";
01155     OS << " Contents:[";
01156     const SmallVectorImpl<char> &Contents = DF->getContents();
01157     for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
01158       if (i) OS << ",";
01159       OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
01160     }
01161     OS << "] (" << Contents.size() << " bytes)";
01162 
01163     if (DF->fixup_begin() != DF->fixup_end()) {
01164       OS << ",\n       ";
01165       OS << " Fixups:[";
01166       for (MCDataFragment::const_fixup_iterator it = DF->fixup_begin(),
01167              ie = DF->fixup_end(); it != ie; ++it) {
01168         if (it != DF->fixup_begin()) OS << ",\n                ";
01169         OS << *it;
01170       }
01171       OS << "]";
01172     }
01173     break;
01174   }
01175   case MCFragment::FT_CompactEncodedInst: {
01176     const MCCompactEncodedInstFragment *CEIF =
01177       cast<MCCompactEncodedInstFragment>(this);
01178     OS << "\n       ";
01179     OS << " Contents:[";
01180     const SmallVectorImpl<char> &Contents = CEIF->getContents();
01181     for (unsigned i = 0, e = Contents.size(); i != e; ++i) {
01182       if (i) OS << ",";
01183       OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
01184     }
01185     OS << "] (" << Contents.size() << " bytes)";
01186     break;
01187   }
01188   case MCFragment::FT_Fill:  {
01189     const MCFillFragment *FF = cast<MCFillFragment>(this);
01190     OS << " Value:" << FF->getValue() << " ValueSize:" << FF->getValueSize()
01191        << " Size:" << FF->getSize();
01192     break;
01193   }
01194   case MCFragment::FT_Relaxable:  {
01195     const MCRelaxableFragment *F = cast<MCRelaxableFragment>(this);
01196     OS << "\n       ";
01197     OS << " Inst:";
01198     F->getInst().dump_pretty(OS);
01199     break;
01200   }
01201   case MCFragment::FT_Org:  {
01202     const MCOrgFragment *OF = cast<MCOrgFragment>(this);
01203     OS << "\n       ";
01204     OS << " Offset:" << OF->getOffset() << " Value:" << OF->getValue();
01205     break;
01206   }
01207   case MCFragment::FT_Dwarf:  {
01208     const MCDwarfLineAddrFragment *OF = cast<MCDwarfLineAddrFragment>(this);
01209     OS << "\n       ";
01210     OS << " AddrDelta:" << OF->getAddrDelta()
01211        << " LineDelta:" << OF->getLineDelta();
01212     break;
01213   }
01214   case MCFragment::FT_DwarfFrame:  {
01215     const MCDwarfCallFrameFragment *CF = cast<MCDwarfCallFrameFragment>(this);
01216     OS << "\n       ";
01217     OS << " AddrDelta:" << CF->getAddrDelta();
01218     break;
01219   }
01220   case MCFragment::FT_LEB: {
01221     const MCLEBFragment *LF = cast<MCLEBFragment>(this);
01222     OS << "\n       ";
01223     OS << " Value:" << LF->getValue() << " Signed:" << LF->isSigned();
01224     break;
01225   }
01226   }
01227   OS << ">";
01228 }
01229 
01230 void MCSectionData::dump() {
01231   raw_ostream &OS = llvm::errs();
01232 
01233   OS << "<MCSectionData";
01234   OS << " Alignment:" << getAlignment()
01235      << " Fragments:[\n      ";
01236   for (iterator it = begin(), ie = end(); it != ie; ++it) {
01237     if (it != begin()) OS << ",\n      ";
01238     it->dump();
01239   }
01240   OS << "]>";
01241 }
01242 
01243 void MCSymbolData::dump() const {
01244   raw_ostream &OS = llvm::errs();
01245 
01246   OS << "<MCSymbolData Symbol:" << getSymbol()
01247      << " Fragment:" << getFragment() << " Offset:" << getOffset()
01248      << " Flags:" << getFlags() << " Index:" << getIndex();
01249   if (isCommon())
01250     OS << " (common, size:" << getCommonSize()
01251        << " align: " << getCommonAlignment() << ")";
01252   if (isExternal())
01253     OS << " (external)";
01254   if (isPrivateExtern())
01255     OS << " (private extern)";
01256   OS << ">";
01257 }
01258 
01259 void MCAssembler::dump() {
01260   raw_ostream &OS = llvm::errs();
01261 
01262   OS << "<MCAssembler\n";
01263   OS << "  Sections:[\n    ";
01264   for (iterator it = begin(), ie = end(); it != ie; ++it) {
01265     if (it != begin()) OS << ",\n    ";
01266     it->dump();
01267   }
01268   OS << "],\n";
01269   OS << "  Symbols:[";
01270 
01271   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
01272     if (it != symbol_begin()) OS << ",\n           ";
01273     it->dump();
01274   }
01275   OS << "]>\n";
01276 }
01277 #endif
01278 
01279 // anchors for MC*Fragment vtables
01280 void MCEncodedFragment::anchor() { }
01281 void MCEncodedFragmentWithFixups::anchor() { }
01282 void MCDataFragment::anchor() { }
01283 void MCCompactEncodedInstFragment::anchor() { }
01284 void MCRelaxableFragment::anchor() { }
01285 void MCAlignFragment::anchor() { }
01286 void MCFillFragment::anchor() { }
01287 void MCOrgFragment::anchor() { }
01288 void MCLEBFragment::anchor() { }
01289 void MCDwarfLineAddrFragment::anchor() { }
01290 void MCDwarfCallFrameFragment::anchor() { }