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