Behold, more work on relocations. Things are looking pretty good now.
[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 #include <list>
23
24 namespace llvm {
25   class GlobalVariable;
26   class Mangler;
27   class MachineCodeEmitter;
28   class MachOCodeEmitter;
29
30   /// MachOSym - This struct contains information about each symbol that is
31   /// added to logical symbol table for the module.  This is eventually
32   /// turned into a real symbol table in the file.
33   struct MachOSym {
34     const GlobalValue *GV;    // The global value this corresponds to.
35     std::string GVName;       // The mangled name of the global value.
36     uint32_t    n_strx;       // index into the string table
37     uint8_t     n_type;       // type flag
38     uint8_t     n_sect;       // section number or NO_SECT
39     int16_t     n_desc;       // see <mach-o/stab.h>
40     uint64_t    n_value;      // value for this symbol (or stab offset)
41     
42     // Constants for the n_sect field
43     // see <mach-o/nlist.h>
44     enum { NO_SECT = 0 };   // symbol is not in any section
45
46     // Constants for the n_type field
47     // see <mach-o/nlist.h>
48     enum { N_UNDF  = 0x0,  // undefined, n_sect == NO_SECT
49            N_ABS   = 0x2,  // absolute, n_sect == NO_SECT
50            N_SECT  = 0xe,  // defined in section number n_sect
51            N_PBUD  = 0xc,  // prebound undefined (defined in a dylib)
52            N_INDR  = 0xa   // indirect
53     };
54     // The following bits are OR'd into the types above. For example, a type
55     // of 0x0f would be an external N_SECT symbol (0x0e | 0x01).
56     enum { N_EXT  = 0x01,   // external symbol bit
57            N_PEXT = 0x10    // private external symbol bit
58     };
59     
60     // Constants for the n_desc field
61     // see <mach-o/loader.h>
62     enum { REFERENCE_FLAG_UNDEFINED_NON_LAZY          = 0,
63            REFERENCE_FLAG_UNDEFINED_LAZY              = 1,
64            REFERENCE_FLAG_DEFINED                     = 2,
65            REFERENCE_FLAG_PRIVATE_DEFINED             = 3,
66            REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY  = 4,
67            REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY      = 5
68     };
69     enum { N_NO_DEAD_STRIP = 0x0020, // symbol is not to be dead stripped
70            N_WEAK_REF      = 0x0040, // symbol is weak referenced
71            N_WEAK_DEF      = 0x0080  // coalesced symbol is a weak definition
72     };
73     
74     MachOSym(const GlobalValue *gv, std::string name, uint8_t sect);
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::list<MachOSection> SectionList;
439
440     /// SectionLookup - This is a mapping from section name to SectionList entry
441     std::map<std::string, MachOSection*> SectionLookup;
442
443     /// getSection - Return the section with the specified name, creating a new
444     /// section if one does not already exist.
445     MachOSection &getSection(const std::string &seg, const std::string &sect,
446                              unsigned Flags = 0) {
447       MachOSection *&SN = SectionLookup[seg+sect];
448       if (SN) return *SN;
449
450       SectionList.push_back(MachOSection(seg, sect));
451       SN = &SectionList.back();
452       SN->Index = SectionList.size();
453       SN->flags = MachOSection::S_REGULAR | Flags;
454       return *SN;
455     }
456     MachOSection &getTextSection(bool isCode = true) {
457       if (isCode)
458         return getSection("__TEXT", "__text", 
459                           MachOSection::S_ATTR_PURE_INSTRUCTIONS |
460                           MachOSection::S_ATTR_SOME_INSTRUCTIONS);
461       else
462         return getSection("__TEXT", "__text");
463     }
464     MachOSection &getBSSSection() {
465       return getSection("__DATA", "__bss", MachOSection::S_ZEROFILL);
466     }
467     MachOSection &getDataSection() {
468       return getSection("__DATA", "__data");
469     }
470     MachOSection &getConstSection(const Type *Ty) {
471       // FIXME: support cstring literals and pointer literal
472       if (Ty->isPrimitiveType()) {
473         unsigned Size = TM.getTargetData()->getTypeSize(Ty);
474         switch(Size) {
475         default: break; // Fall through to __TEXT,__const
476         case 4:
477           return getSection("__TEXT", "__literal4",
478                             MachOSection::S_4BYTE_LITERALS);
479         case 8:
480           return getSection("__TEXT", "__literal8",
481                             MachOSection::S_8BYTE_LITERALS);
482         case 16:
483           return getSection("__TEXT", "__literal16",
484                             MachOSection::S_16BYTE_LITERALS);
485         }
486       }
487       return getSection("__TEXT", "__const");
488     }
489     MachOSection &getJumpTableSection() {
490       if (TM.getRelocationModel() == Reloc::PIC_)
491         return getTextSection(false);
492       else
493         return getSection("__TEXT", "__const");
494     }
495     
496     /// MachOSymTab - This struct contains information about the offsets and 
497     /// size of symbol table information.
498     /// segment.
499     struct MachOSymTab {
500       uint32_t cmd;     // LC_SYMTAB
501       uint32_t cmdsize; // sizeof( MachOSymTab )
502       uint32_t symoff;  // symbol table offset
503       uint32_t nsyms;   // number of symbol table entries
504       uint32_t stroff;  // string table offset
505       uint32_t strsize; // string table size in bytes
506
507       // Constants for the cmd field
508       // see <mach-o/loader.h>
509       enum { LC_SYMTAB = 0x02  // link-edit stab symbol table info
510       };
511       
512       MachOSymTab() : cmd(LC_SYMTAB), cmdsize(6 * sizeof(uint32_t)), symoff(0),
513         nsyms(0), stroff(0), strsize(0) { }
514     };
515     
516     /// MachOSymTab - This struct contains information about the offsets and 
517     /// size of symbol table information.
518     /// segment.
519     struct MachODySymTab {
520       uint32_t cmd;             // LC_DYSYMTAB
521       uint32_t cmdsize;         // sizeof( MachODySymTab )
522       uint32_t ilocalsym;       // index to local symbols
523       uint32_t nlocalsym;       // number of local symbols
524       uint32_t iextdefsym;      // index to externally defined symbols
525       uint32_t nextdefsym;      // number of externally defined symbols
526       uint32_t iundefsym;       // index to undefined symbols
527       uint32_t nundefsym;       // number of undefined symbols
528       uint32_t tocoff;          // file offset to table of contents
529       uint32_t ntoc;            // number of entries in table of contents
530       uint32_t modtaboff;       // file offset to module table
531       uint32_t nmodtab;         // number of module table entries
532       uint32_t extrefsymoff;    // offset to referenced symbol table
533       uint32_t nextrefsyms;     // number of referenced symbol table entries
534       uint32_t indirectsymoff;  // file offset to the indirect symbol table
535       uint32_t nindirectsyms;   // number of indirect symbol table entries
536       uint32_t extreloff;       // offset to external relocation entries
537       uint32_t nextrel;         // number of external relocation entries
538       uint32_t locreloff;       // offset to local relocation entries
539       uint32_t nlocrel;         // number of local relocation entries
540
541       // Constants for the cmd field
542       // see <mach-o/loader.h>
543       enum { LC_DYSYMTAB = 0x0B  // dynamic link-edit symbol table info
544       };
545       
546       MachODySymTab() : cmd(LC_DYSYMTAB), cmdsize(20 * sizeof(uint32_t)),
547         ilocalsym(0), nlocalsym(0), iextdefsym(0), nextdefsym(0),
548         iundefsym(0), nundefsym(0), tocoff(0), ntoc(0), modtaboff(0),
549         nmodtab(0), extrefsymoff(0), nextrefsyms(0), indirectsymoff(0),
550         nindirectsyms(0), extreloff(0), nextrel(0), locreloff(0), nlocrel(0) { }
551     };
552     
553     /// SymTab - The "stab" style symbol table information
554     MachOSymTab   SymTab;     
555     /// DySymTab - symbol table info for the dynamic link editor
556     MachODySymTab DySymTab;
557
558     struct MachOSymCmp {
559       bool operator()(const MachOSym &LHS, const MachOSym &RHS) {
560         return LHS.GVName < RHS.GVName;
561       }
562     };
563
564     /// PartitionByLocal - Simple boolean predicate that returns true if Sym is
565     /// a local symbol rather than an external symbol.
566     static bool PartitionByLocal(const MachOSym &Sym);
567
568     /// PartitionByDefined - Simple boolean predicate that returns true if Sym 
569     /// is defined in this module.
570     static bool PartitionByDefined(const MachOSym &Sym);
571
572   protected:
573   
574     /// SymbolTable - This is the list of symbols we have emitted to the file.
575     /// This actually gets rearranged before emission to the file (to put the
576     /// local symbols first in the list).
577     std::vector<MachOSym> SymbolTable;
578     
579     /// SymT - A buffer to hold the symbol table before we write it out at the
580     /// appropriate location in the file.
581     DataBuffer SymT;
582     
583     /// StrT - A buffer to hold the string table before we write it out at the
584     /// appropriate location in the file.
585     DataBuffer StrT;
586     
587     /// PendingSyms - This is a list of externally defined symbols that we have
588     /// been asked to emit, but have not seen a reference to.  When a reference
589     /// is seen, the symbol will move from this list to the SymbolTable.
590     std::vector<MachOSym> PendingSyms;
591     
592     /// DynamicSymbolTable - This is just a vector of indices into
593     /// SymbolTable to aid in emitting the DYSYMTAB load command.
594     std::vector<unsigned> DynamicSymbolTable;
595     
596     // align - Emit padding into the file until the current output position is
597     // aligned to the specified power of two boundary.
598     static void align(DataBuffer &Output, unsigned Boundary) {
599       assert(Boundary && (Boundary & (Boundary-1)) == 0 &&
600              "Must align to 2^k boundary");
601       size_t Size = Output.size();
602       if (Size & (Boundary-1)) {
603         // Add padding to get alignment to the correct place.
604         size_t Pad = Boundary-(Size & (Boundary-1));
605         Output.resize(Size+Pad);
606       }
607     }
608
609     void outbyte(DataBuffer &Output, unsigned char X) {
610       Output.push_back(X);
611     }
612     void outhalf(DataBuffer &Output, unsigned short X) {
613       if (isLittleEndian) {
614         Output.push_back(X&255);
615         Output.push_back(X >> 8);
616       } else {
617         Output.push_back(X >> 8);
618         Output.push_back(X&255);
619       }
620     }
621     void outword(DataBuffer &Output, unsigned X) {
622       if (isLittleEndian) {
623         Output.push_back((X >>  0) & 255);
624         Output.push_back((X >>  8) & 255);
625         Output.push_back((X >> 16) & 255);
626         Output.push_back((X >> 24) & 255);
627       } else {
628         Output.push_back((X >> 24) & 255);
629         Output.push_back((X >> 16) & 255);
630         Output.push_back((X >>  8) & 255);
631         Output.push_back((X >>  0) & 255);
632       }
633     }
634     void outxword(DataBuffer &Output, uint64_t X) {
635       if (isLittleEndian) {
636         Output.push_back(unsigned(X >>  0) & 255);
637         Output.push_back(unsigned(X >>  8) & 255);
638         Output.push_back(unsigned(X >> 16) & 255);
639         Output.push_back(unsigned(X >> 24) & 255);
640         Output.push_back(unsigned(X >> 32) & 255);
641         Output.push_back(unsigned(X >> 40) & 255);
642         Output.push_back(unsigned(X >> 48) & 255);
643         Output.push_back(unsigned(X >> 56) & 255);
644       } else {
645         Output.push_back(unsigned(X >> 56) & 255);
646         Output.push_back(unsigned(X >> 48) & 255);
647         Output.push_back(unsigned(X >> 40) & 255);
648         Output.push_back(unsigned(X >> 32) & 255);
649         Output.push_back(unsigned(X >> 24) & 255);
650         Output.push_back(unsigned(X >> 16) & 255);
651         Output.push_back(unsigned(X >>  8) & 255);
652         Output.push_back(unsigned(X >>  0) & 255);
653       }
654     }
655     void outaddr32(DataBuffer &Output, unsigned X) {
656       outword(Output, X);
657     }
658     void outaddr64(DataBuffer &Output, uint64_t X) {
659       outxword(Output, X);
660     }
661     void outaddr(DataBuffer &Output, uint64_t X) {
662       if (!is64Bit)
663         outword(Output, (unsigned)X);
664       else
665         outxword(Output, X);
666     }
667     void outstring(DataBuffer &Output, std::string &S, unsigned Length) {
668       unsigned len_to_copy = S.length() < Length ? S.length() : Length;
669       unsigned len_to_fill = S.length() < Length ? Length-S.length() : 0;
670       
671       for (unsigned i = 0; i < len_to_copy; ++i)
672         outbyte(Output, S[i]);
673
674       for (unsigned i = 0; i < len_to_fill; ++i)
675         outbyte(Output, 0);
676       
677     }
678     void fixhalf(DataBuffer &Output, unsigned short X, unsigned Offset) {
679       unsigned char *P = &Output[Offset];
680       P[0] = (X >> (isLittleEndian ?  0 : 8)) & 255;
681       P[1] = (X >> (isLittleEndian ?  8 : 0)) & 255;
682     }
683     void fixword(DataBuffer &Output, unsigned X, unsigned Offset) {
684       unsigned char *P = &Output[Offset];
685       P[0] = (X >> (isLittleEndian ?  0 : 24)) & 255;
686       P[1] = (X >> (isLittleEndian ?  8 : 16)) & 255;
687       P[2] = (X >> (isLittleEndian ? 16 :  8)) & 255;
688       P[3] = (X >> (isLittleEndian ? 24 :  0)) & 255;
689     }
690
691   private:
692     void AddSymbolToSection(MachOSection &MOS, GlobalVariable *GV);
693     void EmitGlobal(GlobalVariable *GV);
694     void EmitHeaderAndLoadCommands();
695     void EmitSections();
696     void BufferSymbolAndStringTable();
697     void CalculateRelocations(MachOSection &MOS, unsigned RelOffset);
698
699     virtual MachineRelocation GetJTRelocation(unsigned Offset,
700                                               MachineBasicBlock *MBB) = 0;
701     virtual void GetTargetRelocation(MachineRelocation &MR, MachOSection &MOS,
702                                      unsigned ToIndex) = 0;
703   };
704 }
705
706 #endif