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