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