1 //===-- MachOWriter.cpp - Target-independent Mach-O Writer code -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Target/TargetAsmInfo.h"
35 #include "llvm/Target/TargetJITInfo.h"
36 #include "llvm/Support/Mangler.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/OutputBuffer.h"
39 #include "llvm/Support/Streams.h"
40 #include "llvm/Support/raw_ostream.h"
45 /// AddMachOWriter - Concrete function to add the Mach-O writer to the function
47 MachineCodeEmitter *llvm::AddMachOWriter(PassManagerBase &PM,
50 MachOWriter *MOW = new MachOWriter(O, TM);
52 return &MOW->getMachineCodeEmitter();
55 //===----------------------------------------------------------------------===//
56 // MachOCodeEmitter Implementation
57 //===----------------------------------------------------------------------===//
60 /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code
61 /// for functions to the Mach-O file.
62 class MachOCodeEmitter : public MachineCodeEmitter {
65 /// Target machine description.
68 /// is64Bit/isLittleEndian - This information is inferred from the target
69 /// machine directly, indicating what header values and flags to set.
70 bool is64Bit, isLittleEndian;
72 /// Relocations - These are the relocations that the function needs, as
74 std::vector<MachineRelocation> Relocations;
76 /// CPLocations - This is a map of constant pool indices to offsets from the
77 /// start of the section for that constant pool index.
78 std::vector<intptr_t> CPLocations;
80 /// CPSections - This is a map of constant pool indices to the MachOSection
81 /// containing the constant pool entry for that index.
82 std::vector<unsigned> CPSections;
84 /// JTLocations - This is a map of jump table indices to offsets from the
85 /// start of the section for that jump table index.
86 std::vector<intptr_t> JTLocations;
88 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
89 /// It is filled in by the StartMachineBasicBlock callback and queried by
90 /// the getMachineBasicBlockAddress callback.
91 std::vector<intptr_t> MBBLocations;
94 MachOCodeEmitter(MachOWriter &mow) : MOW(mow), TM(MOW.TM) {
95 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
96 isLittleEndian = TM.getTargetData()->isLittleEndian();
99 virtual void startFunction(MachineFunction &MF);
100 virtual bool finishFunction(MachineFunction &MF);
102 virtual void addRelocation(const MachineRelocation &MR) {
103 Relocations.push_back(MR);
106 void emitConstantPool(MachineConstantPool *MCP);
107 void emitJumpTables(MachineJumpTableInfo *MJTI);
109 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
110 assert(CPLocations.size() > Index && "CP not emitted!");
111 return CPLocations[Index];
113 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
114 assert(JTLocations.size() > Index && "JT not emitted!");
115 return JTLocations[Index];
118 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
119 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
120 MBBLocations.resize((MBB->getNumber()+1)*2);
121 MBBLocations[MBB->getNumber()] = getCurrentPCOffset();
124 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
125 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
126 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
127 return MBBLocations[MBB->getNumber()];
130 virtual intptr_t getLabelAddress(uint64_t Label) const {
131 assert(0 && "get Label not implemented");
136 virtual void emitLabel(uint64_t LabelID) {
137 assert(0 && "emit Label not implemented");
142 virtual void setModuleInfo(llvm::MachineModuleInfo* MMI) { }
144 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
145 virtual void startGVStub(const GlobalValue* F, unsigned StubSize,
146 unsigned Alignment = 1) {
147 assert(0 && "JIT specific function called!");
150 virtual void *finishGVStub(const GlobalValue* F) {
151 assert(0 && "JIT specific function called!");
158 /// startFunction - This callback is invoked when a new machine function is
159 /// about to be emitted.
160 void MachOCodeEmitter::startFunction(MachineFunction &MF) {
161 const TargetData *TD = TM.getTargetData();
162 const Function *F = MF.getFunction();
164 // Align the output buffer to the appropriate alignment, power of 2.
165 unsigned FnAlign = F->getAlignment();
166 unsigned TDAlign = TD->getPrefTypeAlignment(F->getType());
167 unsigned Align = Log2_32(std::max(FnAlign, TDAlign));
168 assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
170 // Get the Mach-O Section that this function belongs in.
171 MachOWriter::MachOSection *MOS = MOW.getTextSection();
173 // FIXME: better memory management
174 MOS->SectionData.reserve(4096);
175 BufferBegin = &MOS->SectionData[0];
176 BufferEnd = BufferBegin + MOS->SectionData.capacity();
178 // Upgrade the section alignment if required.
179 if (MOS->align < Align) MOS->align = Align;
181 // Round the size up to the correct alignment for starting the new function.
182 if ((MOS->size & ((1 << Align) - 1)) != 0) {
183 MOS->size += (1 << Align);
184 MOS->size &= ~((1 << Align) - 1);
187 // FIXME: Using MOS->size directly here instead of calculating it from the
188 // output buffer size (impossible because the code emitter deals only in raw
189 // bytes) forces us to manually synchronize size and write padding zero bytes
190 // to the output buffer for all non-text sections. For text sections, we do
191 // not synchonize the output buffer, and we just blow up if anyone tries to
192 // write non-code to it. An assert should probably be added to
193 // AddSymbolToSection to prevent calling it on the text section.
194 CurBufferPtr = BufferBegin + MOS->size;
196 // Clear per-function data structures.
200 MBBLocations.clear();
203 /// finishFunction - This callback is invoked after the function is completely
205 bool MachOCodeEmitter::finishFunction(MachineFunction &MF) {
206 // Get the Mach-O Section that this function belongs in.
207 MachOWriter::MachOSection *MOS = MOW.getTextSection();
209 // Get a symbol for the function to add to the symbol table
210 // FIXME: it seems like we should call something like AddSymbolToSection
211 // in startFunction rather than changing the section size and symbol n_value
213 const GlobalValue *FuncV = MF.getFunction();
214 MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, TM);
215 FnSym.n_value = MOS->size;
216 MOS->size = CurBufferPtr - BufferBegin;
218 // Emit constant pool to appropriate section(s)
219 emitConstantPool(MF.getConstantPool());
221 // Emit jump tables to appropriate section
222 emitJumpTables(MF.getJumpTableInfo());
224 // If we have emitted any relocations to function-specific objects such as
225 // basic blocks, constant pools entries, or jump tables, record their
226 // addresses now so that we can rewrite them with the correct addresses
228 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
229 MachineRelocation &MR = Relocations[i];
232 if (MR.isBasicBlock()) {
233 Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
234 MR.setConstantVal(MOS->Index);
235 MR.setResultPointer((void*)Addr);
236 } else if (MR.isJumpTableIndex()) {
237 Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
238 MR.setConstantVal(MOW.getJumpTableSection()->Index);
239 MR.setResultPointer((void*)Addr);
240 } else if (MR.isConstantPoolIndex()) {
241 Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
242 MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
243 MR.setResultPointer((void*)Addr);
244 } else if (MR.isGlobalValue()) {
245 // FIXME: This should be a set or something that uniques
246 MOW.PendingGlobals.push_back(MR.getGlobalValue());
248 assert(0 && "Unhandled relocation type");
250 MOS->Relocations.push_back(MR);
254 // Finally, add it to the symtab.
255 MOW.SymbolTable.push_back(FnSym);
259 /// emitConstantPool - For each constant pool entry, figure out which section
260 /// the constant should live in, allocate space for it, and emit it to the
261 /// Section data buffer.
262 void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
263 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
264 if (CP.empty()) return;
266 // FIXME: handle PIC codegen
267 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
268 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
270 // Although there is no strict necessity that I am aware of, we will do what
271 // gcc for OS X does and put each constant pool entry in a section of constant
272 // objects of a certain size. That means that float constants go in the
273 // literal4 section, and double objects go in literal8, etc.
275 // FIXME: revisit this decision if we ever do the "stick everything into one
276 // "giant object for PIC" optimization.
277 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
278 const Type *Ty = CP[i].getType();
279 unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
281 MachOWriter::MachOSection *Sec = MOW.getConstSection(CP[i].Val.ConstVal);
282 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
284 CPLocations.push_back(Sec->SectionData.size());
285 CPSections.push_back(Sec->Index);
287 // FIXME: remove when we have unified size + output buffer
290 // Allocate space in the section for the global.
291 // FIXME: need alignment?
292 // FIXME: share between here and AddSymbolToSection?
293 for (unsigned j = 0; j < Size; ++j)
294 SecDataOut.outbyte(0);
296 MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
297 TM.getTargetData(), Sec->Relocations);
301 /// emitJumpTables - Emit all the jump tables for a given jump table info
302 /// record to the appropriate section.
303 void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
304 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
305 if (JT.empty()) return;
307 // FIXME: handle PIC codegen
308 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
309 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
311 MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
312 unsigned TextSecIndex = MOW.getTextSection()->Index;
313 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
315 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
316 // For each jump table, record its offset from the start of the section,
317 // reserve space for the relocations to the MBBs, and add the relocations.
318 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
319 JTLocations.push_back(Sec->SectionData.size());
320 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
321 MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
323 MR.setResultPointer((void *)JTLocations[i]);
324 MR.setConstantVal(TextSecIndex);
325 Sec->Relocations.push_back(MR);
326 SecDataOut.outaddr(0);
329 // FIXME: remove when we have unified size + output buffer
330 Sec->size = Sec->SectionData.size();
333 //===----------------------------------------------------------------------===//
334 // MachOWriter Implementation
335 //===----------------------------------------------------------------------===//
337 char MachOWriter::ID = 0;
338 MachOWriter::MachOWriter(raw_ostream &o, TargetMachine &tm)
339 : MachineFunctionPass(&ID), O(o), TM(tm) {
340 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
341 isLittleEndian = TM.getTargetData()->isLittleEndian();
343 // Create the machine code emitter object for this target.
344 MCE = new MachOCodeEmitter(*this);
347 MachOWriter::~MachOWriter() {
351 void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
352 const Type *Ty = GV->getType()->getElementType();
353 unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
354 unsigned Align = TM.getTargetData()->getPreferredAlignment(GV);
356 // Reserve space in the .bss section for this symbol while maintaining the
357 // desired section alignment, which must be at least as much as required by
359 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
362 uint64_t OrigSize = Sec->size;
363 Align = Log2_32(Align);
364 Sec->align = std::max(unsigned(Sec->align), Align);
365 Sec->size = (Sec->size + Align - 1) & ~(Align-1);
367 // Add alignment padding to buffer as well.
368 // FIXME: remove when we have unified size + output buffer
369 unsigned AlignedSize = Sec->size - OrigSize;
370 for (unsigned i = 0; i < AlignedSize; ++i)
371 SecDataOut.outbyte(0);
373 // Globals without external linkage apparently do not go in the symbol table.
374 if (GV->getLinkage() != GlobalValue::InternalLinkage) {
375 MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
376 Sym.n_value = Sec->size;
377 SymbolTable.push_back(Sym);
380 // Record the offset of the symbol, and then allocate space for it.
381 // FIXME: remove when we have unified size + output buffer
384 // Now that we know what section the GlovalVariable is going to be emitted
385 // into, update our mappings.
386 // FIXME: We may also need to update this when outputting non-GlobalVariable
387 // GlobalValues such as functions.
389 GVOffset[GV] = Sec->SectionData.size();
391 // Allocate space in the section for the global.
392 for (unsigned i = 0; i < Size; ++i)
393 SecDataOut.outbyte(0);
396 void MachOWriter::EmitGlobal(GlobalVariable *GV) {
397 const Type *Ty = GV->getType()->getElementType();
398 unsigned Size = TM.getTargetData()->getABITypeSize(Ty);
399 bool NoInit = !GV->hasInitializer();
401 // If this global has a zero initializer, it is part of the .bss or common
403 if (NoInit || GV->getInitializer()->isNullValue()) {
404 // If this global is part of the common block, add it now. Variables are
405 // part of the common block if they are zero initialized and allowed to be
406 // merged with other symbols.
407 if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
408 GV->hasCommonLinkage()) {
409 MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
410 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
411 // bytes of the symbol.
412 ExtOrCommonSym.n_value = Size;
413 SymbolTable.push_back(ExtOrCommonSym);
414 // Remember that we've seen this symbol
418 // Otherwise, this symbol is part of the .bss section.
419 MachOSection *BSS = getBSSSection();
420 AddSymbolToSection(BSS, GV);
424 // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
425 // 16 bytes, or a cstring. Other read only data goes into a regular const
426 // section. Read-write data goes in the data section.
427 MachOSection *Sec = GV->isConstant() ? getConstSection(GV->getInitializer()) :
429 AddSymbolToSection(Sec, GV);
430 InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
431 TM.getTargetData(), Sec->Relocations);
435 bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
436 // Nothing to do here, this is all done through the MCE object.
440 bool MachOWriter::doInitialization(Module &M) {
441 // Set the magic value, now that we know the pointer size and endianness
442 Header.setMagic(isLittleEndian, is64Bit);
445 // FIXME: this only works for object files, we do not support the creation
446 // of dynamic libraries or executables at this time.
447 Header.filetype = MachOHeader::MH_OBJECT;
449 Mang = new Mangler(M);
453 /// doFinalization - Now that the module has been completely processed, emit
454 /// the Mach-O file to 'O'.
455 bool MachOWriter::doFinalization(Module &M) {
456 // FIXME: we don't handle debug info yet, we should probably do that.
458 // Okay, the.text section has been completed, build the .data, .bss, and
459 // "common" sections next.
460 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
464 // Emit the header and load commands.
465 EmitHeaderAndLoadCommands();
467 // Emit the various sections and their relocation info.
470 // Write the symbol table and the string table to the end of the file.
471 O.write((char*)&SymT[0], SymT.size());
472 O.write((char*)&StrT[0], StrT.size());
474 // We are done with the abstract symbols.
477 DynamicSymbolTable.clear();
479 // Release the name mangler object.
480 delete Mang; Mang = 0;
484 void MachOWriter::EmitHeaderAndLoadCommands() {
485 // Step #0: Fill in the segment load command size, since we need it to figure
486 // out the rest of the header fields
487 MachOSegment SEG("", is64Bit);
488 SEG.nsects = SectionList.size();
489 SEG.cmdsize = SEG.cmdSize(is64Bit) +
490 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
492 // Step #1: calculate the number of load commands. We always have at least
493 // one, for the LC_SEGMENT load command, plus two for the normal
494 // and dynamic symbol tables, if there are any symbols.
495 Header.ncmds = SymbolTable.empty() ? 1 : 3;
497 // Step #2: calculate the size of the load commands
498 Header.sizeofcmds = SEG.cmdsize;
499 if (!SymbolTable.empty())
500 Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
502 // Step #3: write the header to the file
503 // Local alias to shortenify coming code.
504 DataBuffer &FH = Header.HeaderData;
505 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
507 FHOut.outword(Header.magic);
508 FHOut.outword(TM.getMachOWriterInfo()->getCPUType());
509 FHOut.outword(TM.getMachOWriterInfo()->getCPUSubType());
510 FHOut.outword(Header.filetype);
511 FHOut.outword(Header.ncmds);
512 FHOut.outword(Header.sizeofcmds);
513 FHOut.outword(Header.flags);
515 FHOut.outword(Header.reserved);
517 // Step #4: Finish filling in the segment load command and write it out
518 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
519 E = SectionList.end(); I != E; ++I)
520 SEG.filesize += (*I)->size;
522 SEG.vmsize = SEG.filesize;
523 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
525 FHOut.outword(SEG.cmd);
526 FHOut.outword(SEG.cmdsize);
527 FHOut.outstring(SEG.segname, 16);
528 FHOut.outaddr(SEG.vmaddr);
529 FHOut.outaddr(SEG.vmsize);
530 FHOut.outaddr(SEG.fileoff);
531 FHOut.outaddr(SEG.filesize);
532 FHOut.outword(SEG.maxprot);
533 FHOut.outword(SEG.initprot);
534 FHOut.outword(SEG.nsects);
535 FHOut.outword(SEG.flags);
537 // Step #5: Finish filling in the fields of the MachOSections
538 uint64_t currentAddr = 0;
539 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
540 E = SectionList.end(); I != E; ++I) {
541 MachOSection *MOS = *I;
542 MOS->addr = currentAddr;
543 MOS->offset = currentAddr + SEG.fileoff;
545 // FIXME: do we need to do something with alignment here?
546 currentAddr += MOS->size;
549 // Step #6: Emit the symbol table to temporary buffers, so that we know the
550 // size of the string table when we write the next load command. This also
551 // sorts and assigns indices to each of the symbols, which is necessary for
552 // emitting relocations to externally-defined objects.
553 BufferSymbolAndStringTable();
555 // Step #7: Calculate the number of relocations for each section and write out
556 // the section commands for each section
557 currentAddr += SEG.fileoff;
558 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
559 E = SectionList.end(); I != E; ++I) {
560 MachOSection *MOS = *I;
561 // Convert the relocations to target-specific relocations, and fill in the
562 // relocation offset for this section.
563 CalculateRelocations(*MOS);
564 MOS->reloff = MOS->nreloc ? currentAddr : 0;
565 currentAddr += MOS->nreloc * 8;
567 // write the finalized section command to the output buffer
568 FHOut.outstring(MOS->sectname, 16);
569 FHOut.outstring(MOS->segname, 16);
570 FHOut.outaddr(MOS->addr);
571 FHOut.outaddr(MOS->size);
572 FHOut.outword(MOS->offset);
573 FHOut.outword(MOS->align);
574 FHOut.outword(MOS->reloff);
575 FHOut.outword(MOS->nreloc);
576 FHOut.outword(MOS->flags);
577 FHOut.outword(MOS->reserved1);
578 FHOut.outword(MOS->reserved2);
580 FHOut.outword(MOS->reserved3);
583 // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
584 SymTab.symoff = currentAddr;
585 SymTab.nsyms = SymbolTable.size();
586 SymTab.stroff = SymTab.symoff + SymT.size();
587 SymTab.strsize = StrT.size();
588 FHOut.outword(SymTab.cmd);
589 FHOut.outword(SymTab.cmdsize);
590 FHOut.outword(SymTab.symoff);
591 FHOut.outword(SymTab.nsyms);
592 FHOut.outword(SymTab.stroff);
593 FHOut.outword(SymTab.strsize);
595 // FIXME: set DySymTab fields appropriately
596 // We should probably just update these in BufferSymbolAndStringTable since
597 // thats where we're partitioning up the different kinds of symbols.
598 FHOut.outword(DySymTab.cmd);
599 FHOut.outword(DySymTab.cmdsize);
600 FHOut.outword(DySymTab.ilocalsym);
601 FHOut.outword(DySymTab.nlocalsym);
602 FHOut.outword(DySymTab.iextdefsym);
603 FHOut.outword(DySymTab.nextdefsym);
604 FHOut.outword(DySymTab.iundefsym);
605 FHOut.outword(DySymTab.nundefsym);
606 FHOut.outword(DySymTab.tocoff);
607 FHOut.outword(DySymTab.ntoc);
608 FHOut.outword(DySymTab.modtaboff);
609 FHOut.outword(DySymTab.nmodtab);
610 FHOut.outword(DySymTab.extrefsymoff);
611 FHOut.outword(DySymTab.nextrefsyms);
612 FHOut.outword(DySymTab.indirectsymoff);
613 FHOut.outword(DySymTab.nindirectsyms);
614 FHOut.outword(DySymTab.extreloff);
615 FHOut.outword(DySymTab.nextrel);
616 FHOut.outword(DySymTab.locreloff);
617 FHOut.outword(DySymTab.nlocrel);
619 O.write((char*)&FH[0], FH.size());
622 /// EmitSections - Now that we have constructed the file header and load
623 /// commands, emit the data for each section to the file.
624 void MachOWriter::EmitSections() {
625 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
626 E = SectionList.end(); I != E; ++I)
627 // Emit the contents of each section
628 O.write((char*)&(*I)->SectionData[0], (*I)->size);
629 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
630 E = SectionList.end(); I != E; ++I)
631 // Emit the relocation entry data for each section.
632 O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
635 /// PartitionByLocal - Simple boolean predicate that returns true if Sym is
636 /// a local symbol rather than an external symbol.
637 bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
638 return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
641 /// PartitionByDefined - Simple boolean predicate that returns true if Sym is
642 /// defined in this module.
643 bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
644 // FIXME: Do N_ABS or N_INDR count as defined?
645 return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
648 /// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
649 /// each a string table index so that they appear in the correct order in the
651 void MachOWriter::BufferSymbolAndStringTable() {
652 // The order of the symbol table is:
654 // 2. defined external symbols (sorted by name)
655 // 3. undefined external symbols (sorted by name)
657 // Before sorting the symbols, check the PendingGlobals for any undefined
658 // globals that need to be put in the symbol table.
659 for (std::vector<GlobalValue*>::iterator I = PendingGlobals.begin(),
660 E = PendingGlobals.end(); I != E; ++I) {
661 if (GVOffset[*I] == 0 && GVSection[*I] == 0) {
662 MachOSym UndfSym(*I, Mang->getValueName(*I), MachOSym::NO_SECT, TM);
663 SymbolTable.push_back(UndfSym);
668 // Sort the symbols by name, so that when we partition the symbols by scope
669 // of definition, we won't have to sort by name within each partition.
670 std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
672 // Parition the symbol table entries so that all local symbols come before
673 // all symbols with external linkage. { 1 | 2 3 }
674 std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
676 // Advance iterator to beginning of external symbols and partition so that
677 // all external symbols defined in this module come before all external
678 // symbols defined elsewhere. { 1 | 2 | 3 }
679 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
680 E = SymbolTable.end(); I != E; ++I) {
681 if (!PartitionByLocal(*I)) {
682 std::partition(I, E, PartitionByDefined);
687 // Calculate the starting index for each of the local, extern defined, and
688 // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
690 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
691 E = SymbolTable.end(); I != E; ++I) {
692 if (PartitionByLocal(*I)) {
693 ++DySymTab.nlocalsym;
694 ++DySymTab.iextdefsym;
695 ++DySymTab.iundefsym;
696 } else if (PartitionByDefined(*I)) {
697 ++DySymTab.nextdefsym;
698 ++DySymTab.iundefsym;
700 ++DySymTab.nundefsym;
704 // Write out a leading zero byte when emitting string table, for n_strx == 0
705 // which means an empty string.
706 OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
709 // The order of the string table is:
710 // 1. strings for external symbols
711 // 2. strings for local symbols
712 // Since this is the opposite order from the symbol table, which we have just
713 // sorted, we can walk the symbol table backwards to output the string table.
714 for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
715 E = SymbolTable.rend(); I != E; ++I) {
716 if (I->GVName == "") {
719 I->n_strx = StrT.size();
720 StrTOut.outstring(I->GVName, I->GVName.length()+1);
724 OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
727 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
728 E = SymbolTable.end(); I != E; ++I, ++index) {
729 // Add the section base address to the section offset in the n_value field
730 // to calculate the full address.
731 // FIXME: handle symbols where the n_value field is not the address
732 GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
733 if (GV && GVSection[GV])
734 I->n_value += GVSection[GV]->addr;
735 if (GV && (GVOffset[GV] == -1))
736 GVOffset[GV] = index;
738 // Emit nlist to buffer
739 SymTOut.outword(I->n_strx);
740 SymTOut.outbyte(I->n_type);
741 SymTOut.outbyte(I->n_sect);
742 SymTOut.outhalf(I->n_desc);
743 SymTOut.outaddr(I->n_value);
747 /// CalculateRelocations - For each MachineRelocation in the current section,
748 /// calculate the index of the section containing the object to be relocated,
749 /// and the offset into that section. From this information, create the
750 /// appropriate target-specific MachORelocation type and add buffer it to be
751 /// written out after we are finished writing out sections.
752 void MachOWriter::CalculateRelocations(MachOSection &MOS) {
753 for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
754 MachineRelocation &MR = MOS.Relocations[i];
755 unsigned TargetSection = MR.getConstantVal();
756 unsigned TargetAddr = 0;
757 unsigned TargetIndex = 0;
759 // This is a scattered relocation entry if it points to a global value with
760 // a non-zero offset.
761 bool Scattered = false;
764 // Since we may not have seen the GlobalValue we were interested in yet at
765 // the time we emitted the relocation for it, fix it up now so that it
766 // points to the offset into the correct section.
767 if (MR.isGlobalValue()) {
768 GlobalValue *GV = MR.getGlobalValue();
769 MachOSection *MOSPtr = GVSection[GV];
770 intptr_t Offset = GVOffset[GV];
772 // If we have never seen the global before, it must be to a symbol
773 // defined in another module (N_UNDF).
775 // FIXME: need to append stub suffix
778 TargetIndex = GVOffset[GV];
780 Scattered = TargetSection != 0;
781 TargetSection = MOSPtr->Index;
783 MR.setResultPointer((void*)Offset);
786 // If the symbol is locally defined, pass in the address of the section and
787 // the section index to the code which will generate the target relocation.
789 MachOSection &To = *SectionList[TargetSection - 1];
790 TargetAddr = To.addr;
791 TargetIndex = To.Index;
794 OutputBuffer RelocOut(MOS.RelocBuffer, is64Bit, isLittleEndian);
795 OutputBuffer SecOut(MOS.SectionData, is64Bit, isLittleEndian);
797 MOS.nreloc += GetTargetRelocation(MR, MOS.Index, TargetAddr, TargetIndex,
798 RelocOut, SecOut, Scattered, Extern);
802 // InitMem - Write the value of a Constant to the specified memory location,
803 // converting it into bytes and relocations.
804 void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
805 const TargetData *TD,
806 std::vector<MachineRelocation> &MRs) {
807 typedef std::pair<const Constant*, intptr_t> CPair;
808 std::vector<CPair> WorkList;
810 WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
812 intptr_t ScatteredOffset = 0;
814 while (!WorkList.empty()) {
815 const Constant *PC = WorkList.back().first;
816 intptr_t PA = WorkList.back().second;
819 if (isa<UndefValue>(PC)) {
821 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(PC)) {
822 unsigned ElementSize =
823 TD->getABITypeSize(CP->getType()->getElementType());
824 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
825 WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
826 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
828 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
830 switch (CE->getOpcode()) {
831 case Instruction::GetElementPtr: {
832 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
833 ScatteredOffset = TD->getIndexedOffset(CE->getOperand(0)->getType(),
834 &Indices[0], Indices.size());
835 WorkList.push_back(CPair(CE->getOperand(0), PA));
838 case Instruction::Add:
840 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
844 } else if (PC->getType()->isSingleValueType()) {
845 unsigned char *ptr = (unsigned char *)PA;
846 switch (PC->getType()->getTypeID()) {
847 case Type::IntegerTyID: {
848 unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
849 uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
852 else if (NumBits <= 16) {
853 if (TD->isBigEndian())
854 val = ByteSwap_16(val);
857 } else if (NumBits <= 32) {
858 if (TD->isBigEndian())
859 val = ByteSwap_32(val);
864 } else if (NumBits <= 64) {
865 if (TD->isBigEndian())
866 val = ByteSwap_64(val);
876 assert(0 && "Not implemented: bit widths > 64");
880 case Type::FloatTyID: {
881 uint32_t val = cast<ConstantFP>(PC)->getValueAPF().bitcastToAPInt().
883 if (TD->isBigEndian())
884 val = ByteSwap_32(val);
891 case Type::DoubleTyID: {
892 uint64_t val = cast<ConstantFP>(PC)->getValueAPF().bitcastToAPInt().
894 if (TD->isBigEndian())
895 val = ByteSwap_64(val);
906 case Type::PointerTyID:
907 if (isa<ConstantPointerNull>(PC))
908 memset(ptr, 0, TD->getPointerSize());
909 else if (const GlobalValue* GV = dyn_cast<GlobalValue>(PC)) {
910 // FIXME: what about function stubs?
911 MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr,
912 MachineRelocation::VANILLA,
913 const_cast<GlobalValue*>(GV),
917 assert(0 && "Unknown constant pointer type!");
920 cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
923 } else if (isa<ConstantAggregateZero>(PC)) {
924 memset((void*)PA, 0, (size_t)TD->getABITypeSize(PC->getType()));
925 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
926 unsigned ElementSize =
927 TD->getABITypeSize(CPA->getType()->getElementType());
928 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
929 WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
930 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
931 const StructLayout *SL =
932 TD->getStructLayout(cast<StructType>(CPS->getType()));
933 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
934 WorkList.push_back(CPair(CPS->getOperand(i),
935 PA+SL->getElementOffset(i)));
937 cerr << "Bad Type: " << *PC->getType() << "\n";
938 assert(0 && "Unknown constant type to initialize memory with!");
943 MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
945 GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
946 n_desc(0), n_value(0) {
948 const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
950 switch (GV->getLinkage()) {
952 assert(0 && "Unexpected linkage type!");
954 case GlobalValue::WeakLinkage:
955 case GlobalValue::LinkOnceLinkage:
956 case GlobalValue::CommonLinkage:
957 assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
958 case GlobalValue::ExternalLinkage:
959 GVName = TAI->getGlobalPrefix() + name;
960 n_type |= GV->hasHiddenVisibility() ? N_PEXT : N_EXT;
962 case GlobalValue::InternalLinkage:
963 GVName = TAI->getGlobalPrefix() + name;