Initial checkin of the Mach-O emitter. There's plenty of fixmes, but it
[oota-llvm.git] / lib / CodeGen / MachOWriter.cpp
1 //===-- MachOWriter.cpp - Target-independent Mach-O Writer code -----------===//
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 implements the target-independent Mach-O writer.  This file writes
11 // out the Mach-O file in the following order:
12 //
13 //  #1 FatHeader (universal-only)
14 //  #2 FatArch (universal-only, 1 per universal arch)
15 //  Per arch:
16 //    #3 Header
17 //    #4 Load Commands
18 //    #5 Sections
19 //    #6 Relocations
20 //    #7 Symbols
21 //    #8 Strings
22 //
23 //===----------------------------------------------------------------------===//
24
25 #include "llvm/Module.h"
26 #include "llvm/CodeGen/MachineCodeEmitter.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineRelocation.h"
29 #include "llvm/CodeGen/MachOWriter.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetJITInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Support/Mangler.h"
34 #include <iostream>
35 using namespace llvm;
36
37 //===----------------------------------------------------------------------===//
38 //                       MachOCodeEmitter Implementation
39 //===----------------------------------------------------------------------===//
40
41 namespace llvm {
42   /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code 
43   /// for functions to the Mach-O file.
44   class MachOCodeEmitter : public MachineCodeEmitter {
45     MachOWriter &MOW;
46     
47     /// MOS - The current section we're writing to
48     MachOWriter::MachOSection *MOS;
49
50     /// Relocations - These are the relocations that the function needs, as
51     /// emitted.
52     std::vector<MachineRelocation> Relocations;
53
54     /// MBBLocations - This vector is a mapping from MBB ID's to their address.
55     /// It is filled in by the StartMachineBasicBlock callback and queried by
56     /// the getMachineBasicBlockAddress callback.
57     std::vector<intptr_t> MBBLocations;
58     
59   public:
60     MachOCodeEmitter(MachOWriter &mow) : MOW(mow) {}
61
62     void startFunction(MachineFunction &F);
63     bool finishFunction(MachineFunction &F);
64
65     void addRelocation(const MachineRelocation &MR) {
66       Relocations.push_back(MR);
67     }
68     
69     virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
70       if (MBBLocations.size() <= (unsigned)MBB->getNumber())
71         MBBLocations.resize((MBB->getNumber()+1)*2);
72       MBBLocations[MBB->getNumber()] = getCurrentPCValue();
73     }
74
75     virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
76       assert(0 && "CP not implementated yet!");
77       return 0;
78     }
79     virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
80       assert(0 && "JT not implementated yet!");
81       return 0;
82     }
83
84     virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
85       assert(MBBLocations.size() > (unsigned)MBB->getNumber() && 
86              MBBLocations[MBB->getNumber()] && "MBB not emitted!");
87       return MBBLocations[MBB->getNumber()];
88     }
89
90     /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
91     void startFunctionStub(unsigned StubSize) {
92       assert(0 && "JIT specific function called!");
93       abort();
94     }
95     void *finishFunctionStub(const Function *F) {
96       assert(0 && "JIT specific function called!");
97       abort();
98       return 0;
99     }
100   };
101 }
102
103 /// startFunction - This callback is invoked when a new machine function is
104 /// about to be emitted.
105 void MachOCodeEmitter::startFunction(MachineFunction &F) {
106   // Align the output buffer to the appropriate alignment, power of 2.
107   // FIXME: GENERICIZE!!
108   unsigned Align = 4;
109
110   // Get the Mach-O Section that this function belongs in.
111   MOS = &MOW.getTextSection();
112   
113    // FIXME: better memory management
114   MOS->SectionData.reserve(4096);
115   BufferBegin = &(MOS->SectionData[0]);
116   BufferEnd = BufferBegin + MOS->SectionData.capacity();
117   CurBufferPtr = BufferBegin + MOS->size;
118
119   // Upgrade the section alignment if required.
120   if (MOS->align < Align) MOS->align = Align;
121
122   // Make sure we only relocate to this function's MBBs.
123   MBBLocations.clear();
124 }
125
126 /// finishFunction - This callback is invoked after the function is completely
127 /// finished.
128 bool MachOCodeEmitter::finishFunction(MachineFunction &F) {
129   MOS->size += CurBufferPtr - BufferBegin;
130   
131   // Get a symbol for the function to add to the symbol table
132   MachOWriter::MachOSym FnSym(F.getFunction(), MOS->Index);
133   
134   // Figure out the binding (linkage) of the symbol.
135   switch (F.getFunction()->getLinkage()) {
136   default:
137     // appending linkage is illegal for functions.
138     assert(0 && "Unknown linkage type!");
139   case GlobalValue::ExternalLinkage:
140     FnSym.n_type = MachOWriter::MachOSym::N_SECT | MachOWriter::MachOSym::N_EXT;
141     break;
142   case GlobalValue::InternalLinkage:
143     FnSym.n_type = MachOWriter::MachOSym::N_SECT;
144     break;
145   }
146   
147   // Resolve the function's relocations either to concrete pointers in the case
148   // of branches from one block to another, or to target relocation entries.
149   for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
150     MachineRelocation &MR = Relocations[i];
151     if (MR.isBasicBlock()) {
152       void *MBBAddr = (void *)getMachineBasicBlockAddress(MR.getBasicBlock());
153       MR.setResultPointer(MBBAddr);
154       MOW.TM.getJITInfo()->relocate(BufferBegin, &MR, 1, 0);
155       // FIXME: we basically want the JITInfo relocate() function to rewrite
156       //        this guy right now, so we just write the correct displacement
157       //        to the file.
158     } else {
159       // isString | isGV | isCPI | isJTI
160       // FIXME: do something smart here.  We won't be able to relocate these
161       //        until the sections are all layed out, but we still need to
162       //        record them.  Maybe emit TargetRelocations and then resolve
163       //        those at file writing time?
164       std::cerr << "whee!\n";
165     }
166   }
167   Relocations.clear();
168   
169   // Finally, add it to the symtab.
170   MOW.SymbolTable.push_back(FnSym);
171   return false;
172 }
173
174 //===----------------------------------------------------------------------===//
175 //                          MachOWriter Implementation
176 //===----------------------------------------------------------------------===//
177
178 MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
179   // FIXME: set cpu type and cpu subtype somehow from TM
180   is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
181   isLittleEndian = TM.getTargetData()->isLittleEndian();
182
183   // Create the machine code emitter object for this target.
184   MCE = new MachOCodeEmitter(*this);
185 }
186
187 MachOWriter::~MachOWriter() {
188   delete MCE;
189 }
190
191 void MachOWriter::EmitGlobal(GlobalVariable *GV) {
192   // FIXME: do something smart here.
193 }
194
195
196 bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
197   // Nothing to do here, this is all done through the MCE object.
198   return false;
199 }
200
201 bool MachOWriter::doInitialization(Module &M) {
202   // Set the magic value, now that we know the pointer size and endianness
203   Header.setMagic(isLittleEndian, is64Bit);
204
205   // Set the file type
206   // FIXME: this only works for object files, we do not support the creation
207   //        of dynamic libraries or executables at this time.
208   Header.filetype = MachOHeader::MH_OBJECT;
209
210   Mang = new Mangler(M);
211   return false;
212 }
213
214 /// doFinalization - Now that the module has been completely processed, emit
215 /// the Mach-O file to 'O'.
216 bool MachOWriter::doFinalization(Module &M) {
217   // Okay, the.text section has been completed, build the .data, .bss, and 
218   // "common" sections next.
219   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
220        I != E; ++I)
221     EmitGlobal(I);
222   
223   // Emit the header and load commands.
224   EmitHeaderAndLoadCommands();
225
226   // Emit the text and data sections.
227   EmitSections();
228
229   // Emit the relocation entry data for each section.
230   // FIXME: presumably this should be a virtual method, since different targets
231   //        have different relocation types.
232   EmitRelocations();
233
234   // Emit the symbol table.
235   // FIXME: we don't handle debug info yet, we should probably do that.
236   EmitSymbolTable();
237
238   // Emit the string table for the sections we have.
239   EmitStringTable();
240
241   // We are done with the abstract symbols.
242   SectionList.clear();
243   SymbolTable.clear();
244   DynamicSymbolTable.clear();
245
246   // Release the name mangler object.
247   delete Mang; Mang = 0;
248   return false;
249 }
250
251 void MachOWriter::EmitHeaderAndLoadCommands() {
252   // Step #0: Fill in the segment load command size, since we need it to figure
253   //          out the rest of the header fields
254   MachOSegment SEG("", is64Bit);
255   SEG.nsects  = SectionList.size();
256   SEG.cmdsize = SEG.cmdSize(is64Bit) + 
257                 SEG.nsects * SectionList.begin()->cmdSize(is64Bit);
258   
259   // Step #1: calculate the number of load commands.  We always have at least
260   //          one, for the LC_SEGMENT load command, plus two for the normal
261   //          and dynamic symbol tables, if there are any symbols.
262   Header.ncmds = SymbolTable.empty() ? 1 : 3;
263   
264   // Step #2: calculate the size of the load commands
265   Header.sizeofcmds = SEG.cmdsize;
266   if (!SymbolTable.empty())
267     Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
268     
269   // Step #3: write the header to the file
270   // Local alias to shortenify coming code.
271   DataBuffer &FH = Header.HeaderData;
272   outword(FH, Header.magic);
273   outword(FH, Header.cputype);
274   outword(FH, Header.cpusubtype);
275   outword(FH, Header.filetype);
276   outword(FH, Header.ncmds);
277   outword(FH, Header.sizeofcmds);
278   outword(FH, Header.flags);
279   if (is64Bit)
280     outword(FH, Header.reserved);
281   
282   // Step #4: Finish filling in the segment load command and write it out
283   for (std::list<MachOSection>::iterator I = SectionList.begin(),
284          E = SectionList.end(); I != E; ++I)
285     SEG.filesize += I->size;
286   SEG.vmsize = SEG.filesize;
287   SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
288   
289   outword(FH, SEG.cmd);
290   outword(FH, SEG.cmdsize);
291   outstring(FH, SEG.segname, 16);
292   outaddr(FH, SEG.vmaddr);
293   outaddr(FH, SEG.vmsize);
294   outaddr(FH, SEG.fileoff);
295   outaddr(FH, SEG.filesize);
296   outword(FH, SEG.maxprot);
297   outword(FH, SEG.initprot);
298   outword(FH, SEG.nsects);
299   outword(FH, SEG.flags);
300   
301   // Step #5: Write out the section commands for each section
302   for (std::list<MachOSection>::iterator I = SectionList.begin(),
303          E = SectionList.end(); I != E; ++I) {
304     I->offset = SEG.fileoff;  // FIXME: separate offset
305     outstring(FH, I->sectname, 16);
306     outstring(FH, I->segname, 16);
307     outaddr(FH, I->addr);
308     outaddr(FH, I->size);
309     outword(FH, I->offset);
310     outword(FH, I->align);
311     outword(FH, I->reloff);
312     outword(FH, I->nreloc);
313     outword(FH, I->flags);
314     outword(FH, I->reserved1);
315     outword(FH, I->reserved2);
316     if (is64Bit)
317       outword(FH, I->reserved3);
318   }
319   
320   // Step #6: Emit LC_SYMTAB/LC_DYSYMTAB load commands
321   // FIXME: We'll need to scan over the symbol table and possibly do the sort
322   // here so that we can set the proper indices in the dysymtab load command for
323   // the index and number of external symbols defined in this module.
324   // FIXME: We'll also need to scan over all the symbols so that we can 
325   // calculate the size of the string table.
326   // FIXME: add size of relocs
327   SymTab.symoff  = SEG.fileoff + SEG.filesize;
328   SymTab.nsyms   = SymbolTable.size();
329   SymTab.stroff  = SymTab.symoff + SymTab.nsyms * MachOSym::entrySize();
330   SymTab.strsize = 10;
331   outword(FH, SymTab.cmd);
332   outword(FH, SymTab.cmdsize);
333   outword(FH, SymTab.symoff);
334   outword(FH, SymTab.nsyms);
335   outword(FH, SymTab.stroff);
336   outword(FH, SymTab.strsize);
337
338   // FIXME: set DySymTab fields appropriately
339   outword(FH, DySymTab.cmd);
340   outword(FH, DySymTab.cmdsize);
341   outword(FH, DySymTab.ilocalsym);
342   outword(FH, DySymTab.nlocalsym);
343   outword(FH, DySymTab.iextdefsym);
344   outword(FH, DySymTab.nextdefsym);
345   outword(FH, DySymTab.iundefsym);
346   outword(FH, DySymTab.nundefsym);
347   outword(FH, DySymTab.tocoff);
348   outword(FH, DySymTab.ntoc);
349   outword(FH, DySymTab.modtaboff);
350   outword(FH, DySymTab.nmodtab);
351   outword(FH, DySymTab.extrefsymoff);
352   outword(FH, DySymTab.nextrefsyms);
353   outword(FH, DySymTab.indirectsymoff);
354   outword(FH, DySymTab.nindirectsyms);
355   outword(FH, DySymTab.extreloff);
356   outword(FH, DySymTab.nextrel);
357   outword(FH, DySymTab.locreloff);
358   outword(FH, DySymTab.nlocrel);
359   
360   O.write((char*)&FH[0], FH.size());
361 }
362
363 /// EmitSections - Now that we have constructed the file header and load
364 /// commands, emit the data for each section to the file.
365 void MachOWriter::EmitSections() {
366   for (std::list<MachOSection>::iterator I = SectionList.begin(),
367          E = SectionList.end(); I != E; ++I) {
368     O.write((char*)&I->SectionData[0], I->size);
369   }
370 }
371
372 void MachOWriter::EmitRelocations() {
373   // FIXME: this should probably be a pure virtual function, since the
374   // relocation types and layout of the relocations themselves are target
375   // specific.
376 }
377
378 /// EmitSymbolTable - Sort the symbols we encountered and assign them each a 
379 /// string table index so that they appear in the correct order in the output 
380 /// file.
381 void MachOWriter::EmitSymbolTable() {
382   // The order of the symbol table is:
383   // local symbols
384   // defined external symbols (sorted by name)
385   // undefined external symbols (sorted by name)
386   DataBuffer ST;
387   
388   // FIXME: enforce the above ordering, presumably by sorting by name, 
389   // then partitioning twice.
390   unsigned stringIndex;
391   for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
392          E = SymbolTable.end(); I != E; ++I) {
393     // FIXME: remove when we actually calculate these correctly
394     I->n_strx = 1;
395     StringTable.push_back(Mang->getValueName(I->GV));
396     // Emit nlist to buffer
397     outword(ST, I->n_strx);
398     outbyte(ST, I->n_type);
399     outbyte(ST, I->n_sect);
400     outhalf(ST, I->n_desc);
401     outaddr(ST, I->n_value);
402   }
403   
404   O.write((char*)&ST[0], ST.size());
405 }
406
407 /// EmitStringTable - This method adds and emits a section for the Mach-O 
408 /// string table.
409 void MachOWriter::EmitStringTable() {
410   // The order of the string table is:
411   // strings for external symbols
412   // strings for local symbols
413   // This is the symbol table, but backwards.  This allows us to avoid a sorting
414   // the symbol table again; all we have to do is use a reverse iterator.
415   DataBuffer ST;
416
417   // Write out a leading zero byte when emitting string table, for n_strx == 0
418   // which means an empty string.
419   outbyte(ST, 0);
420
421   for (std::vector<std::string>::iterator I = StringTable.begin(),
422          E = StringTable.end(); I != E; ++I) {
423     // FIXME: do not arbitrarily cap symbols to 16 characters
424     // FIXME: do something more efficient than outstring
425     outstring(ST, *I, 16);
426   }
427   O.write((char*)&ST[0], ST.size());
428 }