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