MC/Mach-O: Move to MachObjectWriter.{h,cpp}.
[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/MCExpr.h"
14 #include "llvm/MC/MCObjectWriter.h"
15 #include "llvm/MC/MCSymbol.h"
16 #include "llvm/MC/MCValue.h"
17 #include "llvm/MC/MachObjectWriter.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Target/TargetRegistry.h"
25 #include "llvm/Target/TargetAsmBackend.h"
26
27 // FIXME: Gross.
28 #include "../Target/X86/X86FixupKinds.h"
29
30 #include <vector>
31 using namespace llvm;
32
33 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
34
35 // FIXME FIXME FIXME: There are number of places in this file where we convert
36 // what is a 64-bit assembler value used for computation into a value in the
37 // object file, which may truncate it. We should detect that truncation where
38 // invalid and report errors back.
39
40 static bool isFixupKindPCRel(unsigned Kind) {
41   switch (Kind) {
42   default:
43     return false;
44   case X86::reloc_pcrel_1byte:
45   case X86::reloc_pcrel_4byte:
46   case X86::reloc_riprel_4byte:
47     return true;
48   }
49 }
50
51 /* *** */
52
53 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
54 }
55
56 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
57   : Kind(_Kind),
58     Parent(_Parent),
59     FileSize(~UINT64_C(0))
60 {
61   if (Parent)
62     Parent->getFragmentList().push_back(this);
63 }
64
65 MCFragment::~MCFragment() {
66 }
67
68 uint64_t MCFragment::getAddress() const {
69   assert(getParent() && "Missing Section!");
70   return getParent()->getAddress() + Offset;
71 }
72
73 /* *** */
74
75 MCSectionData::MCSectionData() : Section(0) {}
76
77 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
78   : Section(&_Section),
79     Alignment(1),
80     Address(~UINT64_C(0)),
81     Size(~UINT64_C(0)),
82     FileSize(~UINT64_C(0)),
83     HasInstructions(false)
84 {
85   if (A)
86     A->getSectionList().push_back(this);
87 }
88
89 /* *** */
90
91 MCSymbolData::MCSymbolData() : Symbol(0) {}
92
93 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
94                            uint64_t _Offset, MCAssembler *A)
95   : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
96     IsExternal(false), IsPrivateExtern(false),
97     CommonSize(0), CommonAlign(0), Flags(0), Index(0)
98 {
99   if (A)
100     A->getSymbolList().push_back(this);
101 }
102
103 /* *** */
104
105 MCAssembler::MCAssembler(MCContext &_Context, TargetAsmBackend &_Backend,
106                          raw_ostream &_OS)
107   : Context(_Context), Backend(_Backend), OS(_OS), SubsectionsViaSymbols(false)
108 {
109 }
110
111 MCAssembler::~MCAssembler() {
112 }
113
114 static bool isScatteredFixupFullyResolvedSimple(const MCAssembler &Asm,
115                                                 const MCAsmFixup &Fixup,
116                                                 const MCDataFragment *DF,
117                                                 const MCValue Target,
118                                                 const MCSection *BaseSection) {
119   // The effective fixup address is
120   //     addr(atom(A)) + offset(A)
121   //   - addr(atom(B)) - offset(B)
122   //   - addr(<base symbol>) + <fixup offset from base symbol>
123   // and the offsets are not relocatable, so the fixup is fully resolved when
124   //  addr(atom(A)) - addr(atom(B)) - addr(<base symbol>)) == 0.
125   //
126   // The simple (Darwin, except on x86_64) way of dealing with this was to
127   // assume that any reference to a temporary symbol *must* be a temporary
128   // symbol in the same atom, unless the sections differ. Therefore, any PCrel
129   // relocation to a temporary symbol (in the same section) is fully
130   // resolved. This also works in conjunction with absolutized .set, which
131   // requires the compiler to use .set to absolutize the differences between
132   // symbols which the compiler knows to be assembly time constants, so we don't
133   // need to worry about consider symbol differences fully resolved.
134
135   // Non-relative fixups are only resolved if constant.
136   if (!BaseSection)
137     return Target.isAbsolute();
138
139   // Otherwise, relative fixups are only resolved if not a difference and the
140   // target is a temporary in the same section.
141   if (Target.isAbsolute() || Target.getSymB())
142     return false;
143
144   const MCSymbol *A = &Target.getSymA()->getSymbol();
145   if (!A->isTemporary() || !A->isInSection() ||
146       &A->getSection() != BaseSection)
147     return false;
148
149   return true;
150 }
151
152 static bool isScatteredFixupFullyResolved(const MCAssembler &Asm,
153                                           const MCAsmFixup &Fixup,
154                                           const MCDataFragment *DF,
155                                           const MCValue Target,
156                                           const MCSymbolData *BaseSymbol) {
157   // The effective fixup address is
158   //     addr(atom(A)) + offset(A)
159   //   - addr(atom(B)) - offset(B)
160   //   - addr(BaseSymbol) + <fixup offset from base symbol>
161   // and the offsets are not relocatable, so the fixup is fully resolved when
162   //  addr(atom(A)) - addr(atom(B)) - addr(BaseSymbol) == 0.
163   //
164   // Note that "false" is almost always conservatively correct (it means we emit
165   // a relocation which is unnecessary), except when it would force us to emit a
166   // relocation which the target cannot encode.
167
168   const MCSymbolData *A_Base = 0, *B_Base = 0;
169   if (const MCSymbolRefExpr *A = Target.getSymA()) {
170     // Modified symbol references cannot be resolved.
171     if (A->getKind() != MCSymbolRefExpr::VK_None)
172       return false;
173
174     A_Base = Asm.getAtom(&Asm.getSymbolData(A->getSymbol()));
175     if (!A_Base)
176       return false;
177   }
178
179   if (const MCSymbolRefExpr *B = Target.getSymB()) {
180     // Modified symbol references cannot be resolved.
181     if (B->getKind() != MCSymbolRefExpr::VK_None)
182       return false;
183
184     B_Base = Asm.getAtom(&Asm.getSymbolData(B->getSymbol()));
185     if (!B_Base)
186       return false;
187   }
188
189   // If there is no base, A and B have to be the same atom for this fixup to be
190   // fully resolved.
191   if (!BaseSymbol)
192     return A_Base == B_Base;
193
194   // Otherwise, B must be missing and A must be the base.
195   return !B_Base && BaseSymbol == A_Base;
196 }
197
198 bool MCAssembler::isSymbolLinkerVisible(const MCSymbolData *SD) const {
199   // Non-temporary labels should always be visible to the linker.
200   if (!SD->getSymbol().isTemporary())
201     return true;
202
203   // Absolute temporary labels are never visible.
204   if (!SD->getFragment())
205     return false;
206
207   // Otherwise, check if the section requires symbols even for temporary labels.
208   return getBackend().doesSectionRequireSymbols(
209     SD->getFragment()->getParent()->getSection());
210 }
211
212 const MCSymbolData *MCAssembler::getAtomForAddress(const MCSectionData *Section,
213                                                    uint64_t Address) const {
214   const MCSymbolData *Best = 0;
215   for (MCAssembler::const_symbol_iterator it = symbol_begin(),
216          ie = symbol_end(); it != ie; ++it) {
217     // Ignore non-linker visible symbols.
218     if (!isSymbolLinkerVisible(it))
219       continue;
220
221     // Ignore symbols not in the same section.
222     if (!it->getFragment() || it->getFragment()->getParent() != Section)
223       continue;
224
225     // Otherwise, find the closest symbol preceding this address (ties are
226     // resolved in favor of the last defined symbol).
227     if (it->getAddress() <= Address &&
228         (!Best || it->getAddress() >= Best->getAddress()))
229       Best = it;
230   }
231
232   return Best;
233 }
234
235 const MCSymbolData *MCAssembler::getAtom(const MCSymbolData *SD) const {
236   // Linker visible symbols define atoms.
237   if (isSymbolLinkerVisible(SD))
238     return SD;
239
240   // Absolute and undefined symbols have no defining atom.
241   if (!SD->getFragment())
242     return 0;
243
244   // Otherwise, search by address.
245   return getAtomForAddress(SD->getFragment()->getParent(), SD->getAddress());
246 }
247
248 bool MCAssembler::EvaluateFixup(const MCAsmLayout &Layout, MCAsmFixup &Fixup,
249                                 MCDataFragment *DF,
250                                 MCValue &Target, uint64_t &Value) const {
251   if (!Fixup.Value->EvaluateAsRelocatable(Target, &Layout))
252     llvm_report_error("expected relocatable expression");
253
254   // FIXME: How do non-scattered symbols work in ELF? I presume the linker
255   // doesn't support small relocations, but then under what criteria does the
256   // assembler allow symbol differences?
257
258   Value = Target.getConstant();
259
260   bool IsResolved = true, IsPCRel = isFixupKindPCRel(Fixup.Kind);
261   if (const MCSymbolRefExpr *A = Target.getSymA()) {
262     if (A->getSymbol().isDefined())
263       Value += getSymbolData(A->getSymbol()).getAddress();
264     else
265       IsResolved = false;
266   }
267   if (const MCSymbolRefExpr *B = Target.getSymB()) {
268     if (B->getSymbol().isDefined())
269       Value -= getSymbolData(B->getSymbol()).getAddress();
270     else
271       IsResolved = false;
272   }
273
274   // If we are using scattered symbols, determine whether this value is actually
275   // resolved; scattering may cause atoms to move.
276   if (IsResolved && getBackend().hasScatteredSymbols()) {
277     if (getBackend().hasReliableSymbolDifference()) {
278       // If this is a PCrel relocation, find the base atom (identified by its
279       // symbol) that the fixup value is relative to.
280       const MCSymbolData *BaseSymbol = 0;
281       if (IsPCRel) {
282         BaseSymbol = getAtomForAddress(
283           DF->getParent(), DF->getAddress() + Fixup.Offset);
284         if (!BaseSymbol)
285           IsResolved = false;
286       }
287
288       if (IsResolved)
289         IsResolved = isScatteredFixupFullyResolved(*this, Fixup, DF, Target,
290                                                    BaseSymbol);
291     } else {
292       const MCSection *BaseSection = 0;
293       if (IsPCRel)
294         BaseSection = &DF->getParent()->getSection();
295
296       IsResolved = isScatteredFixupFullyResolvedSimple(*this, Fixup, DF, Target,
297                                                        BaseSection);
298     }
299   }
300
301   if (IsPCRel)
302     Value -= DF->getAddress() + Fixup.Offset;
303
304   return IsResolved;
305 }
306
307 void MCAssembler::LayoutSection(MCSectionData &SD) {
308   MCAsmLayout Layout(*this);
309   uint64_t Address = SD.getAddress();
310
311   for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
312     MCFragment &F = *it;
313
314     F.setOffset(Address - SD.getAddress());
315
316     // Evaluate fragment size.
317     switch (F.getKind()) {
318     case MCFragment::FT_Align: {
319       MCAlignFragment &AF = cast<MCAlignFragment>(F);
320
321       uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
322       if (Size > AF.getMaxBytesToEmit())
323         AF.setFileSize(0);
324       else
325         AF.setFileSize(Size);
326       break;
327     }
328
329     case MCFragment::FT_Data:
330     case MCFragment::FT_Fill:
331       F.setFileSize(F.getMaxFileSize());
332       break;
333
334     case MCFragment::FT_Org: {
335       MCOrgFragment &OF = cast<MCOrgFragment>(F);
336
337       int64_t TargetLocation;
338       if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, &Layout))
339         llvm_report_error("expected assembly-time absolute expression");
340
341       // FIXME: We need a way to communicate this error.
342       int64_t Offset = TargetLocation - F.getOffset();
343       if (Offset < 0)
344         llvm_report_error("invalid .org offset '" + Twine(TargetLocation) +
345                           "' (at offset '" + Twine(F.getOffset()) + "'");
346
347       F.setFileSize(Offset);
348       break;
349     }
350
351     case MCFragment::FT_ZeroFill: {
352       MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
353
354       // Align the fragment offset; it is safe to adjust the offset freely since
355       // this is only in virtual sections.
356       Address = RoundUpToAlignment(Address, ZFF.getAlignment());
357       F.setOffset(Address - SD.getAddress());
358
359       // FIXME: This is misnamed.
360       F.setFileSize(ZFF.getSize());
361       break;
362     }
363     }
364
365     Address += F.getFileSize();
366   }
367
368   // Set the section sizes.
369   SD.setSize(Address - SD.getAddress());
370   if (getBackend().isVirtualSection(SD.getSection()))
371     SD.setFileSize(0);
372   else
373     SD.setFileSize(Address - SD.getAddress());
374 }
375
376 /// WriteNopData - Write optimal nops to the output file for the \arg Count
377 /// bytes.  This returns the number of bytes written.  It may return 0 if
378 /// the \arg Count is more than the maximum optimal nops.
379 ///
380 /// FIXME this is X86 32-bit specific and should move to a better place.
381 static uint64_t WriteNopData(uint64_t Count, MCObjectWriter *OW) {
382   static const uint8_t Nops[16][16] = {
383     // nop
384     {0x90},
385     // xchg %ax,%ax
386     {0x66, 0x90},
387     // nopl (%[re]ax)
388     {0x0f, 0x1f, 0x00},
389     // nopl 0(%[re]ax)
390     {0x0f, 0x1f, 0x40, 0x00},
391     // nopl 0(%[re]ax,%[re]ax,1)
392     {0x0f, 0x1f, 0x44, 0x00, 0x00},
393     // nopw 0(%[re]ax,%[re]ax,1)
394     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
395     // nopl 0L(%[re]ax)
396     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
397     // nopl 0L(%[re]ax,%[re]ax,1)
398     {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
399     // nopw 0L(%[re]ax,%[re]ax,1)
400     {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
401     // nopw %cs:0L(%[re]ax,%[re]ax,1)
402     {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
403     // nopl 0(%[re]ax,%[re]ax,1)
404     // nopw 0(%[re]ax,%[re]ax,1)
405     {0x0f, 0x1f, 0x44, 0x00, 0x00,
406      0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
407     // nopw 0(%[re]ax,%[re]ax,1)
408     // nopw 0(%[re]ax,%[re]ax,1)
409     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
410      0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
411     // nopw 0(%[re]ax,%[re]ax,1)
412     // nopl 0L(%[re]ax) */
413     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
414      0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
415     // nopl 0L(%[re]ax)
416     // nopl 0L(%[re]ax)
417     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
418      0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
419     // nopl 0L(%[re]ax)
420     // nopl 0L(%[re]ax,%[re]ax,1)
421     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
422      0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
423   };
424
425   if (Count > 15)
426     return 0;
427
428   for (uint64_t i = 0; i < Count; i++)
429     OW->Write8(uint8_t(Nops[Count - 1][i]));
430
431   return Count;
432 }
433
434 /// WriteFragmentData - Write the \arg F data to the output file.
435 static void WriteFragmentData(const MCFragment &F, MCObjectWriter *OW) {
436   uint64_t Start = OW->getStream().tell();
437   (void) Start;
438
439   ++EmittedFragments;
440
441   // FIXME: Embed in fragments instead?
442   switch (F.getKind()) {
443   case MCFragment::FT_Align: {
444     MCAlignFragment &AF = cast<MCAlignFragment>(F);
445     uint64_t Count = AF.getFileSize() / AF.getValueSize();
446
447     // FIXME: This error shouldn't actually occur (the front end should emit
448     // multiple .align directives to enforce the semantics it wants), but is
449     // severe enough that we want to report it. How to handle this?
450     if (Count * AF.getValueSize() != AF.getFileSize())
451       llvm_report_error("undefined .align directive, value size '" +
452                         Twine(AF.getValueSize()) +
453                         "' is not a divisor of padding size '" +
454                         Twine(AF.getFileSize()) + "'");
455
456     // See if we are aligning with nops, and if so do that first to try to fill
457     // the Count bytes.  Then if that did not fill any bytes or there are any
458     // bytes left to fill use the the Value and ValueSize to fill the rest.
459     if (AF.getEmitNops()) {
460       uint64_t NopByteCount = WriteNopData(Count, OW);
461       Count -= NopByteCount;
462     }
463
464     for (uint64_t i = 0; i != Count; ++i) {
465       switch (AF.getValueSize()) {
466       default:
467         assert(0 && "Invalid size!");
468       case 1: OW->Write8 (uint8_t (AF.getValue())); break;
469       case 2: OW->Write16(uint16_t(AF.getValue())); break;
470       case 4: OW->Write32(uint32_t(AF.getValue())); break;
471       case 8: OW->Write64(uint64_t(AF.getValue())); break;
472       }
473     }
474     break;
475   }
476
477   case MCFragment::FT_Data: {
478     OW->WriteBytes(cast<MCDataFragment>(F).getContents().str());
479     break;
480   }
481
482   case MCFragment::FT_Fill: {
483     MCFillFragment &FF = cast<MCFillFragment>(F);
484     for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
485       switch (FF.getValueSize()) {
486       default:
487         assert(0 && "Invalid size!");
488       case 1: OW->Write8 (uint8_t (FF.getValue())); break;
489       case 2: OW->Write16(uint16_t(FF.getValue())); break;
490       case 4: OW->Write32(uint32_t(FF.getValue())); break;
491       case 8: OW->Write64(uint64_t(FF.getValue())); break;
492       }
493     }
494     break;
495   }
496
497   case MCFragment::FT_Org: {
498     MCOrgFragment &OF = cast<MCOrgFragment>(F);
499
500     for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
501       OW->Write8(uint8_t(OF.getValue()));
502
503     break;
504   }
505
506   case MCFragment::FT_ZeroFill: {
507     assert(0 && "Invalid zero fill fragment in concrete section!");
508     break;
509   }
510   }
511
512   assert(OW->getStream().tell() - Start == F.getFileSize());
513 }
514
515 void MCAssembler::WriteSectionData(const MCSectionData *SD,
516                                    MCObjectWriter *OW) const {
517   // Ignore virtual sections.
518   if (getBackend().isVirtualSection(SD->getSection())) {
519     assert(SD->getFileSize() == 0);
520     return;
521   }
522
523   uint64_t Start = OW->getStream().tell();
524   (void) Start;
525
526   for (MCSectionData::const_iterator it = SD->begin(),
527          ie = SD->end(); it != ie; ++it)
528     WriteFragmentData(*it, OW);
529
530   // Add section padding.
531   assert(SD->getFileSize() >= SD->getSize() && "Invalid section sizes!");
532   OW->WriteZeros(SD->getFileSize() - SD->getSize());
533
534   assert(OW->getStream().tell() - Start == SD->getFileSize());
535 }
536
537 void MCAssembler::Finish() {
538   DEBUG_WITH_TYPE("mc-dump", {
539       llvm::errs() << "assembler backend - pre-layout\n--\n";
540       dump(); });
541
542   // Layout until everything fits.
543   while (LayoutOnce())
544     continue;
545
546   DEBUG_WITH_TYPE("mc-dump", {
547       llvm::errs() << "assembler backend - post-layout\n--\n";
548       dump(); });
549
550   // FIXME: Factor out MCObjectWriter.
551   bool Is64Bit = StringRef(getBackend().getTarget().getName()) == "x86-64";
552   MachObjectWriter MOW(OS, Is64Bit);
553
554   // Allow the object writer a chance to perform post-layout binding (for
555   // example, to set the index fields in the symbol data).
556   MOW.ExecutePostLayoutBinding(*this);
557
558   // Evaluate and apply the fixups, generating relocation entries as necessary.
559   //
560   // FIXME: Share layout object.
561   MCAsmLayout Layout(*this);
562   for (MCAssembler::iterator it = begin(), ie = end(); it != ie; ++it) {
563     for (MCSectionData::iterator it2 = it->begin(),
564            ie2 = it->end(); it2 != ie2; ++it2) {
565       MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
566       if (!DF)
567         continue;
568
569       for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
570              ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
571         MCAsmFixup &Fixup = *it3;
572
573         // Evaluate the fixup.
574         MCValue Target;
575         uint64_t FixedValue;
576         if (!EvaluateFixup(Layout, Fixup, DF, Target, FixedValue)) {
577           // The fixup was unresolved, we need a relocation. Inform the object
578           // writer of the relocation, and give it an opportunity to adjust the
579           // fixup value if need be.
580           MOW.RecordRelocation(*this, *DF, Fixup, Target, FixedValue);
581         }
582
583         getBackend().ApplyFixup(Fixup, *DF, FixedValue);
584       }
585     }
586   }
587
588   // Write the object file.
589   MOW.WriteObject(*this);
590
591   OS.flush();
592 }
593
594 bool MCAssembler::FixupNeedsRelaxation(MCAsmFixup &Fixup, MCDataFragment *DF) {
595   // FIXME: Share layout object.
596   MCAsmLayout Layout(*this);
597
598   // Currently we only need to relax X86::reloc_pcrel_1byte.
599   if (unsigned(Fixup.Kind) != X86::reloc_pcrel_1byte)
600     return false;
601
602   // If we cannot resolve the fixup value, it requires relaxation.
603   MCValue Target;
604   uint64_t Value;
605   if (!EvaluateFixup(Layout, Fixup, DF, Target, Value))
606     return true;
607
608   // Otherwise, relax if the value is too big for a (signed) i8.
609   return int64_t(Value) != int64_t(int8_t(Value));
610 }
611
612 bool MCAssembler::LayoutOnce() {
613   // Layout the concrete sections and fragments.
614   uint64_t Address = 0;
615   MCSectionData *Prev = 0;
616   for (iterator it = begin(), ie = end(); it != ie; ++it) {
617     MCSectionData &SD = *it;
618
619     // Skip virtual sections.
620     if (getBackend().isVirtualSection(SD.getSection()))
621       continue;
622
623     // Align this section if necessary by adding padding bytes to the previous
624     // section.
625     if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
626       assert(Prev && "Missing prev section!");
627       Prev->setFileSize(Prev->getFileSize() + Pad);
628       Address += Pad;
629     }
630
631     // Layout the section fragments and its size.
632     SD.setAddress(Address);
633     LayoutSection(SD);
634     Address += SD.getFileSize();
635
636     Prev = &SD;
637   }
638
639   // Layout the virtual sections.
640   for (iterator it = begin(), ie = end(); it != ie; ++it) {
641     MCSectionData &SD = *it;
642
643     if (!getBackend().isVirtualSection(SD.getSection()))
644       continue;
645
646     // Align this section if necessary by adding padding bytes to the previous
647     // section.
648     if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
649       Address += Pad;
650
651     SD.setAddress(Address);
652     LayoutSection(SD);
653     Address += SD.getSize();
654   }
655
656   // Scan the fixups in order and relax any that don't fit.
657   for (iterator it = begin(), ie = end(); it != ie; ++it) {
658     MCSectionData &SD = *it;
659
660     for (MCSectionData::iterator it2 = SD.begin(),
661            ie2 = SD.end(); it2 != ie2; ++it2) {
662       MCDataFragment *DF = dyn_cast<MCDataFragment>(it2);
663       if (!DF)
664         continue;
665
666       for (MCDataFragment::fixup_iterator it3 = DF->fixup_begin(),
667              ie3 = DF->fixup_end(); it3 != ie3; ++it3) {
668         MCAsmFixup &Fixup = *it3;
669
670         // Check whether we need to relax this fixup.
671         if (!FixupNeedsRelaxation(Fixup, DF))
672           continue;
673
674         // Relax the instruction.
675         //
676         // FIXME: This is a huge temporary hack which just looks for x86
677         // branches; the only thing we need to relax on x86 is
678         // 'X86::reloc_pcrel_1byte'. Once we have MCInst fragments, this will be
679         // replaced by a TargetAsmBackend hook (most likely tblgen'd) to relax
680         // an individual MCInst.
681         SmallVectorImpl<char> &C = DF->getContents();
682         uint64_t PrevOffset = Fixup.Offset;
683         unsigned Amt = 0;
684
685           // jcc instructions
686         if (unsigned(C[Fixup.Offset-1]) >= 0x70 &&
687             unsigned(C[Fixup.Offset-1]) <= 0x7f) {
688           C[Fixup.Offset] = C[Fixup.Offset-1] + 0x10;
689           C[Fixup.Offset-1] = char(0x0f);
690           ++Fixup.Offset;
691           Amt = 4;
692
693           // jmp rel8
694         } else if (C[Fixup.Offset-1] == char(0xeb)) {
695           C[Fixup.Offset-1] = char(0xe9);
696           Amt = 3;
697
698         } else
699           llvm_unreachable("unknown 1 byte pcrel instruction!");
700
701         Fixup.Value = MCBinaryExpr::Create(
702           MCBinaryExpr::Sub, Fixup.Value,
703           MCConstantExpr::Create(3, getContext()),
704           getContext());
705         C.insert(C.begin() + Fixup.Offset, Amt, char(0));
706         Fixup.Kind = MCFixupKind(X86::reloc_pcrel_4byte);
707
708         // Update the remaining fixups, which have slid.
709         //
710         // FIXME: This is bad for performance, but will be eliminated by the
711         // move to MCInst specific fragments.
712         ++it3;
713         for (; it3 != ie3; ++it3)
714           it3->Offset += Amt;
715
716         // Update all the symbols for this fragment, which may have slid.
717         //
718         // FIXME: This is really really bad for performance, but will be
719         // eliminated by the move to MCInst specific fragments.
720         for (MCAssembler::symbol_iterator it = symbol_begin(),
721                ie = symbol_end(); it != ie; ++it) {
722           MCSymbolData &SD = *it;
723
724           if (it->getFragment() != DF)
725             continue;
726
727           if (SD.getOffset() > PrevOffset)
728             SD.setOffset(SD.getOffset() + Amt);
729         }
730
731         // Restart layout.
732         //
733         // FIXME: This is O(N^2), but will be eliminated once we have a smart
734         // MCAsmLayout object.
735         return true;
736       }
737     }
738   }
739
740   return false;
741 }
742
743 // Debugging methods
744
745 namespace llvm {
746
747 raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
748   OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
749      << " Kind:" << AF.Kind << ">";
750   return OS;
751 }
752
753 }
754
755 void MCFragment::dump() {
756   raw_ostream &OS = llvm::errs();
757
758   OS << "<MCFragment " << (void*) this << " Offset:" << Offset
759      << " FileSize:" << FileSize;
760
761   OS << ">";
762 }
763
764 void MCAlignFragment::dump() {
765   raw_ostream &OS = llvm::errs();
766
767   OS << "<MCAlignFragment ";
768   this->MCFragment::dump();
769   OS << "\n       ";
770   OS << " Alignment:" << getAlignment()
771      << " Value:" << getValue() << " ValueSize:" << getValueSize()
772      << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
773 }
774
775 void MCDataFragment::dump() {
776   raw_ostream &OS = llvm::errs();
777
778   OS << "<MCDataFragment ";
779   this->MCFragment::dump();
780   OS << "\n       ";
781   OS << " Contents:[";
782   for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
783     if (i) OS << ",";
784     OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
785   }
786   OS << "] (" << getContents().size() << " bytes)";
787
788   if (!getFixups().empty()) {
789     OS << ",\n       ";
790     OS << " Fixups:[";
791     for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
792       if (it != fixup_begin()) OS << ",\n                ";
793       OS << *it;
794     }
795     OS << "]";
796   }
797
798   OS << ">";
799 }
800
801 void MCFillFragment::dump() {
802   raw_ostream &OS = llvm::errs();
803
804   OS << "<MCFillFragment ";
805   this->MCFragment::dump();
806   OS << "\n       ";
807   OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
808      << " Count:" << getCount() << ">";
809 }
810
811 void MCOrgFragment::dump() {
812   raw_ostream &OS = llvm::errs();
813
814   OS << "<MCOrgFragment ";
815   this->MCFragment::dump();
816   OS << "\n       ";
817   OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
818 }
819
820 void MCZeroFillFragment::dump() {
821   raw_ostream &OS = llvm::errs();
822
823   OS << "<MCZeroFillFragment ";
824   this->MCFragment::dump();
825   OS << "\n       ";
826   OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
827 }
828
829 void MCSectionData::dump() {
830   raw_ostream &OS = llvm::errs();
831
832   OS << "<MCSectionData";
833   OS << " Alignment:" << getAlignment() << " Address:" << Address
834      << " Size:" << Size << " FileSize:" << FileSize
835      << " Fragments:[\n      ";
836   for (iterator it = begin(), ie = end(); it != ie; ++it) {
837     if (it != begin()) OS << ",\n      ";
838     it->dump();
839   }
840   OS << "]>";
841 }
842
843 void MCSymbolData::dump() {
844   raw_ostream &OS = llvm::errs();
845
846   OS << "<MCSymbolData Symbol:" << getSymbol()
847      << " Fragment:" << getFragment() << " Offset:" << getOffset()
848      << " Flags:" << getFlags() << " Index:" << getIndex();
849   if (isCommon())
850     OS << " (common, size:" << getCommonSize()
851        << " align: " << getCommonAlignment() << ")";
852   if (isExternal())
853     OS << " (external)";
854   if (isPrivateExtern())
855     OS << " (private extern)";
856   OS << ">";
857 }
858
859 void MCAssembler::dump() {
860   raw_ostream &OS = llvm::errs();
861
862   OS << "<MCAssembler\n";
863   OS << "  Sections:[\n    ";
864   for (iterator it = begin(), ie = end(); it != ie; ++it) {
865     if (it != begin()) OS << ",\n    ";
866     it->dump();
867   }
868   OS << "],\n";
869   OS << "  Symbols:[";
870
871   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
872     if (it != symbol_begin()) OS << ",\n           ";
873     it->dump();
874   }
875   OS << "]>\n";
876 }