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