llvm-mc: Support .zerofill emission.
[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 /// isVirtualSection - Check if this is a section which does not actually exist
32 /// in the object file.
33 static bool isVirtualSection(const MCSection &Section) {
34   // FIXME: Lame.
35   const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
36   unsigned Type = SMO.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
37   return (Type == MCSectionMachO::S_ZEROFILL);
38 }
39
40 class MachObjectWriter {
41   // See <mach-o/loader.h>.
42   enum {
43     Header_Magic32 = 0xFEEDFACE,
44     Header_Magic64 = 0xFEEDFACF
45   };
46   
47   static const unsigned Header32Size = 28;
48   static const unsigned Header64Size = 32;
49   static const unsigned SegmentLoadCommand32Size = 56;
50   static const unsigned Section32Size = 68;
51   static const unsigned SymtabLoadCommandSize = 24;
52   static const unsigned DysymtabLoadCommandSize = 80;
53   static const unsigned Nlist32Size = 12;
54   static const unsigned RelocationInfoSize = 8;
55
56   enum HeaderFileType {
57     HFT_Object = 0x1
58   };
59
60   enum HeaderFlags {
61     HF_SubsectionsViaSymbols = 0x2000
62   };
63
64   enum LoadCommandType {
65     LCT_Segment = 0x1,
66     LCT_Symtab = 0x2,
67     LCT_Dysymtab = 0xb
68   };
69
70   // See <mach-o/nlist.h>.
71   enum SymbolTypeType {
72     STT_Undefined = 0x00,
73     STT_Absolute  = 0x02,
74     STT_Section   = 0x0e
75   };
76
77   enum SymbolTypeFlags {
78     // If any of these bits are set, then the entry is a stab entry number (see
79     // <mach-o/stab.h>. Otherwise the other masks apply.
80     STF_StabsEntryMask = 0xe0,
81
82     STF_TypeMask       = 0x0e,
83     STF_External       = 0x01,
84     STF_PrivateExtern  = 0x10
85   };
86
87   /// IndirectSymbolFlags - Flags for encoding special values in the indirect
88   /// symbol entry.
89   enum IndirectSymbolFlags {
90     ISF_Local    = 0x80000000,
91     ISF_Absolute = 0x40000000
92   };
93
94   /// RelocationFlags - Special flags for addresses.
95   enum RelocationFlags {
96     RF_Scattered = 0x80000000
97   };
98
99   enum RelocationInfoType {
100     RIT_Vanilla             = 0,
101     RIT_Pair                = 1,
102     RIT_Difference          = 2,
103     RIT_PreboundLazyPointer = 3,
104     RIT_LocalDifference     = 4
105   };
106
107   /// MachSymbolData - Helper struct for containing some precomputed information
108   /// on symbols.
109   struct MachSymbolData {
110     MCSymbolData *SymbolData;
111     uint64_t StringIndex;
112     uint8_t SectionIndex;
113
114     // Support lexicographic sorting.
115     bool operator<(const MachSymbolData &RHS) const {
116       const std::string &Name = SymbolData->getSymbol().getName();
117       return Name < RHS.SymbolData->getSymbol().getName();
118     }
119   };
120
121   raw_ostream &OS;
122   bool IsLSB;
123
124 public:
125   MachObjectWriter(raw_ostream &_OS, bool _IsLSB = true) 
126     : OS(_OS), IsLSB(_IsLSB) {
127   }
128
129   /// @name Helper Methods
130   /// @{
131
132   void Write8(uint8_t Value) {
133     OS << char(Value);
134   }
135
136   void Write16(uint16_t Value) {
137     if (IsLSB) {
138       Write8(uint8_t(Value >> 0));
139       Write8(uint8_t(Value >> 8));
140     } else {
141       Write8(uint8_t(Value >> 8));
142       Write8(uint8_t(Value >> 0));
143     }
144   }
145
146   void Write32(uint32_t Value) {
147     if (IsLSB) {
148       Write16(uint16_t(Value >> 0));
149       Write16(uint16_t(Value >> 16));
150     } else {
151       Write16(uint16_t(Value >> 16));
152       Write16(uint16_t(Value >> 0));
153     }
154   }
155
156   void Write64(uint64_t Value) {
157     if (IsLSB) {
158       Write32(uint32_t(Value >> 0));
159       Write32(uint32_t(Value >> 32));
160     } else {
161       Write32(uint32_t(Value >> 32));
162       Write32(uint32_t(Value >> 0));
163     }
164   }
165
166   void WriteZeros(unsigned N) {
167     const char Zeros[16] = { 0 };
168     
169     for (unsigned i = 0, e = N / 16; i != e; ++i)
170       OS << StringRef(Zeros, 16);
171     
172     OS << StringRef(Zeros, N % 16);
173   }
174
175   void WriteString(const StringRef &Str, unsigned ZeroFillSize = 0) {
176     OS << Str;
177     if (ZeroFillSize)
178       WriteZeros(ZeroFillSize - Str.size());
179   }
180
181   /// @}
182   
183   void WriteHeader32(unsigned NumLoadCommands, unsigned LoadCommandsSize,
184                      bool SubsectionsViaSymbols) {
185     uint32_t Flags = 0;
186
187     if (SubsectionsViaSymbols)
188       Flags |= HF_SubsectionsViaSymbols;
189
190     // struct mach_header (28 bytes)
191
192     uint64_t Start = OS.tell();
193     (void) Start;
194
195     Write32(Header_Magic32);
196
197     // FIXME: Support cputype.
198     Write32(TargetMachOWriterInfo::HDR_CPU_TYPE_I386);
199     // FIXME: Support cpusubtype.
200     Write32(TargetMachOWriterInfo::HDR_CPU_SUBTYPE_I386_ALL);
201     Write32(HFT_Object);
202     Write32(NumLoadCommands);    // Object files have a single load command, the
203                                  // segment.
204     Write32(LoadCommandsSize);
205     Write32(Flags);
206
207     assert(OS.tell() - Start == Header32Size);
208   }
209
210   /// WriteSegmentLoadCommand32 - Write a 32-bit segment load command.
211   ///
212   /// \arg NumSections - The number of sections in this segment.
213   /// \arg SectionDataSize - The total size of the sections.
214   void WriteSegmentLoadCommand32(unsigned NumSections,
215                                  uint64_t VMSize,
216                                  uint64_t SectionDataStartOffset,
217                                  uint64_t SectionDataSize) {
218     // struct segment_command (56 bytes)
219
220     uint64_t Start = OS.tell();
221     (void) Start;
222
223     Write32(LCT_Segment);
224     Write32(SegmentLoadCommand32Size + NumSections * Section32Size);
225
226     WriteString("", 16);
227     Write32(0); // vmaddr
228     Write32(VMSize); // vmsize
229     Write32(SectionDataStartOffset); // file offset
230     Write32(SectionDataSize); // file size
231     Write32(0x7); // maxprot
232     Write32(0x7); // initprot
233     Write32(NumSections);
234     Write32(0); // flags
235
236     assert(OS.tell() - Start == SegmentLoadCommand32Size);
237   }
238
239   void WriteSection32(const MCSectionData &SD, uint64_t FileOffset,
240                       uint64_t RelocationsStart, unsigned NumRelocations) {
241     // The offset is unused for virtual sections.
242     if (isVirtualSection(SD.getSection())) {
243       assert(SD.getFileSize() == 0 && "Invalid file size!");
244       FileOffset = 0;
245     }
246
247     // struct section (68 bytes)
248
249     uint64_t Start = OS.tell();
250     (void) Start;
251
252     // FIXME: cast<> support!
253     const MCSectionMachO &Section =
254       static_cast<const MCSectionMachO&>(SD.getSection());
255     WriteString(Section.getSectionName(), 16);
256     WriteString(Section.getSegmentName(), 16);
257     Write32(SD.getAddress()); // address
258     Write32(SD.getSize()); // size
259     Write32(FileOffset);
260
261     assert(isPowerOf2_32(SD.getAlignment()) && "Invalid alignment!");
262     Write32(Log2_32(SD.getAlignment()));
263     Write32(NumRelocations ? RelocationsStart : 0);
264     Write32(NumRelocations);
265     Write32(Section.getTypeAndAttributes());
266     Write32(0); // reserved1
267     Write32(Section.getStubSize()); // reserved2
268
269     assert(OS.tell() - Start == Section32Size);
270   }
271
272   void WriteSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
273                               uint32_t StringTableOffset,
274                               uint32_t StringTableSize) {
275     // struct symtab_command (24 bytes)
276
277     uint64_t Start = OS.tell();
278     (void) Start;
279
280     Write32(LCT_Symtab);
281     Write32(SymtabLoadCommandSize);
282     Write32(SymbolOffset);
283     Write32(NumSymbols);
284     Write32(StringTableOffset);
285     Write32(StringTableSize);
286
287     assert(OS.tell() - Start == SymtabLoadCommandSize);
288   }
289
290   void WriteDysymtabLoadCommand(uint32_t FirstLocalSymbol,
291                                 uint32_t NumLocalSymbols,
292                                 uint32_t FirstExternalSymbol,
293                                 uint32_t NumExternalSymbols,
294                                 uint32_t FirstUndefinedSymbol,
295                                 uint32_t NumUndefinedSymbols,
296                                 uint32_t IndirectSymbolOffset,
297                                 uint32_t NumIndirectSymbols) {
298     // struct dysymtab_command (80 bytes)
299
300     uint64_t Start = OS.tell();
301     (void) Start;
302
303     Write32(LCT_Dysymtab);
304     Write32(DysymtabLoadCommandSize);
305     Write32(FirstLocalSymbol);
306     Write32(NumLocalSymbols);
307     Write32(FirstExternalSymbol);
308     Write32(NumExternalSymbols);
309     Write32(FirstUndefinedSymbol);
310     Write32(NumUndefinedSymbols);
311     Write32(0); // tocoff
312     Write32(0); // ntoc
313     Write32(0); // modtaboff
314     Write32(0); // nmodtab
315     Write32(0); // extrefsymoff
316     Write32(0); // nextrefsyms
317     Write32(IndirectSymbolOffset);
318     Write32(NumIndirectSymbols);
319     Write32(0); // extreloff
320     Write32(0); // nextrel
321     Write32(0); // locreloff
322     Write32(0); // nlocrel
323
324     assert(OS.tell() - Start == DysymtabLoadCommandSize);
325   }
326
327   void WriteNlist32(MachSymbolData &MSD) {
328     MCSymbolData &Data = *MSD.SymbolData;
329     MCSymbol &Symbol = Data.getSymbol();
330     uint8_t Type = 0;
331
332     // Set the N_TYPE bits. See <mach-o/nlist.h>.
333     //
334     // FIXME: Are the prebound or indirect fields possible here?
335     if (Symbol.isUndefined())
336       Type = STT_Undefined;
337     else if (Symbol.isAbsolute())
338       Type = STT_Absolute;
339     else
340       Type = STT_Section;
341
342     // FIXME: Set STAB bits.
343
344     if (Data.isPrivateExtern())
345       Type |= STF_PrivateExtern;
346
347     // Set external bit.
348     if (Data.isExternal() || Symbol.isUndefined())
349       Type |= STF_External;
350
351     // struct nlist (12 bytes)
352
353     Write32(MSD.StringIndex);
354     Write8(Type);
355     Write8(MSD.SectionIndex);
356     
357     // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
358     // value.
359     Write16(Data.getFlags() & 0xFFFF);
360
361     // Write the symbol address.
362     uint32_t Address = 0;
363     if (Symbol.isDefined()) {
364       if (Symbol.isAbsolute()) {
365         llvm_unreachable("FIXME: Not yet implemented!");
366       } else {
367         Address = Data.getFragment()->getAddress() + Data.getOffset();
368       }
369     }
370     Write32(Address);
371   }
372
373   struct MachRelocationEntry {
374     uint32_t Word0;
375     uint32_t Word1;
376   };
377   void ComputeScatteredRelocationInfo(MCAssembler &Asm,
378                                       MCSectionData::Fixup &Fixup,
379                              DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
380                                      std::vector<MachRelocationEntry> &Relocs) {
381     uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
382     unsigned IsPCRel = 0;
383     unsigned Type = RIT_Vanilla;
384
385     // See <reloc.h>.
386
387     const MCSymbol *A = Fixup.Value.getSymA();
388     MCSymbolData *SD = SymbolMap.lookup(A);
389     uint32_t Value = SD->getFragment()->getAddress() + SD->getOffset();
390     uint32_t Value2 = 0;
391
392     if (const MCSymbol *B = Fixup.Value.getSymB()) {
393       Type = RIT_LocalDifference;
394
395       MCSymbolData *SD = SymbolMap.lookup(B);
396       Value2 = SD->getFragment()->getAddress() + SD->getOffset();
397     }
398
399     unsigned Log2Size = Log2_32(Fixup.Size);
400     assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
401
402     // The value which goes in the fixup is current value of the expression.
403     Fixup.FixedValue = Value - Value2 + Fixup.Value.getConstant();
404
405     MachRelocationEntry MRE;
406     MRE.Word0 = ((Address   <<  0) |
407                  (Type      << 24) |
408                  (Log2Size  << 28) |
409                  (IsPCRel   << 30) |
410                  RF_Scattered);
411     MRE.Word1 = Value;
412     Relocs.push_back(MRE);
413
414     if (Type == RIT_LocalDifference) {
415       Type = RIT_Pair;
416
417       MachRelocationEntry MRE;
418       MRE.Word0 = ((0         <<  0) |
419                    (Type      << 24) |
420                    (Log2Size  << 28) |
421                    (0   << 30) |
422                    RF_Scattered);
423       MRE.Word1 = Value2;
424       Relocs.push_back(MRE);
425     }
426   }
427
428   void ComputeRelocationInfo(MCAssembler &Asm,
429                              MCSectionData::Fixup &Fixup,
430                              DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap,
431                              std::vector<MachRelocationEntry> &Relocs) {
432     // If this is a local symbol plus an offset or a difference, then we need a
433     // scattered relocation entry.
434     if (Fixup.Value.getSymB()) // a - b
435       return ComputeScatteredRelocationInfo(Asm, Fixup, SymbolMap, Relocs);
436     if (Fixup.Value.getSymA() && Fixup.Value.getConstant())
437       if (!Fixup.Value.getSymA()->isUndefined())
438         return ComputeScatteredRelocationInfo(Asm, Fixup, SymbolMap, Relocs);
439         
440     // See <reloc.h>.
441     uint32_t Address = Fixup.Fragment->getOffset() + Fixup.Offset;
442     uint32_t Value = 0;
443     unsigned Index = 0;
444     unsigned IsPCRel = 0;
445     unsigned IsExtern = 0;
446     unsigned Type = 0;
447
448     if (Fixup.Value.isAbsolute()) { // constant
449       // SymbolNum of 0 indicates the absolute section.
450       Type = RIT_Vanilla;
451       Value = 0;
452       llvm_unreachable("FIXME: Not yet implemented!");
453     } else {
454       const MCSymbol *Symbol = Fixup.Value.getSymA();
455       MCSymbolData *SD = SymbolMap.lookup(Symbol);
456       
457       if (Symbol->isUndefined()) {
458         IsExtern = 1;
459         Index = SD->getIndex();
460         Value = 0;
461       } else {
462         // The index is the section ordinal.
463         //
464         // FIXME: O(N)
465         Index = 1;
466         for (MCAssembler::iterator it = Asm.begin(),
467                ie = Asm.end(); it != ie; ++it, ++Index)
468           if (&*it == SD->getFragment()->getParent())
469             break;
470         Value = SD->getFragment()->getAddress() + SD->getOffset();
471       }
472
473       Type = RIT_Vanilla;
474     }
475
476     // The value which goes in the fixup is current value of the expression.
477     Fixup.FixedValue = Value + Fixup.Value.getConstant();
478
479     unsigned Log2Size = Log2_32(Fixup.Size);
480     assert((1U << Log2Size) == Fixup.Size && "Invalid fixup size!");
481
482     // struct relocation_info (8 bytes)
483     MachRelocationEntry MRE;
484     MRE.Word0 = Address;
485     MRE.Word1 = ((Index     <<  0) |
486                  (IsPCRel   << 24) |
487                  (Log2Size  << 25) |
488                  (IsExtern  << 27) |
489                  (Type      << 28));
490     Relocs.push_back(MRE);
491   }
492   
493   void BindIndirectSymbols(MCAssembler &Asm,
494                            DenseMap<const MCSymbol*,MCSymbolData*> &SymbolMap) {
495     // This is the point where 'as' creates actual symbols for indirect symbols
496     // (in the following two passes). It would be easier for us to do this
497     // sooner when we see the attribute, but that makes getting the order in the
498     // symbol table much more complicated than it is worth.
499     //
500     // FIXME: Revisit this when the dust settles.
501
502     // Bind non lazy symbol pointers first.
503     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
504            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
505       // FIXME: cast<> support!
506       const MCSectionMachO &Section =
507         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
508
509       unsigned Type =
510         Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
511       if (Type != MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS)
512         continue;
513
514       MCSymbolData *&Entry = SymbolMap[it->Symbol];
515       if (!Entry)
516         Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
517     }
518
519     // Then lazy symbol pointers and symbol stubs.
520     for (MCAssembler::indirect_symbol_iterator it = Asm.indirect_symbol_begin(),
521            ie = Asm.indirect_symbol_end(); it != ie; ++it) {
522       // FIXME: cast<> support!
523       const MCSectionMachO &Section =
524         static_cast<const MCSectionMachO&>(it->SectionData->getSection());
525
526       unsigned Type =
527         Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
528       if (Type != MCSectionMachO::S_LAZY_SYMBOL_POINTERS &&
529           Type != MCSectionMachO::S_SYMBOL_STUBS)
530         continue;
531
532       MCSymbolData *&Entry = SymbolMap[it->Symbol];
533       if (!Entry) {
534         Entry = new MCSymbolData(*it->Symbol, 0, 0, &Asm);
535
536         // Set the symbol type to undefined lazy, but only on construction.
537         //
538         // FIXME: Do not hardcode.
539         Entry->setFlags(Entry->getFlags() | 0x0001);
540       }
541     }
542   }
543
544   /// ComputeSymbolTable - Compute the symbol table data
545   ///
546   /// \param StringTable [out] - The string table data.
547   /// \param StringIndexMap [out] - Map from symbol names to offsets in the
548   /// string table.
549   void ComputeSymbolTable(MCAssembler &Asm, SmallString<256> &StringTable,
550                           std::vector<MachSymbolData> &LocalSymbolData,
551                           std::vector<MachSymbolData> &ExternalSymbolData,
552                           std::vector<MachSymbolData> &UndefinedSymbolData) {
553     // Build section lookup table.
554     DenseMap<const MCSection*, uint8_t> SectionIndexMap;
555     unsigned Index = 1;
556     for (MCAssembler::iterator it = Asm.begin(),
557            ie = Asm.end(); it != ie; ++it, ++Index)
558       SectionIndexMap[&it->getSection()] = Index;
559     assert(Index <= 256 && "Too many sections!");
560
561     // Index 0 is always the empty string.
562     StringMap<uint64_t> StringIndexMap;
563     StringTable += '\x00';
564
565     // Build the symbol arrays and the string table, but only for non-local
566     // symbols.
567     //
568     // The particular order that we collect the symbols and create the string
569     // table, then sort the symbols is chosen to match 'as'. Even though it
570     // doesn't matter for correctness, this is important for letting us diff .o
571     // files.
572     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
573            ie = Asm.symbol_end(); it != ie; ++it) {
574       MCSymbol &Symbol = it->getSymbol();
575
576       // Ignore assembler temporaries.
577       if (it->getSymbol().isTemporary())
578         continue;
579
580       if (!it->isExternal() && !Symbol.isUndefined())
581         continue;
582
583       uint64_t &Entry = StringIndexMap[Symbol.getName()];
584       if (!Entry) {
585         Entry = StringTable.size();
586         StringTable += Symbol.getName();
587         StringTable += '\x00';
588       }
589
590       MachSymbolData MSD;
591       MSD.SymbolData = it;
592       MSD.StringIndex = Entry;
593
594       if (Symbol.isUndefined()) {
595         MSD.SectionIndex = 0;
596         UndefinedSymbolData.push_back(MSD);
597       } else if (Symbol.isAbsolute()) {
598         MSD.SectionIndex = 0;
599         ExternalSymbolData.push_back(MSD);
600       } else {
601         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
602         assert(MSD.SectionIndex && "Invalid section index!");
603         ExternalSymbolData.push_back(MSD);
604       }
605     }
606
607     // Now add the data for local symbols.
608     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
609            ie = Asm.symbol_end(); it != ie; ++it) {
610       MCSymbol &Symbol = it->getSymbol();
611
612       // Ignore assembler temporaries.
613       if (it->getSymbol().isTemporary())
614         continue;
615
616       if (it->isExternal() || Symbol.isUndefined())
617         continue;
618
619       uint64_t &Entry = StringIndexMap[Symbol.getName()];
620       if (!Entry) {
621         Entry = StringTable.size();
622         StringTable += Symbol.getName();
623         StringTable += '\x00';
624       }
625
626       MachSymbolData MSD;
627       MSD.SymbolData = it;
628       MSD.StringIndex = Entry;
629
630       if (Symbol.isAbsolute()) {
631         MSD.SectionIndex = 0;
632         LocalSymbolData.push_back(MSD);
633       } else {
634         MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
635         assert(MSD.SectionIndex && "Invalid section index!");
636         LocalSymbolData.push_back(MSD);
637       }
638     }
639
640     // External and undefined symbols are required to be in lexicographic order.
641     std::sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
642     std::sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
643
644     // Set the symbol indices.
645     Index = 0;
646     for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
647       LocalSymbolData[i].SymbolData->setIndex(Index++);
648     for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
649       ExternalSymbolData[i].SymbolData->setIndex(Index++);
650     for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
651       UndefinedSymbolData[i].SymbolData->setIndex(Index++);
652
653     // The string table is padded to a multiple of 4.
654     //
655     // FIXME: Check to see if this varies per arch.
656     while (StringTable.size() % 4)
657       StringTable += '\x00';
658   }
659
660   void WriteObject(MCAssembler &Asm) {
661     unsigned NumSections = Asm.size();
662
663     // Compute the symbol -> symbol data map.
664     //
665     // FIXME: This should not be here.
666     DenseMap<const MCSymbol*, MCSymbolData *> SymbolMap;
667     for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
668            ie = Asm.symbol_end(); it != ie; ++it)
669       SymbolMap[&it->getSymbol()] = it;
670
671     // Create symbol data for any indirect symbols.
672     BindIndirectSymbols(Asm, SymbolMap);
673
674     // Compute symbol table information.
675     SmallString<256> StringTable;
676     std::vector<MachSymbolData> LocalSymbolData;
677     std::vector<MachSymbolData> ExternalSymbolData;
678     std::vector<MachSymbolData> UndefinedSymbolData;
679     unsigned NumSymbols = Asm.symbol_size();
680
681     // No symbol table command is written if there are no symbols.
682     if (NumSymbols)
683       ComputeSymbolTable(Asm, StringTable, LocalSymbolData, ExternalSymbolData,
684                          UndefinedSymbolData);
685   
686     // The section data starts after the header, the segment load command (and
687     // section headers) and the symbol table.
688     unsigned NumLoadCommands = 1;
689     uint64_t LoadCommandsSize =
690       SegmentLoadCommand32Size + NumSections * Section32Size;
691
692     // Add the symbol table load command sizes, if used.
693     if (NumSymbols) {
694       NumLoadCommands += 2;
695       LoadCommandsSize += SymtabLoadCommandSize + DysymtabLoadCommandSize;
696     }
697
698     // Compute the total size of the section data, as well as its file size and
699     // vm size.
700     uint64_t SectionDataStart = Header32Size + LoadCommandsSize;
701     uint64_t SectionDataSize = 0;
702     uint64_t SectionDataFileSize = 0;
703     uint64_t VMSize = 0;
704     for (MCAssembler::iterator it = Asm.begin(),
705            ie = Asm.end(); it != ie; ++it) {
706       MCSectionData &SD = *it;
707
708       VMSize = std::max(VMSize, SD.getAddress() + SD.getSize());
709
710       if (isVirtualSection(SD.getSection()))
711         continue;
712
713       SectionDataSize = std::max(SectionDataSize,
714                                  SD.getAddress() + SD.getSize());
715       SectionDataFileSize = std::max(SectionDataFileSize, 
716                                      SD.getAddress() + SD.getFileSize());
717     }
718
719     // The section data is passed to 4 bytes.
720     //
721     // FIXME: Is this machine dependent?
722     unsigned SectionDataPadding = OffsetToAlignment(SectionDataFileSize, 4);
723     SectionDataFileSize += SectionDataPadding;
724
725     // Write the prolog, starting with the header and load command...
726     WriteHeader32(NumLoadCommands, LoadCommandsSize,
727                   Asm.getSubsectionsViaSymbols());
728     WriteSegmentLoadCommand32(NumSections, VMSize,
729                               SectionDataStart, SectionDataSize);
730   
731     // ... and then the section headers.
732     // 
733     // We also compute the section relocations while we do this. Note that
734     // compute relocation info will also update the fixup to have the correct
735     // value; this will be overwrite the appropriate data in the fragment when
736     // it is written.
737     std::vector<MachRelocationEntry> RelocInfos;
738     uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
739     for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie;
740          ++it) {
741       MCSectionData &SD = *it;
742
743       // The assembler writes relocations in the reverse order they were seen.
744       //
745       // FIXME: It is probably more complicated than this.
746       unsigned NumRelocsStart = RelocInfos.size();
747       for (unsigned i = 0, e = SD.fixup_size(); i != e; ++i)
748         ComputeRelocationInfo(Asm, SD.getFixups()[e - i - 1], SymbolMap,
749                               RelocInfos);
750
751       unsigned NumRelocs = RelocInfos.size() - NumRelocsStart;
752       uint64_t SectionStart = SectionDataStart + SD.getAddress();
753       WriteSection32(SD, SectionStart, RelocTableEnd, NumRelocs);
754       RelocTableEnd += NumRelocs * RelocationInfoSize;
755     }
756     
757     // Write the symbol table load command, if used.
758     if (NumSymbols) {
759       unsigned FirstLocalSymbol = 0;
760       unsigned NumLocalSymbols = LocalSymbolData.size();
761       unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
762       unsigned NumExternalSymbols = ExternalSymbolData.size();
763       unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
764       unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
765       unsigned NumIndirectSymbols = Asm.indirect_symbol_size();
766       unsigned NumSymTabSymbols =
767         NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
768       uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
769       uint64_t IndirectSymbolOffset = 0;
770
771       // If used, the indirect symbols are written after the section data.
772       if (NumIndirectSymbols)
773         IndirectSymbolOffset = RelocTableEnd;
774
775       // The symbol table is written after the indirect symbol data.
776       uint64_t SymbolTableOffset = RelocTableEnd + IndirectSymbolSize;
777
778       // The string table is written after symbol table.
779       uint64_t StringTableOffset =
780         SymbolTableOffset + NumSymTabSymbols * Nlist32Size;
781       WriteSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
782                              StringTableOffset, StringTable.size());
783
784       WriteDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
785                                FirstExternalSymbol, NumExternalSymbols,
786                                FirstUndefinedSymbol, NumUndefinedSymbols,
787                                IndirectSymbolOffset, NumIndirectSymbols);
788     }
789
790     // Write the actual section data.
791     for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it)
792       WriteFileData(OS, *it, *this);
793
794     // Write the extra padding.
795     WriteZeros(SectionDataPadding);
796
797     // Write the relocation entries.
798     for (unsigned i = 0, e = RelocInfos.size(); i != e; ++i) {
799       Write32(RelocInfos[i].Word0);
800       Write32(RelocInfos[i].Word1);
801     }
802
803     // Write the symbol table data, if used.
804     if (NumSymbols) {
805       // Write the indirect symbol entries.
806       for (MCAssembler::indirect_symbol_iterator
807              it = Asm.indirect_symbol_begin(),
808              ie = Asm.indirect_symbol_end(); it != ie; ++it) {
809         // Indirect symbols in the non lazy symbol pointer section have some
810         // special handling.
811         const MCSectionMachO &Section =
812           static_cast<const MCSectionMachO&>(it->SectionData->getSection());
813         unsigned Type =
814           Section.getTypeAndAttributes() & MCSectionMachO::SECTION_TYPE;
815         if (Type == MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS) {
816           // If this symbol is defined and internal, mark it as such.
817           if (it->Symbol->isDefined() &&
818               !SymbolMap.lookup(it->Symbol)->isExternal()) {
819             uint32_t Flags = ISF_Local;
820             if (it->Symbol->isAbsolute())
821               Flags |= ISF_Absolute;
822             Write32(Flags);
823             continue;
824           }
825         }
826
827         Write32(SymbolMap[it->Symbol]->getIndex());
828       }
829
830       // FIXME: Check that offsets match computed ones.
831
832       // Write the symbol table entries.
833       for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
834         WriteNlist32(LocalSymbolData[i]);
835       for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
836         WriteNlist32(ExternalSymbolData[i]);
837       for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
838         WriteNlist32(UndefinedSymbolData[i]);
839
840       // Write the string table.
841       OS << StringTable.str();
842     }
843   }
844 };
845
846 /* *** */
847
848 MCFragment::MCFragment() : Kind(FragmentType(~0)) {
849 }
850
851 MCFragment::MCFragment(FragmentType _Kind, MCSectionData *_Parent)
852   : Kind(_Kind),
853     Parent(_Parent),
854     FileSize(~UINT64_C(0))
855 {
856   if (Parent)
857     Parent->getFragmentList().push_back(this);
858 }
859
860 MCFragment::~MCFragment() {
861 }
862
863 uint64_t MCFragment::getAddress() const {
864   assert(getParent() && "Missing Section!");
865   return getParent()->getAddress() + Offset;
866 }
867
868 /* *** */
869
870 MCSectionData::MCSectionData() : Section(0) {}
871
872 MCSectionData::MCSectionData(const MCSection &_Section, MCAssembler *A)
873   : Section(&_Section),
874     Alignment(1),
875     Address(~UINT64_C(0)),
876     Size(~UINT64_C(0)),
877     FileSize(~UINT64_C(0)),
878     LastFixupLookup(~0)
879 {
880   if (A)
881     A->getSectionList().push_back(this);
882 }
883
884 const MCSectionData::Fixup *
885 MCSectionData::LookupFixup(const MCFragment *Fragment, uint64_t Offset) const {
886   // Use a one level cache to turn the common case of accessing the fixups in
887   // order into O(1) instead of O(N).
888   unsigned i = LastFixupLookup, Count = Fixups.size(), End = Fixups.size();
889   if (i >= End)
890     i = 0;
891   while (Count--) {
892     const Fixup &F = Fixups[i];
893     if (F.Fragment == Fragment && F.Offset == Offset) {
894       LastFixupLookup = i;
895       return &F;
896     }
897
898     ++i;
899     if (i == End)
900       i = 0;
901   }
902
903   return 0;
904 }
905                                                        
906 /* *** */
907
908 MCSymbolData::MCSymbolData() : Symbol(*(MCSymbol*)0) {}
909
910 MCSymbolData::MCSymbolData(MCSymbol &_Symbol, MCFragment *_Fragment,
911                            uint64_t _Offset, MCAssembler *A)
912   : Symbol(_Symbol), Fragment(_Fragment), Offset(_Offset),
913     IsExternal(false), IsPrivateExtern(false), Flags(0), Index(0)
914 {
915   if (A)
916     A->getSymbolList().push_back(this);
917 }
918
919 /* *** */
920
921 MCAssembler::MCAssembler(raw_ostream &_OS)
922   : OS(_OS),
923     SubsectionsViaSymbols(false)
924 {
925 }
926
927 MCAssembler::~MCAssembler() {
928 }
929
930 void MCAssembler::LayoutSection(MCSectionData &SD) {
931   uint64_t Address = SD.getAddress();
932
933   for (MCSectionData::iterator it = SD.begin(), ie = SD.end(); it != ie; ++it) {
934     MCFragment &F = *it;
935
936     F.setOffset(Address - SD.getAddress());
937
938     // Evaluate fragment size.
939     switch (F.getKind()) {
940     case MCFragment::FT_Align: {
941       MCAlignFragment &AF = cast<MCAlignFragment>(F);
942       
943       uint64_t Size = OffsetToAlignment(Address, AF.getAlignment());
944       if (Size > AF.getMaxBytesToEmit())
945         AF.setFileSize(0);
946       else
947         AF.setFileSize(Size);
948       break;
949     }
950
951     case MCFragment::FT_Data:
952       F.setFileSize(F.getMaxFileSize());
953       break;
954
955     case MCFragment::FT_Fill: {
956       MCFillFragment &FF = cast<MCFillFragment>(F);
957
958       F.setFileSize(F.getMaxFileSize());
959
960       // If the fill value is constant, thats it.
961       if (FF.getValue().isAbsolute())
962         break;
963
964       // Otherwise, add fixups for the values.
965       for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
966         MCSectionData::Fixup Fix(F, i * FF.getValueSize(),
967                                  FF.getValue(),FF.getValueSize());
968         SD.getFixups().push_back(Fix);
969       }
970       break;
971     }
972
973     case MCFragment::FT_Org: {
974       MCOrgFragment &OF = cast<MCOrgFragment>(F);
975
976       if (!OF.getOffset().isAbsolute())
977         llvm_unreachable("FIXME: Not yet implemented!");
978       uint64_t OrgOffset = OF.getOffset().getConstant();
979       uint64_t Offset = Address - SD.getAddress();
980
981       // FIXME: We need a way to communicate this error.
982       if (OrgOffset < Offset)
983         llvm_report_error("invalid .org offset '" + Twine(OrgOffset) + 
984                           "' (at offset '" + Twine(Offset) + "'");
985         
986       F.setFileSize(OrgOffset - Offset);
987       break;
988     }      
989
990     case MCFragment::FT_ZeroFill: {
991       MCZeroFillFragment &ZFF = cast<MCZeroFillFragment>(F);
992
993       // Align the fragment offset; it is safe to adjust the offset freely since
994       // this is only in virtual sections.
995       uint64_t Aligned = RoundUpToAlignment(Address, ZFF.getAlignment());
996       F.setOffset(Aligned - SD.getAddress());
997
998       // FIXME: This is misnamed.
999       F.setFileSize(ZFF.getSize());
1000       break;
1001     }
1002     }
1003
1004     Address += F.getFileSize();
1005   }
1006
1007   // Set the section sizes.
1008   SD.setSize(Address - SD.getAddress());
1009   if (isVirtualSection(SD.getSection()))
1010     SD.setFileSize(0);
1011   else
1012     SD.setFileSize(Address - SD.getAddress());
1013 }
1014
1015 /// WriteFileData - Write the \arg F data to the output file.
1016 static void WriteFileData(raw_ostream &OS, const MCFragment &F,
1017                           MachObjectWriter &MOW) {
1018   uint64_t Start = OS.tell();
1019   (void) Start;
1020     
1021   ++EmittedFragments;
1022
1023   // FIXME: Embed in fragments instead?
1024   switch (F.getKind()) {
1025   case MCFragment::FT_Align: {
1026     MCAlignFragment &AF = cast<MCAlignFragment>(F);
1027     uint64_t Count = AF.getFileSize() / AF.getValueSize();
1028
1029     // FIXME: This error shouldn't actually occur (the front end should emit
1030     // multiple .align directives to enforce the semantics it wants), but is
1031     // severe enough that we want to report it. How to handle this?
1032     if (Count * AF.getValueSize() != AF.getFileSize())
1033       llvm_report_error("undefined .align directive, value size '" + 
1034                         Twine(AF.getValueSize()) + 
1035                         "' is not a divisor of padding size '" +
1036                         Twine(AF.getFileSize()) + "'");
1037
1038     for (uint64_t i = 0; i != Count; ++i) {
1039       switch (AF.getValueSize()) {
1040       default:
1041         assert(0 && "Invalid size!");
1042       case 1: MOW.Write8 (uint8_t (AF.getValue())); break;
1043       case 2: MOW.Write16(uint16_t(AF.getValue())); break;
1044       case 4: MOW.Write32(uint32_t(AF.getValue())); break;
1045       case 8: MOW.Write64(uint64_t(AF.getValue())); break;
1046       }
1047     }
1048     break;
1049   }
1050
1051   case MCFragment::FT_Data:
1052     OS << cast<MCDataFragment>(F).getContents().str();
1053     break;
1054
1055   case MCFragment::FT_Fill: {
1056     MCFillFragment &FF = cast<MCFillFragment>(F);
1057
1058     int64_t Value = 0;
1059     if (FF.getValue().isAbsolute())
1060       Value = FF.getValue().getConstant();
1061     for (uint64_t i = 0, e = FF.getCount(); i != e; ++i) {
1062       if (!FF.getValue().isAbsolute()) {
1063         // Find the fixup.
1064         //
1065         // FIXME: Find a better way to write in the fixes.
1066         const MCSectionData::Fixup *Fixup =
1067           F.getParent()->LookupFixup(&F, i * FF.getValueSize());
1068         assert(Fixup && "Missing fixup for fill value!");
1069         Value = Fixup->FixedValue;
1070       }
1071
1072       switch (FF.getValueSize()) {
1073       default:
1074         assert(0 && "Invalid size!");
1075       case 1: MOW.Write8 (uint8_t (Value)); break;
1076       case 2: MOW.Write16(uint16_t(Value)); break;
1077       case 4: MOW.Write32(uint32_t(Value)); break;
1078       case 8: MOW.Write64(uint64_t(Value)); break;
1079       }
1080     }
1081     break;
1082   }
1083     
1084   case MCFragment::FT_Org: {
1085     MCOrgFragment &OF = cast<MCOrgFragment>(F);
1086
1087     for (uint64_t i = 0, e = OF.getFileSize(); i != e; ++i)
1088       MOW.Write8(uint8_t(OF.getValue()));
1089
1090     break;
1091   }
1092
1093   case MCFragment::FT_ZeroFill: {
1094     assert(0 && "Invalid zero fill fragment in concrete section!");
1095     break;
1096   }
1097   }
1098
1099   assert(OS.tell() - Start == F.getFileSize());
1100 }
1101
1102 /// WriteFileData - Write the \arg SD data to the output file.
1103 static void WriteFileData(raw_ostream &OS, const MCSectionData &SD,
1104                           MachObjectWriter &MOW) {
1105   // Ignore virtual sections.
1106   if (isVirtualSection(SD.getSection())) {
1107     assert(SD.getFileSize() == 0);
1108     return;
1109   }
1110
1111   uint64_t Start = OS.tell();
1112   (void) Start;
1113       
1114   for (MCSectionData::const_iterator it = SD.begin(),
1115          ie = SD.end(); it != ie; ++it)
1116     WriteFileData(OS, *it, MOW);
1117
1118   // Add section padding.
1119   assert(SD.getFileSize() >= SD.getSize() && "Invalid section sizes!");
1120   MOW.WriteZeros(SD.getFileSize() - SD.getSize());
1121
1122   assert(OS.tell() - Start == SD.getFileSize());
1123 }
1124
1125 void MCAssembler::Finish() {
1126   // Layout the concrete sections and fragments.
1127   uint64_t Address = 0;
1128   MCSectionData *Prev = 0;
1129   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1130     MCSectionData &SD = *it;
1131
1132     // Skip virtual sections.
1133     if (isVirtualSection(SD.getSection()))
1134       continue;
1135
1136     // Align this section if necessary by adding padding bytes to the previous
1137     // section.
1138     if (uint64_t Pad = OffsetToAlignment(Address, it->getAlignment())) {
1139       assert(Prev && "Missing prev section!");
1140       Prev->setFileSize(Prev->getFileSize() + Pad);
1141       Address += Pad;
1142     }
1143
1144     // Layout the section fragments and its size.
1145     SD.setAddress(Address);
1146     LayoutSection(SD);
1147     Address += SD.getFileSize();
1148
1149     Prev = &SD;
1150   }
1151
1152   // Layout the virtual sections.
1153   for (iterator it = begin(), ie = end(); it != ie; ++it) {
1154     MCSectionData &SD = *it;
1155
1156     if (!isVirtualSection(SD.getSection()))
1157       continue;
1158
1159     SD.setAddress(Address);
1160     LayoutSection(SD);
1161     Address += SD.getSize();
1162   }
1163
1164   // Write the object file.
1165   MachObjectWriter MOW(OS);
1166   MOW.WriteObject(*this);
1167
1168   OS.flush();
1169 }