An even better unbreakage...
[oota-llvm.git] / include / llvm / CodeGen / MachOWriter.h
1 //=== MachOWriter.h - Target-independent Mach-O writer support --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Nate Begeman and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the MachOWriter class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CODEGEN_MACHOWRITER_H
15 #define LLVM_CODEGEN_MACHOWRITER_H
16
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineRelocation.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Target/TargetMachine.h"
22
23 namespace llvm {
24   class GlobalVariable;
25   class Mangler;
26   class MachineCodeEmitter;
27   class MachOCodeEmitter;
28
29   /// MachOSym - This struct contains information about each symbol that is
30   /// added to logical symbol table for the module.  This is eventually
31   /// turned into a real symbol table in the file.
32   struct MachOSym {
33     const GlobalValue *GV;    // The global value this corresponds to.
34     std::string GVName;       // The mangled name of the global value.
35     uint32_t    n_strx;       // index into the string table
36     uint8_t     n_type;       // type flag
37     uint8_t     n_sect;       // section number or NO_SECT
38     int16_t     n_desc;       // see <mach-o/stab.h>
39     uint64_t    n_value;      // value for this symbol (or stab offset)
40     
41     // Constants for the n_sect field
42     // see <mach-o/nlist.h>
43     enum { NO_SECT = 0 };   // symbol is not in any section
44
45     // Constants for the n_type field
46     // see <mach-o/nlist.h>
47     enum { N_UNDF  = 0x0,  // undefined, n_sect == NO_SECT
48            N_ABS   = 0x2,  // absolute, n_sect == NO_SECT
49            N_SECT  = 0xe,  // defined in section number n_sect
50            N_PBUD  = 0xc,  // prebound undefined (defined in a dylib)
51            N_INDR  = 0xa   // indirect
52     };
53     // The following bits are OR'd into the types above. For example, a type
54     // of 0x0f would be an external N_SECT symbol (0x0e | 0x01).
55     enum { N_EXT  = 0x01,   // external symbol bit
56            N_PEXT = 0x10    // private external symbol bit
57     };
58     
59     // Constants for the n_desc field
60     // see <mach-o/loader.h>
61     enum { REFERENCE_FLAG_UNDEFINED_NON_LAZY          = 0,
62            REFERENCE_FLAG_UNDEFINED_LAZY              = 1,
63            REFERENCE_FLAG_DEFINED                     = 2,
64            REFERENCE_FLAG_PRIVATE_DEFINED             = 3,
65            REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY  = 4,
66            REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY      = 5
67     };
68     enum { N_NO_DEAD_STRIP = 0x0020, // symbol is not to be dead stripped
69            N_WEAK_REF      = 0x0040, // symbol is weak referenced
70            N_WEAK_DEF      = 0x0080  // coalesced symbol is a weak definition
71     };
72     
73     MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
74              TargetMachine &TM);
75   };
76       
77   /// MachOWriter - This class implements the common target-independent code for
78   /// writing Mach-O files.  Targets should derive a class from this to
79   /// parameterize the output format.
80   ///
81   class MachOWriter : public MachineFunctionPass {
82     friend class MachOCodeEmitter;
83   public:
84     MachineCodeEmitter &getMachineCodeEmitter() const {
85       return *(MachineCodeEmitter*)MCE;
86     }
87
88     ~MachOWriter();
89
90     typedef std::vector<unsigned char> DataBuffer;
91
92   protected:
93     MachOWriter(std::ostream &O, TargetMachine &TM);
94
95     /// Output stream to send the resultant object file to.
96     ///
97     std::ostream &O;
98
99     /// Target machine description.
100     ///
101     TargetMachine &TM;
102
103     /// Mang - The object used to perform name mangling for this module.
104     ///
105     Mangler *Mang;
106     
107     /// MCE - The MachineCodeEmitter object that we are exposing to emit machine
108     /// code for functions to the .o file.
109     MachOCodeEmitter *MCE;
110
111     /// is64Bit/isLittleEndian - This information is inferred from the target
112     /// machine directly, indicating what header values and flags to set.
113     bool is64Bit, isLittleEndian;
114
115     /// doInitialization - Emit the file header and all of the global variables
116     /// for the module to the Mach-O file.
117     bool doInitialization(Module &M);
118
119     bool runOnMachineFunction(MachineFunction &MF);
120
121     /// doFinalization - Now that the module has been completely processed, emit
122     /// the Mach-O file to 'O'.
123     bool doFinalization(Module &M);
124
125     /// MachOHeader - This struct contains the header information about a
126     /// specific architecture type/subtype pair that is emitted to the file.
127     struct MachOHeader {
128       uint32_t  magic;      // mach magic number identifier
129       uint32_t  cputype;    // cpu specifier
130       uint32_t  cpusubtype; // machine specifier
131       uint32_t  filetype;   // type of file
132       uint32_t  ncmds;      // number of load commands
133       uint32_t  sizeofcmds; // the size of all the load commands
134       uint32_t  flags;      // flags
135       uint32_t  reserved;   // 64-bit only
136       
137       /// HeaderData - The actual data for the header which we are building
138       /// up for emission to the file.
139       DataBuffer HeaderData;
140
141       // Constants for the cputype field
142       // see <mach/machine.h>
143       enum { CPU_TYPE_I386      = 7,
144              CPU_TYPE_X86_64    = 7 | 0x1000000,
145              CPU_TYPE_ARM       = 12,
146              CPU_TYPE_SPARC     = 14,
147              CPU_TYPE_POWERPC   = 18,
148              CPU_TYPE_POWERPC64 = 18 | 0x1000000
149       };
150       
151       // Constants for the cpusubtype field
152       // see <mach/machine.h>
153       enum { CPU_SUBTYPE_I386_ALL    = 3,
154              CPU_SUBTYPE_X86_64_ALL  = 3,
155              CPU_SUBTYPE_ARM_ALL     = 0,
156              CPU_SUBTYPE_SPARC_ALL   = 0,
157              CPU_SUBTYPE_POWERPC_ALL = 0
158       };
159              
160       // Constants for the filetype field
161       // see <mach-o/loader.h> for additional info on the various types
162       enum { MH_OBJECT     = 1, // relocatable object file
163              MH_EXECUTE    = 2, // demand paged executable file
164              MH_FVMLIB     = 3, // fixed VM shared library file
165              MH_CORE       = 4, // core file
166              MH_PRELOAD    = 5, // preloaded executable file
167              MH_DYLIB      = 6, // dynamically bound shared library
168              MH_DYLINKER   = 7, // dynamic link editor
169              MH_BUNDLE     = 8, // dynamically bound bundle file
170              MH_DYLIB_STUB = 9, // shared library stub for static linking only
171              MH_DSYM       = 10 // companion file wiht only debug sections
172       };
173       
174       // Constants for the flags field
175       enum { MH_NOUNDEFS                = 1 << 0,
176                 // the object file has no undefined references
177              MH_INCRLINK                = 1 << 1,
178                 // the object file is the output of an incremental link against
179                 // a base file and cannot be link edited again
180              MH_DYLDLINK                = 1 << 2,
181                 // the object file is input for the dynamic linker and cannot be
182                 // statically link edited again.
183              MH_BINDATLOAD              = 1 << 3,
184                 // the object file's undefined references are bound by the
185                 // dynamic linker when loaded.
186              MH_PREBOUND                = 1 << 4,
187                 // the file has its dynamic undefined references prebound
188              MH_SPLIT_SEGS              = 1 << 5,
189                 // the file has its read-only and read-write segments split
190                 // see <mach/shared_memory_server.h>
191              MH_LAZY_INIT               = 1 << 6,
192                 // the shared library init routine is to be run lazily via
193                 // catching memory faults to its writable segments (obsolete)
194              MH_TWOLEVEL                = 1 << 7,
195                 // the image is using two-level namespace bindings
196              MH_FORCE_FLAT              = 1 << 8,
197                 // the executable is forcing all images to use flat namespace
198                 // bindings.
199              MH_NOMULTIDEFS             = 1 << 8,
200                 // this umbrella guarantees no multiple definitions of symbols
201                 // in its sub-images so the two-level namespace hints can
202                 // always be used.
203              MH_NOFIXPREBINDING         = 1 << 10,
204                 // do not have dyld notify the prebidning agent about this
205                 // executable.
206              MH_PREBINDABLE             = 1 << 11,
207                 // the binary is not prebound but can have its prebinding
208                 // redone.  only used when MH_PREBOUND is not set.
209              MH_ALLMODSBOUND            = 1 << 12,
210                 // indicates that this binary binds to all two-level namespace
211                 // modules of its dependent libraries.  Only used when
212                 // MH_PREBINDABLE and MH_TWOLEVEL are both set.
213              MH_SUBSECTIONS_VIA_SYMBOLS = 1 << 13,
214                 // safe to divide up the sections into sub-sections via symbols
215                 // for dead code stripping.
216              MH_CANONICAL               = 1 << 14,
217                 // the binary has been canonicalized via the unprebind operation
218              MH_WEAK_DEFINES            = 1 << 15,
219                 // the final linked image contains external weak symbols
220              MH_BINDS_TO_WEAK           = 1 << 16,
221                 // the final linked image uses weak symbols
222              MH_ALLOW_STACK_EXECUTION   = 1 << 17
223                 // When this bit is set, all stacks in the task will be given
224                 // stack execution privilege.  Only used in MH_EXECUTE filetype
225       };
226
227       MachOHeader() : magic(0), cputype(0), cpusubtype(0), filetype(0),
228                       ncmds(0), sizeofcmds(0), flags(0), reserved(0) { }
229       
230       /// cmdSize - This routine returns the size of the MachOSection as written
231       /// to disk, depending on whether the destination is a 64 bit Mach-O file.
232       unsigned cmdSize(bool is64Bit) const {
233         if (is64Bit)
234           return 8 * sizeof(uint32_t);
235         else
236           return 7 * sizeof(uint32_t);
237       }
238
239       /// setMagic - This routine sets the appropriate value for the 'magic'
240       /// field based on pointer size and endianness.
241       void setMagic(bool isLittleEndian, bool is64Bit) {
242         if (isLittleEndian)
243           if (is64Bit) magic = 0xcffaedfe;
244           else         magic = 0xcefaedfe;
245         else
246           if (is64Bit) magic = 0xfeedfacf;
247           else         magic = 0xfeedface;
248       }
249     };
250     
251     /// Header - An instance of MachOHeader that we will update while we build
252     /// the file, and then emit during finalization.
253     MachOHeader Header;
254     
255     /// MachOSegment - This struct contains the necessary information to
256     /// emit the load commands for each section in the file.
257     struct MachOSegment {
258       uint32_t    cmd;      // LC_SEGMENT or LC_SEGMENT_64
259       uint32_t    cmdsize;  // Total size of this struct and section commands
260       std::string segname;  // segment name
261       uint64_t    vmaddr;   // address of this segment
262       uint64_t    vmsize;   // size of this segment, may be larger than filesize
263       uint64_t    fileoff;  // offset in file
264       uint64_t    filesize; // amount to read from file
265       uint32_t    maxprot;  // maximum VM protection
266       uint32_t    initprot; // initial VM protection
267       uint32_t    nsects;   // number of sections in this segment
268       uint32_t    flags;    // flags
269       
270       // Constants for the vm protection fields
271       // see <mach-o/vm_prot.h>
272       enum { VM_PROT_NONE    = 0x00, 
273              VM_PROT_READ    = 0x01, // read permission
274              VM_PROT_WRITE   = 0x02, // write permission
275              VM_PROT_EXECUTE = 0x04, // execute permission,
276              VM_PROT_ALL     = 0x07
277       };
278       
279       // Constants for the cmd field
280       // see <mach-o/loader.h>
281       enum { LC_SEGMENT    = 0x01,  // segment of this file to be mapped
282              LC_SEGMENT_64 = 0x19   // 64-bit segment of this file to be mapped
283       };
284       
285       /// cmdSize - This routine returns the size of the MachOSection as written
286       /// to disk, depending on whether the destination is a 64 bit Mach-O file.
287       unsigned cmdSize(bool is64Bit) const {
288         if (is64Bit)
289           return 6 * sizeof(uint32_t) + 4 * sizeof(uint64_t) + 16;
290         else
291           return 10 * sizeof(uint32_t) + 16;  // addresses only 32 bits
292       }
293
294       MachOSegment(const std::string &seg, bool is64Bit)
295         : cmd(is64Bit ? LC_SEGMENT_64 : LC_SEGMENT), cmdsize(0), segname(seg),
296           vmaddr(0), vmsize(0), fileoff(0), filesize(0), maxprot(VM_PROT_ALL),
297           initprot(VM_PROT_ALL), nsects(0), flags(0) { }
298     };
299
300     /// MachORelocation - This struct contains information about each relocation
301     /// that needs to be emitted to the file.
302     /// see <mach-o/reloc.h>
303     struct MachORelocation {
304       uint32_t r_address;   // offset in the section to what is being  relocated
305       uint32_t r_symbolnum; // symbol index if r_extern == 1 else section index
306       bool     r_pcrel;     // was relocated pc-relative already
307       uint8_t  r_length;    // length = 2 ^ r_length
308       bool     r_extern;    // 
309       uint8_t  r_type;      // if not 0, machine-specific relocation type.
310       
311       uint32_t getPackedFields() { 
312         return (r_symbolnum << 8) | (r_pcrel << 7) | ((r_length & 3) << 5) |
313                (r_extern << 4) | (r_type & 15);
314       }
315       
316       MachORelocation(uint32_t addr, uint32_t index, bool pcrel, uint8_t len,
317                       bool ext, uint8_t type) : r_address(addr),
318         r_symbolnum(index), r_pcrel(pcrel), r_length(len), r_extern(ext),
319         r_type(type) {}
320     };
321
322     /// MachOSection - This struct contains information about each section in a 
323     /// particular segment that is emitted to the file.  This is eventually
324     /// turned into the SectionCommand in the load command for a particlar
325     /// segment.
326     struct MachOSection { 
327       std::string  sectname; // name of this section, 
328       std::string  segname;  // segment this section goes in
329       uint64_t  addr;        // memory address of this section
330       uint64_t  size;        // size in bytes of this section
331       uint32_t  offset;      // file offset of this section
332       uint32_t  align;       // section alignment (power of 2)
333       uint32_t  reloff;      // file offset of relocation entries
334       uint32_t  nreloc;      // number of relocation entries
335       uint32_t  flags;       // flags (section type and attributes)
336       uint32_t  reserved1;   // reserved (for offset or index)
337       uint32_t  reserved2;   // reserved (for count or sizeof)
338       uint32_t  reserved3;   // reserved (64 bit only)
339       
340       /// A unique number for this section, which will be used to match symbols
341       /// to the correct section.
342       uint32_t Index;
343       
344       /// SectionData - The actual data for this section which we are building
345       /// up for emission to the file.
346       DataBuffer SectionData;
347
348       /// RelocBuffer - A buffer to hold the mach-o relocations before we write
349       /// them out at the appropriate location in the file.
350       DataBuffer RelocBuffer;
351       
352       /// Relocations - The relocations that we have encountered so far in this 
353       /// section that we will need to convert to MachORelocation entries when
354       /// the file is written.
355       std::vector<MachineRelocation> Relocations;
356       
357       // Constants for the section types (low 8 bits of flags field)
358       // see <mach-o/loader.h>
359       enum { S_REGULAR = 0,
360                 // regular section
361              S_ZEROFILL = 1,
362                 // zero fill on demand section
363              S_CSTRING_LITERALS = 2,
364                 // section with only literal C strings
365              S_4BYTE_LITERALS = 3,
366                 // section with only 4 byte literals
367              S_8BYTE_LITERALS = 4,
368                 // section with only 8 byte literals
369              S_LITERAL_POINTERS = 5, 
370                 // section with only pointers to literals
371              S_NON_LAZY_SYMBOL_POINTERS = 6,
372                 // section with only non-lazy symbol pointers
373              S_LAZY_SYMBOL_POINTERS = 7,
374                 // section with only lazy symbol pointers
375              S_SYMBOL_STUBS = 8,
376                 // section with only symbol stubs
377                 // byte size of stub in the reserved2 field
378              S_MOD_INIT_FUNC_POINTERS = 9,
379                 // section with only function pointers for initialization
380              S_MOD_TERM_FUNC_POINTERS = 10,
381                 // section with only function pointers for termination
382              S_COALESCED = 11,
383                 // section contains symbols that are coalesced
384              S_GB_ZEROFILL = 12,
385                 // zero fill on demand section (that can be larger than 4GB)
386              S_INTERPOSING = 13,
387                 // section with only pairs of function pointers for interposing
388              S_16BYTE_LITERALS = 14
389                 // section with only 16 byte literals
390       };
391       
392       // Constants for the section flags (high 24 bits of flags field)
393       // see <mach-o/loader.h>
394       enum { S_ATTR_PURE_INSTRUCTIONS   = 1 << 31,
395                 // section contains only true machine instructions
396              S_ATTR_NO_TOC              = 1 << 30,
397                 // section contains coalesced symbols that are not to be in a 
398                 // ranlib table of contents
399              S_ATTR_STRIP_STATIC_SYMS   = 1 << 29,
400                 // ok to strip static symbols in this section in files with the
401                 // MY_DYLDLINK flag
402              S_ATTR_NO_DEAD_STRIP       = 1 << 28,
403                 // no dead stripping
404              S_ATTR_LIVE_SUPPORT        = 1 << 27,
405                 // blocks are live if they reference live blocks
406              S_ATTR_SELF_MODIFYING_CODE = 1 << 26,
407                 // used with i386 code stubs written on by dyld
408              S_ATTR_DEBUG               = 1 << 25,
409                 // a debug section
410              S_ATTR_SOME_INSTRUCTIONS   = 1 << 10,
411                 // section contains some machine instructions
412              S_ATTR_EXT_RELOC           = 1 << 9,
413                 // section has external relocation entries
414              S_ATTR_LOC_RELOC           = 1 << 8
415                 // section has local relocation entries
416       };
417
418       /// cmdSize - This routine returns the size of the MachOSection as written
419       /// to disk, depending on whether the destination is a 64 bit Mach-O file.
420       unsigned cmdSize(bool is64Bit) const {
421         if (is64Bit)
422           return 7 * sizeof(uint32_t) + 2 * sizeof(uint64_t) + 32;
423         else
424           return 9 * sizeof(uint32_t) + 32;  // addresses only 32 bits
425       }
426
427       MachOSection(const std::string &seg, const std::string &sect)
428         : sectname(sect), segname(seg), addr(0), size(0), offset(0), align(2),
429           reloff(0), nreloc(0), flags(0), reserved1(0), reserved2(0),
430           reserved3(0) { }
431     };
432
433   private:
434
435     /// SectionList - This is the list of sections that we have emitted to the
436     /// file.  Once the file has been completely built, the segment load command
437     /// SectionCommands are constructed from this info.
438     std::vector<MachOSection*> SectionList;
439
440     /// SectionLookup - This is a mapping from section name to SectionList entry
441     std::map<std::string, MachOSection*> SectionLookup;
442     
443     /// GVSection - This is a mapping from a GlobalValue to a MachOSection,
444     /// to aid in emitting relocations.
445     std::map<GlobalValue*, MachOSection*> GVSection;
446
447     /// GVOffset - This is a mapping from a GlobalValue to an offset from the 
448     /// start of the section in which the GV resides, to aid in emitting
449     /// relocations.
450     std::map<GlobalValue*, intptr_t> GVOffset;
451
452     /// getSection - Return the section with the specified name, creating a new
453     /// section if one does not already exist.
454     MachOSection *getSection(const std::string &seg, const std::string &sect,
455                              unsigned Flags = 0) {
456       MachOSection *MOS = SectionLookup[seg+sect];
457       if (MOS) return MOS;
458
459       MOS = new MachOSection(seg, sect);
460       SectionList.push_back(MOS);
461       MOS->Index = SectionList.size();
462       MOS->flags = MachOSection::S_REGULAR | Flags;
463       SectionLookup[seg+sect] = MOS;
464       return MOS;
465     }
466     MachOSection *getTextSection(bool isCode = true) {
467       if (isCode)
468         return getSection("__TEXT", "__text", 
469                           MachOSection::S_ATTR_PURE_INSTRUCTIONS |
470                           MachOSection::S_ATTR_SOME_INSTRUCTIONS);
471       else
472         return getSection("__TEXT", "__text");
473     }
474     MachOSection *getBSSSection() {
475       return getSection("__DATA", "__bss", MachOSection::S_ZEROFILL);
476     }
477     MachOSection *getDataSection() {
478       return getSection("__DATA", "__data");
479     }
480     MachOSection *getConstSection(const Type *Ty) {
481       // FIXME: support cstring literals and pointer literal
482       if (Ty->isPrimitiveType()) {
483         unsigned Size = TM.getTargetData()->getTypeSize(Ty);
484         switch(Size) {
485         default: break; // Fall through to __TEXT,__const
486         case 4:
487           return getSection("__TEXT", "__literal4",
488                             MachOSection::S_4BYTE_LITERALS);
489         case 8:
490           return getSection("__TEXT", "__literal8",
491                             MachOSection::S_8BYTE_LITERALS);
492         case 16:
493           return getSection("__TEXT", "__literal16",
494                             MachOSection::S_16BYTE_LITERALS);
495         }
496       }
497       return getSection("__TEXT", "__const");
498     }
499     MachOSection *getJumpTableSection() {
500       if (TM.getRelocationModel() == Reloc::PIC_)
501         return getTextSection(false);
502       else
503         return getSection("__TEXT", "__const");
504     }
505     
506     /// MachOSymTab - This struct contains information about the offsets and 
507     /// size of symbol table information.
508     /// segment.
509     struct MachOSymTab {
510       uint32_t cmd;     // LC_SYMTAB
511       uint32_t cmdsize; // sizeof( MachOSymTab )
512       uint32_t symoff;  // symbol table offset
513       uint32_t nsyms;   // number of symbol table entries
514       uint32_t stroff;  // string table offset
515       uint32_t strsize; // string table size in bytes
516
517       // Constants for the cmd field
518       // see <mach-o/loader.h>
519       enum { LC_SYMTAB = 0x02  // link-edit stab symbol table info
520       };
521       
522       MachOSymTab() : cmd(LC_SYMTAB), cmdsize(6 * sizeof(uint32_t)), symoff(0),
523         nsyms(0), stroff(0), strsize(0) { }
524     };
525     
526     /// MachOSymTab - This struct contains information about the offsets and 
527     /// size of symbol table information.
528     /// segment.
529     struct MachODySymTab {
530       uint32_t cmd;             // LC_DYSYMTAB
531       uint32_t cmdsize;         // sizeof( MachODySymTab )
532       uint32_t ilocalsym;       // index to local symbols
533       uint32_t nlocalsym;       // number of local symbols
534       uint32_t iextdefsym;      // index to externally defined symbols
535       uint32_t nextdefsym;      // number of externally defined symbols
536       uint32_t iundefsym;       // index to undefined symbols
537       uint32_t nundefsym;       // number of undefined symbols
538       uint32_t tocoff;          // file offset to table of contents
539       uint32_t ntoc;            // number of entries in table of contents
540       uint32_t modtaboff;       // file offset to module table
541       uint32_t nmodtab;         // number of module table entries
542       uint32_t extrefsymoff;    // offset to referenced symbol table
543       uint32_t nextrefsyms;     // number of referenced symbol table entries
544       uint32_t indirectsymoff;  // file offset to the indirect symbol table
545       uint32_t nindirectsyms;   // number of indirect symbol table entries
546       uint32_t extreloff;       // offset to external relocation entries
547       uint32_t nextrel;         // number of external relocation entries
548       uint32_t locreloff;       // offset to local relocation entries
549       uint32_t nlocrel;         // number of local relocation entries
550
551       // Constants for the cmd field
552       // see <mach-o/loader.h>
553       enum { LC_DYSYMTAB = 0x0B  // dynamic link-edit symbol table info
554       };
555       
556       MachODySymTab() : cmd(LC_DYSYMTAB), cmdsize(20 * sizeof(uint32_t)),
557         ilocalsym(0), nlocalsym(0), iextdefsym(0), nextdefsym(0),
558         iundefsym(0), nundefsym(0), tocoff(0), ntoc(0), modtaboff(0),
559         nmodtab(0), extrefsymoff(0), nextrefsyms(0), indirectsymoff(0),
560         nindirectsyms(0), extreloff(0), nextrel(0), locreloff(0), nlocrel(0) { }
561     };
562     
563     /// SymTab - The "stab" style symbol table information
564     MachOSymTab   SymTab;     
565     /// DySymTab - symbol table info for the dynamic link editor
566     MachODySymTab DySymTab;
567
568     struct MachOSymCmp {
569       // FIXME: this does not appear to be sorting 'f' after 'F'
570       bool operator()(const MachOSym &LHS, const MachOSym &RHS) {
571         return LHS.GVName < RHS.GVName;
572       }
573     };
574
575     /// PartitionByLocal - Simple boolean predicate that returns true if Sym is
576     /// a local symbol rather than an external symbol.
577     static bool PartitionByLocal(const MachOSym &Sym);
578
579     /// PartitionByDefined - Simple boolean predicate that returns true if Sym 
580     /// is defined in this module.
581     static bool PartitionByDefined(const MachOSym &Sym);
582
583   protected:
584   
585     /// SymbolTable - This is the list of symbols we have emitted to the file.
586     /// This actually gets rearranged before emission to the file (to put the
587     /// local symbols first in the list).
588     std::vector<MachOSym> SymbolTable;
589     
590     /// SymT - A buffer to hold the symbol table before we write it out at the
591     /// appropriate location in the file.
592     DataBuffer SymT;
593     
594     /// StrT - A buffer to hold the string table before we write it out at the
595     /// appropriate location in the file.
596     DataBuffer StrT;
597     
598     /// PendingSyms - This is a list of externally defined symbols that we have
599     /// been asked to emit, but have not seen a reference to.  When a reference
600     /// is seen, the symbol will move from this list to the SymbolTable.
601     std::vector<MachOSym> PendingSyms;
602     
603     /// DynamicSymbolTable - This is just a vector of indices into
604     /// SymbolTable to aid in emitting the DYSYMTAB load command.
605     std::vector<unsigned> DynamicSymbolTable;
606     
607     // align - Emit padding into the file until the current output position is
608     // aligned to the specified power of two boundary.
609     static void align(DataBuffer &Output, unsigned Boundary) {
610       assert(Boundary && (Boundary & (Boundary-1)) == 0 &&
611              "Must align to 2^k boundary");
612       size_t Size = Output.size();
613       if (Size & (Boundary-1)) {
614         // Add padding to get alignment to the correct place.
615         size_t Pad = Boundary-(Size & (Boundary-1));
616         Output.resize(Size+Pad);
617       }
618     }
619
620     void outbyte(DataBuffer &Output, unsigned char X) {
621       Output.push_back(X);
622     }
623     void outhalf(DataBuffer &Output, unsigned short X) {
624       if (isLittleEndian) {
625         Output.push_back(X&255);
626         Output.push_back(X >> 8);
627       } else {
628         Output.push_back(X >> 8);
629         Output.push_back(X&255);
630       }
631     }
632     void outword(DataBuffer &Output, unsigned X) {
633       if (isLittleEndian) {
634         Output.push_back((X >>  0) & 255);
635         Output.push_back((X >>  8) & 255);
636         Output.push_back((X >> 16) & 255);
637         Output.push_back((X >> 24) & 255);
638       } else {
639         Output.push_back((X >> 24) & 255);
640         Output.push_back((X >> 16) & 255);
641         Output.push_back((X >>  8) & 255);
642         Output.push_back((X >>  0) & 255);
643       }
644     }
645     void outxword(DataBuffer &Output, uint64_t X) {
646       if (isLittleEndian) {
647         Output.push_back(unsigned(X >>  0) & 255);
648         Output.push_back(unsigned(X >>  8) & 255);
649         Output.push_back(unsigned(X >> 16) & 255);
650         Output.push_back(unsigned(X >> 24) & 255);
651         Output.push_back(unsigned(X >> 32) & 255);
652         Output.push_back(unsigned(X >> 40) & 255);
653         Output.push_back(unsigned(X >> 48) & 255);
654         Output.push_back(unsigned(X >> 56) & 255);
655       } else {
656         Output.push_back(unsigned(X >> 56) & 255);
657         Output.push_back(unsigned(X >> 48) & 255);
658         Output.push_back(unsigned(X >> 40) & 255);
659         Output.push_back(unsigned(X >> 32) & 255);
660         Output.push_back(unsigned(X >> 24) & 255);
661         Output.push_back(unsigned(X >> 16) & 255);
662         Output.push_back(unsigned(X >>  8) & 255);
663         Output.push_back(unsigned(X >>  0) & 255);
664       }
665     }
666     void outaddr32(DataBuffer &Output, unsigned X) {
667       outword(Output, X);
668     }
669     void outaddr64(DataBuffer &Output, uint64_t X) {
670       outxword(Output, X);
671     }
672     void outaddr(DataBuffer &Output, uint64_t X) {
673       if (!is64Bit)
674         outword(Output, (unsigned)X);
675       else
676         outxword(Output, X);
677     }
678     void outstring(DataBuffer &Output, std::string &S, unsigned Length) {
679       unsigned len_to_copy = S.length() < Length ? S.length() : Length;
680       unsigned len_to_fill = S.length() < Length ? Length-S.length() : 0;
681       
682       for (unsigned i = 0; i < len_to_copy; ++i)
683         outbyte(Output, S[i]);
684
685       for (unsigned i = 0; i < len_to_fill; ++i)
686         outbyte(Output, 0);
687       
688     }
689     void fixhalf(DataBuffer &Output, unsigned short X, unsigned Offset) {
690       unsigned char *P = &Output[Offset];
691       P[0] = (X >> (isLittleEndian ?  0 : 8)) & 255;
692       P[1] = (X >> (isLittleEndian ?  8 : 0)) & 255;
693     }
694     void fixword(DataBuffer &Output, unsigned X, unsigned Offset) {
695       unsigned char *P = &Output[Offset];
696       P[0] = (X >> (isLittleEndian ?  0 : 24)) & 255;
697       P[1] = (X >> (isLittleEndian ?  8 : 16)) & 255;
698       P[2] = (X >> (isLittleEndian ? 16 :  8)) & 255;
699       P[3] = (X >> (isLittleEndian ? 24 :  0)) & 255;
700     }
701     
702     static void InitMem(const Constant *C, void *Addr, intptr_t Offset,
703                         const TargetData *TD, 
704                         std::vector<MachineRelocation> &MRs);
705
706   private:
707     void AddSymbolToSection(MachOSection *MOS, GlobalVariable *GV);
708     void EmitGlobal(GlobalVariable *GV);
709     void EmitHeaderAndLoadCommands();
710     void EmitSections();
711     void BufferSymbolAndStringTable();
712     void CalculateRelocations(MachOSection &MOS);
713
714     virtual MachineRelocation GetJTRelocation(unsigned Offset,
715                                               MachineBasicBlock *MBB) = 0;
716     virtual void GetTargetRelocation(MachineRelocation &MR, MachOSection &From,
717                                      MachOSection &To) = 0;
718   };
719 }
720
721 #endif