llvm-mc: Add statistic for number of fragments emitted by the assembler.
[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/MCSectionMachO.h"
13 #include "llvm/Target/TargetMachOWriterInfo.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include <vector>
22 using namespace llvm;
23
24 class MachObjectWriter;
25
26 STATISTIC(EmittedFragments, "Number of emitted assembler fragments");
27
28 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
29                           MachObjectWriter &MOW);
30
31 class MachObjectWriter {
32   // See <mach-o/loader.h>.
33   enum {
34     Header_Magic32 = 0xFEEDFACE,
35     Header_Magic64 = 0xFEEDFACF
36   };
37   
38   static const unsigned Header32Size = 28;
39   static const unsigned Header64Size = 32;
40   static const unsigned SegmentLoadCommand32Size = 56;
41   static const unsigned Section32Size = 68;
42   static const unsigned SymtabLoadCommandSize = 24;
43   static const unsigned DysymtabLoadCommandSize = 80;
44   static const unsigned Nlist32Size = 12;
45
46   enum HeaderFileType {
47     HFT_Object = 0x1
48   };
49
50   enum LoadCommandType {
51     LCT_Segment = 0x1,
52     LCT_Symtab = 0x2,
53     LCT_Dysymtab = 0xb
54   };
55
56   // See <mach-o/nlist.h>.
57   enum SymbolTypeType {
58     STT_Undefined = 0x00,
59     STT_Absolute  = 0x02,
60     STT_Section   = 0x0e
61   };
62
63   enum SymbolTypeFlags {
64     // If any of these bits are set, then the entry is a stab entry number (see
65     // <mach-o/stab.h>. Otherwise the other masks apply.
66     STF_StabsEntryMask = 0xe0,
67
68     STF_TypeMask       = 0x0e,
69     STF_External       = 0x01,
70     STF_PrivateExtern  = 0x10
71   };
72
73   /// MachSymbolData - Helper struct for containing some precomputed information
74   /// on symbols.
75   struct MachSymbolData {
76     MCSymbolData *SymbolData;
77     uint64_t StringIndex;
78     uint8_t SectionIndex;
79
80     // Support lexicographic sorting.
81     bool operator<(const MachSymbolData &RHS) const {
82       const std::string &Name = SymbolData->getSymbol().getName();
83       return Name < RHS.SymbolData->getSymbol().getName();
84     }
85   };
86
87   raw_ostream &OS;
88   bool IsLSB;
89
90 public:
91   MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true) 
92     : OS(_OS), IsLSB(_IsLSB) {
93   }
94
95   /// @name Helper Methods
96   /// @{
97
98   void Write8(uint8_t Value) {
99     OS << char(Value);
100   }
101
102   void Write16(uint16_t Value) {
103     if (IsLSB) {
104       Write8(uint8_t(Value >> 0));
105       Write8(uint8_t(Value >> 8));
106     } else {
107       Write8(uint8_t(Value >> 8));
108       Write8(uint8_t(Value >> 0));
109     }
110   }
111
112   void Write32(uint32_t Value) {
113     if (IsLSB) {
114       Write16(uint16_t(Value >> 0));
115       Write16(uint16_t(Value >> 16));
116     } else {
117       Write16(uint16_t(Value >> 16));
118       Write16(uint16_t(Value >> 0));
119     }
120   }
121
122   void Write64(uint64_t Value) {
123     if (IsLSB) {
124       Write32(uint32_t(Value >> 0));
125       Write32(uint32_t(Value >> 32));
126     } else {
127       Write32(uint32_t(Value >> 32));
128       Write32(uint32_t(Value >> 0));
129     }
130   }
131
132   void WriteZeros(unsigned N) {
133     const char Zeros[16] = { 0 };
134     
135     for (unsigned i = 0, e = N / 16; i != e; ++i)
136       OS << StringRef(Zeros, 16);
137     
138     OS << StringRef(Zeros, N % 16);
139   }
140
141   void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
142     OS << Str;
143     if (ZeroFillSize)
144       WriteZeros(ZeroFillSize - Str.size());
145   }
146
147   /// @}
148   
149   void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize) {
150     // struct mach_header (28 bytes)
151
152     uint64_t Start = OS.tell();
153     (void) Start;
154
155     Write32(Header_Magic32);
156
157     // FIXME: Support cputype.
158     Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
159
160     // FIXME: Support cpusubtype.
161     Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
162
163     Write32(HFT_Object);
164
165     // Object files have a single load command, the segment.
166     Write32(NumLoadCommands);
167     Write32(LoadCommandsSize);
168     Write32(0); // Flags
169
170     assert(OS.tell() - Start == Header32Size);
171   }
172
173   /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
174   ///
175   /// \arg NumSections - The number of sections in this segment.
176   /// \arg SectionDataSize - The total size of the sections.
177   void WriteSegmentLoadCommand32(unsigned NumSections,
178                                  uint64_t SectionDataStartOffset,
179                                  uint64_t SectionDataSize) {
180     // struct segment_command (56 bytes)
181
182     uint64_t Start = OS.tell();
183     (void) Start;
184
185     Write32(LCT_Segment);
186     Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
187
188     WriteString("", 16);
189     Write32(0); // vmaddr
190     Write32(SectionDataSize); // vmsize
191     Write32(SectionDataStartOffset); // file offset
192     Write32(SectionDataSize); // file size
193     Write32(0x7); // maxprot
194     Write32(0x7); // initprot
195     Write32(NumSections);
196     Write32(0); // flags
197
198     assert(OS.tell() - Start == SegmentLoadCommand32Size);
199   }
200
201   void WriteSection32(const MCSectionData &SD, uint64_t FileOffset) {
202     // struct section (68 bytes)
203
204     uint64_t Start = OS.tell();
205     (void) Start;
206
207     // FIXME: cast<> support!
208     const MCSectionMachO &Section =
209       static_cast<const MCSectionMachO&>(SD.getSection());
210     WriteString(Section.getSectionName(), 16);
211     WriteString(Section.getSegmentName(), 16);
212     Write32(0); // address
213     Write32(SD.getFileSize()); // size
214     Write32(FileOffset);
215
216     assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
217     Write32(Log2_32(SD.getAlignment()));
218     Write32(0); // file offset of relocation entries
219     Write32(0); // number of relocation entrions
220     Write32(Section.getTypeAndAttributes());
221     Write32(0); // reserved1
222     Write32(Section.getStubSize()); // reserved2
223
224     assert(OS.tell() - Start == Section32Size);
225   }
226
227   void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
228                               uint32_t StringTableOffset,
229                               uint32_t StringTableSize) {
230     // struct symtab_command (24 bytes)
231
232     uint64_t Start = OS.tell();
233     (void) Start;
234
235     Write32(LCT_Symtab);
236     Write32(SymtabLoadCommandSize);
237     Write32(SymbolOffset);
238     Write32(NumSymbols);
239     Write32(StringTableOffset);
240     Write32(StringTableSize);
241
242     assert(OS.tell() - Start == SymtabLoadCommandSize);
243   }
244
245   void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
246                                 uint32_t NumLocalSymbols,
247                                 uint32_t FirstExternalSymbol,
248                                 uint32_t NumExternalSymbols,
249                                 uint32_t FirstUndefinedSymbol,
250                                 uint32_t NumUndefinedSymbols,
251                                 uint32_t IndirectSymbolOffset,
252                                 uint32_t NumIndirectSymbols) {
253     // struct dysymtab_command (80 bytes)
254
255     uint64_t Start = OS.tell();
256     (void) Start;
257
258     Write32(LCT_Dysymtab);
259     Write32(DysymtabLoadCommandSize);
260     Write32(FirstLocalSymbol);
261     Write32(NumLocalSymbols);
262     Write32(FirstExternalSymbol);
263     Write32(NumExternalSymbols);
264     Write32(FirstUndefinedSymbol);
265     Write32(NumUndefinedSymbols);
266     Write32(0); // tocoff
267     Write32(0); // ntoc
268     Write32(0); // modtaboff
269     Write32(0); // nmodtab
270     Write32(0); // extrefsymoff
271     Write32(0); // nextrefsyms
272     Write32(IndirectSymbolOffset);
273     Write32(NumIndirectSymbols);
274     Write32(0); // extreloff
275     Write32(0); // nextrel
276     Write32(0); // locreloff
277     Write32(0); // nlocrel
278
279     assert(OS.tell() - Start == DysymtabLoadCommandSize);
280   }
281
282   void WriteNlist32(MachSymbolData &MSD) {
283     MCSymbol &Symbol = MSD.SymbolData->getSymbol();
284     uint8_t Type = 0;
285
286     // Set the N_TYPE bits. See <mach-o/nlist.h>.
287     //
288     // FIXME: Are the prebound or indirect fields possible here?
289     if (Symbol.isUndefined())
290       Type = STT_Undefined;
291     else if (Symbol.isAbsolute())
292       Type = STT_Absolute;
293     else
294       Type = STT_Section;
295
296     // FIXME: Set STAB bits.
297
298     if (MSD.SymbolData->isPrivateExtern())
299       Type |= STF_PrivateExtern;
300
301     // Set external bit.
302     if (MSD.SymbolData->isExternal() || Symbol.isUndefined())
303       Type |= STF_External;
304
305     // struct nlist (12 bytes)
306
307     Write32(MSD.StringIndex);
308     Write8(Type);
309     Write8(MSD.SectionIndex);
310     
311     // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
312     // value.
313     Write16(MSD.SymbolData->getFlags() & 0xFFFF);
314
315     Write32(0); // FIXME: Value
316   }
317
318   void BindIndirectSymbols(MCAssembler &Asm) {
319     // This is the point where 'as' creates actual symbols for indirect symbols
320     // (in the following two passes). It would be easier for us to do this
321     // sooner when we see the attribute, but that makes getting the order in the
322     // symbol table much more complicated than it is worth.
323     //
324     // FIXME: Revisit this when the dust settles.
325
326     // FIXME: This should not be needed.
327     DenseMap<MCSymbol*, MCSymbolData *> SymbolMap;
328
329     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
330            ie = Asm.symbol_end(); it != ie; ++it)
331       SymbolMap[&it->getSymbol()] = it;
332
333     // Bind non lazy symbol pointers first.
334     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
335            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
336       // FIXME: cast<> support!
337       const MCSectionMachO &Section =
338         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
339
340       unsigned Type =
341         Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
342       if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
343         continue;
344
345       MCSymbolData *&Entry = SymbolMap[it->Symbol];
346       if (!Entry)
347         Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
348     }
349
350     // Then lazy symbol pointers and symbol stubs.
351     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
352            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
353       // FIXME: cast<> support!
354       const MCSectionMachO &Section =
355         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
356
357       unsigned Type =
358         Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
359       if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
360           Type != MCSectionMachO::S_SYMBOL_STUBS)
361         continue;
362
363       MCSymbolData *&Entry = SymbolMap[it->Symbol];
364       if (!Entry) {
365         Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
366
367         // Set the symbol type to undefined lazy, but only on construction.
368         //
369         // FIXME: Do not hardcode.
370         Entry->setFlags(Entry->getFlags() | 0x0001);
371       }
372     }
373   }
374
375   /// ComputeSymbolTable - Compute the symbol table data
376   ///
377   /// \param StringTable [out] - The string table data.
378   /// \param StringIndexMap [out] - Map from symbol names to offsets in the
379   /// string table.
380   void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
381                           std::vector<MachSymbolData> &LocalSymbolData,
382                           std::vector<MachSymbolData> &ExternalSymbolData,
383                           std::vector<MachSymbolData> &UndefinedSymbolData) {
384     // Build section lookup table.
385     DenseMap<const MCSection*, uint8_t> SectionIndexMap;
386     unsigned Index = 1;
387     for (MCAssembler::iterator it = Asm.begin(),
388            ie = Asm.end(); it != ie; ++it, ++Index)
389       SectionIndexMap[&it->getSection()] = Index;
390     assert(Index <= 256 && "Too many sections!");
391
392     // Index 0 is always the empty string.
393     StringMap<uint64_t> StringIndexMap;
394     StringTable += '\x00';
395
396     // Build the symbol arrays and the string table, but only for non-local
397     // symbols.
398     //
399     // The particular order that we collect the symbols and create the string
400     // table, then sort the symbols is chosen to match 'as'. Even though it
401     // doesn't matter for correctness, this is important for letting us diff .o
402     // files.
403     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
404            ie = Asm.symbol_end(); it != ie; ++it) {
405       MCSymbol &Symbol = it->getSymbol();
406
407       if (!it->isExternal() && !Symbol.isUndefined())
408         continue;
409
410       uint64_t &Entry = StringIndexMap[Symbol.getName()];
411       if (!Entry) {
412         Entry = StringTable.size();
413         StringTable += Symbol.getName();
414         StringTable += '\x00';
415       }
416
417       MachSymbolData MSD;
418       MSD.SymbolData = it;
419       MSD.StringIndex = Entry;
420
421       if (Symbol.isUndefined()) {
422         MSD.SectionIndex = 0;
423         UndefinedSymbolData.push_back(MSD);
424       } else if (Symbol.isAbsolute()) {
425         MSD.SectionIndex = 0;
426         ExternalSymbolData.push_back(MSD);
427       } else {
428         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
429         assert(MSD.SectionIndex && "Invalid section index!");
430         ExternalSymbolData.push_back(MSD);
431       }
432     }
433
434     // Now add the data for local symbols.
435     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
436            ie = Asm.symbol_end(); it != ie; ++it) {
437       MCSymbol &Symbol = it->getSymbol();
438
439       if (it->isExternal() || Symbol.isUndefined())
440         continue;
441
442       uint64_t &Entry = StringIndexMap[Symbol.getName()];
443       if (!Entry) {
444         Entry = StringTable.size();
445         StringTable += Symbol.getName();
446         StringTable += '\x00';
447       }
448
449       MachSymbolData MSD;
450       MSD.SymbolData = it;
451       MSD.StringIndex = Entry;
452
453       if (Symbol.isAbsolute()) {
454         MSD.SectionIndex = 0;
455         LocalSymbolData.push_back(MSD);
456       } else {
457         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
458         assert(MSD.SectionIndex && "Invalid section index!");
459         LocalSymbolData.push_back(MSD);
460       }
461     }
462
463     // External and undefined symbols are required to be in lexicographic order.
464     std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
465     std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
466
467     // The string table is padded to a multiple of 4.
468     //
469     // FIXME: Check to see if this varies per arch.
470     while (StringTable.size() % 4)
471       StringTable += '\x00';
472   }
473
474   void WriteObject(MCAssembler &Asm) {
475     unsigned NumSections = Asm.size();
476
477     BindIndirectSymbols(Asm);
478
479     // Compute symbol table information.
480     SmallString<256> StringTable;
481     std::vector<MachSymbolData> LocalSymbolData;
482     std::vector<MachSymbolData> ExternalSymbolData;
483     std::vector<MachSymbolData> UndefinedSymbolData;
484     unsigned NumSymbols = Asm.symbol_size();
485
486     // No symbol table command is written if there are no symbols.
487     if (NumSymbols)
488       ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
489                          UndefinedSymbolData);
490
491     // Compute the file offsets for all the sections in advance, so that we can
492     // write things out in order.
493     SmallVector<uint64_t, 16> SectionFileOffsets;
494     SectionFileOffsets.resize(NumSections);
495   
496     // The section data starts after the header, the segment load command (and
497     // section headers) and the symbol table.
498     unsigned NumLoadCommands = 1;
499     uint64_t LoadCommandsSize =
500       SegmentLoadCommand32Size + NumSections * Section32Size;
501
502     // Add the symbol table load command sizes, if used.
503     if (NumSymbols) {
504       NumLoadCommands += 2;
505       LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
506     }
507
508     uint64_t FileOffset = Header32Size + LoadCommandsSize;
509     uint64_t SectionDataStartOffset = FileOffset;
510     uint64_t SectionDataSize = 0;
511     unsigned Index = 0;
512     for (MCAssembler::iterator it = Asm.begin(),
513            ie = Asm.end(); it != ie; ++it, ++Index) {
514       SectionFileOffsets[Index] = FileOffset;
515       FileOffset += it->getFileSize();
516       SectionDataSize += it->getFileSize();
517     }
518
519     // Write the prolog, starting with the header and load command...
520     WriteHeader32(NumLoadCommands, LoadCommandsSize);
521     WriteSegmentLoadCommand32(NumSections, SectionDataStartOffset,
522                               SectionDataSize);
523   
524     // ... and then the section headers.
525     Index = 0;
526     for (MCAssembler::iterator it = Asm.begin(),
527            ie = Asm.end(); it != ie; ++it, ++Index)
528       WriteSection32(*it, SectionFileOffsets[Index]);
529
530     // Write the symbol table load command, if used.
531     if (NumSymbols) {
532       unsigned FirstLocalSymbol = 0;
533       unsigned NumLocalSymbols = LocalSymbolData.size();
534       unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
535       unsigned NumExternalSymbols = ExternalSymbolData.size();
536       unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
537       unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
538       unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
539       unsigned NumSymTabSymbols =
540         NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
541       uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
542       uint64_t IndirectSymbolOffset = 0;
543
544       // If used, the indirect symbols are written after the section data.
545       if (NumIndirectSymbols)
546         IndirectSymbolOffset = SectionDataStartOffset + SectionDataSize;
547
548       // The symbol table is written after the indirect symbol data.
549       uint64_t SymbolTableOffset =
550         SectionDataStartOffset + SectionDataSize + IndirectSymbolSize;
551
552       // The string table is written after symbol table.
553       uint64_t StringTableOffset =
554         SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
555       WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
556                              StringTableOffset, StringTable.size());
557
558       WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
559                                FirstExternalSymbol, NumExternalSymbols,
560                                FirstUndefinedSymbol, NumUndefinedSymbols,
561                                IndirectSymbolOffset, NumIndirectSymbols);
562     }
563
564     // Write the actual section data.
565     for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
566       WriteFileData(OS, *it, *this);
567
568     // Write the symbol table data, if used.
569     if (NumSymbols) {
570       // Write the indirect symbol entries.
571       //
572       // FIXME: We need the symbol index map for this.
573       for (unsigned i = 0, e = Asm.indirect_symbol_size(); i != e; ++i)
574         Write32(0);
575
576       // FIXME: Check that offsets match computed ones.
577
578       // Write the symbol table entries.
579       for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
580         WriteNlist32(LocalSymbolData[i]);
581       for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
582         WriteNlist32(ExternalSymbolData[i]);
583       for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
584         WriteNlist32(UndefinedSymbolData[i]);
585
586       // Write the string table.
587       OS << StringTable.str();
588     }
589   }
590 };
591
592 /* *** */
593
594 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
595 }
596
597 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *SD)
598   : Kind(_Kind),
599     FileSize(~UINT64_C(0))
600 {
601   if (SD)
602     SD->getFragmentList().push_back(this);
603 }
604
605 MCFragment::~MCFragment() {
606 }
607
608 /* *** */
609
610 MCSectionData::MCSectionData() : Section(*(MCSection*)0) {}
611
612 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
613   : Section(_Section),
614     Alignment(1),
615     FileSize(~UINT64_C(0))
616 {
617   if (A)
618     A->getSectionList().push_back(this);
619 }
620
621 /* *** */
622
623 MCSymbolData::MCSymbolData() : Symbol(*(MCSymbol*)0) {}
624
625 MCSymbolData::MCSymbolData(MCSymbol &_Symbol, MCFragment *_Fragment,
626                            uint64_t _Offset, MCAssembler *A)
627   : Symbol(_Symbol), Fragment(_Fragment), Offset(_Offset),
628     IsExternal(false), IsPrivateExtern(false), Flags(0)
629 {
630   if (A)
631     A->getSymbolList().push_back(this);
632 }
633
634 /* *** */
635
636 MCAssembler::MCAssembler(raw_ostream &_OS) : OS(_OS) {}
637
638 MCAssembler::~MCAssembler() {
639 }
640
641 void MCAssembler::LayoutSection(MCSectionData &SD) {
642   uint64_t Offset = 0;
643
644   for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
645     MCFragment &F = *it;
646
647     F.setOffset(Offset);
648
649     // Evaluate fragment size.
650     switch (F.getKind()) {
651     case MCFragment::FT_Align: {
652       MCAlignFragment &AF = cast<MCAlignFragment>(F);
653       
654       uint64_t AlignedOffset = RoundUpToAlignment(Offset, AF.getAlignment());
655       uint64_t PaddingBytes = AlignedOffset - Offset;
656
657       if (PaddingBytes > AF.getMaxBytesToEmit())
658         AF.setFileSize(0);
659       else
660         AF.setFileSize(PaddingBytes);
661       break;
662     }
663
664     case MCFragment::FT_Data:
665     case MCFragment::FT_Fill:
666       F.setFileSize(F.getMaxFileSize());
667       break;
668
669     case MCFragment::FT_Org: {
670       MCOrgFragment &OF = cast<MCOrgFragment>(F);
671
672       if (!OF.getOffset().isAbsolute())
673         llvm_unreachable("FIXME: Not yet implemented!");
674       uint64_t OrgOffset = OF.getOffset().getConstant();
675
676       // FIXME: We need a way to communicate this error.
677       if (OrgOffset < Offset)
678         llvm_report_error("invalid .org offset '" + Twine(OrgOffset) + 
679                           "' (section offset '" + Twine(Offset) + "'");
680         
681       F.setFileSize(OrgOffset - Offset);
682       break;
683     }      
684     }
685
686     Offset += F.getFileSize();
687   }
688
689   // FIXME: Pad section?
690   SD.setFileSize(Offset);
691 }
692
693 /// WriteFileData - Write the \arg F data to the output file.
694 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
695                           MachObjectWriter &MOW) {
696   uint64_t Start = OS.tell();
697   (void) Start;
698     
699   ++EmittedFragments;
700
701   // FIXME: Embed in fragments instead?
702   switch (F.getKind()) {
703   case MCFragment::FT_Align: {
704     MCAlignFragment &AF = cast<MCAlignFragment>(F);
705     uint64_t Count = AF.getFileSize() / AF.getValueSize();
706
707     // FIXME: This error shouldn't actually occur (the front end should emit
708     // multiple .align directives to enforce the semantics it wants), but is
709     // severe enough that we want to report it. How to handle this?
710     if (Count * AF.getValueSize() != AF.getFileSize())
711       llvm_report_error("undefined .align directive, value size '" + 
712                         Twine(AF.getValueSize()) + 
713                         "' is not a divisor of padding size '" +
714                         Twine(AF.getFileSize()) + "'");
715
716     for (uint64_t i = 0; i != Count; ++i) {
717       switch (AF.getValueSize()) {
718       default:
719         assert(0 && "Invalid size!");
720       case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
721       case 2: MOW.Write16(uint16_t(AF.getValue())); break;
722       case 4: MOW.Write32(uint32_t(AF.getValue())); break;
723       case 8: MOW.Write64(uint64_t(AF.getValue())); break;
724       }
725     }
726     break;
727   }
728
729   case MCFragment::FT_Data:
730     OS << cast<MCDataFragment>(F).getContents().str();
731     break;
732
733   case MCFragment::FT_Fill: {
734     MCFillFragment &FF = cast<MCFillFragment>(F);
735
736     if (!FF.getValue().isAbsolute())
737       llvm_unreachable("FIXME: Not yet implemented!");
738     int64_t Value = FF.getValue().getConstant();
739
740     for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
741       switch (FF.getValueSize()) {
742       default:
743         assert(0 && "Invalid size!");
744       case 1: MOW.Write8 (uint8_t (Value)); break;
745       case 2: MOW.Write16(uint16_t(Value)); break;
746       case 4: MOW.Write32(uint32_t(Value)); break;
747       case 8: MOW.Write64(uint64_t(Value)); break;
748       }
749     }
750     break;
751   }
752     
753   case MCFragment::FT_Org: {
754     MCOrgFragment &OF = cast<MCOrgFragment>(F);
755
756     for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
757       MOW.Write8(uint8_t(OF.getValue()));
758
759     break;
760   }
761   }
762
763   assert(OS.tell() - Start == F.getFileSize());
764 }
765
766 /// WriteFileData - Write the \arg SD data to the output file.
767 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
768                           MachObjectWriter &MOW) {
769   uint64_t Start = OS.tell();
770   (void) Start;
771       
772   for (MCSectionData::const_iterator it = SD.begin(),
773          ie = SD.end(); it != ie; ++it)
774     WriteFileData(OS, *it, MOW);
775
776   assert(OS.tell() - Start == SD.getFileSize());
777 }
778
779 void MCAssembler::Finish() {
780   // Layout the sections and fragments.
781   for (iterator it = begin(), ie = end(); it != ie; ++it)
782     LayoutSection(*it);
783
784   // Write the object file.
785   MachObjectWriter MOW(OS);
786   MOW.WriteObject(*this);
787
788   OS.flush();
789 }