Generalize TargetData strings, to support more interesting forms of data.
[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 "MachOWriter.h"
26 #include "llvm/Constants.h"
27 #include "llvm/DerivedTypes.h"
28 #include "llvm/Module.h"
29 #include "llvm/PassManager.h"
30 #include "llvm/CodeGen/FileWriters.h"
31 #include "llvm/CodeGen/MachineCodeEmitter.h"
32 #include "llvm/CodeGen/MachineConstantPool.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/ExecutionEngine/ExecutionEngine.h"
35 #include "llvm/Target/TargetAsmInfo.h"
36 #include "llvm/Target/TargetJITInfo.h"
37 #include "llvm/Support/Mangler.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/OutputBuffer.h"
40 #include "llvm/Support/Streams.h"
41 #include <algorithm>
42 using namespace llvm;
43
44 /// AddMachOWriter - Concrete function to add the Mach-O writer to the function
45 /// pass manager.
46 MachineCodeEmitter *llvm::AddMachOWriter(FunctionPassManager &FPM,
47                                          std::ostream &O,
48                                          TargetMachine &TM) {
49   MachOWriter *MOW = new MachOWriter(O, TM);
50   FPM.add(MOW);
51   return &MOW->getMachineCodeEmitter();
52 }
53
54 //===----------------------------------------------------------------------===//
55 //                       MachOCodeEmitter Implementation
56 //===----------------------------------------------------------------------===//
57
58 namespace llvm {
59   /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code 
60   /// for functions to the Mach-O file.
61   class MachOCodeEmitter : public MachineCodeEmitter {
62     MachOWriter &MOW;
63
64     /// Target machine description.
65     TargetMachine &TM;
66
67     /// is64Bit/isLittleEndian - This information is inferred from the target
68     /// machine directly, indicating what header values and flags to set.
69     bool is64Bit, isLittleEndian;
70
71     /// Relocations - These are the relocations that the function needs, as
72     /// emitted.
73     std::vector<MachineRelocation> Relocations;
74     
75     /// CPLocations - This is a map of constant pool indices to offsets from the
76     /// start of the section for that constant pool index.
77     std::vector<intptr_t> CPLocations;
78
79     /// CPSections - This is a map of constant pool indices to the MachOSection
80     /// containing the constant pool entry for that index.
81     std::vector<unsigned> CPSections;
82
83     /// JTLocations - This is a map of jump table indices to offsets from the
84     /// start of the section for that jump table index.
85     std::vector<intptr_t> JTLocations;
86
87     /// MBBLocations - This vector is a mapping from MBB ID's to their address.
88     /// It is filled in by the StartMachineBasicBlock callback and queried by
89     /// the getMachineBasicBlockAddress callback.
90     std::vector<intptr_t> MBBLocations;
91     
92   public:
93     MachOCodeEmitter(MachOWriter &mow) : MOW(mow), TM(MOW.TM) {
94       is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
95       isLittleEndian = TM.getTargetData()->isLittleEndian();
96     }
97
98     virtual void startFunction(MachineFunction &MF);
99     virtual bool finishFunction(MachineFunction &MF);
100
101     virtual void addRelocation(const MachineRelocation &MR) {
102       Relocations.push_back(MR);
103     }
104     
105     void emitConstantPool(MachineConstantPool *MCP);
106     void emitJumpTables(MachineJumpTableInfo *MJTI);
107     
108     virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
109       assert(CPLocations.size() > Index && "CP not emitted!");
110       return CPLocations[Index];
111     }
112     virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
113       assert(JTLocations.size() > Index && "JT not emitted!");
114       return JTLocations[Index];
115     }
116
117     virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
118       if (MBBLocations.size() <= (unsigned)MBB->getNumber())
119         MBBLocations.resize((MBB->getNumber()+1)*2);
120       MBBLocations[MBB->getNumber()] = getCurrentPCOffset();
121     }
122
123     virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
124       assert(MBBLocations.size() > (unsigned)MBB->getNumber() && 
125              MBBLocations[MBB->getNumber()] && "MBB not emitted!");
126       return MBBLocations[MBB->getNumber()];
127     }
128
129     /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
130     virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
131       assert(0 && "JIT specific function called!");
132       abort();
133     }
134     virtual void *finishFunctionStub(const Function *F) {
135       assert(0 && "JIT specific function called!");
136       abort();
137       return 0;
138     }
139   };
140 }
141
142 /// startFunction - This callback is invoked when a new machine function is
143 /// about to be emitted.
144 void MachOCodeEmitter::startFunction(MachineFunction &MF) {
145   const TargetData *TD = TM.getTargetData();
146   const Function *F = MF.getFunction();
147
148   // Align the output buffer to the appropriate alignment, power of 2.
149   unsigned FnAlign = F->getAlignment();
150   unsigned TDAlign = TD->getPrefTypeAlignment(F->getType());
151   unsigned Align = Log2_32(std::max(FnAlign, TDAlign));
152   assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
153
154   // Get the Mach-O Section that this function belongs in.
155   MachOWriter::MachOSection *MOS = MOW.getTextSection();
156   
157   // FIXME: better memory management
158   MOS->SectionData.reserve(4096);
159   BufferBegin = &MOS->SectionData[0];
160   BufferEnd = BufferBegin + MOS->SectionData.capacity();
161
162   // Upgrade the section alignment if required.
163   if (MOS->align < Align) MOS->align = Align;
164
165   // Round the size up to the correct alignment for starting the new function.
166   if ((MOS->size & ((1 << Align) - 1)) != 0) {
167     MOS->size += (1 << Align);
168     MOS->size &= ~((1 << Align) - 1);
169   }
170
171   // FIXME: Using MOS->size directly here instead of calculating it from the
172   // output buffer size (impossible because the code emitter deals only in raw
173   // bytes) forces us to manually synchronize size and write padding zero bytes
174   // to the output buffer for all non-text sections.  For text sections, we do
175   // not synchonize the output buffer, and we just blow up if anyone tries to
176   // write non-code to it.  An assert should probably be added to
177   // AddSymbolToSection to prevent calling it on the text section.
178   CurBufferPtr = BufferBegin + MOS->size;
179
180   // Clear per-function data structures.
181   CPLocations.clear();
182   CPSections.clear();
183   JTLocations.clear();
184   MBBLocations.clear();
185 }
186
187 /// finishFunction - This callback is invoked after the function is completely
188 /// finished.
189 bool MachOCodeEmitter::finishFunction(MachineFunction &MF) {
190   // Get the Mach-O Section that this function belongs in.
191   MachOWriter::MachOSection *MOS = MOW.getTextSection();
192
193   // Get a symbol for the function to add to the symbol table
194   // FIXME: it seems like we should call something like AddSymbolToSection
195   // in startFunction rather than changing the section size and symbol n_value
196   // here.
197   const GlobalValue *FuncV = MF.getFunction();
198   MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, TM);
199   FnSym.n_value = MOS->size;
200   MOS->size = CurBufferPtr - BufferBegin;
201   
202   // Emit constant pool to appropriate section(s)
203   emitConstantPool(MF.getConstantPool());
204
205   // Emit jump tables to appropriate section
206   emitJumpTables(MF.getJumpTableInfo());
207   
208   // If we have emitted any relocations to function-specific objects such as 
209   // basic blocks, constant pools entries, or jump tables, record their
210   // addresses now so that we can rewrite them with the correct addresses
211   // later.
212   for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
213     MachineRelocation &MR = Relocations[i];
214     intptr_t Addr;
215
216     if (MR.isBasicBlock()) {
217       Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
218       MR.setConstantVal(MOS->Index);
219       MR.setResultPointer((void*)Addr);
220     } else if (MR.isJumpTableIndex()) {
221       Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
222       MR.setConstantVal(MOW.getJumpTableSection()->Index);
223       MR.setResultPointer((void*)Addr);
224     } else if (MR.isConstantPoolIndex()) {
225       Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
226       MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
227       MR.setResultPointer((void*)Addr);
228     } else if (!MR.isGlobalValue()) {
229       assert(0 && "Unhandled relocation type");
230     }
231     MOS->Relocations.push_back(MR);
232   }
233   Relocations.clear();
234   
235   // Finally, add it to the symtab.
236   MOW.SymbolTable.push_back(FnSym);
237   return false;
238 }
239
240 /// emitConstantPool - For each constant pool entry, figure out which section
241 /// the constant should live in, allocate space for it, and emit it to the 
242 /// Section data buffer.
243 void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
244   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
245   if (CP.empty()) return;
246
247   // FIXME: handle PIC codegen
248   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
249   assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
250
251   // Although there is no strict necessity that I am aware of, we will do what
252   // gcc for OS X does and put each constant pool entry in a section of constant
253   // objects of a certain size.  That means that float constants go in the
254   // literal4 section, and double objects go in literal8, etc.
255   //
256   // FIXME: revisit this decision if we ever do the "stick everything into one
257   // "giant object for PIC" optimization.
258   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
259     const Type *Ty = CP[i].getType();
260     unsigned Size = TM.getTargetData()->getTypeSize(Ty);
261
262     MachOWriter::MachOSection *Sec = MOW.getConstSection(CP[i].Val.ConstVal);
263     OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
264
265     CPLocations.push_back(Sec->SectionData.size());
266     CPSections.push_back(Sec->Index);
267     
268     // FIXME: remove when we have unified size + output buffer
269     Sec->size += Size;
270
271     // Allocate space in the section for the global.
272     // FIXME: need alignment?
273     // FIXME: share between here and AddSymbolToSection?
274     for (unsigned j = 0; j < Size; ++j)
275       SecDataOut.outbyte(0);
276
277     MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
278                 TM.getTargetData(), Sec->Relocations);
279   }
280 }
281
282 /// emitJumpTables - Emit all the jump tables for a given jump table info
283 /// record to the appropriate section.
284 void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
285   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
286   if (JT.empty()) return;
287
288   // FIXME: handle PIC codegen
289   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
290   assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
291
292   MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
293   unsigned TextSecIndex = MOW.getTextSection()->Index;
294   OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
295
296   for (unsigned i = 0, e = JT.size(); i != e; ++i) {
297     // For each jump table, record its offset from the start of the section,
298     // reserve space for the relocations to the MBBs, and add the relocations.
299     const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
300     JTLocations.push_back(Sec->SectionData.size());
301     for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
302       MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
303                                                MBBs[mi]));
304       MR.setResultPointer((void *)JTLocations[i]);
305       MR.setConstantVal(TextSecIndex);
306       Sec->Relocations.push_back(MR);
307       SecDataOut.outaddr(0);
308     }
309   }
310   // FIXME: remove when we have unified size + output buffer
311   Sec->size = Sec->SectionData.size();
312 }
313
314 //===----------------------------------------------------------------------===//
315 //                          MachOWriter Implementation
316 //===----------------------------------------------------------------------===//
317
318 MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
319   is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
320   isLittleEndian = TM.getTargetData()->isLittleEndian();
321
322   // Create the machine code emitter object for this target.
323   MCE = new MachOCodeEmitter(*this);
324 }
325
326 MachOWriter::~MachOWriter() {
327   delete MCE;
328 }
329
330 void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
331   const Type *Ty = GV->getType()->getElementType();
332   unsigned Size = TM.getTargetData()->getTypeSize(Ty);
333   unsigned Align = GV->getAlignment();
334   if (Align == 0)
335     Align = TM.getTargetData()->getPrefTypeAlignment(Ty);
336   
337   MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
338   
339   // Reserve space in the .bss section for this symbol while maintaining the
340   // desired section alignment, which must be at least as much as required by
341   // this symbol.
342   OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
343
344   if (Align) {
345     uint64_t OrigSize = Sec->size;
346     Align = Log2_32(Align);
347     Sec->align = std::max(unsigned(Sec->align), Align);
348     Sec->size = (Sec->size + Align - 1) & ~(Align-1);
349     
350     // Add alignment padding to buffer as well.
351     // FIXME: remove when we have unified size + output buffer
352     unsigned AlignedSize = Sec->size - OrigSize;
353     for (unsigned i = 0; i < AlignedSize; ++i)
354       SecDataOut.outbyte(0);
355   }
356   // Record the offset of the symbol, and then allocate space for it.
357   // FIXME: remove when we have unified size + output buffer
358   Sym.n_value = Sec->size;
359   Sec->size += Size;
360   SymbolTable.push_back(Sym);
361
362   // Now that we know what section the GlovalVariable is going to be emitted 
363   // into, update our mappings.
364   // FIXME: We may also need to update this when outputting non-GlobalVariable
365   // GlobalValues such as functions.
366   GVSection[GV] = Sec;
367   GVOffset[GV] = Sec->SectionData.size();
368   
369   // Allocate space in the section for the global.
370   for (unsigned i = 0; i < Size; ++i)
371     SecDataOut.outbyte(0);
372 }
373
374 void MachOWriter::EmitGlobal(GlobalVariable *GV) {
375   const Type *Ty = GV->getType()->getElementType();
376   unsigned Size = TM.getTargetData()->getTypeSize(Ty);
377   bool NoInit = !GV->hasInitializer();
378   
379   // If this global has a zero initializer, it is part of the .bss or common
380   // section.
381   if (NoInit || GV->getInitializer()->isNullValue()) {
382     // If this global is part of the common block, add it now.  Variables are
383     // part of the common block if they are zero initialized and allowed to be
384     // merged with other symbols.
385     if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
386       MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
387       // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
388       // bytes of the symbol.
389       ExtOrCommonSym.n_value = Size;
390       // If the symbol is external, we'll put it on a list of symbols whose
391       // addition to the symbol table is being pended until we find a reference
392       if (NoInit)
393         PendingSyms.push_back(ExtOrCommonSym);
394       else
395         SymbolTable.push_back(ExtOrCommonSym);
396       return;
397     }
398     // Otherwise, this symbol is part of the .bss section.
399     MachOSection *BSS = getBSSSection();
400     AddSymbolToSection(BSS, GV);
401     return;
402   }
403   
404   // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
405   // 16 bytes, or a cstring.  Other read only data goes into a regular const
406   // section.  Read-write data goes in the data section.
407   MachOSection *Sec = GV->isConstant() ? getConstSection(GV->getInitializer()) : 
408                                          getDataSection();
409   AddSymbolToSection(Sec, GV);
410   InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
411           TM.getTargetData(), Sec->Relocations);
412 }
413
414
415 bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
416   // Nothing to do here, this is all done through the MCE object.
417   return false;
418 }
419
420 bool MachOWriter::doInitialization(Module &M) {
421   // Set the magic value, now that we know the pointer size and endianness
422   Header.setMagic(isLittleEndian, is64Bit);
423
424   // Set the file type
425   // FIXME: this only works for object files, we do not support the creation
426   //        of dynamic libraries or executables at this time.
427   Header.filetype = MachOHeader::MH_OBJECT;
428
429   Mang = new Mangler(M);
430   return false;
431 }
432
433 /// doFinalization - Now that the module has been completely processed, emit
434 /// the Mach-O file to 'O'.
435 bool MachOWriter::doFinalization(Module &M) {
436   // FIXME: we don't handle debug info yet, we should probably do that.
437
438   // Okay, the.text section has been completed, build the .data, .bss, and 
439   // "common" sections next.
440   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
441        I != E; ++I)
442     EmitGlobal(I);
443   
444   // Emit the header and load commands.
445   EmitHeaderAndLoadCommands();
446
447   // Emit the various sections and their relocation info.
448   EmitSections();
449
450   // Write the symbol table and the string table to the end of the file.
451   O.write((char*)&SymT[0], SymT.size());
452   O.write((char*)&StrT[0], StrT.size());
453
454   // We are done with the abstract symbols.
455   SectionList.clear();
456   SymbolTable.clear();
457   DynamicSymbolTable.clear();
458
459   // Release the name mangler object.
460   delete Mang; Mang = 0;
461   return false;
462 }
463
464 void MachOWriter::EmitHeaderAndLoadCommands() {
465   // Step #0: Fill in the segment load command size, since we need it to figure
466   //          out the rest of the header fields
467   MachOSegment SEG("", is64Bit);
468   SEG.nsects  = SectionList.size();
469   SEG.cmdsize = SEG.cmdSize(is64Bit) + 
470                 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
471   
472   // Step #1: calculate the number of load commands.  We always have at least
473   //          one, for the LC_SEGMENT load command, plus two for the normal
474   //          and dynamic symbol tables, if there are any symbols.
475   Header.ncmds = SymbolTable.empty() ? 1 : 3;
476   
477   // Step #2: calculate the size of the load commands
478   Header.sizeofcmds = SEG.cmdsize;
479   if (!SymbolTable.empty())
480     Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
481     
482   // Step #3: write the header to the file
483   // Local alias to shortenify coming code.
484   DataBuffer &FH = Header.HeaderData;
485   OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
486
487   FHOut.outword(Header.magic);
488   FHOut.outword(TM.getMachOWriterInfo()->getCPUType());
489   FHOut.outword(TM.getMachOWriterInfo()->getCPUSubType());
490   FHOut.outword(Header.filetype);
491   FHOut.outword(Header.ncmds);
492   FHOut.outword(Header.sizeofcmds);
493   FHOut.outword(Header.flags);
494   if (is64Bit)
495     FHOut.outword(Header.reserved);
496   
497   // Step #4: Finish filling in the segment load command and write it out
498   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
499          E = SectionList.end(); I != E; ++I)
500     SEG.filesize += (*I)->size;
501
502   SEG.vmsize = SEG.filesize;
503   SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
504   
505   FHOut.outword(SEG.cmd);
506   FHOut.outword(SEG.cmdsize);
507   FHOut.outstring(SEG.segname, 16);
508   FHOut.outaddr(SEG.vmaddr);
509   FHOut.outaddr(SEG.vmsize);
510   FHOut.outaddr(SEG.fileoff);
511   FHOut.outaddr(SEG.filesize);
512   FHOut.outword(SEG.maxprot);
513   FHOut.outword(SEG.initprot);
514   FHOut.outword(SEG.nsects);
515   FHOut.outword(SEG.flags);
516   
517   // Step #5: Finish filling in the fields of the MachOSections 
518   uint64_t currentAddr = 0;
519   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
520          E = SectionList.end(); I != E; ++I) {
521     MachOSection *MOS = *I;
522     MOS->addr = currentAddr;
523     MOS->offset = currentAddr + SEG.fileoff;
524
525     // FIXME: do we need to do something with alignment here?
526     currentAddr += MOS->size;
527   }
528   
529   // Step #6: Calculate the number of relocations for each section and write out
530   // the section commands for each section
531   currentAddr += SEG.fileoff;
532   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
533          E = SectionList.end(); I != E; ++I) {
534     MachOSection *MOS = *I;
535     // Convert the relocations to target-specific relocations, and fill in the
536     // relocation offset for this section.
537     CalculateRelocations(*MOS);
538     MOS->reloff = MOS->nreloc ? currentAddr : 0;
539     currentAddr += MOS->nreloc * 8;
540     
541     // write the finalized section command to the output buffer
542     FHOut.outstring(MOS->sectname, 16);
543     FHOut.outstring(MOS->segname, 16);
544     FHOut.outaddr(MOS->addr);
545     FHOut.outaddr(MOS->size);
546     FHOut.outword(MOS->offset);
547     FHOut.outword(MOS->align);
548     FHOut.outword(MOS->reloff);
549     FHOut.outword(MOS->nreloc);
550     FHOut.outword(MOS->flags);
551     FHOut.outword(MOS->reserved1);
552     FHOut.outword(MOS->reserved2);
553     if (is64Bit)
554       FHOut.outword(MOS->reserved3);
555   }
556   
557   // Step #7: Emit the symbol table to temporary buffers, so that we know the
558   // size of the string table when we write the next load command.
559   BufferSymbolAndStringTable();
560   
561   // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
562   SymTab.symoff  = currentAddr;
563   SymTab.nsyms   = SymbolTable.size();
564   SymTab.stroff  = SymTab.symoff + SymT.size();
565   SymTab.strsize = StrT.size();
566   FHOut.outword(SymTab.cmd);
567   FHOut.outword(SymTab.cmdsize);
568   FHOut.outword(SymTab.symoff);
569   FHOut.outword(SymTab.nsyms);
570   FHOut.outword(SymTab.stroff);
571   FHOut.outword(SymTab.strsize);
572
573   // FIXME: set DySymTab fields appropriately
574   // We should probably just update these in BufferSymbolAndStringTable since
575   // thats where we're partitioning up the different kinds of symbols.
576   FHOut.outword(DySymTab.cmd);
577   FHOut.outword(DySymTab.cmdsize);
578   FHOut.outword(DySymTab.ilocalsym);
579   FHOut.outword(DySymTab.nlocalsym);
580   FHOut.outword(DySymTab.iextdefsym);
581   FHOut.outword(DySymTab.nextdefsym);
582   FHOut.outword(DySymTab.iundefsym);
583   FHOut.outword(DySymTab.nundefsym);
584   FHOut.outword(DySymTab.tocoff);
585   FHOut.outword(DySymTab.ntoc);
586   FHOut.outword(DySymTab.modtaboff);
587   FHOut.outword(DySymTab.nmodtab);
588   FHOut.outword(DySymTab.extrefsymoff);
589   FHOut.outword(DySymTab.nextrefsyms);
590   FHOut.outword(DySymTab.indirectsymoff);
591   FHOut.outword(DySymTab.nindirectsyms);
592   FHOut.outword(DySymTab.extreloff);
593   FHOut.outword(DySymTab.nextrel);
594   FHOut.outword(DySymTab.locreloff);
595   FHOut.outword(DySymTab.nlocrel);
596   
597   O.write((char*)&FH[0], FH.size());
598 }
599
600 /// EmitSections - Now that we have constructed the file header and load
601 /// commands, emit the data for each section to the file.
602 void MachOWriter::EmitSections() {
603   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
604          E = SectionList.end(); I != E; ++I)
605     // Emit the contents of each section
606     O.write((char*)&(*I)->SectionData[0], (*I)->size);
607   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
608          E = SectionList.end(); I != E; ++I)
609     // Emit the relocation entry data for each section.
610     O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
611 }
612
613 /// PartitionByLocal - Simple boolean predicate that returns true if Sym is
614 /// a local symbol rather than an external symbol.
615 bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
616   return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
617 }
618
619 /// PartitionByDefined - Simple boolean predicate that returns true if Sym is
620 /// defined in this module.
621 bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
622   // FIXME: Do N_ABS or N_INDR count as defined?
623   return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
624 }
625
626 /// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
627 /// each a string table index so that they appear in the correct order in the
628 /// output file.
629 void MachOWriter::BufferSymbolAndStringTable() {
630   // The order of the symbol table is:
631   // 1. local symbols
632   // 2. defined external symbols (sorted by name)
633   // 3. undefined external symbols (sorted by name)
634   
635   // Sort the symbols by name, so that when we partition the symbols by scope
636   // of definition, we won't have to sort by name within each partition.
637   std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
638
639   // Parition the symbol table entries so that all local symbols come before 
640   // all symbols with external linkage. { 1 | 2 3 }
641   std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
642   
643   // Advance iterator to beginning of external symbols and partition so that
644   // all external symbols defined in this module come before all external
645   // symbols defined elsewhere. { 1 | 2 | 3 }
646   for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
647          E = SymbolTable.end(); I != E; ++I) {
648     if (!PartitionByLocal(*I)) {
649       std::partition(I, E, PartitionByDefined);
650       break;
651     }
652   }
653
654   // Calculate the starting index for each of the local, extern defined, and 
655   // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
656   // load command.
657   for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
658          E = SymbolTable.end(); I != E; ++I) {
659     if (PartitionByLocal(*I)) {
660       ++DySymTab.nlocalsym;
661       ++DySymTab.iextdefsym;
662       ++DySymTab.iundefsym;
663     } else if (PartitionByDefined(*I)) {
664       ++DySymTab.nextdefsym;
665       ++DySymTab.iundefsym;
666     } else {
667       ++DySymTab.nundefsym;
668     }
669   }
670   
671   // Write out a leading zero byte when emitting string table, for n_strx == 0
672   // which means an empty string.
673   OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
674   StrTOut.outbyte(0);
675
676   // The order of the string table is:
677   // 1. strings for external symbols
678   // 2. strings for local symbols
679   // Since this is the opposite order from the symbol table, which we have just
680   // sorted, we can walk the symbol table backwards to output the string table.
681   for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
682         E = SymbolTable.rend(); I != E; ++I) {
683     if (I->GVName == "") {
684       I->n_strx = 0;
685     } else {
686       I->n_strx = StrT.size();
687       StrTOut.outstring(I->GVName, I->GVName.length()+1);
688     }
689   }
690
691   OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
692
693   for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
694          E = SymbolTable.end(); I != E; ++I) {
695     // Add the section base address to the section offset in the n_value field
696     // to calculate the full address.
697     // FIXME: handle symbols where the n_value field is not the address
698     GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
699     if (GV && GVSection[GV])
700       I->n_value += GVSection[GV]->addr;
701          
702     // Emit nlist to buffer
703     SymTOut.outword(I->n_strx);
704     SymTOut.outbyte(I->n_type);
705     SymTOut.outbyte(I->n_sect);
706     SymTOut.outhalf(I->n_desc);
707     SymTOut.outaddr(I->n_value);
708   }
709 }
710
711 /// CalculateRelocations - For each MachineRelocation in the current section,
712 /// calculate the index of the section containing the object to be relocated,
713 /// and the offset into that section.  From this information, create the
714 /// appropriate target-specific MachORelocation type and add buffer it to be
715 /// written out after we are finished writing out sections.
716 void MachOWriter::CalculateRelocations(MachOSection &MOS) {
717   for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
718     MachineRelocation &MR = MOS.Relocations[i];
719     unsigned TargetSection = MR.getConstantVal();
720
721     // This is a scattered relocation entry if it points to a global value with
722     // a non-zero offset.
723     bool Scattered = false;
724     
725     // Since we may not have seen the GlobalValue we were interested in yet at
726     // the time we emitted the relocation for it, fix it up now so that it
727     // points to the offset into the correct section.
728     if (MR.isGlobalValue()) {
729       GlobalValue *GV = MR.getGlobalValue();
730       MachOSection *MOSPtr = GVSection[GV];
731       intptr_t Offset = GVOffset[GV];
732       Scattered = TargetSection != 0;
733       
734       if (!MOSPtr) {
735         cerr << "Trying to relocate unknown global " << *GV << '\n';
736         continue;
737         //abort();
738       }
739       
740       TargetSection = MOSPtr->Index;
741       MR.setResultPointer((void*)Offset);
742     }
743
744     OutputBuffer RelocOut(MOS.RelocBuffer, is64Bit, isLittleEndian);
745     OutputBuffer SecOut(MOS.SectionData, is64Bit, isLittleEndian);
746     MachOSection &To = *SectionList[TargetSection - 1];
747
748     MOS.nreloc += GetTargetRelocation(MR, MOS.Index, To.addr, To.Index,
749                                       RelocOut, SecOut, Scattered);
750   }
751 }
752
753 // InitMem - Write the value of a Constant to the specified memory location,
754 // converting it into bytes and relocations.
755 void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
756                           const TargetData *TD, 
757                           std::vector<MachineRelocation> &MRs) {
758   typedef std::pair<const Constant*, intptr_t> CPair;
759   std::vector<CPair> WorkList;
760   
761   WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
762   
763   intptr_t ScatteredOffset = 0;
764   
765   while (!WorkList.empty()) {
766     const Constant *PC = WorkList.back().first;
767     intptr_t PA = WorkList.back().second;
768     WorkList.pop_back();
769     
770     if (isa<UndefValue>(PC)) {
771       continue;
772     } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(PC)) {
773       unsigned ElementSize = TD->getTypeSize(CP->getType()->getElementType());
774       for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
775         WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
776     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
777       //
778       // FIXME: Handle ConstantExpression.  See EE::getConstantValue()
779       //
780       switch (CE->getOpcode()) {
781       case Instruction::GetElementPtr: {
782         SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
783         ScatteredOffset = TD->getIndexedOffset(CE->getOperand(0)->getType(),
784                                                &Indices[0], Indices.size());
785         WorkList.push_back(CPair(CE->getOperand(0), PA));
786         break;
787       }
788       case Instruction::Add:
789       default:
790         cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
791         abort();
792         break;
793       }
794     } else if (PC->getType()->isFirstClassType()) {
795       unsigned char *ptr = (unsigned char *)PA;
796       switch (PC->getType()->getTypeID()) {
797       case Type::IntegerTyID: {
798         unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
799         uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
800         if (NumBits <= 8)
801           ptr[0] = val;
802         else if (NumBits <= 16) {
803           if (TD->isBigEndian())
804             val = ByteSwap_16(val);
805           ptr[0] = val;
806           ptr[1] = val >> 8;
807         } else if (NumBits <= 32) {
808           if (TD->isBigEndian())
809             val = ByteSwap_32(val);
810           ptr[0] = val;
811           ptr[1] = val >> 8;
812           ptr[2] = val >> 16;
813           ptr[3] = val >> 24;
814         } else if (NumBits <= 64) {
815           if (TD->isBigEndian())
816             val = ByteSwap_64(val);
817           ptr[0] = val;
818           ptr[1] = val >> 8;
819           ptr[2] = val >> 16;
820           ptr[3] = val >> 24;
821           ptr[4] = val >> 32;
822           ptr[5] = val >> 40;
823           ptr[6] = val >> 48;
824           ptr[7] = val >> 56;
825         } else {
826           assert(0 && "Not implemented: bit widths > 64");
827         }
828         break;
829       }
830       case Type::FloatTyID: {
831         uint64_t val = FloatToBits(cast<ConstantFP>(PC)->getValue());
832         if (TD->isBigEndian())
833           val = ByteSwap_32(val);
834         ptr[0] = val;
835         ptr[1] = val >> 8;
836         ptr[2] = val >> 16;
837         ptr[3] = val >> 24;
838         break;
839       }
840       case Type::DoubleTyID: {
841         uint64_t val = DoubleToBits(cast<ConstantFP>(PC)->getValue());
842         if (TD->isBigEndian())
843           val = ByteSwap_64(val);
844         ptr[0] = val;
845         ptr[1] = val >> 8;
846         ptr[2] = val >> 16;
847         ptr[3] = val >> 24;
848         ptr[4] = val >> 32;
849         ptr[5] = val >> 40;
850         ptr[6] = val >> 48;
851         ptr[7] = val >> 56;
852         break;
853       }
854       case Type::PointerTyID:
855         if (isa<ConstantPointerNull>(PC))
856           memset(ptr, 0, TD->getPointerSize());
857         else if (const GlobalValue* GV = dyn_cast<GlobalValue>(PC)) {
858           // FIXME: what about function stubs?
859           MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr, 
860                                                  MachineRelocation::VANILLA,
861                                                  const_cast<GlobalValue*>(GV),
862                                                  ScatteredOffset));
863           ScatteredOffset = 0;
864         } else
865           assert(0 && "Unknown constant pointer type!");
866         break;
867       default:
868         cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
869         abort();
870       }
871     } else if (isa<ConstantAggregateZero>(PC)) {
872       memset((void*)PA, 0, (size_t)TD->getTypeSize(PC->getType()));
873     } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
874       unsigned ElementSize = TD->getTypeSize(CPA->getType()->getElementType());
875       for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
876         WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
877     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
878       const StructLayout *SL =
879         TD->getStructLayout(cast<StructType>(CPS->getType()));
880       for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
881         WorkList.push_back(CPair(CPS->getOperand(i),
882                                  PA+SL->getElementOffset(i)));
883     } else {
884       cerr << "Bad Type: " << *PC->getType() << "\n";
885       assert(0 && "Unknown constant type to initialize memory with!");
886     }
887   }
888 }
889
890 MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
891                    TargetMachine &TM) :
892   GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
893   n_desc(0), n_value(0) {
894
895   const TargetAsmInfo *TAI = TM.getTargetAsmInfo();  
896   
897   switch (GV->getLinkage()) {
898   default:
899     assert(0 && "Unexpected linkage type!");
900     break;
901   case GlobalValue::WeakLinkage:
902   case GlobalValue::LinkOnceLinkage:
903     assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
904   case GlobalValue::ExternalLinkage:
905     GVName = TAI->getGlobalPrefix() + name;
906     n_type |= GV->hasHiddenVisibility() ? N_PEXT : N_EXT;
907     break;
908   case GlobalValue::InternalLinkage:
909     GVName = TAI->getGlobalPrefix() + name;
910     break;
911   }
912 }