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