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