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