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