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