1 //===-- MachOWriter.cpp - Target-independent Mach-O Writer code -----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements the target-independent Mach-O writer. This file writes
11 // out the Mach-O file in the following order:
13 // #1 FatHeader (universal-only)
14 // #2 FatArch (universal-only, 1 per universal arch)
23 //===----------------------------------------------------------------------===//
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"
43 //===----------------------------------------------------------------------===//
44 // MachOCodeEmitter Implementation
45 //===----------------------------------------------------------------------===//
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 {
53 /// Target machine description.
56 /// Relocations - These are the relocations that the function needs, as
58 std::vector<MachineRelocation> Relocations;
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;
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;
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;
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;
78 MachOCodeEmitter(MachOWriter &mow) : MOW(mow), TM(MOW.TM) {}
80 virtual void startFunction(MachineFunction &F);
81 virtual bool finishFunction(MachineFunction &F);
83 virtual void addRelocation(const MachineRelocation &MR) {
84 Relocations.push_back(MR);
87 void emitConstantPool(MachineConstantPool *MCP);
88 void emitJumpTables(MachineJumpTableInfo *MJTI);
90 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
91 assert(CPLocations.size() > Index && "CP not emitted!");
92 return CPLocations[Index];
94 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
95 assert(JTLocations.size() > Index && "JT not emitted!");
96 return JTLocations[Index];
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();
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()];
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!");
116 virtual void *finishFunctionStub(const Function *F) {
117 assert(0 && "JIT specific function called!");
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.
133 // Get the Mach-O Section that this function belongs in.
134 MachOWriter::MachOSection *MOS = MOW.getTextSection();
136 // FIXME: better memory management
137 MOS->SectionData.reserve(4096);
138 BufferBegin = &MOS->SectionData[0];
139 BufferEnd = BufferBegin + MOS->SectionData.capacity();
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;
150 // Upgrade the section alignment if required.
151 if (MOS->align < Align) MOS->align = Align;
153 // Clear per-function data structures.
157 MBBLocations.clear();
160 /// finishFunction - This callback is invoked after the function is completely
162 bool MachOCodeEmitter::finishFunction(MachineFunction &F) {
163 // Get the Mach-O Section that this function belongs in.
164 MachOWriter::MachOSection *MOS = MOW.getTextSection();
166 MOS->size += CurBufferPtr - BufferBegin;
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);
172 // Emit constant pool to appropriate section(s)
173 emitConstantPool(F.getConstantPool());
175 // Emit jump tables to appropriate section
176 emitJumpTables(F.getJumpTableInfo());
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
182 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
183 MachineRelocation &MR = Relocations[i];
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");
201 MOS->Relocations.push_back(MR);
205 // Finally, add it to the symtab.
206 MOW.SymbolTable.push_back(FnSym);
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;
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!");
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.
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);
232 MachOWriter::MachOSection *Sec = MOW.getConstSection(Ty);
233 OutputBuffer SecDataOut(TM, Sec->SectionData);
235 CPLocations.push_back(Sec->SectionData.size());
236 CPSections.push_back(Sec->Index);
238 // FIXME: remove when we have unified size + output buffer
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);
247 MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
248 TM.getTargetData(), Sec->Relocations);
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;
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!");
262 MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
263 unsigned TextSecIndex = MOW.getTextSection()->Index;
264 OutputBuffer SecDataOut(TM, Sec->SectionData);
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(),
274 MR.setResultPointer((void *)JTLocations[i]);
275 MR.setConstantVal(TextSecIndex);
276 Sec->Relocations.push_back(MR);
277 SecDataOut.outaddr(0);
280 // FIXME: remove when we have unified size + output buffer
281 Sec->size = Sec->SectionData.size();
284 //===----------------------------------------------------------------------===//
285 // MachOWriter Implementation
286 //===----------------------------------------------------------------------===//
288 MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
289 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
290 isLittleEndian = TM.getTargetData()->isLittleEndian();
292 // Create the machine code emitter object for this target.
293 MCE = new MachOCodeEmitter(*this);
296 MachOWriter::~MachOWriter() {
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();
305 Align = TM.getTargetData()->getTypeAlignment(Ty);
307 MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
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
312 OutputBuffer SecDataOut(TM, Sec->SectionData);
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);
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);
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;
330 SymbolTable.push_back(Sym);
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.
337 GVOffset[GV] = Sec->SectionData.size();
339 // Allocate space in the section for the global.
340 for (unsigned i = 0; i < Size; ++i)
341 SecDataOut.outbyte(0);
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();
349 // If this global has a zero initializer, it is part of the .bss or common
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
363 PendingSyms.push_back(ExtOrCommonSym);
365 SymbolTable.push_back(ExtOrCommonSym);
368 // Otherwise, this symbol is part of the .bss section.
369 MachOSection *BSS = getBSSSection();
370 AddSymbolToSection(BSS, GV);
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);
384 bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
385 // Nothing to do here, this is all done through the MCE object.
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);
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;
398 Mang = new Mangler(M);
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.
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();
413 // Emit the header and load commands.
414 EmitHeaderAndLoadCommands();
416 // Emit the various sections and their relocation info.
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());
423 // We are done with the abstract symbols.
426 DynamicSymbolTable.clear();
428 // Release the name mangler object.
429 delete Mang; Mang = 0;
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);
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;
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;
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);
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);
464 FHOut.outword(Header.reserved);
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;
471 SEG.vmsize = SEG.filesize;
472 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
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);
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;
494 // FIXME: do we need to do something with alignment here?
495 currentAddr += MOS->size;
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;
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);
523 FHOut.outword(MOS->reserved3);
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();
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);
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);
566 O.write((char*)&FH[0], FH.size());
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());
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;
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;
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
598 void MachOWriter::BufferSymbolAndStringTable() {
599 // The order of the symbol table is:
601 // 2. defined external symbols (sorted by name)
602 // 3. undefined external symbols (sorted by name)
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());
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);
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);
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
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;
635 ++DySymTab.nundefsym;
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);
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 == "") {
654 I->n_strx = StrT.size();
655 StrTOut.outstring(I->GVName, I->GVName.length()+1);
659 OutputBuffer SymTOut(TM, SymT);
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;
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);
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();
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];
697 assert(MOSPtr && "Trying to relocate unknown global!");
699 TargetSection = MOSPtr->Index;
700 MR.setResultPointer((void*)offset);
703 GetTargetRelocation(MR, MOS, *SectionList[TargetSection-1]);
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;
715 WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
717 while (!WorkList.empty()) {
718 const Constant *PC = WorkList.back().first;
719 intptr_t PA = WorkList.back().second;
722 if (isa<UndefValue>(PC)) {
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)) {
730 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
732 switch (CE->getOpcode()) {
733 case Instruction::GetElementPtr:
734 case Instruction::Add:
736 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
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();
748 else if (NumBits <= 16) {
749 if (TD->isBigEndian())
750 val = ByteSwap_16(val);
753 } else if (NumBits <= 32) {
754 if (TD->isBigEndian())
755 val = ByteSwap_32(val);
760 } else if (NumBits <= 64) {
761 if (TD->isBigEndian())
762 val = ByteSwap_64(val);
772 assert(0 && "Not implemented: bit widths > 64");
776 case Type::FloatTyID: {
777 uint64_t val = FloatToBits(cast<ConstantFP>(PC)->getValue());
778 if (TD->isBigEndian())
779 val = ByteSwap_32(val);
786 case Type::DoubleTyID: {
787 uint64_t val = DoubleToBits(cast<ConstantFP>(PC)->getValue());
788 if (TD->isBigEndian())
789 val = ByteSwap_64(val);
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)));
809 assert(0 && "Unknown constant pointer type!");
812 cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
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]));
827 cerr << "Bad Type: " << *PC->getType() << "\n";
828 assert(0 && "Unknown constant type to initialize memory with!");
833 MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
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) {
838 const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
840 switch (GV->getLinkage()) {
842 assert(0 && "Unexpected linkage type!");
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;
851 case GlobalValue::InternalLinkage:
852 GVName = TAI->getPrivateGlobalPrefix() + name;