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 "MachO.h"
00026 #include "MachOWriter.h"
00027 #include "MachOCodeEmitter.h"
00028 #include "llvm/Constants.h"
00029 #include "llvm/DerivedTypes.h"
00030 #include "llvm/Module.h"
00031 #include "llvm/PassManager.h"
00032 #include "llvm/Target/TargetAsmInfo.h"
00033 #include "llvm/Target/TargetData.h"
00034 #include "llvm/Target/TargetMachine.h"
00035 #include "llvm/Target/TargetMachOWriterInfo.h"
00036 #include "llvm/Support/Mangler.h"
00037 #include "llvm/Support/OutputBuffer.h"
00038 #include "llvm/Support/ErrorHandling.h"
00039 #include "llvm/Support/raw_ostream.h"
00040 
00041 namespace llvm {
00042 
00043 /// AddMachOWriter - Concrete function to add the Mach-O writer to the function
00044 /// pass manager.
00045 ObjectCodeEmitter *AddMachOWriter(PassManagerBase &PM,
00046                                          raw_ostream &O,
00047                                          TargetMachine &TM) {
00048   MachOWriter *MOW = new MachOWriter(O, TM);
00049   PM.add(MOW);
00050   return MOW->getObjectCodeEmitter();
00051 }
00052 
00053 //===----------------------------------------------------------------------===//
00054 //                          MachOWriter Implementation
00055 //===----------------------------------------------------------------------===//
00056 
00057 char MachOWriter::ID = 0;
00058 
00059 MachOWriter::MachOWriter(raw_ostream &o, TargetMachine &tm)
00060   : MachineFunctionPass(&ID), O(o), TM(tm) {
00061   is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
00062   isLittleEndian = TM.getTargetData()->isLittleEndian();
00063 
00064   TAI = TM.getTargetAsmInfo();
00065 
00066   // Create the machine code emitter object for this target.
00067   MachOCE = new MachOCodeEmitter(*this, *getTextSection(true));
00068 }
00069 
00070 MachOWriter::~MachOWriter() {
00071   delete MachOCE;
00072 }
00073 
00074 bool MachOWriter::doInitialization(Module &M) {
00075   // Set the magic value, now that we know the pointer size and endianness
00076   Header.setMagic(isLittleEndian, is64Bit);
00077 
00078   // Set the file type
00079   // FIXME: this only works for object files, we do not support the creation
00080   //        of dynamic libraries or executables at this time.
00081   Header.filetype = MachOHeader::MH_OBJECT;
00082 
00083   Mang = new Mangler(M);
00084   return false;
00085 }
00086 
00087 bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
00088   return false;
00089 }
00090 
00091 /// doFinalization - Now that the module has been completely processed, emit
00092 /// the Mach-O file to 'O'.
00093 bool MachOWriter::doFinalization(Module &M) {
00094   // FIXME: we don't handle debug info yet, we should probably do that.
00095   // Okay, the.text section has been completed, build the .data, .bss, and
00096   // "common" sections next.
00097 
00098   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
00099        I != E; ++I)
00100     EmitGlobal(I);
00101 
00102   // Emit the header and load commands.
00103   EmitHeaderAndLoadCommands();
00104 
00105   // Emit the various sections and their relocation info.
00106   EmitSections();
00107   EmitRelocations();
00108 
00109   // Write the symbol table and the string table to the end of the file.
00110   O.write((char*)&SymT[0], SymT.size());
00111   O.write((char*)&StrT[0], StrT.size());
00112 
00113   // We are done with the abstract symbols.
00114   SectionList.clear();
00115   SymbolTable.clear();
00116   DynamicSymbolTable.clear();
00117 
00118   // Release the name mangler object.
00119   delete Mang; Mang = 0;
00120   return false;
00121 }
00122 
00123 // getConstSection - Get constant section for Constant 'C'
00124 MachOSection *MachOWriter::getConstSection(Constant *C) {
00125   const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
00126   if (CVA && CVA->isCString())
00127     return getSection("__TEXT", "__cstring", 
00128                       MachOSection::S_CSTRING_LITERALS);
00129 
00130   const Type *Ty = C->getType();
00131   if (Ty->isPrimitiveType() || Ty->isInteger()) {
00132     unsigned Size = TM.getTargetData()->getTypeAllocSize(Ty);
00133     switch(Size) {
00134     default: break; // Fall through to __TEXT,__const
00135     case 4:
00136       return getSection("__TEXT", "__literal4",
00137                         MachOSection::S_4BYTE_LITERALS);
00138     case 8:
00139       return getSection("__TEXT", "__literal8",
00140                         MachOSection::S_8BYTE_LITERALS);
00141     case 16:
00142       return getSection("__TEXT", "__literal16",
00143                         MachOSection::S_16BYTE_LITERALS);
00144     }
00145   }
00146   return getSection("__TEXT", "__const");
00147 }
00148 
00149 // getJumpTableSection - Select the Jump Table section
00150 MachOSection *MachOWriter::getJumpTableSection() {
00151   if (TM.getRelocationModel() == Reloc::PIC_)
00152     return getTextSection(false);
00153   else
00154     return getSection("__TEXT", "__const");
00155 }
00156 
00157 // getSection - Return the section with the specified name, creating a new
00158 // section if one does not already exist.
00159 MachOSection *MachOWriter::getSection(const std::string &seg,
00160                                       const std::string &sect,
00161                                       unsigned Flags /* = 0 */ ) {
00162   MachOSection *MOS = SectionLookup[seg+sect];
00163   if (MOS) return MOS;
00164 
00165   MOS = new MachOSection(seg, sect);
00166   SectionList.push_back(MOS);
00167   MOS->Index = SectionList.size();
00168   MOS->flags = MachOSection::S_REGULAR | Flags;
00169   SectionLookup[seg+sect] = MOS;
00170   return MOS;
00171 }
00172 
00173 // getTextSection - Return text section with different flags for code/data
00174 MachOSection *MachOWriter::getTextSection(bool isCode /* = true */ ) {
00175   if (isCode)
00176     return getSection("__TEXT", "__text",
00177                       MachOSection::S_ATTR_PURE_INSTRUCTIONS |
00178                       MachOSection::S_ATTR_SOME_INSTRUCTIONS);
00179   else
00180     return getSection("__TEXT", "__text");
00181 }
00182 
00183 MachOSection *MachOWriter::getBSSSection() {
00184   return getSection("__DATA", "__bss", MachOSection::S_ZEROFILL);
00185 }
00186 
00187 // GetJTRelocation - Get a relocation a new BB relocation based
00188 // on target information.
00189 MachineRelocation MachOWriter::GetJTRelocation(unsigned Offset,
00190                                                MachineBasicBlock *MBB) const {
00191   return TM.getMachOWriterInfo()->GetJTRelocation(Offset, MBB);
00192 }
00193 
00194 // GetTargetRelocation - Returns the number of relocations.
00195 unsigned MachOWriter::GetTargetRelocation(MachineRelocation &MR,
00196                              unsigned FromIdx, unsigned ToAddr,
00197                              unsigned ToIndex, OutputBuffer &RelocOut,
00198                              OutputBuffer &SecOut, bool Scattered,
00199                              bool Extern) {
00200   return TM.getMachOWriterInfo()->GetTargetRelocation(MR, FromIdx, ToAddr,
00201                                                       ToIndex, RelocOut,
00202                                                       SecOut, Scattered,
00203                                                       Extern);
00204 }
00205 
00206 void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
00207   const Type *Ty = GV->getType()->getElementType();
00208   unsigned Size = TM.getTargetData()->getTypeAllocSize(Ty);
00209   unsigned Align = TM.getTargetData()->getPreferredAlignment(GV);
00210 
00211   // Reserve space in the .bss section for this symbol while maintaining the
00212   // desired section alignment, which must be at least as much as required by
00213   // this symbol.
00214   OutputBuffer SecDataOut(Sec->getData(), is64Bit, isLittleEndian);
00215 
00216   if (Align) {
00217     Align = Log2_32(Align);
00218     Sec->align = std::max(unsigned(Sec->align), Align);
00219 
00220     Sec->emitAlignment(Sec->align);
00221   }
00222   // Globals without external linkage apparently do not go in the symbol table.
00223   if (!GV->hasLocalLinkage()) {
00224     MachOSym Sym(GV, Mang->getMangledName(GV), Sec->Index, TAI);
00225     Sym.n_value = Sec->size();
00226     SymbolTable.push_back(Sym);
00227   }
00228 
00229   // Record the offset of the symbol, and then allocate space for it.
00230   // FIXME: remove when we have unified size + output buffer
00231 
00232   // Now that we know what section the GlovalVariable is going to be emitted
00233   // into, update our mappings.
00234   // FIXME: We may also need to update this when outputting non-GlobalVariable
00235   // GlobalValues such as functions.
00236 
00237   GVSection[GV] = Sec;
00238   GVOffset[GV] = Sec->size();
00239 
00240   // Allocate space in the section for the global.
00241   for (unsigned i = 0; i < Size; ++i)
00242     SecDataOut.outbyte(0);
00243 }
00244 
00245 void MachOWriter::EmitGlobal(GlobalVariable *GV) {
00246   const Type *Ty = GV->getType()->getElementType();
00247   unsigned Size = TM.getTargetData()->getTypeAllocSize(Ty);
00248   bool NoInit = !GV->hasInitializer();
00249 
00250   // If this global has a zero initializer, it is part of the .bss or common
00251   // section.
00252   if (NoInit || GV->getInitializer()->isNullValue()) {
00253     // If this global is part of the common block, add it now.  Variables are
00254     // part of the common block if they are zero initialized and allowed to be
00255     // merged with other symbols.
00256     if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
00257         GV->hasCommonLinkage()) {
00258       MachOSym ExtOrCommonSym(GV, Mang->getMangledName(GV),
00259                               MachOSym::NO_SECT, TAI);
00260       // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
00261       // bytes of the symbol.
00262       ExtOrCommonSym.n_value = Size;
00263       SymbolTable.push_back(ExtOrCommonSym);
00264       // Remember that we've seen this symbol
00265       GVOffset[GV] = Size;
00266       return;
00267     }
00268     // Otherwise, this symbol is part of the .bss section.
00269     MachOSection *BSS = getBSSSection();
00270     AddSymbolToSection(BSS, GV);
00271     return;
00272   }
00273 
00274   // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
00275   // 16 bytes, or a cstring.  Other read only data goes into a regular const
00276   // section.  Read-write data goes in the data section.
00277   MachOSection *Sec = GV->isConstant() ? getConstSection(GV->getInitializer()) :
00278                                          getDataSection();
00279   AddSymbolToSection(Sec, GV);
00280   InitMem(GV->getInitializer(), GVOffset[GV], TM.getTargetData(), Sec);
00281 }
00282 
00283 
00284 
00285 void MachOWriter::EmitHeaderAndLoadCommands() {
00286   // Step #0: Fill in the segment load command size, since we need it to figure
00287   //          out the rest of the header fields
00288 
00289   MachOSegment SEG("", is64Bit);
00290   SEG.nsects  = SectionList.size();
00291   SEG.cmdsize = SEG.cmdSize(is64Bit) +
00292                 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
00293 
00294   // Step #1: calculate the number of load commands.  We always have at least
00295   //          one, for the LC_SEGMENT load command, plus two for the normal
00296   //          and dynamic symbol tables, if there are any symbols.
00297   Header.ncmds = SymbolTable.empty() ? 1 : 3;
00298 
00299   // Step #2: calculate the size of the load commands
00300   Header.sizeofcmds = SEG.cmdsize;
00301   if (!SymbolTable.empty())
00302     Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
00303 
00304   // Step #3: write the header to the file
00305   // Local alias to shortenify coming code.
00306   std::vector<unsigned char> &FH = Header.HeaderData;
00307   OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
00308 
00309   FHOut.outword(Header.magic);
00310   FHOut.outword(TM.getMachOWriterInfo()->getCPUType());
00311   FHOut.outword(TM.getMachOWriterInfo()->getCPUSubType());
00312   FHOut.outword(Header.filetype);
00313   FHOut.outword(Header.ncmds);
00314   FHOut.outword(Header.sizeofcmds);
00315   FHOut.outword(Header.flags);
00316   if (is64Bit)
00317     FHOut.outword(Header.reserved);
00318 
00319   // Step #4: Finish filling in the segment load command and write it out
00320   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
00321          E = SectionList.end(); I != E; ++I)
00322     SEG.filesize += (*I)->size();
00323 
00324   SEG.vmsize = SEG.filesize;
00325   SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
00326 
00327   FHOut.outword(SEG.cmd);
00328   FHOut.outword(SEG.cmdsize);
00329   FHOut.outstring(SEG.segname, 16);
00330   FHOut.outaddr(SEG.vmaddr);
00331   FHOut.outaddr(SEG.vmsize);
00332   FHOut.outaddr(SEG.fileoff);
00333   FHOut.outaddr(SEG.filesize);
00334   FHOut.outword(SEG.maxprot);
00335   FHOut.outword(SEG.initprot);
00336   FHOut.outword(SEG.nsects);
00337   FHOut.outword(SEG.flags);
00338 
00339   // Step #5: Finish filling in the fields of the MachOSections
00340   uint64_t currentAddr = 0;
00341   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
00342          E = SectionList.end(); I != E; ++I) {
00343     MachOSection *MOS = *I;
00344     MOS->addr = currentAddr;
00345     MOS->offset = currentAddr + SEG.fileoff;
00346     // FIXME: do we need to do something with alignment here?
00347     currentAddr += MOS->size();
00348   }
00349 
00350   // Step #6: Emit the symbol table to temporary buffers, so that we know the
00351   // size of the string table when we write the next load command.  This also
00352   // sorts and assigns indices to each of the symbols, which is necessary for
00353   // emitting relocations to externally-defined objects.
00354   BufferSymbolAndStringTable();
00355 
00356   // Step #7: Calculate the number of relocations for each section and write out
00357   // the section commands for each section
00358   currentAddr += SEG.fileoff;
00359   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
00360          E = SectionList.end(); I != E; ++I) {
00361     MachOSection *MOS = *I;
00362 
00363     // Convert the relocations to target-specific relocations, and fill in the
00364     // relocation offset for this section.
00365     CalculateRelocations(*MOS);
00366     MOS->reloff = MOS->nreloc ? currentAddr : 0;
00367     currentAddr += MOS->nreloc * 8;
00368 
00369     // write the finalized section command to the output buffer
00370     FHOut.outstring(MOS->sectname, 16);
00371     FHOut.outstring(MOS->segname, 16);
00372     FHOut.outaddr(MOS->addr);
00373     FHOut.outaddr(MOS->size());
00374     FHOut.outword(MOS->offset);
00375     FHOut.outword(MOS->align);
00376     FHOut.outword(MOS->reloff);
00377     FHOut.outword(MOS->nreloc);
00378     FHOut.outword(MOS->flags);
00379     FHOut.outword(MOS->reserved1);
00380     FHOut.outword(MOS->reserved2);
00381     if (is64Bit)
00382       FHOut.outword(MOS->reserved3);
00383   }
00384 
00385   // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
00386   SymTab.symoff  = currentAddr;
00387   SymTab.nsyms   = SymbolTable.size();
00388   SymTab.stroff  = SymTab.symoff + SymT.size();
00389   SymTab.strsize = StrT.size();
00390   FHOut.outword(SymTab.cmd);
00391   FHOut.outword(SymTab.cmdsize);
00392   FHOut.outword(SymTab.symoff);
00393   FHOut.outword(SymTab.nsyms);
00394   FHOut.outword(SymTab.stroff);
00395   FHOut.outword(SymTab.strsize);
00396 
00397   // FIXME: set DySymTab fields appropriately
00398   // We should probably just update these in BufferSymbolAndStringTable since
00399   // thats where we're partitioning up the different kinds of symbols.
00400   FHOut.outword(DySymTab.cmd);
00401   FHOut.outword(DySymTab.cmdsize);
00402   FHOut.outword(DySymTab.ilocalsym);
00403   FHOut.outword(DySymTab.nlocalsym);
00404   FHOut.outword(DySymTab.iextdefsym);
00405   FHOut.outword(DySymTab.nextdefsym);
00406   FHOut.outword(DySymTab.iundefsym);
00407   FHOut.outword(DySymTab.nundefsym);
00408   FHOut.outword(DySymTab.tocoff);
00409   FHOut.outword(DySymTab.ntoc);
00410   FHOut.outword(DySymTab.modtaboff);
00411   FHOut.outword(DySymTab.nmodtab);
00412   FHOut.outword(DySymTab.extrefsymoff);
00413   FHOut.outword(DySymTab.nextrefsyms);
00414   FHOut.outword(DySymTab.indirectsymoff);
00415   FHOut.outword(DySymTab.nindirectsyms);
00416   FHOut.outword(DySymTab.extreloff);
00417   FHOut.outword(DySymTab.nextrel);
00418   FHOut.outword(DySymTab.locreloff);
00419   FHOut.outword(DySymTab.nlocrel);
00420 
00421   O.write((char*)&FH[0], FH.size());
00422 }
00423 
00424 /// EmitSections - Now that we have constructed the file header and load
00425 /// commands, emit the data for each section to the file.
00426 void MachOWriter::EmitSections() {
00427   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
00428          E = SectionList.end(); I != E; ++I)
00429     // Emit the contents of each section
00430     if ((*I)->size())
00431       O.write((char*)&(*I)->getData()[0], (*I)->size());
00432 }
00433 
00434 /// EmitRelocations - emit relocation data from buffer.
00435 void MachOWriter::EmitRelocations() {
00436   for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
00437          E = SectionList.end(); I != E; ++I)
00438     // Emit the relocation entry data for each section.
00439     if ((*I)->RelocBuffer.size())
00440       O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
00441 }
00442 
00443 /// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
00444 /// each a string table index so that they appear in the correct order in the
00445 /// output file.
00446 void MachOWriter::BufferSymbolAndStringTable() {
00447   // The order of the symbol table is:
00448   // 1. local symbols
00449   // 2. defined external symbols (sorted by name)
00450   // 3. undefined external symbols (sorted by name)
00451 
00452   // Before sorting the symbols, check the PendingGlobals for any undefined
00453   // globals that need to be put in the symbol table.
00454   for (std::vector<GlobalValue*>::iterator I = PendingGlobals.begin(),
00455          E = PendingGlobals.end(); I != E; ++I) {
00456     if (GVOffset[*I] == 0 && GVSection[*I] == 0) {
00457       MachOSym UndfSym(*I, Mang->getMangledName(*I), MachOSym::NO_SECT, TAI);
00458       SymbolTable.push_back(UndfSym);
00459       GVOffset[*I] = -1;
00460     }
00461   }
00462 
00463   // Sort the symbols by name, so that when we partition the symbols by scope
00464   // of definition, we won't have to sort by name within each partition.
00465   std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSym::SymCmp());
00466 
00467   // Parition the symbol table entries so that all local symbols come before
00468   // all symbols with external linkage. { 1 | 2 3 }
00469   std::partition(SymbolTable.begin(), SymbolTable.end(),
00470                  MachOSym::PartitionByLocal);
00471 
00472   // Advance iterator to beginning of external symbols and partition so that
00473   // all external symbols defined in this module come before all external
00474   // symbols defined elsewhere. { 1 | 2 | 3 }
00475   for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
00476          E = SymbolTable.end(); I != E; ++I) {
00477     if (!MachOSym::PartitionByLocal(*I)) {
00478       std::partition(I, E, MachOSym::PartitionByDefined);
00479       break;
00480     }
00481   }
00482 
00483   // Calculate the starting index for each of the local, extern defined, and
00484   // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
00485   // load command.
00486   for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
00487          E = SymbolTable.end(); I != E; ++I) {
00488     if (MachOSym::PartitionByLocal(*I)) {
00489       ++DySymTab.nlocalsym;
00490       ++DySymTab.iextdefsym;
00491       ++DySymTab.iundefsym;
00492     } else if (MachOSym::PartitionByDefined(*I)) {
00493       ++DySymTab.nextdefsym;
00494       ++DySymTab.iundefsym;
00495     } else {
00496       ++DySymTab.nundefsym;
00497     }
00498   }
00499 
00500   // Write out a leading zero byte when emitting string table, for n_strx == 0
00501   // which means an empty string.
00502   OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
00503   StrTOut.outbyte(0);
00504 
00505   // The order of the string table is:
00506   // 1. strings for external symbols
00507   // 2. strings for local symbols
00508   // Since this is the opposite order from the symbol table, which we have just
00509   // sorted, we can walk the symbol table backwards to output the string table.
00510   for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
00511         E = SymbolTable.rend(); I != E; ++I) {
00512     if (I->GVName == "") {
00513       I->n_strx = 0;
00514     } else {
00515       I->n_strx = StrT.size();
00516       StrTOut.outstring(I->GVName, I->GVName.length()+1);
00517     }
00518   }
00519 
00520   OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
00521 
00522   unsigned index = 0;
00523   for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
00524          E = SymbolTable.end(); I != E; ++I, ++index) {
00525     // Add the section base address to the section offset in the n_value field
00526     // to calculate the full address.
00527     // FIXME: handle symbols where the n_value field is not the address
00528     GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
00529     if (GV && GVSection[GV])
00530       I->n_value += GVSection[GV]->addr;
00531     if (GV && (GVOffset[GV] == -1))
00532       GVOffset[GV] = index;
00533 
00534     // Emit nlist to buffer
00535     SymTOut.outword(I->n_strx);
00536     SymTOut.outbyte(I->n_type);
00537     SymTOut.outbyte(I->n_sect);
00538     SymTOut.outhalf(I->n_desc);
00539     SymTOut.outaddr(I->n_value);
00540   }
00541 }
00542 
00543 /// CalculateRelocations - For each MachineRelocation in the current section,
00544 /// calculate the index of the section containing the object to be relocated,
00545 /// and the offset into that section.  From this information, create the
00546 /// appropriate target-specific MachORelocation type and add buffer it to be
00547 /// written out after we are finished writing out sections.
00548 void MachOWriter::CalculateRelocations(MachOSection &MOS) {
00549   std::vector<MachineRelocation> Relocations =  MOS.getRelocations();
00550   for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
00551     MachineRelocation &MR = Relocations[i];
00552     unsigned TargetSection = MR.getConstantVal();
00553     unsigned TargetAddr = 0;
00554     unsigned TargetIndex = 0;
00555 
00556     // This is a scattered relocation entry if it points to a global value with
00557     // a non-zero offset.
00558     bool Scattered = false;
00559     bool Extern = false;
00560 
00561     // Since we may not have seen the GlobalValue we were interested in yet at
00562     // the time we emitted the relocation for it, fix it up now so that it
00563     // points to the offset into the correct section.
00564     if (MR.isGlobalValue()) {
00565       GlobalValue *GV = MR.getGlobalValue();
00566       MachOSection *MOSPtr = GVSection[GV];
00567       intptr_t Offset = GVOffset[GV];
00568 
00569       // If we have never seen the global before, it must be to a symbol
00570       // defined in another module (N_UNDF).
00571       if (!MOSPtr) {
00572         // FIXME: need to append stub suffix
00573         Extern = true;
00574         TargetAddr = 0;
00575         TargetIndex = GVOffset[GV];
00576       } else {
00577         Scattered = TargetSection != 0;
00578         TargetSection = MOSPtr->Index;
00579       }
00580       MR.setResultPointer((void*)Offset);
00581     }
00582 
00583     // If the symbol is locally defined, pass in the address of the section and
00584     // the section index to the code which will generate the target relocation.
00585     if (!Extern) {
00586         MachOSection &To = *SectionList[TargetSection - 1];
00587         TargetAddr = To.addr;
00588         TargetIndex = To.Index;
00589     }
00590 
00591     OutputBuffer RelocOut(MOS.RelocBuffer, is64Bit, isLittleEndian);
00592     OutputBuffer SecOut(MOS.getData(), is64Bit, isLittleEndian);
00593 
00594     MOS.nreloc += GetTargetRelocation(MR, MOS.Index, TargetAddr, TargetIndex,
00595                                       RelocOut, SecOut, Scattered, Extern);
00596   }
00597 }
00598 
00599 // InitMem - Write the value of a Constant to the specified memory location,
00600 // converting it into bytes and relocations.
00601 void MachOWriter::InitMem(const Constant *C, uintptr_t Offset,
00602                           const TargetData *TD, MachOSection* mos) {
00603   typedef std::pair<const Constant*, intptr_t> CPair;
00604   std::vector<CPair> WorkList;
00605   uint8_t *Addr = &mos->getData()[0];
00606 
00607   WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
00608 
00609   intptr_t ScatteredOffset = 0;
00610 
00611   while (!WorkList.empty()) {
00612     const Constant *PC = WorkList.back().first;
00613     intptr_t PA = WorkList.back().second;
00614     WorkList.pop_back();
00615 
00616     if (isa<UndefValue>(PC)) {
00617       continue;
00618     } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(PC)) {
00619       unsigned ElementSize =
00620         TD->getTypeAllocSize(CP->getType()->getElementType());
00621       for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
00622         WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
00623     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
00624       //
00625       // FIXME: Handle ConstantExpression.  See EE::getConstantValue()
00626       //
00627       switch (CE->getOpcode()) {
00628       case Instruction::GetElementPtr: {
00629         SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
00630         ScatteredOffset = TD->getIndexedOffset(CE->getOperand(0)->getType(),
00631                                                &Indices[0], Indices.size());
00632         WorkList.push_back(CPair(CE->getOperand(0), PA));
00633         break;
00634       }
00635       case Instruction::Add:
00636       default:
00637         cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
00638         llvm_unreachable(0);
00639       }
00640     } else if (PC->getType()->isSingleValueType()) {
00641       unsigned char *ptr = (unsigned char *)PA;
00642       switch (PC->getType()->getTypeID()) {
00643       case Type::IntegerTyID: {
00644         unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
00645         uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
00646         if (NumBits <= 8)
00647           ptr[0] = val;
00648         else if (NumBits <= 16) {
00649           if (TD->isBigEndian())
00650             val = ByteSwap_16(val);
00651           ptr[0] = val;
00652           ptr[1] = val >> 8;
00653         } else if (NumBits <= 32) {
00654           if (TD->isBigEndian())
00655             val = ByteSwap_32(val);
00656           ptr[0] = val;
00657           ptr[1] = val >> 8;
00658           ptr[2] = val >> 16;
00659           ptr[3] = val >> 24;
00660         } else if (NumBits <= 64) {
00661           if (TD->isBigEndian())
00662             val = ByteSwap_64(val);
00663           ptr[0] = val;
00664           ptr[1] = val >> 8;
00665           ptr[2] = val >> 16;
00666           ptr[3] = val >> 24;
00667           ptr[4] = val >> 32;
00668           ptr[5] = val >> 40;
00669           ptr[6] = val >> 48;
00670           ptr[7] = val >> 56;
00671         } else {
00672           llvm_unreachable("Not implemented: bit widths > 64");
00673         }
00674         break;
00675       }
00676       case Type::FloatTyID: {
00677         uint32_t val = cast<ConstantFP>(PC)->getValueAPF().bitcastToAPInt().
00678                         getZExtValue();
00679         if (TD->isBigEndian())
00680           val = ByteSwap_32(val);
00681         ptr[0] = val;
00682         ptr[1] = val >> 8;
00683         ptr[2] = val >> 16;
00684         ptr[3] = val >> 24;
00685         break;
00686       }
00687       case Type::DoubleTyID: {
00688         uint64_t val = cast<ConstantFP>(PC)->getValueAPF().bitcastToAPInt().
00689                          getZExtValue();
00690         if (TD->isBigEndian())
00691           val = ByteSwap_64(val);
00692         ptr[0] = val;
00693         ptr[1] = val >> 8;
00694         ptr[2] = val >> 16;
00695         ptr[3] = val >> 24;
00696         ptr[4] = val >> 32;
00697         ptr[5] = val >> 40;
00698         ptr[6] = val >> 48;
00699         ptr[7] = val >> 56;
00700         break;
00701       }
00702       case Type::PointerTyID:
00703         if (isa<ConstantPointerNull>(PC))
00704           memset(ptr, 0, TD->getPointerSize());
00705         else if (const GlobalValue* GV = dyn_cast<GlobalValue>(PC)) {
00706           // FIXME: what about function stubs?
00707           mos->addRelocation(MachineRelocation::getGV(PA-(intptr_t)Addr,
00708                                                  MachineRelocation::VANILLA,
00709                                                  const_cast<GlobalValue*>(GV),
00710                                                  ScatteredOffset));
00711           ScatteredOffset = 0;
00712         } else
00713           llvm_unreachable("Unknown constant pointer type!");
00714         break;
00715       default:
00716         std::string msg;
00717         raw_string_ostream Msg(msg);
00718         Msg << "ERROR: Constant unimp for type: " << *PC->getType();
00719         llvm_report_error(Msg.str());
00720       }
00721     } else if (isa<ConstantAggregateZero>(PC)) {
00722       memset((void*)PA, 0, (size_t)TD->getTypeAllocSize(PC->getType()));
00723     } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
00724       unsigned ElementSize =
00725         TD->getTypeAllocSize(CPA->getType()->getElementType());
00726       for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
00727         WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
00728     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
00729       const StructLayout *SL =
00730         TD->getStructLayout(cast<StructType>(CPS->getType()));
00731       for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
00732         WorkList.push_back(CPair(CPS->getOperand(i),
00733                                  PA+SL->getElementOffset(i)));
00734     } else {
00735       cerr << "Bad Type: " << *PC->getType() << "\n";
00736       llvm_unreachable("Unknown constant type to initialize memory with!");
00737     }
00738   }
00739 }
00740 
00741 //===----------------------------------------------------------------------===//
00742 //                          MachOSym Implementation
00743 //===----------------------------------------------------------------------===//
00744 
00745 MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
00746                    const TargetAsmInfo *TAI) :
00747   GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
00748   n_desc(0), n_value(0) {
00749 
00750   // FIXME: This is completely broken, it should use the mangler interface.
00751   switch (GV->getLinkage()) {
00752   default:
00753     llvm_unreachable("Unexpected linkage type!");
00754     break;
00755   case GlobalValue::WeakAnyLinkage:
00756   case GlobalValue::WeakODRLinkage:
00757   case GlobalValue::LinkOnceAnyLinkage:
00758   case GlobalValue::LinkOnceODRLinkage:
00759   case GlobalValue::CommonLinkage:
00760     assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
00761   case GlobalValue::ExternalLinkage:
00762     GVName = TAI->getGlobalPrefix() + name;
00763     n_type |= GV->hasHiddenVisibility() ? N_PEXT : N_EXT;
00764     break;
00765   case GlobalValue::PrivateLinkage:
00766     GVName = TAI->getPrivateGlobalPrefix() + name;
00767     break;
00768   case GlobalValue::LinkerPrivateLinkage:
00769     GVName = TAI->getLinkerPrivateGlobalPrefix() + name;
00770     break;
00771   case GlobalValue::InternalLinkage:
00772     GVName = TAI->getGlobalPrefix() + name;
00773     break;
00774   }
00775 }
00776 
00777 } // end namespace llvm