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