LLVM API Documentation

MachOWriter.cpp

Go to the documentation of this file.
00001 //===-- MachOWriter.cpp - Target-independent Mach-O Writer code -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the target-independent Mach-O writer.  This file writes
00011 // out the Mach-O file in the following order:
00012 //
00013 //  #1 FatHeader (universal-only)
00014 //  #2 FatArch (universal-only, 1 per universal arch)
00015 //  Per arch:
00016 //    #3 Header
00017 //    #4 Load Commands
00018 //    #5 Sections
00019 //    #6 Relocations
00020 //    #7 Symbols
00021 //    #8 Strings
00022 //
00023 //===----------------------------------------------------------------------===//
00024 
00025 #include "MachOWriter.h"
00026 #include "llvm/Constants.h"
00027 #include "llvm/DerivedTypes.h"
00028 #include "llvm/Module.h"
00029 #include "llvm/PassManager.h"
00030 #include "llvm/CodeGen/FileWriters.h"
00031 #include "llvm/CodeGen/MachineCodeEmitter.h"
00032 #include "llvm/CodeGen/MachineConstantPool.h"
00033 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00034 #include "llvm/Target/TargetAsmInfo.h"
00035 #include "llvm/Target/TargetJITInfo.h"
00036 #include "llvm/Support/Mangler.h"
00037 #include "llvm/Support/MathExtras.h"
00038 #include "llvm/Support/OutputBuffer.h"
00039 #include "llvm/Support/Streams.h"
00040 #include "llvm/Support/raw_ostream.h"
00041 #include <algorithm>
00042 #include <cstring>
00043 using namespace llvm;
00044 
00045 /// AddMachOWriter - Concrete function to add the Mach-O writer to the function
00046 /// pass manager.
00047 MachineCodeEmitter *llvm::AddMachOWriter(PassManagerBase &PM,
00048                                          raw_ostream &O,
00049                                          TargetMachine &TM) {
00050   MachOWriter *MOW = new MachOWriter(O, TM);
00051   PM.add(MOW);
00052   return &MOW->getMachineCodeEmitter();
00053 }
00054 
00055 //===----------------------------------------------------------------------===//
00056 //                       MachOCodeEmitter Implementation
00057 //===----------------------------------------------------------------------===//
00058 
00059 namespace llvm {
00060   /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code 
00061   /// for functions to the Mach-O file.
00062   class MachOCodeEmitter : public MachineCodeEmitter {
00063     MachOWriter &MOW;
00064 
00065     /// Target machine description.
00066     TargetMachine &TM;
00067 
00068     /// is64Bit/isLittleEndian - This information is inferred from the target
00069     /// machine directly, indicating what header values and flags to set.
00070     bool is64Bit, isLittleEndian;
00071 
00072     /// Relocations - These are the relocations that the function needs, as
00073     /// emitted.
00074     std::vector<MachineRelocation> Relocations;
00075     
00076     /// CPLocations - This is a map of constant pool indices to offsets from the
00077     /// start of the section for that constant pool index.
00078     std::vector<uintptr_t> CPLocations;
00079 
00080     /// CPSections - This is a map of constant pool indices to the MachOSection
00081     /// containing the constant pool entry for that index.
00082     std::vector<unsigned> CPSections;
00083 
00084     /// JTLocations - This is a map of jump table indices to offsets from the
00085     /// start of the section for that jump table index.
00086     std::vector<uintptr_t> JTLocations;
00087 
00088     /// MBBLocations - This vector is a mapping from MBB ID's to their address.
00089     /// It is filled in by the StartMachineBasicBlock callback and queried by
00090     /// the getMachineBasicBlockAddress callback.
00091     std::vector<uintptr_t> MBBLocations;
00092     
00093   public:
00094     MachOCodeEmitter(MachOWriter &mow) : MOW(mow), TM(MOW.TM) {
00095       is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
00096       isLittleEndian = TM.getTargetData()->isLittleEndian();
00097     }
00098 
00099     virtual void startFunction(MachineFunction &MF);
00100     virtual bool finishFunction(MachineFunction &MF);
00101 
00102     virtual void addRelocation(const MachineRelocation &MR) {
00103       Relocations.push_back(MR);
00104     }
00105     
00106     void emitConstantPool(MachineConstantPool *MCP);
00107     void emitJumpTables(MachineJumpTableInfo *MJTI);
00108     
00109     virtual uintptr_t getConstantPoolEntryAddress(unsigned Index) const {
00110       assert(CPLocations.size() > Index && "CP not emitted!");
00111       return CPLocations[Index];
00112     }
00113     virtual uintptr_t getJumpTableEntryAddress(unsigned Index) const {
00114       assert(JTLocations.size() > Index && "JT not emitted!");
00115       return JTLocations[Index];
00116     }
00117 
00118     virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
00119       if (MBBLocations.size() <= (unsigned)MBB->getNumber())
00120         MBBLocations.resize((MBB->getNumber()+1)*2);
00121       MBBLocations[MBB->getNumber()] = getCurrentPCOffset();
00122     }
00123 
00124     virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
00125       assert(MBBLocations.size() > (unsigned)MBB->getNumber() && 
00126              MBBLocations[MBB->getNumber()] && "MBB not emitted!");
00127       return MBBLocations[MBB->getNumber()];
00128     }
00129 
00130     virtual uintptr_t getLabelAddress(uint64_t Label) const {
00131       assert(0 && "get Label not implemented");
00132       abort();
00133       return 0;
00134     }
00135 
00136     virtual void emitLabel(uint64_t LabelID) {
00137       assert(0 && "emit Label not implemented");
00138       abort();
00139     }
00140 
00141 
00142     virtual void setModuleInfo(llvm::MachineModuleInfo* MMI) { }
00143 
00144     /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
00145     virtual void startGVStub(const GlobalValue* F, unsigned StubSize,
00146                              unsigned Alignment = 1) {
00147       assert(0 && "JIT specific function called!");
00148       abort();
00149     }
00150     virtual void *finishGVStub(const GlobalValue* F) {
00151       assert(0 && "JIT specific function called!");
00152       abort();
00153       return 0;
00154     }
00155   };
00156 }
00157 
00158 /// startFunction - This callback is invoked when a new machine function is
00159 /// about to be emitted.
00160 void MachOCodeEmitter::startFunction(MachineFunction &MF) {
00161   const TargetData *TD = TM.getTargetData();
00162   const Function *F = MF.getFunction();
00163 
00164   // Align the output buffer to the appropriate alignment, power of 2.
00165   unsigned FnAlign = F->getAlignment();
00166   unsigned TDAlign = TD->getPrefTypeAlignment(F->getType());
00167   unsigned Align = Log2_32(std::max(FnAlign, TDAlign));
00168   assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
00169 
00170   // Get the Mach-O Section that this function belongs in.
00171   MachOWriter::MachOSection *MOS = MOW.getTextSection();
00172   
00173   // FIXME: better memory management
00174   MOS->SectionData.reserve(4096);
00175   BufferBegin = &MOS->SectionData[0];
00176   BufferEnd = BufferBegin + MOS->SectionData.capacity();
00177 
00178   // Upgrade the section alignment if required.
00179   if (MOS->align < Align) MOS->align = Align;
00180 
00181   // Round the size up to the correct alignment for starting the new function.
00182   if ((MOS->size & ((1 << Align) - 1)) != 0) {
00183     MOS->size += (1 << Align);
00184     MOS->size &= ~((1 << Align) - 1);
00185   }
00186 
00187   // FIXME: Using MOS->size directly here instead of calculating it from the
00188   // output buffer size (impossible because the code emitter deals only in raw
00189   // bytes) forces us to manually synchronize size and write padding zero bytes
00190   // to the output buffer for all non-text sections.  For text sections, we do
00191   // not synchonize the output buffer, and we just blow up if anyone tries to
00192   // write non-code to it.  An assert should probably be added to
00193   // AddSymbolToSection to prevent calling it on the text section.
00194   CurBufferPtr = BufferBegin + MOS->size;
00195 
00196   // Clear per-function data structures.
00197   CPLocations.clear();
00198   CPSections.clear();
00199   JTLocations.clear();
00200   MBBLocations.clear();
00201 }
00202 
00203 /// finishFunction - This callback is invoked after the function is completely
00204 /// finished.
00205 bool MachOCodeEmitter::finishFunction(MachineFunction &MF) {
00206   // Get the Mach-O Section that this function belongs in.
00207   MachOWriter::MachOSection *MOS = MOW.getTextSection();
00208 
00209   // Get a symbol for the function to add to the symbol table
00210   // FIXME: it seems like we should call something like AddSymbolToSection
00211   // in startFunction rather than changing the section size and symbol n_value
00212   // here.
00213   const GlobalValue *FuncV = MF.getFunction();
00214   MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, TM);
00215   FnSym.n_value = MOS->size;
00216   MOS->size = CurBufferPtr - BufferBegin;
00217   
00218   // Emit constant pool to appropriate section(s)
00219   emitConstantPool(MF.getConstantPool());
00220 
00221   // Emit jump tables to appropriate section
00222   emitJumpTables(MF.getJumpTableInfo());
00223   
00224   // If we have emitted any relocations to function-specific objects such as 
00225   // basic blocks, constant pools entries, or jump tables, record their
00226   // addresses now so that we can rewrite them with the correct addresses
00227   // later.
00228   for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
00229     MachineRelocation &MR = Relocations[i];
00230     intptr_t Addr;
00231 
00232     if (MR.isBasicBlock()) {
00233       Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
00234       MR.setConstantVal(MOS->Index);
00235       MR.setResultPointer((void*)Addr);
00236     } else if (MR.isJumpTableIndex()) {
00237       Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
00238       MR.setConstantVal(MOW.getJumpTableSection()->Index);
00239       MR.setResultPointer((void*)Addr);
00240     } else if (MR.isConstantPoolIndex()) {
00241       Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
00242       MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
00243       MR.setResultPointer((void*)Addr);
00244     } else if (MR.isGlobalValue()) {
00245       // FIXME: This should be a set or something that uniques
00246       MOW.PendingGlobals.push_back(MR.getGlobalValue());
00247     } else {
00248       assert(0 && "Unhandled relocation type");
00249     }
00250     MOS->Relocations.push_back(MR);
00251   }
00252   Relocations.clear();
00253   
00254   // Finally, add it to the symtab.
00255   MOW.SymbolTable.push_back(FnSym);
00256   return false;
00257 }
00258 
00259 /// emitConstantPool - For each constant pool entry, figure out which section
00260 /// the constant should live in, allocate space for it, and emit it to the 
00261 /// Section data buffer.
00262 void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
00263   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
00264   if (CP.empty()) return;
00265 
00266   // FIXME: handle PIC codegen
00267   assert(TM.getRelocationModel() != Reloc::PIC_ &&
00268          "PIC codegen not yet handled for mach-o jump tables!");
00269 
00270   // Although there is no strict necessity that I am aware of, we will do what
00271   // gcc for OS X does and put each constant pool entry in a section of constant
00272   // objects of a certain size.  That means that float constants go in the
00273   // literal4 section, and double objects go in literal8, etc.
00274   //
00275   // FIXME: revisit this decision if we ever do the "stick everything into one
00276   // "giant object for PIC" optimization.
00277   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
00278     const Type *Ty = CP[i].getType();
00279     unsigned Size = TM.getTargetData()->getTypePaddedSize(Ty);
00280 
00281     MachOWriter::MachOSection *Sec = MOW.getConstSection(CP[i].Val.ConstVal);
00282     OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
00283 
00284     CPLocations.push_back(Sec->SectionData.size());
00285     CPSections.push_back(Sec->Index);
00286     
00287     // FIXME: remove when we have unified size + output buffer
00288     Sec->size += Size;
00289 
00290     // Allocate space in the section for the global.
00291     // FIXME: need alignment?
00292     // FIXME: share between here and AddSymbolToSection?
00293     for (unsigned j = 0; j < Size; ++j)
00294       SecDataOut.outbyte(0);
00295 
00296     MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
00297                 TM.getTargetData(), Sec->Relocations);
00298   }
00299 }
00300 
00301 /// emitJumpTables - Emit all the jump tables for a given jump table info
00302 /// record to the appropriate section.
00303 void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
00304   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
00305   if (JT.empty()) return;
00306 
00307   // FIXME: handle PIC codegen
00308   assert(TM.getRelocationModel() != Reloc::PIC_ &&
00309          "PIC codegen not yet handled for mach-o jump tables!");
00310 
00311   MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
00312   unsigned TextSecIndex = MOW.getTextSection()->Index;
00313   OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
00314 
00315   for (unsigned i = 0, e = JT.size(); i != e; ++i) {
00316     // For each jump table, record its offset from the start of the section,
00317     // reserve space for the relocations to the MBBs, and add the relocations.
00318     const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
00319     JTLocations.push_back(Sec->SectionData.size());
00320     for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
00321       MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
00322                                                MBBs[mi]));
00323       MR.setResultPointer((void *)JTLocations[i]);
00324       MR.setConstantVal(TextSecIndex);
00325       Sec->Relocations.push_back(MR);
00326       SecDataOut.outaddr(0);
00327     }
00328   }
00329   // FIXME: remove when we have unified size + output buffer
00330   Sec->size = Sec->SectionData.size();
00331 }
00332 
00333 //===----------------------------------------------------------------------===//
00334 //                          MachOWriter Implementation
00335 //===----------------------------------------------------------------------===//
00336 
00337 char MachOWriter::ID = 0;
00338 MachOWriter::MachOWriter(raw_ostream &o, TargetMachine &tm) 
00339   : MachineFunctionPass(&ID), O(o), TM(tm) {
00340   is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
00341   isLittleEndian = TM.getTargetData()->isLittleEndian();
00342 
00343   // Create the machine code emitter object for this target.
00344   MCE = new MachOCodeEmitter(*this);
00345 }
00346 
00347 MachOWriter::~MachOWriter() {
00348   delete MCE;
00349 }
00350 
00351 void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
00352   const Type *Ty = GV->getType()->getElementType();
00353   unsigned Size = TM.getTargetData()->getTypePaddedSize(Ty);
00354   unsigned Align = TM.getTargetData()->getPreferredAlignment(GV);
00355 
00356   // Reserve space in the .bss section for this symbol while maintaining the
00357   // desired section alignment, which must be at least as much as required by
00358   // this symbol.
00359   OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
00360 
00361   if (Align) {
00362     uint64_t OrigSize = Sec->size;
00363     Align = Log2_32(Align);
00364     Sec->align = std::max(unsigned(Sec->align), Align);
00365     Sec->size = (Sec->size + Align - 1) & ~(Align-1);
00366     
00367     // Add alignment padding to buffer as well.
00368     // FIXME: remove when we have unified size + output buffer
00369     unsigned AlignedSize = Sec->size - OrigSize;
00370     for (unsigned i = 0; i < AlignedSize; ++i)
00371       SecDataOut.outbyte(0);
00372   }
00373   // Globals without external linkage apparently do not go in the symbol table.
00374   if (!GV->hasLocalLinkage()) {
00375     MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
00376     Sym.n_value = Sec->size;
00377     SymbolTable.push_back(Sym);
00378   }
00379 
00380   // Record the offset of the symbol, and then allocate space for it.
00381   // FIXME: remove when we have unified size + output buffer
00382   Sec->size += Size;
00383   
00384   // Now that we know what section the GlovalVariable is going to be emitted 
00385   // into, update our mappings.
00386   // FIXME: We may also need to update this when outputting non-GlobalVariable
00387   // GlobalValues such as functions.
00388   GVSection[GV] = Sec;
00389   GVOffset[GV] = Sec->SectionData.size();
00390   
00391   // Allocate space in the section for the global.
00392   for (unsigned i = 0; i < Size; ++i)
00393     SecDataOut.outbyte(0);
00394 }
00395 
00396 void MachOWriter::EmitGlobal(GlobalVariable *GV) {
00397   const Type *Ty = GV->getType()->getElementType();
00398   unsigned Size = TM.getTargetData()->getTypePaddedSize(Ty);
00399   bool NoInit = !GV->hasInitializer();
00400   
00401   // If this global has a zero initializer, it is part of the .bss or common
00402   // section.
00403   if (NoInit || GV->getInitializer()->isNullValue()) {
00404     // If this global is part of the common block, add it now.  Variables are
00405     // part of the common block if they are zero initialized and allowed to be
00406     // merged with other symbols.
00407     if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
00408         GV->hasCommonLinkage()) {
00409       MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
00410       // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
00411       // bytes of the symbol.
00412       ExtOrCommonSym.n_value = Size;
00413       SymbolTable.push_back(ExtOrCommonSym);
00414       // Remember that we've seen this symbol
00415       GVOffset[GV] = Size;
00416       return;
00417     }
00418     // Otherwise, this symbol is part of the .bss section.
00419     MachOSection *BSS = getBSSSection();
00420     AddSymbolToSection(BSS, GV);
00421     return;
00422   }
00423   
00424   // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
00425   // 16 bytes, or a cstring.  Other read only data goes into a regular const
00426   // section.  Read-write data goes in the data section.
00427   MachOSection *Sec = GV->isConstant() ? getConstSection(GV->getInitializer()) : 
00428                                          getDataSection();
00429   AddSymbolToSection(Sec, GV);
00430   InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
00431           TM.getTargetData(), Sec->Relocations);
00432 }
00433 
00434 
00435 bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
00436   // Nothing to do here, this is all done through the MCE object.
00437   return false;
00438 }
00439 
00440 bool MachOWriter::doInitialization(Module &M) {
00441   // Set the magic value, now that we know the pointer size and endianness
00442   Header.setMagic(isLittleEndian, is64Bit);
00443 
00444   // Set the file type
00445   // FIXME: this only works for object files, we do not support the creation
00446   //        of dynamic libraries or executables at this time.
00447   Header.filetype = MachOHeader::MH_OBJECT;
00448 
00449   Mang = new Mangler(M);
00450   return false;
00451 }
00452 
00453 /// doFinalization - Now that the module has been completely processed, emit
00454 /// the Mach-O file to 'O'.
00455 bool MachOWriter::doFinalization(Module &M) {
00456   // FIXME: we don't handle debug info yet, we should probably do that.
00457 
00458   // Okay, the.text section has been completed, build the .data, .bss, and 
00459   // "common" sections next.
00460   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
00461        I != E; ++I)
00462     EmitGlobal(I);
00463   
00464   // Emit the header and load commands.
00465   EmitHeaderAndLoadCommands();
00466 
00467   // Emit the various sections and their relocation info.
00468   EmitSections();
00469 
00470   // Write the symbol table and the string table to the end of the file.
00471   O.write((char*)&SymT[0], SymT.size());
00472   O.write((char*)&StrT[0], StrT.size());
00473 
00474   // We are done with the abstract symbols.
00475   SectionList.clear();
00476   SymbolTable.clear();
00477   DynamicSymbolTable.clear();
00478 
00479   // Release the name mangler object.
00480   delete Mang; Mang = 0;
00481   return false;
00482 }
00483 
00484 void MachOWriter::EmitHeaderAndLoadCommands() {
00485   // Step #0: Fill in the segment load command size, since we need it to figure
00486   //          out the rest of the header fields
00487   MachOSegment SEG("", is64Bit);
00488   SEG.nsects  = SectionList.size();
00489   SEG.cmdsize = SEG.cmdSize(is64Bit) + 
00490                 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
00491   
00492   // Step #1: calculate the number of load commands.  We always have at least
00493   //          one, for the LC_SEGMENT load command, plus two for the normal
00494   //          and dynamic symbol tables, if there are any symbols.
00495   Header.ncmds = SymbolTable.empty() ? 1 : 3;
00496   
00497   // Step #2: calculate the size of the load commands
00498   Header.sizeofcmds = SEG.cmdsize;
00499   if (!SymbolTable.empty())
00500     Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
00501     
00502   // Step #3: write the header to the file
00503   // Local alias to shortenify coming code.
00504   DataBuffer &FH = Header.HeaderData;
00505   OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
00506 
00507   FHOut.outword(Header.magic);
00508   FHOut.outword(TM.getMachOWriterInfo()->getCPUType());
00509   FHOut.outword(TM.getMachOWriterInfo()->getCPUSubType());
00510   FHOut.outword(Header.filetype);
00511   FHOut.outword(Header.ncmds);
00512   FHOut.outword(Header.sizeofcmds);
00513   FHOut.outword(Header.flags);
00514   if (is64Bit)
00515     FHOut.outword(Header.reserved);
00516   
00517   // Step #4: Finish filling in the segment load command and write it out
00518   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
00519          E = SectionList.end(); I != E; ++I)
00520     SEG.filesize += (*I)->size;
00521 
00522   SEG.vmsize = SEG.filesize;
00523   SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
00524   
00525   FHOut.outword(SEG.cmd);
00526   FHOut.outword(SEG.cmdsize);
00527   FHOut.outstring(SEG.segname, 16);
00528   FHOut.outaddr(SEG.vmaddr);
00529   FHOut.outaddr(SEG.vmsize);
00530   FHOut.outaddr(SEG.fileoff);
00531   FHOut.outaddr(SEG.filesize);
00532   FHOut.outword(SEG.maxprot);
00533   FHOut.outword(SEG.initprot);
00534   FHOut.outword(SEG.nsects);
00535   FHOut.outword(SEG.flags);
00536   
00537   // Step #5: Finish filling in the fields of the MachOSections 
00538   uint64_t currentAddr = 0;
00539   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
00540          E = SectionList.end(); I != E; ++I) {
00541     MachOSection *MOS = *I;
00542     MOS->addr = currentAddr;
00543     MOS->offset = currentAddr + SEG.fileoff;
00544 
00545     // FIXME: do we need to do something with alignment here?
00546     currentAddr += MOS->size;
00547   }
00548   
00549   // Step #6: Emit the symbol table to temporary buffers, so that we know the
00550   // size of the string table when we write the next load command.  This also
00551   // sorts and assigns indices to each of the symbols, which is necessary for
00552   // emitting relocations to externally-defined objects.
00553   BufferSymbolAndStringTable();
00554   
00555   // Step #7: Calculate the number of relocations for each section and write out
00556   // the section commands for each section
00557   currentAddr += SEG.fileoff;
00558   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
00559          E = SectionList.end(); I != E; ++I) {
00560     MachOSection *MOS = *I;
00561     // Convert the relocations to target-specific relocations, and fill in the
00562     // relocation offset for this section.
00563     CalculateRelocations(*MOS);
00564     MOS->reloff = MOS->nreloc ? currentAddr : 0;
00565     currentAddr += MOS->nreloc * 8;
00566     
00567     // write the finalized section command to the output buffer
00568     FHOut.outstring(MOS->sectname, 16);
00569     FHOut.outstring(MOS->segname, 16);
00570     FHOut.outaddr(MOS->addr);
00571     FHOut.outaddr(MOS->size);
00572     FHOut.outword(MOS->offset);
00573     FHOut.outword(MOS->align);
00574     FHOut.outword(MOS->reloff);
00575     FHOut.outword(MOS->nreloc);
00576     FHOut.outword(MOS->flags);
00577     FHOut.outword(MOS->reserved1);
00578     FHOut.outword(MOS->reserved2);
00579     if (is64Bit)
00580       FHOut.outword(MOS->reserved3);
00581   }
00582   
00583   // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
00584   SymTab.symoff  = currentAddr;
00585   SymTab.nsyms   = SymbolTable.size();
00586   SymTab.stroff  = SymTab.symoff + SymT.size();
00587   SymTab.strsize = StrT.size();
00588   FHOut.outword(SymTab.cmd);
00589   FHOut.outword(SymTab.cmdsize);
00590   FHOut.outword(SymTab.symoff);
00591   FHOut.outword(SymTab.nsyms);
00592   FHOut.outword(SymTab.stroff);
00593   FHOut.outword(SymTab.strsize);
00594 
00595   // FIXME: set DySymTab fields appropriately
00596   // We should probably just update these in BufferSymbolAndStringTable since
00597   // thats where we're partitioning up the different kinds of symbols.
00598   FHOut.outword(DySymTab.cmd);
00599   FHOut.outword(DySymTab.cmdsize);
00600   FHOut.outword(DySymTab.ilocalsym);
00601   FHOut.outword(DySymTab.nlocalsym);
00602   FHOut.outword(DySymTab.iextdefsym);
00603   FHOut.outword(DySymTab.nextdefsym);
00604   FHOut.outword(DySymTab.iundefsym);
00605   FHOut.outword(DySymTab.nundefsym);
00606   FHOut.outword(DySymTab.tocoff);
00607   FHOut.outword(DySymTab.ntoc);
00608   FHOut.outword(DySymTab.modtaboff);
00609   FHOut.outword(DySymTab.nmodtab);
00610   FHOut.outword(DySymTab.extrefsymoff);
00611   FHOut.outword(DySymTab.nextrefsyms);
00612   FHOut.outword(DySymTab.indirectsymoff);
00613   FHOut.outword(DySymTab.nindirectsyms);
00614   FHOut.outword(DySymTab.extreloff);
00615   FHOut.outword(DySymTab.nextrel);
00616   FHOut.outword(DySymTab.locreloff);
00617   FHOut.outword(DySymTab.nlocrel);
00618   
00619   O.write((char*)&FH[0], FH.size());
00620 }
00621 
00622 /// EmitSections - Now that we have constructed the file header and load
00623 /// commands, emit the data for each section to the file.
00624 void MachOWriter::EmitSections() {
00625   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
00626          E = SectionList.end(); I != E; ++I)
00627     // Emit the contents of each section
00628     O.write((char*)&(*I)->SectionData[0], (*I)->size);
00629   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
00630          E = SectionList.end(); I != E; ++I)
00631     // Emit the relocation entry data for each section.
00632     O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
00633 }
00634 
00635 /// PartitionByLocal - Simple boolean predicate that returns true if Sym is
00636 /// a local symbol rather than an external symbol.
00637 bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
00638   return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
00639 }
00640 
00641 /// PartitionByDefined - Simple boolean predicate that returns true if Sym is
00642 /// defined in this module.
00643 bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
00644   // FIXME: Do N_ABS or N_INDR count as defined?
00645   return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
00646 }
00647 
00648 /// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
00649 /// each a string table index so that they appear in the correct order in the
00650 /// output file.
00651 void MachOWriter::BufferSymbolAndStringTable() {
00652   // The order of the symbol table is:
00653   // 1. local symbols
00654   // 2. defined external symbols (sorted by name)
00655   // 3. undefined external symbols (sorted by name)
00656   
00657   // Before sorting the symbols, check the PendingGlobals for any undefined
00658   // globals that need to be put in the symbol table.
00659   for (std::vector<GlobalValue*>::iterator I = PendingGlobals.begin(),
00660          E = PendingGlobals.end(); I != E; ++I) {
00661     if (GVOffset[*I] == 0 && GVSection[*I] == 0) {
00662       MachOSym UndfSym(*I, Mang->getValueName(*I), MachOSym::NO_SECT, TM);
00663       SymbolTable.push_back(UndfSym);
00664       GVOffset[*I] = -1;
00665     }
00666   }
00667   
00668   // Sort the symbols by name, so that when we partition the symbols by scope
00669   // of definition, we won't have to sort by name within each partition.
00670   std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
00671 
00672   // Parition the symbol table entries so that all local symbols come before 
00673   // all symbols with external linkage. { 1 | 2 3 }
00674   std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
00675   
00676   // Advance iterator to beginning of external symbols and partition so that
00677   // all external symbols defined in this module come before all external
00678   // symbols defined elsewhere. { 1 | 2 | 3 }
00679   for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
00680          E = SymbolTable.end(); I != E; ++I) {
00681     if (!PartitionByLocal(*I)) {
00682       std::partition(I, E, PartitionByDefined);
00683       break;
00684     }
00685   }
00686 
00687   // Calculate the starting index for each of the local, extern defined, and 
00688   // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
00689   // load command.
00690   for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
00691          E = SymbolTable.end(); I != E; ++I) {
00692     if (PartitionByLocal(*I)) {
00693       ++DySymTab.nlocalsym;
00694       ++DySymTab.iextdefsym;
00695       ++DySymTab.iundefsym;
00696     } else if (PartitionByDefined(*I)) {
00697       ++DySymTab.nextdefsym;
00698       ++DySymTab.iundefsym;
00699     } else {
00700       ++DySymTab.nundefsym;
00701     }
00702   }
00703   
00704   // Write out a leading zero byte when emitting string table, for n_strx == 0
00705   // which means an empty string.
00706   OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
00707   StrTOut.outbyte(0);
00708 
00709   // The order of the string table is:
00710   // 1. strings for external symbols
00711   // 2. strings for local symbols
00712   // Since this is the opposite order from the symbol table, which we have just
00713   // sorted, we can walk the symbol table backwards to output the string table.
00714   for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
00715         E = SymbolTable.rend(); I != E; ++I) {
00716     if (I->GVName == "") {
00717       I->n_strx = 0;
00718     } else {
00719       I->n_strx = StrT.size();
00720       StrTOut.outstring(I->GVName, I->GVName.length()+1);
00721     }
00722   }
00723 
00724   OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
00725 
00726   unsigned index = 0;
00727   for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
00728          E = SymbolTable.end(); I != E; ++I, ++index) {
00729     // Add the section base address to the section offset in the n_value field
00730     // to calculate the full address.
00731     // FIXME: handle symbols where the n_value field is not the address
00732     GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
00733     if (GV && GVSection[GV])
00734       I->n_value += GVSection[GV]->addr;
00735     if (GV && (GVOffset[GV] == -1))
00736       GVOffset[GV] = index;
00737          
00738     // Emit nlist to buffer
00739     SymTOut.outword(I->n_strx);
00740     SymTOut.outbyte(I->n_type);
00741     SymTOut.outbyte(I->n_sect);
00742     SymTOut.outhalf(I->n_desc);
00743     SymTOut.outaddr(I->n_value);
00744   }
00745 }
00746 
00747 /// CalculateRelocations - For each MachineRelocation in the current section,
00748 /// calculate the index of the section containing the object to be relocated,
00749 /// and the offset into that section.  From this information, create the
00750 /// appropriate target-specific MachORelocation type and add buffer it to be
00751 /// written out after we are finished writing out sections.
00752 void MachOWriter::CalculateRelocations(MachOSection &MOS) {
00753   for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
00754     MachineRelocation &MR = MOS.Relocations[i];
00755     unsigned TargetSection = MR.getConstantVal();
00756     unsigned TargetAddr = 0;
00757     unsigned TargetIndex = 0;
00758 
00759     // This is a scattered relocation entry if it points to a global value with
00760     // a non-zero offset.
00761     bool Scattered = false;
00762     bool Extern = false;
00763 
00764     // Since we may not have seen the GlobalValue we were interested in yet at
00765     // the time we emitted the relocation for it, fix it up now so that it
00766     // points to the offset into the correct section.
00767     if (MR.isGlobalValue()) {
00768       GlobalValue *GV = MR.getGlobalValue();
00769       MachOSection *MOSPtr = GVSection[GV];
00770       intptr_t Offset = GVOffset[GV];
00771       
00772       // If we have never seen the global before, it must be to a symbol
00773       // defined in another module (N_UNDF).
00774       if (!MOSPtr) {
00775         // FIXME: need to append stub suffix
00776         Extern = true;
00777         TargetAddr = 0;
00778         TargetIndex = GVOffset[GV];
00779       } else {
00780         Scattered = TargetSection != 0;
00781         TargetSection = MOSPtr->Index;
00782       }
00783       MR.setResultPointer((void*)Offset);
00784     }
00785     
00786     // If the symbol is locally defined, pass in the address of the section and
00787     // the section index to the code which will generate the target relocation.
00788     if (!Extern) {
00789         MachOSection &To = *SectionList[TargetSection - 1];
00790         TargetAddr = To.addr;
00791         TargetIndex = To.Index;
00792     }
00793 
00794     OutputBuffer RelocOut(MOS.RelocBuffer, is64Bit, isLittleEndian);
00795     OutputBuffer SecOut(MOS.SectionData, is64Bit, isLittleEndian);
00796     
00797     MOS.nreloc += GetTargetRelocation(MR, MOS.Index, TargetAddr, TargetIndex,
00798                                       RelocOut, SecOut, Scattered, Extern);
00799   }
00800 }
00801 
00802 // InitMem - Write the value of a Constant to the specified memory location,
00803 // converting it into bytes and relocations.
00804 void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
00805                           const TargetData *TD, 
00806                           std::vector<MachineRelocation> &MRs) {
00807   typedef std::pair<const Constant*, intptr_t> CPair;
00808   std::vector<CPair> WorkList;
00809   
00810   WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
00811   
00812   intptr_t ScatteredOffset = 0;
00813   
00814   while (!WorkList.empty()) {
00815     const Constant *PC = WorkList.back().first;
00816     intptr_t PA = WorkList.back().second;
00817     WorkList.pop_back();
00818     
00819     if (isa<UndefValue>(PC)) {
00820       continue;
00821     } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(PC)) {
00822       unsigned ElementSize =
00823         TD->getTypePaddedSize(CP->getType()->getElementType());
00824       for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
00825         WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
00826     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
00827       //
00828       // FIXME: Handle ConstantExpression.  See EE::getConstantValue()
00829       //
00830       switch (CE->getOpcode()) {
00831       case Instruction::GetElementPtr: {
00832         SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
00833         ScatteredOffset = TD->getIndexedOffset(CE->getOperand(0)->getType(),
00834                                                &Indices[0], Indices.size());
00835         WorkList.push_back(CPair(CE->getOperand(0), PA));
00836         break;
00837       }
00838       case Instruction::Add:
00839       default:
00840         cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
00841         abort();
00842         break;
00843       }
00844     } else if (PC->getType()->isSingleValueType()) {
00845       unsigned char *ptr = (unsigned char *)PA;
00846       switch (PC->getType()->getTypeID()) {
00847       case Type::IntegerTyID: {
00848         unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
00849         uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
00850         if (NumBits <= 8)
00851           ptr[0] = val;
00852         else if (NumBits <= 16) {
00853           if (TD->isBigEndian())
00854             val = ByteSwap_16(val);
00855           ptr[0] = val;
00856           ptr[1] = val >> 8;
00857         } else if (NumBits <= 32) {
00858           if (TD->isBigEndian())
00859             val = ByteSwap_32(val);
00860           ptr[0] = val;
00861           ptr[1] = val >> 8;
00862           ptr[2] = val >> 16;
00863           ptr[3] = val >> 24;
00864         } else if (NumBits <= 64) {
00865           if (TD->isBigEndian())
00866             val = ByteSwap_64(val);
00867           ptr[0] = val;
00868           ptr[1] = val >> 8;
00869           ptr[2] = val >> 16;
00870           ptr[3] = val >> 24;
00871           ptr[4] = val >> 32;
00872           ptr[5] = val >> 40;
00873           ptr[6] = val >> 48;
00874           ptr[7] = val >> 56;
00875         } else {
00876           assert(0 && "Not implemented: bit widths > 64");
00877         }
00878         break;
00879       }
00880       case Type::FloatTyID: {
00881         uint32_t val = cast<ConstantFP>(PC)->getValueAPF().bitcastToAPInt().
00882                         getZExtValue();
00883         if (TD->isBigEndian())
00884           val = ByteSwap_32(val);
00885         ptr[0] = val;
00886         ptr[1] = val >> 8;
00887         ptr[2] = val >> 16;
00888         ptr[3] = val >> 24;
00889         break;
00890       }
00891       case Type::DoubleTyID: {
00892         uint64_t val = cast<ConstantFP>(PC)->getValueAPF().bitcastToAPInt().
00893                          getZExtValue();
00894         if (TD->isBigEndian())
00895           val = ByteSwap_64(val);
00896         ptr[0] = val;
00897         ptr[1] = val >> 8;
00898         ptr[2] = val >> 16;
00899         ptr[3] = val >> 24;
00900         ptr[4] = val >> 32;
00901         ptr[5] = val >> 40;
00902         ptr[6] = val >> 48;
00903         ptr[7] = val >> 56;
00904         break;
00905       }
00906       case Type::PointerTyID:
00907         if (isa<ConstantPointerNull>(PC))
00908           memset(ptr, 0, TD->getPointerSize());
00909         else if (const GlobalValue* GV = dyn_cast<GlobalValue>(PC)) {
00910           // FIXME: what about function stubs?
00911           MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr, 
00912                                                  MachineRelocation::VANILLA,
00913                                                  const_cast<GlobalValue*>(GV),
00914                                                  ScatteredOffset));
00915           ScatteredOffset = 0;
00916         } else
00917           assert(0 && "Unknown constant pointer type!");
00918         break;
00919       default:
00920         cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
00921         abort();
00922       }
00923     } else if (isa<ConstantAggregateZero>(PC)) {
00924       memset((void*)PA, 0, (size_t)TD->getTypePaddedSize(PC->getType()));
00925     } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
00926       unsigned ElementSize =
00927         TD->getTypePaddedSize(CPA->getType()->getElementType());
00928       for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
00929         WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
00930     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
00931       const StructLayout *SL =
00932         TD->getStructLayout(cast<StructType>(CPS->getType()));
00933       for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
00934         WorkList.push_back(CPair(CPS->getOperand(i),
00935                                  PA+SL->getElementOffset(i)));
00936     } else {
00937       cerr << "Bad Type: " << *PC->getType() << "\n";
00938       assert(0 && "Unknown constant type to initialize memory with!");
00939     }
00940   }
00941 }
00942 
00943 MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
00944                    TargetMachine &TM) :
00945   GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
00946   n_desc(0), n_value(0) {
00947 
00948   const TargetAsmInfo *TAI = TM.getTargetAsmInfo();  
00949   
00950   switch (GV->getLinkage()) {
00951   default:
00952     assert(0 && "Unexpected linkage type!");
00953     break;
00954   case GlobalValue::WeakLinkage:
00955   case GlobalValue::LinkOnceLinkage:
00956   case GlobalValue::CommonLinkage:
00957     assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
00958   case GlobalValue::ExternalLinkage:
00959     GVName = TAI->getGlobalPrefix() + name;
00960     n_type |= GV->hasHiddenVisibility() ? N_PEXT : N_EXT;
00961     break;
00962   case GlobalValue::PrivateLinkage:
00963     GVName = TAI->getPrivateGlobalPrefix() + name;
00964     break;
00965   case GlobalValue::InternalLinkage:
00966     GVName = TAI->getGlobalPrefix() + name;
00967     break;
00968   }
00969 }