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