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 "MachOWriter.h"
26 #include "llvm/Constants.h"
27 #include "llvm/DerivedTypes.h"
28 #include "llvm/Module.h"
29 #include "llvm/PassManager.h"
30 #include "llvm/CodeGen/FileWriters.h"
31 #include "llvm/CodeGen/MachineCodeEmitter.h"
32 #include "llvm/CodeGen/MachineConstantPool.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/ExecutionEngine/ExecutionEngine.h"
35 #include "llvm/Target/TargetAsmInfo.h"
36 #include "llvm/Target/TargetJITInfo.h"
37 #include "llvm/Support/Mangler.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/OutputBuffer.h"
40 #include "llvm/Support/Streams.h"
44 /// AddMachOWriter - Concrete function to add the Mach-O writer to the function
46 MachineCodeEmitter *llvm::AddMachOWriter(FunctionPassManager &FPM,
49 MachOWriter *MOW = new MachOWriter(O, TM);
51 return &MOW->getMachineCodeEmitter();
54 //===----------------------------------------------------------------------===//
55 // MachOCodeEmitter Implementation
56 //===----------------------------------------------------------------------===//
59 /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code
60 /// for functions to the Mach-O file.
61 class MachOCodeEmitter : public MachineCodeEmitter {
64 /// Target machine description.
67 /// is64Bit/isLittleEndian - This information is inferred from the target
68 /// machine directly, indicating what header values and flags to set.
69 bool is64Bit, isLittleEndian;
71 /// Relocations - These are the relocations that the function needs, as
73 std::vector<MachineRelocation> Relocations;
75 /// CPLocations - This is a map of constant pool indices to offsets from the
76 /// start of the section for that constant pool index.
77 std::vector<intptr_t> CPLocations;
79 /// CPSections - This is a map of constant pool indices to the MachOSection
80 /// containing the constant pool entry for that index.
81 std::vector<unsigned> CPSections;
83 /// JTLocations - This is a map of jump table indices to offsets from the
84 /// start of the section for that jump table index.
85 std::vector<intptr_t> JTLocations;
87 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
88 /// It is filled in by the StartMachineBasicBlock callback and queried by
89 /// the getMachineBasicBlockAddress callback.
90 std::vector<intptr_t> MBBLocations;
93 MachOCodeEmitter(MachOWriter &mow) : MOW(mow), TM(MOW.TM) {
94 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
95 isLittleEndian = TM.getTargetData()->isLittleEndian();
98 virtual void startFunction(MachineFunction &MF);
99 virtual bool finishFunction(MachineFunction &MF);
101 virtual void addRelocation(const MachineRelocation &MR) {
102 Relocations.push_back(MR);
105 void emitConstantPool(MachineConstantPool *MCP);
106 void emitJumpTables(MachineJumpTableInfo *MJTI);
108 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
109 assert(CPLocations.size() > Index && "CP not emitted!");
110 return CPLocations[Index];
112 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
113 assert(JTLocations.size() > Index && "JT not emitted!");
114 return JTLocations[Index];
117 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
118 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
119 MBBLocations.resize((MBB->getNumber()+1)*2);
120 MBBLocations[MBB->getNumber()] = getCurrentPCOffset();
123 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
124 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
125 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
126 return MBBLocations[MBB->getNumber()];
129 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
130 virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
131 assert(0 && "JIT specific function called!");
134 virtual void *finishFunctionStub(const Function *F) {
135 assert(0 && "JIT specific function called!");
142 /// startFunction - This callback is invoked when a new machine function is
143 /// about to be emitted.
144 void MachOCodeEmitter::startFunction(MachineFunction &MF) {
145 const TargetData *TD = TM.getTargetData();
146 const Function *F = MF.getFunction();
148 // Align the output buffer to the appropriate alignment, power of 2.
149 unsigned FnAlign = F->getAlignment();
150 unsigned TDAlign = TD->getPrefTypeAlignment(F->getType());
151 unsigned Align = Log2_32(std::max(FnAlign, TDAlign));
152 assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
154 // Get the Mach-O Section that this function belongs in.
155 MachOWriter::MachOSection *MOS = MOW.getTextSection();
157 // FIXME: better memory management
158 MOS->SectionData.reserve(4096);
159 BufferBegin = &MOS->SectionData[0];
160 BufferEnd = BufferBegin + MOS->SectionData.capacity();
162 // Upgrade the section alignment if required.
163 if (MOS->align < Align) MOS->align = Align;
165 // Round the size up to the correct alignment for starting the new function.
166 if ((MOS->size & ((1 << Align) - 1)) != 0) {
167 MOS->size += (1 << Align);
168 MOS->size &= ~((1 << Align) - 1);
171 // FIXME: Using MOS->size directly here instead of calculating it from the
172 // output buffer size (impossible because the code emitter deals only in raw
173 // bytes) forces us to manually synchronize size and write padding zero bytes
174 // to the output buffer for all non-text sections. For text sections, we do
175 // not synchonize the output buffer, and we just blow up if anyone tries to
176 // write non-code to it. An assert should probably be added to
177 // AddSymbolToSection to prevent calling it on the text section.
178 CurBufferPtr = BufferBegin + MOS->size;
180 // Clear per-function data structures.
184 MBBLocations.clear();
187 /// finishFunction - This callback is invoked after the function is completely
189 bool MachOCodeEmitter::finishFunction(MachineFunction &MF) {
190 // Get the Mach-O Section that this function belongs in.
191 MachOWriter::MachOSection *MOS = MOW.getTextSection();
193 // Get a symbol for the function to add to the symbol table
194 // FIXME: it seems like we should call something like AddSymbolToSection
195 // in startFunction rather than changing the section size and symbol n_value
197 const GlobalValue *FuncV = MF.getFunction();
198 MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, TM);
199 FnSym.n_value = MOS->size;
200 MOS->size = CurBufferPtr - BufferBegin;
202 // Emit constant pool to appropriate section(s)
203 emitConstantPool(MF.getConstantPool());
205 // Emit jump tables to appropriate section
206 emitJumpTables(MF.getJumpTableInfo());
208 // If we have emitted any relocations to function-specific objects such as
209 // basic blocks, constant pools entries, or jump tables, record their
210 // addresses now so that we can rewrite them with the correct addresses
212 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
213 MachineRelocation &MR = Relocations[i];
216 if (MR.isBasicBlock()) {
217 Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
218 MR.setConstantVal(MOS->Index);
219 MR.setResultPointer((void*)Addr);
220 } else if (MR.isJumpTableIndex()) {
221 Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
222 MR.setConstantVal(MOW.getJumpTableSection()->Index);
223 MR.setResultPointer((void*)Addr);
224 } else if (MR.isConstantPoolIndex()) {
225 Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
226 MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
227 MR.setResultPointer((void*)Addr);
228 } else if (MR.isGlobalValue()) {
229 // FIXME: This should be a set or something that uniques
230 MOW.PendingGlobals.push_back(MR.getGlobalValue());
232 assert(0 && "Unhandled relocation type");
234 MOS->Relocations.push_back(MR);
238 // Finally, add it to the symtab.
239 MOW.SymbolTable.push_back(FnSym);
243 /// emitConstantPool - For each constant pool entry, figure out which section
244 /// the constant should live in, allocate space for it, and emit it to the
245 /// Section data buffer.
246 void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
247 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
248 if (CP.empty()) return;
250 // FIXME: handle PIC codegen
251 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
252 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
254 // Although there is no strict necessity that I am aware of, we will do what
255 // gcc for OS X does and put each constant pool entry in a section of constant
256 // objects of a certain size. That means that float constants go in the
257 // literal4 section, and double objects go in literal8, etc.
259 // FIXME: revisit this decision if we ever do the "stick everything into one
260 // "giant object for PIC" optimization.
261 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
262 const Type *Ty = CP[i].getType();
263 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
265 MachOWriter::MachOSection *Sec = MOW.getConstSection(CP[i].Val.ConstVal);
266 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
268 CPLocations.push_back(Sec->SectionData.size());
269 CPSections.push_back(Sec->Index);
271 // FIXME: remove when we have unified size + output buffer
274 // Allocate space in the section for the global.
275 // FIXME: need alignment?
276 // FIXME: share between here and AddSymbolToSection?
277 for (unsigned j = 0; j < Size; ++j)
278 SecDataOut.outbyte(0);
280 MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
281 TM.getTargetData(), Sec->Relocations);
285 /// emitJumpTables - Emit all the jump tables for a given jump table info
286 /// record to the appropriate section.
287 void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
288 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
289 if (JT.empty()) return;
291 // FIXME: handle PIC codegen
292 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
293 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
295 MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
296 unsigned TextSecIndex = MOW.getTextSection()->Index;
297 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
299 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
300 // For each jump table, record its offset from the start of the section,
301 // reserve space for the relocations to the MBBs, and add the relocations.
302 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
303 JTLocations.push_back(Sec->SectionData.size());
304 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
305 MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
307 MR.setResultPointer((void *)JTLocations[i]);
308 MR.setConstantVal(TextSecIndex);
309 Sec->Relocations.push_back(MR);
310 SecDataOut.outaddr(0);
313 // FIXME: remove when we have unified size + output buffer
314 Sec->size = Sec->SectionData.size();
317 //===----------------------------------------------------------------------===//
318 // MachOWriter Implementation
319 //===----------------------------------------------------------------------===//
321 MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
322 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
323 isLittleEndian = TM.getTargetData()->isLittleEndian();
325 // Create the machine code emitter object for this target.
326 MCE = new MachOCodeEmitter(*this);
329 MachOWriter::~MachOWriter() {
333 void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
334 const Type *Ty = GV->getType()->getElementType();
335 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
336 unsigned Align = GV->getAlignment();
338 Align = TM.getTargetData()->getPrefTypeAlignment(Ty);
340 // Reserve space in the .bss section for this symbol while maintaining the
341 // desired section alignment, which must be at least as much as required by
343 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
346 uint64_t OrigSize = Sec->size;
347 Align = Log2_32(Align);
348 Sec->align = std::max(unsigned(Sec->align), Align);
349 Sec->size = (Sec->size + Align - 1) & ~(Align-1);
351 // Add alignment padding to buffer as well.
352 // FIXME: remove when we have unified size + output buffer
353 unsigned AlignedSize = Sec->size - OrigSize;
354 for (unsigned i = 0; i < AlignedSize; ++i)
355 SecDataOut.outbyte(0);
357 // Globals without external linkage apparently do not go in the symbol table.
358 if (GV->getLinkage() != GlobalValue::InternalLinkage) {
359 MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
360 Sym.n_value = Sec->size;
361 SymbolTable.push_back(Sym);
364 // Record the offset of the symbol, and then allocate space for it.
365 // FIXME: remove when we have unified size + output buffer
368 // Now that we know what section the GlovalVariable is going to be emitted
369 // into, update our mappings.
370 // FIXME: We may also need to update this when outputting non-GlobalVariable
371 // GlobalValues such as functions.
373 GVOffset[GV] = Sec->SectionData.size();
375 // Allocate space in the section for the global.
376 for (unsigned i = 0; i < Size; ++i)
377 SecDataOut.outbyte(0);
380 void MachOWriter::EmitGlobal(GlobalVariable *GV) {
381 const Type *Ty = GV->getType()->getElementType();
382 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
383 bool NoInit = !GV->hasInitializer();
385 // If this global has a zero initializer, it is part of the .bss or common
387 if (NoInit || GV->getInitializer()->isNullValue()) {
388 // If this global is part of the common block, add it now. Variables are
389 // part of the common block if they are zero initialized and allowed to be
390 // merged with other symbols.
391 if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
392 MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
393 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
394 // bytes of the symbol.
395 ExtOrCommonSym.n_value = Size;
396 SymbolTable.push_back(ExtOrCommonSym);
397 // Remember that we've seen this symbol
401 // Otherwise, this symbol is part of the .bss section.
402 MachOSection *BSS = getBSSSection();
403 AddSymbolToSection(BSS, GV);
407 // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
408 // 16 bytes, or a cstring. Other read only data goes into a regular const
409 // section. Read-write data goes in the data section.
410 MachOSection *Sec = GV->isConstant() ? getConstSection(GV->getInitializer()) :
412 AddSymbolToSection(Sec, GV);
413 InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
414 TM.getTargetData(), Sec->Relocations);
418 bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
419 // Nothing to do here, this is all done through the MCE object.
423 bool MachOWriter::doInitialization(Module &M) {
424 // Set the magic value, now that we know the pointer size and endianness
425 Header.setMagic(isLittleEndian, is64Bit);
428 // FIXME: this only works for object files, we do not support the creation
429 // of dynamic libraries or executables at this time.
430 Header.filetype = MachOHeader::MH_OBJECT;
432 Mang = new Mangler(M);
436 /// doFinalization - Now that the module has been completely processed, emit
437 /// the Mach-O file to 'O'.
438 bool MachOWriter::doFinalization(Module &M) {
439 // FIXME: we don't handle debug info yet, we should probably do that.
441 // Okay, the.text section has been completed, build the .data, .bss, and
442 // "common" sections next.
443 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
447 // Emit the header and load commands.
448 EmitHeaderAndLoadCommands();
450 // Emit the various sections and their relocation info.
453 // Write the symbol table and the string table to the end of the file.
454 O.write((char*)&SymT[0], SymT.size());
455 O.write((char*)&StrT[0], StrT.size());
457 // We are done with the abstract symbols.
460 DynamicSymbolTable.clear();
462 // Release the name mangler object.
463 delete Mang; Mang = 0;
467 void MachOWriter::EmitHeaderAndLoadCommands() {
468 // Step #0: Fill in the segment load command size, since we need it to figure
469 // out the rest of the header fields
470 MachOSegment SEG("", is64Bit);
471 SEG.nsects = SectionList.size();
472 SEG.cmdsize = SEG.cmdSize(is64Bit) +
473 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
475 // Step #1: calculate the number of load commands. We always have at least
476 // one, for the LC_SEGMENT load command, plus two for the normal
477 // and dynamic symbol tables, if there are any symbols.
478 Header.ncmds = SymbolTable.empty() ? 1 : 3;
480 // Step #2: calculate the size of the load commands
481 Header.sizeofcmds = SEG.cmdsize;
482 if (!SymbolTable.empty())
483 Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
485 // Step #3: write the header to the file
486 // Local alias to shortenify coming code.
487 DataBuffer &FH = Header.HeaderData;
488 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
490 FHOut.outword(Header.magic);
491 FHOut.outword(TM.getMachOWriterInfo()->getCPUType());
492 FHOut.outword(TM.getMachOWriterInfo()->getCPUSubType());
493 FHOut.outword(Header.filetype);
494 FHOut.outword(Header.ncmds);
495 FHOut.outword(Header.sizeofcmds);
496 FHOut.outword(Header.flags);
498 FHOut.outword(Header.reserved);
500 // Step #4: Finish filling in the segment load command and write it out
501 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
502 E = SectionList.end(); I != E; ++I)
503 SEG.filesize += (*I)->size;
505 SEG.vmsize = SEG.filesize;
506 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
508 FHOut.outword(SEG.cmd);
509 FHOut.outword(SEG.cmdsize);
510 FHOut.outstring(SEG.segname, 16);
511 FHOut.outaddr(SEG.vmaddr);
512 FHOut.outaddr(SEG.vmsize);
513 FHOut.outaddr(SEG.fileoff);
514 FHOut.outaddr(SEG.filesize);
515 FHOut.outword(SEG.maxprot);
516 FHOut.outword(SEG.initprot);
517 FHOut.outword(SEG.nsects);
518 FHOut.outword(SEG.flags);
520 // Step #5: Finish filling in the fields of the MachOSections
521 uint64_t currentAddr = 0;
522 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
523 E = SectionList.end(); I != E; ++I) {
524 MachOSection *MOS = *I;
525 MOS->addr = currentAddr;
526 MOS->offset = currentAddr + SEG.fileoff;
528 // FIXME: do we need to do something with alignment here?
529 currentAddr += MOS->size;
532 // Step #6: Emit the symbol table to temporary buffers, so that we know the
533 // size of the string table when we write the next load command. This also
534 // sorts and assigns indices to each of the symbols, which is necessary for
535 // emitting relocations to externally-defined objects.
536 BufferSymbolAndStringTable();
538 // Step #7: Calculate the number of relocations for each section and write out
539 // the section commands for each section
540 currentAddr += SEG.fileoff;
541 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
542 E = SectionList.end(); I != E; ++I) {
543 MachOSection *MOS = *I;
544 // Convert the relocations to target-specific relocations, and fill in the
545 // relocation offset for this section.
546 CalculateRelocations(*MOS);
547 MOS->reloff = MOS->nreloc ? currentAddr : 0;
548 currentAddr += MOS->nreloc * 8;
550 // write the finalized section command to the output buffer
551 FHOut.outstring(MOS->sectname, 16);
552 FHOut.outstring(MOS->segname, 16);
553 FHOut.outaddr(MOS->addr);
554 FHOut.outaddr(MOS->size);
555 FHOut.outword(MOS->offset);
556 FHOut.outword(MOS->align);
557 FHOut.outword(MOS->reloff);
558 FHOut.outword(MOS->nreloc);
559 FHOut.outword(MOS->flags);
560 FHOut.outword(MOS->reserved1);
561 FHOut.outword(MOS->reserved2);
563 FHOut.outword(MOS->reserved3);
566 // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
567 SymTab.symoff = currentAddr;
568 SymTab.nsyms = SymbolTable.size();
569 SymTab.stroff = SymTab.symoff + SymT.size();
570 SymTab.strsize = StrT.size();
571 FHOut.outword(SymTab.cmd);
572 FHOut.outword(SymTab.cmdsize);
573 FHOut.outword(SymTab.symoff);
574 FHOut.outword(SymTab.nsyms);
575 FHOut.outword(SymTab.stroff);
576 FHOut.outword(SymTab.strsize);
578 // FIXME: set DySymTab fields appropriately
579 // We should probably just update these in BufferSymbolAndStringTable since
580 // thats where we're partitioning up the different kinds of symbols.
581 FHOut.outword(DySymTab.cmd);
582 FHOut.outword(DySymTab.cmdsize);
583 FHOut.outword(DySymTab.ilocalsym);
584 FHOut.outword(DySymTab.nlocalsym);
585 FHOut.outword(DySymTab.iextdefsym);
586 FHOut.outword(DySymTab.nextdefsym);
587 FHOut.outword(DySymTab.iundefsym);
588 FHOut.outword(DySymTab.nundefsym);
589 FHOut.outword(DySymTab.tocoff);
590 FHOut.outword(DySymTab.ntoc);
591 FHOut.outword(DySymTab.modtaboff);
592 FHOut.outword(DySymTab.nmodtab);
593 FHOut.outword(DySymTab.extrefsymoff);
594 FHOut.outword(DySymTab.nextrefsyms);
595 FHOut.outword(DySymTab.indirectsymoff);
596 FHOut.outword(DySymTab.nindirectsyms);
597 FHOut.outword(DySymTab.extreloff);
598 FHOut.outword(DySymTab.nextrel);
599 FHOut.outword(DySymTab.locreloff);
600 FHOut.outword(DySymTab.nlocrel);
602 O.write((char*)&FH[0], FH.size());
605 /// EmitSections - Now that we have constructed the file header and load
606 /// commands, emit the data for each section to the file.
607 void MachOWriter::EmitSections() {
608 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
609 E = SectionList.end(); I != E; ++I)
610 // Emit the contents of each section
611 O.write((char*)&(*I)->SectionData[0], (*I)->size);
612 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
613 E = SectionList.end(); I != E; ++I)
614 // Emit the relocation entry data for each section.
615 O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
618 /// PartitionByLocal - Simple boolean predicate that returns true if Sym is
619 /// a local symbol rather than an external symbol.
620 bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
621 return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
624 /// PartitionByDefined - Simple boolean predicate that returns true if Sym is
625 /// defined in this module.
626 bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
627 // FIXME: Do N_ABS or N_INDR count as defined?
628 return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
631 /// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
632 /// each a string table index so that they appear in the correct order in the
634 void MachOWriter::BufferSymbolAndStringTable() {
635 // The order of the symbol table is:
637 // 2. defined external symbols (sorted by name)
638 // 3. undefined external symbols (sorted by name)
640 // Before sorting the symbols, check the PendingGlobals for any undefined
641 // globals that need to be put in the symbol table.
642 for (std::vector<GlobalValue*>::iterator I = PendingGlobals.begin(),
643 E = PendingGlobals.end(); I != E; ++I) {
644 if (GVOffset[*I] == 0 && GVSection[*I] == 0) {
645 MachOSym UndfSym(*I, Mang->getValueName(*I), MachOSym::NO_SECT, TM);
646 SymbolTable.push_back(UndfSym);
651 // Sort the symbols by name, so that when we partition the symbols by scope
652 // of definition, we won't have to sort by name within each partition.
653 std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
655 // Parition the symbol table entries so that all local symbols come before
656 // all symbols with external linkage. { 1 | 2 3 }
657 std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
659 // Advance iterator to beginning of external symbols and partition so that
660 // all external symbols defined in this module come before all external
661 // symbols defined elsewhere. { 1 | 2 | 3 }
662 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
663 E = SymbolTable.end(); I != E; ++I) {
664 if (!PartitionByLocal(*I)) {
665 std::partition(I, E, PartitionByDefined);
670 // Calculate the starting index for each of the local, extern defined, and
671 // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
673 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
674 E = SymbolTable.end(); I != E; ++I) {
675 if (PartitionByLocal(*I)) {
676 ++DySymTab.nlocalsym;
677 ++DySymTab.iextdefsym;
678 ++DySymTab.iundefsym;
679 } else if (PartitionByDefined(*I)) {
680 ++DySymTab.nextdefsym;
681 ++DySymTab.iundefsym;
683 ++DySymTab.nundefsym;
687 // Write out a leading zero byte when emitting string table, for n_strx == 0
688 // which means an empty string.
689 OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
692 // The order of the string table is:
693 // 1. strings for external symbols
694 // 2. strings for local symbols
695 // Since this is the opposite order from the symbol table, which we have just
696 // sorted, we can walk the symbol table backwards to output the string table.
697 for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
698 E = SymbolTable.rend(); I != E; ++I) {
699 if (I->GVName == "") {
702 I->n_strx = StrT.size();
703 StrTOut.outstring(I->GVName, I->GVName.length()+1);
707 OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
710 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
711 E = SymbolTable.end(); I != E; ++I, ++index) {
712 // Add the section base address to the section offset in the n_value field
713 // to calculate the full address.
714 // FIXME: handle symbols where the n_value field is not the address
715 GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
716 if (GV && GVSection[GV])
717 I->n_value += GVSection[GV]->addr;
718 if (GV && (GVOffset[GV] == -1))
719 GVOffset[GV] = index;
721 // Emit nlist to buffer
722 SymTOut.outword(I->n_strx);
723 SymTOut.outbyte(I->n_type);
724 SymTOut.outbyte(I->n_sect);
725 SymTOut.outhalf(I->n_desc);
726 SymTOut.outaddr(I->n_value);
730 /// CalculateRelocations - For each MachineRelocation in the current section,
731 /// calculate the index of the section containing the object to be relocated,
732 /// and the offset into that section. From this information, create the
733 /// appropriate target-specific MachORelocation type and add buffer it to be
734 /// written out after we are finished writing out sections.
735 void MachOWriter::CalculateRelocations(MachOSection &MOS) {
736 for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
737 MachineRelocation &MR = MOS.Relocations[i];
738 unsigned TargetSection = MR.getConstantVal();
740 unsigned TargetIndex;
742 // This is a scattered relocation entry if it points to a global value with
743 // a non-zero offset.
744 bool Scattered = false;
747 // Since we may not have seen the GlobalValue we were interested in yet at
748 // the time we emitted the relocation for it, fix it up now so that it
749 // points to the offset into the correct section.
750 if (MR.isGlobalValue()) {
751 GlobalValue *GV = MR.getGlobalValue();
752 MachOSection *MOSPtr = GVSection[GV];
753 intptr_t Offset = GVOffset[GV];
755 // If we have never seen the global before, it must be to a symbol
756 // defined in another module (N_UNDF).
758 // FIXME: need to append stub suffix
761 TargetIndex = GVOffset[GV];
763 Scattered = TargetSection != 0;
764 TargetSection = MOSPtr->Index;
765 MachOSection &To = *SectionList[TargetSection - 1];
766 TargetAddr = To.addr;
767 TargetIndex = To.Index;
769 MR.setResultPointer((void*)Offset);
772 OutputBuffer RelocOut(MOS.RelocBuffer, is64Bit, isLittleEndian);
773 OutputBuffer SecOut(MOS.SectionData, is64Bit, isLittleEndian);
775 MOS.nreloc += GetTargetRelocation(MR, MOS.Index, TargetAddr, TargetIndex,
776 RelocOut, SecOut, Scattered, Extern);
780 // InitMem - Write the value of a Constant to the specified memory location,
781 // converting it into bytes and relocations.
782 void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
783 const TargetData *TD,
784 std::vector<MachineRelocation> &MRs) {
785 typedef std::pair<const Constant*, intptr_t> CPair;
786 std::vector<CPair> WorkList;
788 WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
790 intptr_t ScatteredOffset = 0;
792 while (!WorkList.empty()) {
793 const Constant *PC = WorkList.back().first;
794 intptr_t PA = WorkList.back().second;
797 if (isa<UndefValue>(PC)) {
799 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(PC)) {
800 unsigned ElementSize = TD->getTypeSize(CP->getType()->getElementType());
801 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
802 WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
803 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
805 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
807 switch (CE->getOpcode()) {
808 case Instruction::GetElementPtr: {
809 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
810 ScatteredOffset = TD->getIndexedOffset(CE->getOperand(0)->getType(),
811 &Indices[0], Indices.size());
812 WorkList.push_back(CPair(CE->getOperand(0), PA));
815 case Instruction::Add:
817 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
821 } else if (PC->getType()->isFirstClassType()) {
822 unsigned char *ptr = (unsigned char *)PA;
823 switch (PC->getType()->getTypeID()) {
824 case Type::IntegerTyID: {
825 unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
826 uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
829 else if (NumBits <= 16) {
830 if (TD->isBigEndian())
831 val = ByteSwap_16(val);
834 } else if (NumBits <= 32) {
835 if (TD->isBigEndian())
836 val = ByteSwap_32(val);
841 } else if (NumBits <= 64) {
842 if (TD->isBigEndian())
843 val = ByteSwap_64(val);
853 assert(0 && "Not implemented: bit widths > 64");
857 case Type::FloatTyID: {
858 uint64_t val = FloatToBits(cast<ConstantFP>(PC)->getValue());
859 if (TD->isBigEndian())
860 val = ByteSwap_32(val);
867 case Type::DoubleTyID: {
868 uint64_t val = DoubleToBits(cast<ConstantFP>(PC)->getValue());
869 if (TD->isBigEndian())
870 val = ByteSwap_64(val);
881 case Type::PointerTyID:
882 if (isa<ConstantPointerNull>(PC))
883 memset(ptr, 0, TD->getPointerSize());
884 else if (const GlobalValue* GV = dyn_cast<GlobalValue>(PC)) {
885 // FIXME: what about function stubs?
886 MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr,
887 MachineRelocation::VANILLA,
888 const_cast<GlobalValue*>(GV),
892 assert(0 && "Unknown constant pointer type!");
895 cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
898 } else if (isa<ConstantAggregateZero>(PC)) {
899 memset((void*)PA, 0, (size_t)TD->getTypeSize(PC->getType()));
900 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
901 unsigned ElementSize = TD->getTypeSize(CPA->getType()->getElementType());
902 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
903 WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
904 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
905 const StructLayout *SL =
906 TD->getStructLayout(cast<StructType>(CPS->getType()));
907 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
908 WorkList.push_back(CPair(CPS->getOperand(i),
909 PA+SL->getElementOffset(i)));
911 cerr << "Bad Type: " << *PC->getType() << "\n";
912 assert(0 && "Unknown constant type to initialize memory with!");
917 MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
919 GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
920 n_desc(0), n_value(0) {
922 const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
924 switch (GV->getLinkage()) {
926 assert(0 && "Unexpected linkage type!");
928 case GlobalValue::WeakLinkage:
929 case GlobalValue::LinkOnceLinkage:
930 assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
931 case GlobalValue::ExternalLinkage:
932 GVName = TAI->getGlobalPrefix() + name;
933 n_type |= GV->hasHiddenVisibility() ? N_PEXT : N_EXT;
935 case GlobalValue::InternalLinkage:
936 GVName = TAI->getGlobalPrefix() + name;