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