MC/Mach-O: Start passing in the basic MCAsmLayout object.
[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/MCSectionMachO.h"
15 #include "llvm/MC/MCSymbol.h"
16 #include "llvm/MC/MCValue.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/MachO.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/Debug.h"
27
28 // FIXME: Gross.
29 #include "../Target/X86/X86FixupKinds.h"
30
31 #include <vector>
32 using namespace llvm;
33
34 class MachObjectWriter;
35
36 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
37
38 // FIXME FIXME FIXME: There are number of places in this file where we convert
39 // what is a 64-bit assembler value used for computation into a value in the
40 // object file, which may truncate it. We should detect that truncation where
41 // invalid and report errors back.
42
43 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
44                           MachObjectWriter &MOW);
45
46 static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW);
47
48 /// isVirtualSection - Check if this is a section which does not actually exist
49 /// in the object file.
50 static bool isVirtualSection(const MCSection &Section) {
51   // FIXME: Lame.
52   const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
53   unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
54   return (Type == MCSectionMachO::S_ZEROFILL);
55 }
56
57 static unsigned getFixupKindLog2Size(unsigned Kind) {
58   switch (Kind) {
59   default: llvm_unreachable("invalid fixup kind!");
60   case X86::reloc_pcrel_1byte:
61   case FK_Data_1: return 0;
62   case FK_Data_2: return 1;
63   case X86::reloc_pcrel_4byte:
64   case X86::reloc_riprel_4byte:
65   case FK_Data_4: return 2;
66   case FK_Data_8: return 3;
67   }
68 }
69
70 static bool isFixupKindPCRel(unsigned Kind) {
71   switch (Kind) {
72   default:
73     return false;
74   case X86::reloc_pcrel_1byte:
75   case X86::reloc_pcrel_4byte:
76   case X86::reloc_riprel_4byte:
77     return true;
78   }
79 }
80
81 class MachObjectWriter {
82   // See <mach-o/loader.h>.
83   enum {
84     Header_Magic32 = 0xFEEDFACE,
85     Header_Magic64 = 0xFEEDFACF
86   };
87
88   static const unsigned Header32Size = 28;
89   static const unsigned Header64Size = 32;
90   static const unsigned SegmentLoadCommand32Size = 56;
91   static const unsigned Section32Size = 68;
92   static const unsigned SymtabLoadCommandSize = 24;
93   static const unsigned DysymtabLoadCommandSize = 80;
94   static const unsigned Nlist32Size = 12;
95   static const unsigned RelocationInfoSize = 8;
96
97   enum HeaderFileType {
98     HFT_Object = 0x1
99   };
100
101   enum HeaderFlags {
102     HF_SubsectionsViaSymbols = 0x2000
103   };
104
105   enum LoadCommandType {
106     LCT_Segment = 0x1,
107     LCT_Symtab = 0x2,
108     LCT_Dysymtab = 0xb
109   };
110
111   // See <mach-o/nlist.h>.
112   enum SymbolTypeType {
113     STT_Undefined = 0x00,
114     STT_Absolute  = 0x02,
115     STT_Section   = 0x0e
116   };
117
118   enum SymbolTypeFlags {
119     // If any of these bits are set, then the entry is a stab entry number (see
120     // <mach-o/stab.h>. Otherwise the other masks apply.
121     STF_StabsEntryMask = 0xe0,
122
123     STF_TypeMask       = 0x0e,
124     STF_External       = 0x01,
125     STF_PrivateExtern  = 0x10
126   };
127
128   /// IndirectSymbolFlags - Flags for encoding special values in the indirect
129   /// symbol entry.
130   enum IndirectSymbolFlags {
131     ISF_Local    = 0x80000000,
132     ISF_Absolute = 0x40000000
133   };
134
135   /// RelocationFlags - Special flags for addresses.
136   enum RelocationFlags {
137     RF_Scattered = 0x80000000
138   };
139
140   enum RelocationInfoType {
141     RIT_Vanilla             = 0,
142     RIT_Pair                = 1,
143     RIT_Difference          = 2,
144     RIT_PreboundLazyPointer = 3,
145     RIT_LocalDifference     = 4
146   };
147
148   /// MachSymbolData - Helper struct for containing some precomputed information
149   /// on symbols.
150   struct MachSymbolData {
151     MCSymbolData *SymbolData;
152     uint64_t StringIndex;
153     uint8_t SectionIndex;
154
155     // Support lexicographic sorting.
156     bool operator<(const MachSymbolData &RHS) const {
157       const std::string &Name = SymbolData->getSymbol().getName();
158       return Name < RHS.SymbolData->getSymbol().getName();
159     }
160   };
161
162   raw_ostream &OS;
163   bool IsLSB;
164
165 public:
166   MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true)
167     : OS(_OS), IsLSB(_IsLSB) {
168   }
169
170   /// @name Helper Methods
171   /// @{
172
173   void Write8(uint8_t Value) {
174     OS << char(Value);
175   }
176
177   void Write16(uint16_t Value) {
178     if (IsLSB) {
179       Write8(uint8_t(Value >> 0));
180       Write8(uint8_t(Value >> 8));
181     } else {
182       Write8(uint8_t(Value >> 8));
183       Write8(uint8_t(Value >> 0));
184     }
185   }
186
187   void Write32(uint32_t Value) {
188     if (IsLSB) {
189       Write16(uint16_t(Value >> 0));
190       Write16(uint16_t(Value >> 16));
191     } else {
192       Write16(uint16_t(Value >> 16));
193       Write16(uint16_t(Value >> 0));
194     }
195   }
196
197   void Write64(uint64_t Value) {
198     if (IsLSB) {
199       Write32(uint32_t(Value >> 0));
200       Write32(uint32_t(Value >> 32));
201     } else {
202       Write32(uint32_t(Value >> 32));
203       Write32(uint32_t(Value >> 0));
204     }
205   }
206
207   void WriteZeros(unsigned N) {
208     const char Zeros[16] = { 0 };
209
210     for (unsigned i = 0, e = N / 16; i != e; ++i)
211       OS << StringRef(Zeros, 16);
212
213     OS << StringRef(Zeros, N % 16);
214   }
215
216   void WriteString(StringRef Str, unsigned ZeroFillSize = 0) {
217     OS << Str;
218     if (ZeroFillSize)
219       WriteZeros(ZeroFillSize - Str.size());
220   }
221
222   /// @}
223
224   void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
225                      bool SubsectionsViaSymbols) {
226     uint32_t Flags = 0;
227
228     if (SubsectionsViaSymbols)
229       Flags |= HF_SubsectionsViaSymbols;
230
231     // struct mach_header (28 bytes)
232
233     uint64_t Start = OS.tell();
234     (void) Start;
235
236     Write32(Header_Magic32);
237
238     // FIXME: Support cputype.
239     Write32(MachO::CPUTypeI386);
240     // FIXME: Support cpusubtype.
241     Write32(MachO::CPUSubType_I386_ALL);
242     Write32(HFT_Object);
243     Write32(NumLoadCommands);    // Object files have a single load command, the
244                                  // segment.
245     Write32(LoadCommandsSize);
246     Write32(Flags);
247
248     assert(OS.tell() - Start == Header32Size);
249   }
250
251   /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
252   ///
253   /// \arg NumSections - The number of sections in this segment.
254   /// \arg SectionDataSize - The total size of the sections.
255   void WriteSegmentLoadCommand32(unsigned NumSections,
256                                  uint64_t VMSize,
257                                  uint64_t SectionDataStartOffset,
258                                  uint64_t SectionDataSize) {
259     // struct segment_command (56 bytes)
260
261     uint64_t Start = OS.tell();
262     (void) Start;
263
264     Write32(LCT_Segment);
265     Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
266
267     WriteString("", 16);
268     Write32(0); // vmaddr
269     Write32(VMSize); // vmsize
270     Write32(SectionDataStartOffset); // file offset
271     Write32(SectionDataSize); // file size
272     Write32(0x7); // maxprot
273     Write32(0x7); // initprot
274     Write32(NumSections);
275     Write32(0); // flags
276
277     assert(OS.tell() - Start == SegmentLoadCommand32Size);
278   }
279
280   void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
281                       uint64_t RelocationsStart, unsigned NumRelocations) {
282     // The offset is unused for virtual sections.
283     if (isVirtualSection(SD.getSection())) {
284       assert(SD.getFileSize() == 0 && "Invalid file size!");
285       FileOffset = 0;
286     }
287
288     // struct section (68 bytes)
289
290     uint64_t Start = OS.tell();
291     (void) Start;
292
293     // FIXME: cast<> support!
294     const MCSectionMachO &Section =
295       static_cast<const MCSectionMachO&>(SD.getSection());
296     WriteString(Section.getSectionName(), 16);
297     WriteString(Section.getSegmentName(), 16);
298     Write32(SD.getAddress()); // address
299     Write32(SD.getSize()); // size
300     Write32(FileOffset);
301
302     unsigned Flags = Section.getTypeAndAttributes();
303     if (SD.hasInstructions())
304       Flags |= MCSectionMachO::S_ATTR_SOME_INSTRUCTIONS;
305
306     assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
307     Write32(Log2_32(SD.getAlignment()));
308     Write32(NumRelocations ? RelocationsStart : 0);
309     Write32(NumRelocations);
310     Write32(Flags);
311     Write32(0); // reserved1
312     Write32(Section.getStubSize()); // reserved2
313
314     assert(OS.tell() - Start == Section32Size);
315   }
316
317   void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
318                               uint32_t StringTableOffset,
319                               uint32_t StringTableSize) {
320     // struct symtab_command (24 bytes)
321
322     uint64_t Start = OS.tell();
323     (void) Start;
324
325     Write32(LCT_Symtab);
326     Write32(SymtabLoadCommandSize);
327     Write32(SymbolOffset);
328     Write32(NumSymbols);
329     Write32(StringTableOffset);
330     Write32(StringTableSize);
331
332     assert(OS.tell() - Start == SymtabLoadCommandSize);
333   }
334
335   void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
336                                 uint32_t NumLocalSymbols,
337                                 uint32_t FirstExternalSymbol,
338                                 uint32_t NumExternalSymbols,
339                                 uint32_t FirstUndefinedSymbol,
340                                 uint32_t NumUndefinedSymbols,
341                                 uint32_t IndirectSymbolOffset,
342                                 uint32_t NumIndirectSymbols) {
343     // struct dysymtab_command (80 bytes)
344
345     uint64_t Start = OS.tell();
346     (void) Start;
347
348     Write32(LCT_Dysymtab);
349     Write32(DysymtabLoadCommandSize);
350     Write32(FirstLocalSymbol);
351     Write32(NumLocalSymbols);
352     Write32(FirstExternalSymbol);
353     Write32(NumExternalSymbols);
354     Write32(FirstUndefinedSymbol);
355     Write32(NumUndefinedSymbols);
356     Write32(0); // tocoff
357     Write32(0); // ntoc
358     Write32(0); // modtaboff
359     Write32(0); // nmodtab
360     Write32(0); // extrefsymoff
361     Write32(0); // nextrefsyms
362     Write32(IndirectSymbolOffset);
363     Write32(NumIndirectSymbols);
364     Write32(0); // extreloff
365     Write32(0); // nextrel
366     Write32(0); // locreloff
367     Write32(0); // nlocrel
368
369     assert(OS.tell() - Start == DysymtabLoadCommandSize);
370   }
371
372   void WriteNlist32(MachSymbolData &MSD) {
373     MCSymbolData &Data = *MSD.SymbolData;
374     const MCSymbol &Symbol = Data.getSymbol();
375     uint8_t Type = 0;
376     uint16_t Flags = Data.getFlags();
377     uint32_t Address = 0;
378
379     // Set the N_TYPE bits. See <mach-o/nlist.h>.
380     //
381     // FIXME: Are the prebound or indirect fields possible here?
382     if (Symbol.isUndefined())
383       Type = STT_Undefined;
384     else if (Symbol.isAbsolute())
385       Type = STT_Absolute;
386     else
387       Type = STT_Section;
388
389     // FIXME: Set STAB bits.
390
391     if (Data.isPrivateExtern())
392       Type |= STF_PrivateExtern;
393
394     // Set external bit.
395     if (Data.isExternal() || Symbol.isUndefined())
396       Type |= STF_External;
397
398     // Compute the symbol address.
399     if (Symbol.isDefined()) {
400       if (Symbol.isAbsolute()) {
401         llvm_unreachable("FIXME: Not yet implemented!");
402       } else {
403         Address = Data.getFragment()->getAddress() + Data.getOffset();
404       }
405     } else if (Data.isCommon()) {
406       // Common symbols are encoded with the size in the address
407       // field, and their alignment in the flags.
408       Address = Data.getCommonSize();
409
410       // Common alignment is packed into the 'desc' bits.
411       if (unsigned Align = Data.getCommonAlignment()) {
412         unsigned Log2Size = Log2_32(Align);
413         assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
414         if (Log2Size > 15)
415           llvm_report_error("invalid 'common' alignment '" +
416                             Twine(Align) + "'");
417         // FIXME: Keep this mask with the SymbolFlags enumeration.
418         Flags = (Flags & 0xF0FF) | (Log2Size << 8);
419       }
420     }
421
422     // struct nlist (12 bytes)
423
424     Write32(MSD.StringIndex);
425     Write8(Type);
426     Write8(MSD.SectionIndex);
427
428     // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
429     // value.
430     Write16(Flags);
431     Write32(Address);
432   }
433
434   struct MachRelocationEntry {
435     uint32_t Word0;
436     uint32_t Word1;
437   };
438   void ComputeScatteredRelocationInfo(MCAssembler &Asm, MCFragment &Fragment,
439                                       MCAsmFixup &Fixup,
440                                       const MCValue &Target,
441                                      std::vector<MachRelocationEntry> &Relocs) {
442     uint32_t Address = Fragment.getOffset() + Fixup.Offset;
443     unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
444     unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
445     unsigned Type = RIT_Vanilla;
446
447     // See <reloc.h>.
448     const MCSymbol *A = Target.getSymA();
449     MCSymbolData *A_SD = &Asm.getSymbolData(*A);
450
451     if (!A_SD->getFragment())
452       llvm_report_error("symbol '" + A->getName() +
453                         "' can not be undefined in a subtraction expression");
454
455     uint32_t Value = A_SD->getFragment()->getAddress() + A_SD->getOffset();
456     uint32_t Value2 = 0;
457
458     if (const MCSymbol *B = Target.getSymB()) {
459       MCSymbolData *B_SD = &Asm.getSymbolData(*B);
460
461       if (!B_SD->getFragment())
462         llvm_report_error("symbol '" + B->getName() +
463                           "' can not be undefined in a subtraction expression");
464
465       // Select the appropriate difference relocation type.
466       //
467       // Note that there is no longer any semantic difference between these two
468       // relocation types from the linkers point of view, this is done solely
469       // for pedantic compatibility with 'as'.
470       Type = A_SD->isExternal() ? RIT_Difference : RIT_LocalDifference;
471       Value2 = B_SD->getFragment()->getAddress() + B_SD->getOffset();
472     }
473
474     // The value which goes in the fixup is current value of the expression.
475     Fixup.FixedValue = Value - Value2 + Target.getConstant();
476     if (IsPCRel)
477       Fixup.FixedValue -= Address;
478
479     // If this fixup is a vanilla PC relative relocation for a local label, we
480     // don't need a relocation.
481     //
482     // FIXME: Implement proper atom support.
483     if (IsPCRel && Target.getSymA() && Target.getSymA()->isTemporary() &&
484         !Target.getSymB())
485       return;
486
487     MachRelocationEntry MRE;
488     MRE.Word0 = ((Address   <<  0) |
489                  (Type      << 24) |
490                  (Log2Size  << 28) |
491                  (IsPCRel   << 30) |
492                  RF_Scattered);
493     MRE.Word1 = Value;
494     Relocs.push_back(MRE);
495
496     if (Type == RIT_Difference || Type == RIT_LocalDifference) {
497       MachRelocationEntry MRE;
498       MRE.Word0 = ((0         <<  0) |
499                    (RIT_Pair  << 24) |
500                    (Log2Size  << 28) |
501                    (IsPCRel   << 30) |
502                    RF_Scattered);
503       MRE.Word1 = Value2;
504       Relocs.push_back(MRE);
505     }
506   }
507
508   void ComputeRelocationInfo(MCAssembler &Asm, MCDataFragment &Fragment,
509                              MCAsmFixup &Fixup,
510                              std::vector<MachRelocationEntry> &Relocs) {
511     unsigned IsPCRel = isFixupKindPCRel(Fixup.Kind);
512     unsigned Log2Size = getFixupKindLog2Size(Fixup.Kind);
513
514     // FIXME: Share layout object.
515     MCAsmLayout Layout(Asm);
516
517     MCValue Target;
518     if (!Fixup.Value->EvaluateAsRelocatable(Target, &Layout))
519       llvm_report_error("expected relocatable expression");
520
521     // If this is a difference or a defined symbol plus an offset, then we need
522     // a scattered relocation entry.
523     uint32_t Offset = Target.getConstant();
524     if (IsPCRel)
525       Offset += 1 << Log2Size;
526     if (Target.getSymB() ||
527         (Target.getSymA() && !Target.getSymA()->isUndefined() &&
528          Offset))
529       return ComputeScatteredRelocationInfo(Asm, Fragment, Fixup, Target,
530                                             Relocs);
531
532     // See <reloc.h>.
533     uint32_t Address = Fragment.getOffset() + Fixup.Offset;
534     uint32_t Value = 0;
535     unsigned Index = 0;
536     unsigned IsExtern = 0;
537     unsigned Type = 0;
538
539     if (Target.isAbsolute()) { // constant
540       // SymbolNum of 0 indicates the absolute section.
541       //
542       // FIXME: When is this generated?
543       Type = RIT_Vanilla;
544       Value = 0;
545       llvm_unreachable("FIXME: Not yet implemented!");
546     } else {
547       const MCSymbol *Symbol = Target.getSymA();
548       MCSymbolData *SD = &Asm.getSymbolData(*Symbol);
549
550       if (Symbol->isUndefined()) {
551         IsExtern = 1;
552         Index = SD->getIndex();
553         Value = 0;
554       } else {
555         // The index is the section ordinal.
556         //
557         // FIXME: O(N)
558         Index = 1;
559         MCAssembler::iterator it = Asm.begin(), ie = Asm.end();
560         for (; it != ie; ++it, ++Index)
561           if (&*it == SD->getFragment()->getParent())
562             break;
563         assert(it != ie && "Unable to find section index!");
564         Value = SD->getFragment()->getAddress() + SD->getOffset();
565       }
566
567       Type = RIT_Vanilla;
568     }
569
570     // The value which goes in the fixup is current value of the expression.
571     Fixup.FixedValue = Value + Target.getConstant();
572     if (IsPCRel)
573       Fixup.FixedValue -= Address;
574
575     // If this fixup is a vanilla PC relative relocation for a local label, we
576     // don't need a relocation.
577     //
578     // FIXME: Implement proper atom support.
579     if (IsPCRel && Target.getSymA() && Target.getSymA()->isTemporary())
580       return;
581
582     // struct relocation_info (8 bytes)
583     MachRelocationEntry MRE;
584     MRE.Word0 = Address;
585     MRE.Word1 = ((Index     <<  0) |
586                  (IsPCRel   << 24) |
587                  (Log2Size  << 25) |
588                  (IsExtern  << 27) |
589                  (Type      << 28));
590     Relocs.push_back(MRE);
591   }
592
593   void BindIndirectSymbols(MCAssembler &Asm) {
594     // This is the point where 'as' creates actual symbols for indirect symbols
595     // (in the following two passes). It would be easier for us to do this
596     // sooner when we see the attribute, but that makes getting the order in the
597     // symbol table much more complicated than it is worth.
598     //
599     // FIXME: Revisit this when the dust settles.
600
601     // Bind non lazy symbol pointers first.
602     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
603            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
604       // FIXME: cast<> support!
605       const MCSectionMachO &Section =
606         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
607
608       unsigned Type =
609         Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
610       if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
611         continue;
612
613       Asm.getOrCreateSymbolData(*it->Symbol);
614     }
615
616     // Then lazy symbol pointers and symbol stubs.
617     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
618            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
619       // FIXME: cast<> support!
620       const MCSectionMachO &Section =
621         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
622
623       unsigned Type =
624         Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
625       if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
626           Type != MCSectionMachO::S_SYMBOL_STUBS)
627         continue;
628
629       // Set the symbol type to undefined lazy, but only on construction.
630       //
631       // FIXME: Do not hardcode.
632       bool Created;
633       MCSymbolData &Entry = Asm.getOrCreateSymbolData(*it->Symbol, &Created);
634       if (Created)
635         Entry.setFlags(Entry.getFlags() | 0x0001);
636     }
637   }
638
639   /// ComputeSymbolTable - Compute the symbol table data
640   ///
641   /// \param StringTable [out] - The string table data.
642   /// \param StringIndexMap [out] - Map from symbol names to offsets in the
643   /// string table.
644   void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
645                           std::vector<MachSymbolData> &LocalSymbolData,
646                           std::vector<MachSymbolData> &ExternalSymbolData,
647                           std::vector<MachSymbolData> &UndefinedSymbolData) {
648     // Build section lookup table.
649     DenseMap<const MCSection*, uint8_t> SectionIndexMap;
650     unsigned Index = 1;
651     for (MCAssembler::iterator it = Asm.begin(),
652            ie = Asm.end(); it != ie; ++it, ++Index)
653       SectionIndexMap[&it->getSection()] = Index;
654     assert(Index <= 256 && "Too many sections!");
655
656     // Index 0 is always the empty string.
657     StringMap<uint64_t> StringIndexMap;
658     StringTable += '\x00';
659
660     // Build the symbol arrays and the string table, but only for non-local
661     // symbols.
662     //
663     // The particular order that we collect the symbols and create the string
664     // table, then sort the symbols is chosen to match 'as'. Even though it
665     // doesn't matter for correctness, this is important for letting us diff .o
666     // files.
667     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
668            ie = Asm.symbol_end(); it != ie; ++it) {
669       const MCSymbol &Symbol = it->getSymbol();
670
671       // Ignore assembler temporaries.
672       if (it->getSymbol().isTemporary())
673         continue;
674
675       if (!it->isExternal() && !Symbol.isUndefined())
676         continue;
677
678       uint64_t &Entry = StringIndexMap[Symbol.getName()];
679       if (!Entry) {
680         Entry = StringTable.size();
681         StringTable += Symbol.getName();
682         StringTable += '\x00';
683       }
684
685       MachSymbolData MSD;
686       MSD.SymbolData = it;
687       MSD.StringIndex = Entry;
688
689       if (Symbol.isUndefined()) {
690         MSD.SectionIndex = 0;
691         UndefinedSymbolData.push_back(MSD);
692       } else if (Symbol.isAbsolute()) {
693         MSD.SectionIndex = 0;
694         ExternalSymbolData.push_back(MSD);
695       } else {
696         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
697         assert(MSD.SectionIndex && "Invalid section index!");
698         ExternalSymbolData.push_back(MSD);
699       }
700     }
701
702     // Now add the data for local symbols.
703     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
704            ie = Asm.symbol_end(); it != ie; ++it) {
705       const MCSymbol &Symbol = it->getSymbol();
706
707       // Ignore assembler temporaries.
708       if (it->getSymbol().isTemporary())
709         continue;
710
711       if (it->isExternal() || Symbol.isUndefined())
712         continue;
713
714       uint64_t &Entry = StringIndexMap[Symbol.getName()];
715       if (!Entry) {
716         Entry = StringTable.size();
717         StringTable += Symbol.getName();
718         StringTable += '\x00';
719       }
720
721       MachSymbolData MSD;
722       MSD.SymbolData = it;
723       MSD.StringIndex = Entry;
724
725       if (Symbol.isAbsolute()) {
726         MSD.SectionIndex = 0;
727         LocalSymbolData.push_back(MSD);
728       } else {
729         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
730         assert(MSD.SectionIndex && "Invalid section index!");
731         LocalSymbolData.push_back(MSD);
732       }
733     }
734
735     // External and undefined symbols are required to be in lexicographic order.
736     std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
737     std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
738
739     // Set the symbol indices.
740     Index = 0;
741     for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
742       LocalSymbolData[i].SymbolData->setIndex(Index++);
743     for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
744       ExternalSymbolData[i].SymbolData->setIndex(Index++);
745     for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
746       UndefinedSymbolData[i].SymbolData->setIndex(Index++);
747
748     // The string table is padded to a multiple of 4.
749     while (StringTable.size() % 4)
750       StringTable += '\x00';
751   }
752
753   void WriteObject(MCAssembler &Asm) {
754     unsigned NumSections = Asm.size();
755
756     // Create symbol data for any indirect symbols.
757     BindIndirectSymbols(Asm);
758
759     // Compute symbol table information.
760     SmallString<256> StringTable;
761     std::vector<MachSymbolData> LocalSymbolData;
762     std::vector<MachSymbolData> ExternalSymbolData;
763     std::vector<MachSymbolData> UndefinedSymbolData;
764     unsigned NumSymbols = Asm.symbol_size();
765
766     // No symbol table command is written if there are no symbols.
767     if (NumSymbols)
768       ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
769                          UndefinedSymbolData);
770
771     // The section data starts after the header, the segment load command (and
772     // section headers) and the symbol table.
773     unsigned NumLoadCommands = 1;
774     uint64_t LoadCommandsSize =
775       SegmentLoadCommand32Size + NumSections * Section32Size;
776
777     // Add the symbol table load command sizes, if used.
778     if (NumSymbols) {
779       NumLoadCommands += 2;
780       LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
781     }
782
783     // Compute the total size of the section data, as well as its file size and
784     // vm size.
785     uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
786     uint64_t SectionDataSize = 0;
787     uint64_t SectionDataFileSize = 0;
788     uint64_t VMSize = 0;
789     for (MCAssembler::iterator it = Asm.begin(),
790            ie = Asm.end(); it != ie; ++it) {
791       MCSectionData &SD = *it;
792
793       VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
794
795       if (isVirtualSection(SD.getSection()))
796         continue;
797
798       SectionDataSize = std::max(SectionDataSize,
799                                  SD.getAddress() + SD.getSize());
800       SectionDataFileSize = std::max(SectionDataFileSize,
801                                      SD.getAddress() + SD.getFileSize());
802     }
803
804     // The section data is padded to 4 bytes.
805     //
806     // FIXME: Is this machine dependent?
807     unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
808     SectionDataFileSize += SectionDataPadding;
809
810     // Write the prolog, starting with the header and load command...
811     WriteHeader32(NumLoadCommands, LoadCommandsSize,
812                   Asm.getSubsectionsViaSymbols());
813     WriteSegmentLoadCommand32(NumSections, VMSize,
814                               SectionDataStart, SectionDataSize);
815
816     // ... and then the section headers.
817     //
818     // We also compute the section relocations while we do this. Note that
819     // computing relocation info will also update the fixup to have the correct
820     // value; this will overwrite the appropriate data in the fragment when it
821     // is written.
822     std::vector<MachRelocationEntry> RelocInfos;
823     uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
824     for (MCAssembler::iterator it = Asm.begin(),
825            ie = Asm.end(); it != ie; ++it) {
826       MCSectionData &SD = *it;
827
828       // The assembler writes relocations in the reverse order they were seen.
829       //
830       // FIXME: It is probably more complicated than this.
831       unsigned NumRelocsStart = RelocInfos.size();
832       for (MCSectionData::reverse_iterator it2 = SD.rbegin(),
833              ie2 = SD.rend(); it2 != ie2; ++it2)
834         if (MCDataFragment *DF = dyn_cast<MCDataFragment>(&*it2))
835           for (unsigned i = 0, e = DF->fixup_size(); i != e; ++i)
836             ComputeRelocationInfo(Asm, *DF, DF->getFixups()[e - i - 1],
837                                   RelocInfos);
838
839       unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
840       uint64_t SectionStart = SectionDataStart + SD.getAddress();
841       WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
842       RelocTableEnd += NumRelocs * RelocationInfoSize;
843     }
844
845     // Write the symbol table load command, if used.
846     if (NumSymbols) {
847       unsigned FirstLocalSymbol = 0;
848       unsigned NumLocalSymbols = LocalSymbolData.size();
849       unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
850       unsigned NumExternalSymbols = ExternalSymbolData.size();
851       unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
852       unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
853       unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
854       unsigned NumSymTabSymbols =
855         NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
856       uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
857       uint64_t IndirectSymbolOffset = 0;
858
859       // If used, the indirect symbols are written after the section data.
860       if (NumIndirectSymbols)
861         IndirectSymbolOffset = RelocTableEnd;
862
863       // The symbol table is written after the indirect symbol data.
864       uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
865
866       // The string table is written after symbol table.
867       uint64_t StringTableOffset =
868         SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
869       WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
870                              StringTableOffset, StringTable.size());
871
872       WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
873                                FirstExternalSymbol, NumExternalSymbols,
874                                FirstUndefinedSymbol, NumUndefinedSymbols,
875                                IndirectSymbolOffset, NumIndirectSymbols);
876     }
877
878     // Write the actual section data.
879     for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
880       WriteFileData(OS, *it, *this);
881
882     // Write the extra padding.
883     WriteZeros(SectionDataPadding);
884
885     // Write the relocation entries.
886     for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
887       Write32(RelocInfos[i].Word0);
888       Write32(RelocInfos[i].Word1);
889     }
890
891     // Write the symbol table data, if used.
892     if (NumSymbols) {
893       // Write the indirect symbol entries.
894       for (MCAssembler::indirect_symbol_iterator
895              it = Asm.indirect_symbol_begin(),
896              ie = Asm.indirect_symbol_end(); it != ie; ++it) {
897         // Indirect symbols in the non lazy symbol pointer section have some
898         // special handling.
899         const MCSectionMachO &Section =
900           static_cast<const MCSectionMachO&>(it->SectionData->getSection());
901         unsigned Type =
902           Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
903         if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
904           // If this symbol is defined and internal, mark it as such.
905           if (it->Symbol->isDefined() &&
906               !Asm.getSymbolData(*it->Symbol).isExternal()) {
907             uint32_t Flags = ISF_Local;
908             if (it->Symbol->isAbsolute())
909               Flags |= ISF_Absolute;
910             Write32(Flags);
911             continue;
912           }
913         }
914
915         Write32(Asm.getSymbolData(*it->Symbol).getIndex());
916       }
917
918       // FIXME: Check that offsets match computed ones.
919
920       // Write the symbol table entries.
921       for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
922         WriteNlist32(LocalSymbolData[i]);
923       for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
924         WriteNlist32(ExternalSymbolData[i]);
925       for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
926         WriteNlist32(UndefinedSymbolData[i]);
927
928       // Write the string table.
929       OS << StringTable.str();
930     }
931   }
932
933   void ApplyFixup(const MCAsmFixup &Fixup, MCDataFragment &DF) {
934     unsigned Size = 1 << getFixupKindLog2Size(Fixup.Kind);
935
936     // FIXME: Endianness assumption.
937     assert(Fixup.Offset + Size <= DF.getContents().size() &&
938            "Invalid fixup offset!");
939     for (unsigned i = 0; i != Size; ++i)
940       DF.getContents()[Fixup.Offset + i] = uint8_t(Fixup.FixedValue >> (i * 8));
941   }
942 };
943
944 /* *** */
945
946 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
947 }
948
949 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
950   : Kind(_Kind),
951     Parent(_Parent),
952     FileSize(~UINT64_C(0))
953 {
954   if (Parent)
955     Parent->getFragmentList().push_back(this);
956 }
957
958 MCFragment::~MCFragment() {
959 }
960
961 uint64_t MCFragment::getAddress() const {
962   assert(getParent() && "Missing Section!");
963   return getParent()->getAddress() + Offset;
964 }
965
966 /* *** */
967
968 MCSectionData::MCSectionData() : Section(0) {}
969
970 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
971   : Section(&_Section),
972     Alignment(1),
973     Address(~UINT64_C(0)),
974     Size(~UINT64_C(0)),
975     FileSize(~UINT64_C(0)),
976     HasInstructions(false)
977 {
978   if (A)
979     A->getSectionList().push_back(this);
980 }
981
982 /* *** */
983
984 MCSymbolData::MCSymbolData() : Symbol(0) {}
985
986 MCSymbolData::MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment,
987                            uint64_t _Offset, MCAssembler *A)
988   : Symbol(&_Symbol), Fragment(_Fragment), Offset(_Offset),
989     IsExternal(false), IsPrivateExtern(false),
990     CommonSize(0), CommonAlign(0), Flags(0), Index(0)
991 {
992   if (A)
993     A->getSymbolList().push_back(this);
994 }
995
996 /* *** */
997
998 MCAssembler::MCAssembler(MCContext &_Context, TargetAsmBackend &_Backend,
999                          raw_ostream &_OS)
1000   : Context(_Context), Backend(_Backend), OS(_OS), SubsectionsViaSymbols(false)
1001 {
1002 }
1003
1004 MCAssembler::~MCAssembler() {
1005 }
1006
1007 void MCAssembler::LayoutSection(MCSectionData &SD) {
1008   MCAsmLayout Layout(*this);
1009   uint64_t Address = SD.getAddress();
1010
1011   for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
1012     MCFragment &F = *it;
1013
1014     F.setOffset(Address - SD.getAddress());
1015
1016     // Evaluate fragment size.
1017     switch (F.getKind()) {
1018     case MCFragment::FT_Align: {
1019       MCAlignFragment &AF = cast<MCAlignFragment>(F);
1020
1021       uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
1022       if (Size > AF.getMaxBytesToEmit())
1023         AF.setFileSize(0);
1024       else
1025         AF.setFileSize(Size);
1026       break;
1027     }
1028
1029     case MCFragment::FT_Data:
1030     case MCFragment::FT_Fill:
1031       F.setFileSize(F.getMaxFileSize());
1032       break;
1033
1034     case MCFragment::FT_Org: {
1035       MCOrgFragment &OF = cast<MCOrgFragment>(F);
1036
1037       int64_t TargetLocation;
1038       if (!OF.getOffset().EvaluateAsAbsolute(TargetLocation, &Layout))
1039         llvm_report_error("expected assembly-time absolute expression");
1040
1041       // FIXME: We need a way to communicate this error.
1042       int64_t Offset = TargetLocation - F.getOffset();
1043       if (Offset < 0)
1044         llvm_report_error("invalid .org offset '" + Twine(TargetLocation) +
1045                           "' (at offset '" + Twine(F.getOffset()) + "'");
1046
1047       F.setFileSize(Offset);
1048       break;
1049     }
1050
1051     case MCFragment::FT_ZeroFill: {
1052       MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
1053
1054       // Align the fragment offset; it is safe to adjust the offset freely since
1055       // this is only in virtual sections.
1056       Address = RoundUpToAlignment(Address, ZFF.getAlignment());
1057       F.setOffset(Address - SD.getAddress());
1058
1059       // FIXME: This is misnamed.
1060       F.setFileSize(ZFF.getSize());
1061       break;
1062     }
1063     }
1064
1065     Address += F.getFileSize();
1066   }
1067
1068   // Set the section sizes.
1069   SD.setSize(Address - SD.getAddress());
1070   if (isVirtualSection(SD.getSection()))
1071     SD.setFileSize(0);
1072   else
1073     SD.setFileSize(Address - SD.getAddress());
1074 }
1075
1076 /// WriteNopData - Write optimal nops to the output file for the \arg Count
1077 /// bytes.  This returns the number of bytes written.  It may return 0 if
1078 /// the \arg Count is more than the maximum optimal nops.
1079 ///
1080 /// FIXME this is X86 32-bit specific and should move to a better place.
1081 static uint64_t WriteNopData(uint64_t Count, MachObjectWriter &MOW) {
1082   static const uint8_t Nops[16][16] = {
1083     // nop
1084     {0x90},
1085     // xchg %ax,%ax
1086     {0x66, 0x90},
1087     // nopl (%[re]ax)
1088     {0x0f, 0x1f, 0x00},
1089     // nopl 0(%[re]ax)
1090     {0x0f, 0x1f, 0x40, 0x00},
1091     // nopl 0(%[re]ax,%[re]ax,1)
1092     {0x0f, 0x1f, 0x44, 0x00, 0x00},
1093     // nopw 0(%[re]ax,%[re]ax,1)
1094     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1095     // nopl 0L(%[re]ax)
1096     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1097     // nopl 0L(%[re]ax,%[re]ax,1)
1098     {0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1099     // nopw 0L(%[re]ax,%[re]ax,1)
1100     {0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1101     // nopw %cs:0L(%[re]ax,%[re]ax,1)
1102     {0x66, 0x2e, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00},
1103     // nopl 0(%[re]ax,%[re]ax,1)
1104     // nopw 0(%[re]ax,%[re]ax,1)
1105     {0x0f, 0x1f, 0x44, 0x00, 0x00,
1106      0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1107     // nopw 0(%[re]ax,%[re]ax,1)
1108     // nopw 0(%[re]ax,%[re]ax,1)
1109     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1110      0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00},
1111     // nopw 0(%[re]ax,%[re]ax,1)
1112     // nopl 0L(%[re]ax) */
1113     {0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00,
1114      0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1115     // nopl 0L(%[re]ax)
1116     // nopl 0L(%[re]ax)
1117     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1118      0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00},
1119     // nopl 0L(%[re]ax)
1120     // nopl 0L(%[re]ax,%[re]ax,1)
1121     {0x0f, 0x1f, 0x80, 0x00, 0x00, 0x00, 0x00,
1122      0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00}
1123   };
1124
1125   if (Count > 15)
1126     return 0;
1127
1128   for (uint64_t i = 0; i < Count; i++)
1129     MOW.Write8 (uint8_t(Nops[Count - 1][i]));
1130
1131   return Count;
1132 }
1133
1134 /// WriteFileData - Write the \arg F data to the output file.
1135 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1136                           MachObjectWriter &MOW) {
1137   uint64_t Start = OS.tell();
1138   (void) Start;
1139
1140   ++EmittedFragments;
1141
1142   // FIXME: Embed in fragments instead?
1143   switch (F.getKind()) {
1144   case MCFragment::FT_Align: {
1145     MCAlignFragment &AF = cast<MCAlignFragment>(F);
1146     uint64_t Count = AF.getFileSize() / AF.getValueSize();
1147
1148     // FIXME: This error shouldn't actually occur (the front end should emit
1149     // multiple .align directives to enforce the semantics it wants), but is
1150     // severe enough that we want to report it. How to handle this?
1151     if (Count * AF.getValueSize() != AF.getFileSize())
1152       llvm_report_error("undefined .align directive, value size '" +
1153                         Twine(AF.getValueSize()) +
1154                         "' is not a divisor of padding size '" +
1155                         Twine(AF.getFileSize()) + "'");
1156
1157     // See if we are aligning with nops, and if so do that first to try to fill
1158     // the Count bytes.  Then if that did not fill any bytes or there are any
1159     // bytes left to fill use the the Value and ValueSize to fill the rest.
1160     if (AF.getEmitNops()) {
1161       uint64_t NopByteCount = WriteNopData(Count, MOW);
1162       Count -= NopByteCount;
1163     }
1164
1165     for (uint64_t i = 0; i != Count; ++i) {
1166       switch (AF.getValueSize()) {
1167       default:
1168         assert(0 && "Invalid size!");
1169       case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1170       case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1171       case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1172       case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1173       }
1174     }
1175     break;
1176   }
1177
1178   case MCFragment::FT_Data: {
1179     MCDataFragment &DF = cast<MCDataFragment>(F);
1180
1181     // Apply the fixups.
1182     //
1183     // FIXME: Move elsewhere.
1184     for (MCDataFragment::const_fixup_iterator it = DF.fixup_begin(),
1185            ie = DF.fixup_end(); it != ie; ++it)
1186       MOW.ApplyFixup(*it, DF);
1187
1188     OS << cast<MCDataFragment>(F).getContents().str();
1189     break;
1190   }
1191
1192   case MCFragment::FT_Fill: {
1193     MCFillFragment &FF = cast<MCFillFragment>(F);
1194     for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1195       switch (FF.getValueSize()) {
1196       default:
1197         assert(0 && "Invalid size!");
1198       case 1: MOW.Write8 (uint8_t (FF.getValue())); break;
1199       case 2: MOW.Write16(uint16_t(FF.getValue())); break;
1200       case 4: MOW.Write32(uint32_t(FF.getValue())); break;
1201       case 8: MOW.Write64(uint64_t(FF.getValue())); break;
1202       }
1203     }
1204     break;
1205   }
1206
1207   case MCFragment::FT_Org: {
1208     MCOrgFragment &OF = cast<MCOrgFragment>(F);
1209
1210     for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1211       MOW.Write8(uint8_t(OF.getValue()));
1212
1213     break;
1214   }
1215
1216   case MCFragment::FT_ZeroFill: {
1217     assert(0 && "Invalid zero fill fragment in concrete section!");
1218     break;
1219   }
1220   }
1221
1222   assert(OS.tell() - Start == F.getFileSize());
1223 }
1224
1225 /// WriteFileData - Write the \arg SD data to the output file.
1226 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1227                           MachObjectWriter &MOW) {
1228   // Ignore virtual sections.
1229   if (isVirtualSection(SD.getSection())) {
1230     assert(SD.getFileSize() == 0);
1231     return;
1232   }
1233
1234   uint64_t Start = OS.tell();
1235   (void) Start;
1236
1237   for (MCSectionData::const_iterator it = SD.begin(),
1238          ie = SD.end(); it != ie; ++it)
1239     WriteFileData(OS, *it, MOW);
1240
1241   // Add section padding.
1242   assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1243   MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1244
1245   assert(OS.tell() - Start == SD.getFileSize());
1246 }
1247
1248 void MCAssembler::Finish() {
1249   DEBUG_WITH_TYPE("mc-dump", {
1250       llvm::errs() << "assembler backend - pre-layout\n--\n";
1251       dump(); });
1252
1253   // Layout the concrete sections and fragments.
1254   uint64_t Address = 0;
1255   MCSectionData *Prev = 0;
1256   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1257     MCSectionData &SD = *it;
1258
1259     // Skip virtual sections.
1260     if (isVirtualSection(SD.getSection()))
1261       continue;
1262
1263     // Align this section if necessary by adding padding bytes to the previous
1264     // section.
1265     if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1266       assert(Prev && "Missing prev section!");
1267       Prev->setFileSize(Prev->getFileSize() + Pad);
1268       Address += Pad;
1269     }
1270
1271     // Layout the section fragments and its size.
1272     SD.setAddress(Address);
1273     LayoutSection(SD);
1274     Address += SD.getFileSize();
1275
1276     Prev = &SD;
1277   }
1278
1279   // Layout the virtual sections.
1280   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1281     MCSectionData &SD = *it;
1282
1283     if (!isVirtualSection(SD.getSection()))
1284       continue;
1285
1286     // Align this section if necessary by adding padding bytes to the previous
1287     // section.
1288     if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment()))
1289       Address += Pad;
1290
1291     SD.setAddress(Address);
1292     LayoutSection(SD);
1293     Address += SD.getSize();
1294
1295   }
1296
1297   DEBUG_WITH_TYPE("mc-dump", {
1298       llvm::errs() << "assembler backend - post-layout\n--\n";
1299       dump(); });
1300
1301   // Write the object file.
1302   MachObjectWriter MOW(OS);
1303   MOW.WriteObject(*this);
1304
1305   OS.flush();
1306 }
1307
1308
1309 // Debugging methods
1310
1311 namespace llvm {
1312
1313 raw_ostream &operator<<(raw_ostream &OS, const MCAsmFixup &AF) {
1314   OS << "<MCAsmFixup" << " Offset:" << AF.Offset << " Value:" << *AF.Value
1315      << " Kind:" << AF.Kind << ">";
1316   return OS;
1317 }
1318
1319 }
1320
1321 void MCFragment::dump() {
1322   raw_ostream &OS = llvm::errs();
1323
1324   OS << "<MCFragment " << (void*) this << " Offset:" << Offset
1325      << " FileSize:" << FileSize;
1326
1327   OS << ">";
1328 }
1329
1330 void MCAlignFragment::dump() {
1331   raw_ostream &OS = llvm::errs();
1332
1333   OS << "<MCAlignFragment ";
1334   this->MCFragment::dump();
1335   OS << "\n       ";
1336   OS << " Alignment:" << getAlignment()
1337      << " Value:" << getValue() << " ValueSize:" << getValueSize()
1338      << " MaxBytesToEmit:" << getMaxBytesToEmit() << ">";
1339 }
1340
1341 void MCDataFragment::dump() {
1342   raw_ostream &OS = llvm::errs();
1343
1344   OS << "<MCDataFragment ";
1345   this->MCFragment::dump();
1346   OS << "\n       ";
1347   OS << " Contents:[";
1348   for (unsigned i = 0, e = getContents().size(); i != e; ++i) {
1349     if (i) OS << ",";
1350     OS << hexdigit((Contents[i] >> 4) & 0xF) << hexdigit(Contents[i] & 0xF);
1351   }
1352   OS << "] (" << getContents().size() << " bytes)";
1353
1354   if (!getFixups().empty()) {
1355     OS << ",\n       ";
1356     OS << " Fixups:[";
1357     for (fixup_iterator it = fixup_begin(), ie = fixup_end(); it != ie; ++it) {
1358       if (it != fixup_begin()) OS << ",\n                ";
1359       OS << *it;
1360     }
1361     OS << "]";
1362   }
1363
1364   OS << ">";
1365 }
1366
1367 void MCFillFragment::dump() {
1368   raw_ostream &OS = llvm::errs();
1369
1370   OS << "<MCFillFragment ";
1371   this->MCFragment::dump();
1372   OS << "\n       ";
1373   OS << " Value:" << getValue() << " ValueSize:" << getValueSize()
1374      << " Count:" << getCount() << ">";
1375 }
1376
1377 void MCOrgFragment::dump() {
1378   raw_ostream &OS = llvm::errs();
1379
1380   OS << "<MCOrgFragment ";
1381   this->MCFragment::dump();
1382   OS << "\n       ";
1383   OS << " Offset:" << getOffset() << " Value:" << getValue() << ">";
1384 }
1385
1386 void MCZeroFillFragment::dump() {
1387   raw_ostream &OS = llvm::errs();
1388
1389   OS << "<MCZeroFillFragment ";
1390   this->MCFragment::dump();
1391   OS << "\n       ";
1392   OS << " Size:" << getSize() << " Alignment:" << getAlignment() << ">";
1393 }
1394
1395 void MCSectionData::dump() {
1396   raw_ostream &OS = llvm::errs();
1397
1398   OS << "<MCSectionData";
1399   OS << " Alignment:" << getAlignment() << " Address:" << Address
1400      << " Size:" << Size << " FileSize:" << FileSize
1401      << " Fragments:[\n      ";
1402   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1403     if (it != begin()) OS << ",\n      ";
1404     it->dump();
1405   }
1406   OS << "]>";
1407 }
1408
1409 void MCSymbolData::dump() {
1410   raw_ostream &OS = llvm::errs();
1411
1412   OS << "<MCSymbolData Symbol:" << getSymbol()
1413      << " Fragment:" << getFragment() << " Offset:" << getOffset()
1414      << " Flags:" << getFlags() << " Index:" << getIndex();
1415   if (isCommon())
1416     OS << " (common, size:" << getCommonSize()
1417        << " align: " << getCommonAlignment() << ")";
1418   if (isExternal())
1419     OS << " (external)";
1420   if (isPrivateExtern())
1421     OS << " (private extern)";
1422   OS << ">";
1423 }
1424
1425 void MCAssembler::dump() {
1426   raw_ostream &OS = llvm::errs();
1427
1428   OS << "<MCAssembler\n";
1429   OS << "  Sections:[\n    ";
1430   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1431     if (it != begin()) OS << ",\n    ";
1432     it->dump();
1433   }
1434   OS << "],\n";
1435   OS << "  Symbols:[";
1436
1437   for (symbol_iterator it = symbol_begin(), ie = symbol_end(); it != ie; ++it) {
1438     if (it != symbol_begin()) OS << ",\n           ";
1439     it->dump();
1440   }
1441   OS << "]>\n";
1442 }