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