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