blob: de81e5fd6a1b2aff1fc09a908ff61ae46a41066e [file] [log] [blame]
Nate Begemaneb883af2006-08-23 21:08:52 +00001//===-- MachOWriter.cpp - Target-independent Mach-O Writer code -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the target-independent Mach-O writer. This file writes
11// out the Mach-O file in the following order:
12//
13// #1 FatHeader (universal-only)
14// #2 FatArch (universal-only, 1 per universal arch)
15// Per arch:
16// #3 Header
17// #4 Load Commands
18// #5 Sections
19// #6 Relocations
20// #7 Symbols
21// #8 Strings
22//
23//===----------------------------------------------------------------------===//
24
Bill Wendling8f84f1f2007-02-08 01:35:27 +000025#include "MachOWriter.h"
Nate Begemanbfaaaa62006-12-11 02:20:45 +000026#include "llvm/Constants.h"
27#include "llvm/DerivedTypes.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000028#include "llvm/Module.h"
Bill Wendling8f84f1f2007-02-08 01:35:27 +000029#include "llvm/PassManager.h"
30#include "llvm/CodeGen/FileWriters.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000031#include "llvm/CodeGen/MachineCodeEmitter.h"
32#include "llvm/CodeGen/MachineConstantPool.h"
Nate Begeman019f8512006-09-10 23:03:44 +000033#include "llvm/CodeGen/MachineJumpTableInfo.h"
Nate Begeman94be2482006-09-08 22:42:09 +000034#include "llvm/ExecutionEngine/ExecutionEngine.h"
Nate Begemanbfaaaa62006-12-11 02:20:45 +000035#include "llvm/Target/TargetAsmInfo.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000036#include "llvm/Target/TargetJITInfo.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000037#include "llvm/Support/Mangler.h"
Nate Begemanf8f2c5a2006-08-25 06:36:58 +000038#include "llvm/Support/MathExtras.h"
Bill Wendling203d3e42007-01-17 22:22:31 +000039#include "llvm/Support/OutputBuffer.h"
Nate Begemanbfaaaa62006-12-11 02:20:45 +000040#include "llvm/Support/Streams.h"
Nate Begemand2030e62006-08-26 15:46:34 +000041#include <algorithm>
Nate Begemaneb883af2006-08-23 21:08:52 +000042using namespace llvm;
43
Bill Wendling8f84f1f2007-02-08 01:35:27 +000044/// AddMachOWriter - Concrete function to add the Mach-O writer to the function
45/// pass manager.
46MachineCodeEmitter *llvm::AddMachOWriter(FunctionPassManager &FPM,
47 std::ostream &O,
48 TargetMachine &TM) {
49 MachOWriter *MOW = new MachOWriter(O, TM);
50 FPM.add(MOW);
51 return &MOW->getMachineCodeEmitter();
52}
53
Nate Begemaneb883af2006-08-23 21:08:52 +000054//===----------------------------------------------------------------------===//
55// MachOCodeEmitter Implementation
56//===----------------------------------------------------------------------===//
57
58namespace llvm {
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 {
62 MachOWriter &MOW;
Nate Begemaneb883af2006-08-23 21:08:52 +000063
Bill Wendling203d3e42007-01-17 22:22:31 +000064 /// Target machine description.
65 TargetMachine &TM;
66
Bill Wendlingc904a5b2007-01-18 01:23:11 +000067 /// is64Bit/isLittleEndian - This information is inferred from the target
68 /// machine directly, indicating what header values and flags to set.
69 bool is64Bit, isLittleEndian;
70
Nate Begemaneb883af2006-08-23 21:08:52 +000071 /// Relocations - These are the relocations that the function needs, as
72 /// emitted.
73 std::vector<MachineRelocation> Relocations;
Nate Begeman019f8512006-09-10 23:03:44 +000074
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;
78
Nate Begemanbfaaaa62006-12-11 02:20:45 +000079 /// 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;
82
Nate Begeman019f8512006-09-10 23:03:44 +000083 /// 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;
Nate Begemaneb883af2006-08-23 21:08:52 +000086
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;
91
92 public:
Bill Wendlingc904a5b2007-01-18 01:23:11 +000093 MachOCodeEmitter(MachOWriter &mow) : MOW(mow), TM(MOW.TM) {
94 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
95 isLittleEndian = TM.getTargetData()->isLittleEndian();
96 }
Nate Begemaneb883af2006-08-23 21:08:52 +000097
Nate Begemanc2b2d6a2007-02-07 05:47:16 +000098 virtual void startFunction(MachineFunction &MF);
99 virtual bool finishFunction(MachineFunction &MF);
Nate Begemaneb883af2006-08-23 21:08:52 +0000100
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000101 virtual void addRelocation(const MachineRelocation &MR) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000102 Relocations.push_back(MR);
103 }
104
Nate Begeman019f8512006-09-10 23:03:44 +0000105 void emitConstantPool(MachineConstantPool *MCP);
106 void emitJumpTables(MachineJumpTableInfo *MJTI);
107
Nate Begemaneb883af2006-08-23 21:08:52 +0000108 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000109 assert(CPLocations.size() > Index && "CP not emitted!");
Nate Begemanfec910c2007-02-28 07:40:50 +0000110 return CPLocations[Index];\
Nate Begemaneb883af2006-08-23 21:08:52 +0000111 }
112 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman019f8512006-09-10 23:03:44 +0000113 assert(JTLocations.size() > Index && "JT not emitted!");
114 return JTLocations[Index];
115 }
116
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();
Nate Begemaneb883af2006-08-23 21:08:52 +0000121 }
122
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()];
127 }
128
129 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000130 virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000131 assert(0 && "JIT specific function called!");
132 abort();
133 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000134 virtual void *finishFunctionStub(const Function *F) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000135 assert(0 && "JIT specific function called!");
136 abort();
137 return 0;
138 }
139 };
140}
141
142/// startFunction - This callback is invoked when a new machine function is
143/// about to be emitted.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000144void MachOCodeEmitter::startFunction(MachineFunction &MF) {
145 const TargetData *TD = TM.getTargetData();
146 const Function *F = MF.getFunction();
147
Nate Begemaneb883af2006-08-23 21:08:52 +0000148 // Align the output buffer to the appropriate alignment, power of 2.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000149 unsigned FnAlign = F->getAlignment();
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000150 unsigned TDAlign = TD->getPrefTypeAlignment(F->getType());
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000151 unsigned Align = Log2_32(std::max(FnAlign, TDAlign));
152 assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
Nate Begemaneb883af2006-08-23 21:08:52 +0000153
154 // Get the Mach-O Section that this function belongs in.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000155 MachOWriter::MachOSection *MOS = MOW.getTextSection();
Nate Begemaneb883af2006-08-23 21:08:52 +0000156
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000157 // FIXME: better memory management
Nate Begemaneb883af2006-08-23 21:08:52 +0000158 MOS->SectionData.reserve(4096);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000159 BufferBegin = &MOS->SectionData[0];
Nate Begemaneb883af2006-08-23 21:08:52 +0000160 BufferEnd = BufferBegin + MOS->SectionData.capacity();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000161
Nate Begeman6635f352007-01-26 22:39:48 +0000162 // Upgrade the section alignment if required.
163 if (MOS->align < Align) MOS->align = Align;
164
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);
169 }
170
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000171 // 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.
Nate Begemaneb883af2006-08-23 21:08:52 +0000178 CurBufferPtr = BufferBegin + MOS->size;
179
Nate Begeman019f8512006-09-10 23:03:44 +0000180 // Clear per-function data structures.
181 CPLocations.clear();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000182 CPSections.clear();
Nate Begeman019f8512006-09-10 23:03:44 +0000183 JTLocations.clear();
Nate Begemaneb883af2006-08-23 21:08:52 +0000184 MBBLocations.clear();
185}
186
187/// finishFunction - This callback is invoked after the function is completely
188/// finished.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000189bool MachOCodeEmitter::finishFunction(MachineFunction &MF) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000190 // Get the Mach-O Section that this function belongs in.
191 MachOWriter::MachOSection *MOS = MOW.getTextSection();
192
Nate Begemaneb883af2006-08-23 21:08:52 +0000193 // Get a symbol for the function to add to the symbol table
Nate Begeman6635f352007-01-26 22:39:48 +0000194 // FIXME: it seems like we should call something like AddSymbolToSection
195 // in startFunction rather than changing the section size and symbol n_value
196 // here.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000197 const GlobalValue *FuncV = MF.getFunction();
Bill Wendling203d3e42007-01-17 22:22:31 +0000198 MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, TM);
Nate Begeman6635f352007-01-26 22:39:48 +0000199 FnSym.n_value = MOS->size;
200 MOS->size = CurBufferPtr - BufferBegin;
201
Nate Begeman019f8512006-09-10 23:03:44 +0000202 // Emit constant pool to appropriate section(s)
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000203 emitConstantPool(MF.getConstantPool());
Nate Begeman019f8512006-09-10 23:03:44 +0000204
205 // Emit jump tables to appropriate section
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000206 emitJumpTables(MF.getJumpTableInfo());
Nate Begemaneb883af2006-08-23 21:08:52 +0000207
Nate Begeman019f8512006-09-10 23:03:44 +0000208 // 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
211 // later.
Nate Begemaneb883af2006-08-23 21:08:52 +0000212 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
213 MachineRelocation &MR = Relocations[i];
Nate Begeman019f8512006-09-10 23:03:44 +0000214 intptr_t Addr;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000215
Nate Begemaneb883af2006-08-23 21:08:52 +0000216 if (MR.isBasicBlock()) {
Nate Begeman019f8512006-09-10 23:03:44 +0000217 Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000218 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);
Nate Begeman019f8512006-09-10 23:03:44 +0000224 } else if (MR.isConstantPoolIndex()) {
225 Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000226 MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
227 MR.setResultPointer((void*)Addr);
Nate Begemanfec910c2007-02-28 07:40:50 +0000228 } else if (MR.isGlobalValue()) {
229 // FIXME: This should be a set or something that uniques
230 MOW.PendingGlobals.push_back(MR.getGlobalValue());
231 } else {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000232 assert(0 && "Unhandled relocation type");
Nate Begemaneb883af2006-08-23 21:08:52 +0000233 }
Nate Begeman019f8512006-09-10 23:03:44 +0000234 MOS->Relocations.push_back(MR);
Nate Begemaneb883af2006-08-23 21:08:52 +0000235 }
236 Relocations.clear();
237
238 // Finally, add it to the symtab.
239 MOW.SymbolTable.push_back(FnSym);
240 return false;
241}
242
Nate Begeman019f8512006-09-10 23:03:44 +0000243/// 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.
246void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000247 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
248 if (CP.empty()) return;
249
250 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000251 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000252 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
253
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.
258 //
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();
Bill Wendling203d3e42007-01-17 22:22:31 +0000263 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000264
Nate Begeman1257c852007-01-29 21:20:42 +0000265 MachOWriter::MachOSection *Sec = MOW.getConstSection(CP[i].Val.ConstVal);
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000266 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000267
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000268 CPLocations.push_back(Sec->SectionData.size());
269 CPSections.push_back(Sec->Index);
270
271 // FIXME: remove when we have unified size + output buffer
272 Sec->size += Size;
273
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)
Bill Wendling203d3e42007-01-17 22:22:31 +0000278 SecDataOut.outbyte(0);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000279
280 MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
Bill Wendling203d3e42007-01-17 22:22:31 +0000281 TM.getTargetData(), Sec->Relocations);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000282 }
Nate Begeman019f8512006-09-10 23:03:44 +0000283}
284
285/// emitJumpTables - Emit all the jump tables for a given jump table info
286/// record to the appropriate section.
287void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
288 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
289 if (JT.empty()) return;
290
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000291 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000292 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begeman019f8512006-09-10 23:03:44 +0000293 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
294
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000295 MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
296 unsigned TextSecIndex = MOW.getTextSection()->Index;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000297 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Nate Begeman019f8512006-09-10 23:03:44 +0000298
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;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000303 JTLocations.push_back(Sec->SectionData.size());
Nate Begeman019f8512006-09-10 23:03:44 +0000304 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000305 MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
Nate Begeman019f8512006-09-10 23:03:44 +0000306 MBBs[mi]));
307 MR.setResultPointer((void *)JTLocations[i]);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000308 MR.setConstantVal(TextSecIndex);
309 Sec->Relocations.push_back(MR);
Bill Wendling203d3e42007-01-17 22:22:31 +0000310 SecDataOut.outaddr(0);
Nate Begeman019f8512006-09-10 23:03:44 +0000311 }
312 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000313 // FIXME: remove when we have unified size + output buffer
314 Sec->size = Sec->SectionData.size();
Nate Begeman019f8512006-09-10 23:03:44 +0000315}
316
Nate Begemaneb883af2006-08-23 21:08:52 +0000317//===----------------------------------------------------------------------===//
318// MachOWriter Implementation
319//===----------------------------------------------------------------------===//
320
321MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000322 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
323 isLittleEndian = TM.getTargetData()->isLittleEndian();
324
325 // Create the machine code emitter object for this target.
Bill Wendlinge9116152007-01-17 09:06:13 +0000326 MCE = new MachOCodeEmitter(*this);
Nate Begemaneb883af2006-08-23 21:08:52 +0000327}
328
329MachOWriter::~MachOWriter() {
330 delete MCE;
331}
332
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000333void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000334 const Type *Ty = GV->getType()->getElementType();
335 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000336 unsigned Align = GV->getAlignment();
337 if (Align == 0)
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000338 Align = TM.getTargetData()->getPrefTypeAlignment(Ty);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000339
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000340 // 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
342 // this symbol.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000343 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000344
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000345 if (Align) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000346 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);
350
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)
Bill Wendling203d3e42007-01-17 22:22:31 +0000355 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000356 }
Nate Begemanfec910c2007-02-28 07:40:50 +0000357 // 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);
362 }
363
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000364 // Record the offset of the symbol, and then allocate space for it.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000365 // FIXME: remove when we have unified size + output buffer
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000366 Sec->size += Size;
Nate Begemanfec910c2007-02-28 07:40:50 +0000367
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000368 // 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.
372 GVSection[GV] = Sec;
373 GVOffset[GV] = Sec->SectionData.size();
374
375 // Allocate space in the section for the global.
376 for (unsigned i = 0; i < Size; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000377 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000378}
379
Nate Begemaneb883af2006-08-23 21:08:52 +0000380void MachOWriter::EmitGlobal(GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000381 const Type *Ty = GV->getType()->getElementType();
382 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
383 bool NoInit = !GV->hasInitializer();
Nate Begemand2030e62006-08-26 15:46:34 +0000384
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000385 // If this global has a zero initializer, it is part of the .bss or common
386 // section.
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()) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000392 MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000393 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
394 // bytes of the symbol.
395 ExtOrCommonSym.n_value = Size;
Nate Begemanfec910c2007-02-28 07:40:50 +0000396 SymbolTable.push_back(ExtOrCommonSym);
397 // Remember that we've seen this symbol
398 GVOffset[GV] = Size;
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000399 return;
400 }
401 // Otherwise, this symbol is part of the .bss section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000402 MachOSection *BSS = getBSSSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000403 AddSymbolToSection(BSS, GV);
404 return;
405 }
406
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.
Nate Begeman1257c852007-01-29 21:20:42 +0000410 MachOSection *Sec = GV->isConstant() ? getConstSection(GV->getInitializer()) :
411 getDataSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000412 AddSymbolToSection(Sec, GV);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000413 InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
414 TM.getTargetData(), Sec->Relocations);
Nate Begemaneb883af2006-08-23 21:08:52 +0000415}
416
417
418bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
419 // Nothing to do here, this is all done through the MCE object.
420 return false;
421}
422
423bool MachOWriter::doInitialization(Module &M) {
424 // Set the magic value, now that we know the pointer size and endianness
425 Header.setMagic(isLittleEndian, is64Bit);
426
427 // Set the file type
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;
431
432 Mang = new Mangler(M);
433 return false;
434}
435
436/// doFinalization - Now that the module has been completely processed, emit
437/// the Mach-O file to 'O'.
438bool MachOWriter::doFinalization(Module &M) {
Nate Begemand2030e62006-08-26 15:46:34 +0000439 // FIXME: we don't handle debug info yet, we should probably do that.
440
Nate Begemaneb883af2006-08-23 21:08:52 +0000441 // 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();
444 I != E; ++I)
445 EmitGlobal(I);
446
447 // Emit the header and load commands.
448 EmitHeaderAndLoadCommands();
449
Nate Begeman019f8512006-09-10 23:03:44 +0000450 // Emit the various sections and their relocation info.
Nate Begemaneb883af2006-08-23 21:08:52 +0000451 EmitSections();
452
Nate Begemand2030e62006-08-26 15:46:34 +0000453 // 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());
Nate Begemaneb883af2006-08-23 21:08:52 +0000456
457 // We are done with the abstract symbols.
458 SectionList.clear();
459 SymbolTable.clear();
460 DynamicSymbolTable.clear();
461
462 // Release the name mangler object.
463 delete Mang; Mang = 0;
464 return false;
465}
466
467void 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) +
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000473 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
Nate Begemaneb883af2006-08-23 21:08:52 +0000474
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;
479
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;
484
485 // Step #3: write the header to the file
486 // Local alias to shortenify coming code.
487 DataBuffer &FH = Header.HeaderData;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000488 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000489
490 FHOut.outword(Header.magic);
Bill Wendling2b721822007-01-24 07:13:56 +0000491 FHOut.outword(TM.getMachOWriterInfo()->getCPUType());
492 FHOut.outword(TM.getMachOWriterInfo()->getCPUSubType());
Bill Wendling203d3e42007-01-17 22:22:31 +0000493 FHOut.outword(Header.filetype);
494 FHOut.outword(Header.ncmds);
495 FHOut.outword(Header.sizeofcmds);
496 FHOut.outword(Header.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000497 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000498 FHOut.outword(Header.reserved);
Nate Begemaneb883af2006-08-23 21:08:52 +0000499
500 // Step #4: Finish filling in the segment load command and write it out
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000501 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000502 E = SectionList.end(); I != E; ++I)
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000503 SEG.filesize += (*I)->size;
504
Nate Begemaneb883af2006-08-23 21:08:52 +0000505 SEG.vmsize = SEG.filesize;
506 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
507
Bill Wendling203d3e42007-01-17 22:22:31 +0000508 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);
Nate Begemaneb883af2006-08-23 21:08:52 +0000519
Nate Begeman94be2482006-09-08 22:42:09 +0000520 // Step #5: Finish filling in the fields of the MachOSections
521 uint64_t currentAddr = 0;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000522 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000523 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000524 MachOSection *MOS = *I;
525 MOS->addr = currentAddr;
526 MOS->offset = currentAddr + SEG.fileoff;
Nate Begeman019f8512006-09-10 23:03:44 +0000527
Nate Begeman94be2482006-09-08 22:42:09 +0000528 // FIXME: do we need to do something with alignment here?
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000529 currentAddr += MOS->size;
Nate Begeman94be2482006-09-08 22:42:09 +0000530 }
531
Nate Begemanfec910c2007-02-28 07:40:50 +0000532 // 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();
537
538 // Step #7: Calculate the number of relocations for each section and write out
Nate Begeman94be2482006-09-08 22:42:09 +0000539 // the section commands for each section
540 currentAddr += SEG.fileoff;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000541 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman94be2482006-09-08 22:42:09 +0000542 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000543 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;
Nate Begeman94be2482006-09-08 22:42:09 +0000549
550 // write the finalized section command to the output buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000551 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);
Nate Begemaneb883af2006-08-23 21:08:52 +0000562 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000563 FHOut.outword(MOS->reserved3);
Nate Begemaneb883af2006-08-23 21:08:52 +0000564 }
565
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000566 // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
Nate Begeman94be2482006-09-08 22:42:09 +0000567 SymTab.symoff = currentAddr;
Nate Begemaneb883af2006-08-23 21:08:52 +0000568 SymTab.nsyms = SymbolTable.size();
Nate Begemand2030e62006-08-26 15:46:34 +0000569 SymTab.stroff = SymTab.symoff + SymT.size();
570 SymTab.strsize = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000571 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);
Nate Begemaneb883af2006-08-23 21:08:52 +0000577
578 // FIXME: set DySymTab fields appropriately
Nate Begemand2030e62006-08-26 15:46:34 +0000579 // We should probably just update these in BufferSymbolAndStringTable since
580 // thats where we're partitioning up the different kinds of symbols.
Bill Wendling203d3e42007-01-17 22:22:31 +0000581 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);
Nate Begemaneb883af2006-08-23 21:08:52 +0000601
602 O.write((char*)&FH[0], FH.size());
603}
604
605/// EmitSections - Now that we have constructed the file header and load
606/// commands, emit the data for each section to the file.
607void MachOWriter::EmitSections() {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000608 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000609 E = SectionList.end(); I != E; ++I)
610 // Emit the contents of each section
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000611 O.write((char*)&(*I)->SectionData[0], (*I)->size);
612 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000613 E = SectionList.end(); I != E; ++I)
614 // Emit the relocation entry data for each section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000615 O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000616}
617
Nate Begemand2030e62006-08-26 15:46:34 +0000618/// PartitionByLocal - Simple boolean predicate that returns true if Sym is
619/// a local symbol rather than an external symbol.
620bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
Nate Begemand2030e62006-08-26 15:46:34 +0000621 return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
Nate Begemaneb883af2006-08-23 21:08:52 +0000622}
623
Nate Begemand2030e62006-08-26 15:46:34 +0000624/// PartitionByDefined - Simple boolean predicate that returns true if Sym is
625/// defined in this module.
626bool 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;
629}
Nate Begemaneb883af2006-08-23 21:08:52 +0000630
Nate Begemand2030e62006-08-26 15:46:34 +0000631/// 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
633/// output file.
634void MachOWriter::BufferSymbolAndStringTable() {
635 // The order of the symbol table is:
636 // 1. local symbols
637 // 2. defined external symbols (sorted by name)
638 // 3. undefined external symbols (sorted by name)
639
Nate Begemanfec910c2007-02-28 07:40:50 +0000640 // 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);
647 GVOffset[*I] = -1;
648 }
649 }
650
Nate Begemand2030e62006-08-26 15:46:34 +0000651 // 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());
654
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);
658
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);
666 break;
667 }
668 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000669
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
672 // load command.
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;
Nate Begeman6635f352007-01-26 22:39:48 +0000678 ++DySymTab.iundefsym;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000679 } else if (PartitionByDefined(*I)) {
680 ++DySymTab.nextdefsym;
681 ++DySymTab.iundefsym;
682 } else {
683 ++DySymTab.nundefsym;
684 }
685 }
Nate Begemand2030e62006-08-26 15:46:34 +0000686
Nate Begemaneb883af2006-08-23 21:08:52 +0000687 // Write out a leading zero byte when emitting string table, for n_strx == 0
688 // which means an empty string.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000689 OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000690 StrTOut.outbyte(0);
Nate Begemaneb883af2006-08-23 21:08:52 +0000691
Nate Begemand2030e62006-08-26 15:46:34 +0000692 // 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 == "") {
700 I->n_strx = 0;
701 } else {
702 I->n_strx = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000703 StrTOut.outstring(I->GVName, I->GVName.length()+1);
Nate Begemand2030e62006-08-26 15:46:34 +0000704 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000705 }
Nate Begemand2030e62006-08-26 15:46:34 +0000706
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000707 OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000708
Nate Begemanfec910c2007-02-28 07:40:50 +0000709 unsigned index = 0;
Nate Begemand2030e62006-08-26 15:46:34 +0000710 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
Nate Begemanfec910c2007-02-28 07:40:50 +0000711 E = SymbolTable.end(); I != E; ++I, ++index) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000712 // 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;
Nate Begemanfec910c2007-02-28 07:40:50 +0000718 if (GV && (GVOffset[GV] == -1))
719 GVOffset[GV] = index;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000720
Nate Begemand2030e62006-08-26 15:46:34 +0000721 // Emit nlist to buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000722 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);
Nate Begemand2030e62006-08-26 15:46:34 +0000727 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000728}
Nate Begeman94be2482006-09-08 22:42:09 +0000729
Nate Begeman019f8512006-09-10 23:03:44 +0000730/// 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.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000735void MachOWriter::CalculateRelocations(MachOSection &MOS) {
Nate Begeman019f8512006-09-10 23:03:44 +0000736 for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000737 MachineRelocation &MR = MOS.Relocations[i];
738 unsigned TargetSection = MR.getConstantVal();
Nate Begemanfec910c2007-02-28 07:40:50 +0000739 unsigned TargetAddr;
740 unsigned TargetIndex;
Nate Begeman6635f352007-01-26 22:39:48 +0000741
742 // This is a scattered relocation entry if it points to a global value with
743 // a non-zero offset.
744 bool Scattered = false;
Nate Begemanfec910c2007-02-28 07:40:50 +0000745 bool Extern = false;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000746
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];
Nate Begeman6635f352007-01-26 22:39:48 +0000753 intptr_t Offset = GVOffset[GV];
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000754
Nate Begemanfec910c2007-02-28 07:40:50 +0000755 // If we have never seen the global before, it must be to a symbol
756 // defined in another module (N_UNDF).
Nate Begeman1257c852007-01-29 21:20:42 +0000757 if (!MOSPtr) {
Nate Begemanfec910c2007-02-28 07:40:50 +0000758 // FIXME: need to append stub suffix
759 Extern = true;
760 TargetAddr = 0;
761 TargetIndex = GVOffset[GV];
762 } else {
763 Scattered = TargetSection != 0;
764 TargetSection = MOSPtr->Index;
765 MachOSection &To = *SectionList[TargetSection - 1];
766 TargetAddr = To.addr;
767 TargetIndex = To.Index;
Nate Begeman1257c852007-01-29 21:20:42 +0000768 }
Nate Begeman6635f352007-01-26 22:39:48 +0000769 MR.setResultPointer((void*)Offset);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000770 }
Bill Wendling886b4122007-02-03 02:39:40 +0000771
772 OutputBuffer RelocOut(MOS.RelocBuffer, is64Bit, isLittleEndian);
773 OutputBuffer SecOut(MOS.SectionData, is64Bit, isLittleEndian);
Nate Begemanfec910c2007-02-28 07:40:50 +0000774
775 MOS.nreloc += GetTargetRelocation(MR, MOS.Index, TargetAddr, TargetIndex,
776 RelocOut, SecOut, Scattered, Extern);
Nate Begeman019f8512006-09-10 23:03:44 +0000777 }
Nate Begeman019f8512006-09-10 23:03:44 +0000778}
779
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000780// InitMem - Write the value of a Constant to the specified memory location,
781// converting it into bytes and relocations.
782void 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;
787
788 WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
789
Nate Begeman6635f352007-01-26 22:39:48 +0000790 intptr_t ScatteredOffset = 0;
791
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000792 while (!WorkList.empty()) {
793 const Constant *PC = WorkList.back().first;
794 intptr_t PA = WorkList.back().second;
795 WorkList.pop_back();
796
797 if (isa<UndefValue>(PC)) {
798 continue;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000799 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(PC)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000800 unsigned ElementSize = TD->getTypeSize(CP->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000801 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)) {
804 //
805 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
806 //
807 switch (CE->getOpcode()) {
Nate Begeman6635f352007-01-26 22:39:48 +0000808 case Instruction::GetElementPtr: {
Chris Lattner7f6b9d22007-02-10 20:31:59 +0000809 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Nate Begeman6635f352007-01-26 22:39:48 +0000810 ScatteredOffset = TD->getIndexedOffset(CE->getOperand(0)->getType(),
Chris Lattner7f6b9d22007-02-10 20:31:59 +0000811 &Indices[0], Indices.size());
Nate Begeman6635f352007-01-26 22:39:48 +0000812 WorkList.push_back(CPair(CE->getOperand(0), PA));
813 break;
814 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000815 case Instruction::Add:
816 default:
817 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
818 abort();
819 break;
820 }
821 } else if (PC->getType()->isFirstClassType()) {
822 unsigned char *ptr = (unsigned char *)PA;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000823 switch (PC->getType()->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000824 case Type::IntegerTyID: {
825 unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
826 uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
827 if (NumBits <= 8)
828 ptr[0] = val;
829 else if (NumBits <= 16) {
830 if (TD->isBigEndian())
831 val = ByteSwap_16(val);
832 ptr[0] = val;
833 ptr[1] = val >> 8;
834 } else if (NumBits <= 32) {
835 if (TD->isBigEndian())
836 val = ByteSwap_32(val);
837 ptr[0] = val;
838 ptr[1] = val >> 8;
839 ptr[2] = val >> 16;
840 ptr[3] = val >> 24;
841 } else if (NumBits <= 64) {
842 if (TD->isBigEndian())
843 val = ByteSwap_64(val);
844 ptr[0] = val;
845 ptr[1] = val >> 8;
846 ptr[2] = val >> 16;
847 ptr[3] = val >> 24;
848 ptr[4] = val >> 32;
849 ptr[5] = val >> 40;
850 ptr[6] = val >> 48;
851 ptr[7] = val >> 56;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000852 } else {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000853 assert(0 && "Not implemented: bit widths > 64");
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000854 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000855 break;
856 }
857 case Type::FloatTyID: {
858 uint64_t val = FloatToBits(cast<ConstantFP>(PC)->getValue());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000859 if (TD->isBigEndian())
860 val = ByteSwap_32(val);
861 ptr[0] = val;
862 ptr[1] = val >> 8;
863 ptr[2] = val >> 16;
864 ptr[3] = val >> 24;
865 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000866 }
867 case Type::DoubleTyID: {
868 uint64_t val = DoubleToBits(cast<ConstantFP>(PC)->getValue());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000869 if (TD->isBigEndian())
870 val = ByteSwap_64(val);
871 ptr[0] = val;
872 ptr[1] = val >> 8;
873 ptr[2] = val >> 16;
874 ptr[3] = val >> 24;
875 ptr[4] = val >> 32;
876 ptr[5] = val >> 40;
877 ptr[6] = val >> 48;
878 ptr[7] = val >> 56;
879 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000880 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000881 case Type::PointerTyID:
Nate Begeman6635f352007-01-26 22:39:48 +0000882 if (isa<ConstantPointerNull>(PC))
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000883 memset(ptr, 0, TD->getPointerSize());
Nate Begeman6635f352007-01-26 22:39:48 +0000884 else if (const GlobalValue* GV = dyn_cast<GlobalValue>(PC)) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000885 // FIXME: what about function stubs?
886 MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr,
887 MachineRelocation::VANILLA,
Nate Begeman6635f352007-01-26 22:39:48 +0000888 const_cast<GlobalValue*>(GV),
889 ScatteredOffset));
890 ScatteredOffset = 0;
891 } else
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000892 assert(0 && "Unknown constant pointer type!");
893 break;
894 default:
895 cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
896 abort();
897 }
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)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000901 unsigned ElementSize = TD->getTypeSize(CPA->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000902 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)
Chris Lattnerb1919e22007-02-10 19:55:17 +0000908 WorkList.push_back(CPair(CPS->getOperand(i),
909 PA+SL->getElementOffset(i)));
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000910 } else {
911 cerr << "Bad Type: " << *PC->getType() << "\n";
912 assert(0 && "Unknown constant type to initialize memory with!");
913 }
914 }
915}
916
917MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
918 TargetMachine &TM) :
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) {
921
922 const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
923
Nate Begeman94be2482006-09-08 22:42:09 +0000924 switch (GV->getLinkage()) {
925 default:
926 assert(0 && "Unexpected linkage type!");
927 break;
928 case GlobalValue::WeakLinkage:
929 case GlobalValue::LinkOnceLinkage:
930 assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
931 case GlobalValue::ExternalLinkage:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000932 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman6635f352007-01-26 22:39:48 +0000933 n_type |= GV->hasHiddenVisibility() ? N_PEXT : N_EXT;
Nate Begeman94be2482006-09-08 22:42:09 +0000934 break;
935 case GlobalValue::InternalLinkage:
Nate Begeman6635f352007-01-26 22:39:48 +0000936 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman94be2482006-09-08 22:42:09 +0000937 break;
938 }
939}