blob: e6cfedab57f173ec899e84b51702cbcc49beee91 [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
Nate Begemanbfaaaa62006-12-11 02:20:45 +000025#include "llvm/Constants.h"
26#include "llvm/DerivedTypes.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000027#include "llvm/Module.h"
28#include "llvm/CodeGen/MachineCodeEmitter.h"
29#include "llvm/CodeGen/MachineConstantPool.h"
Nate Begeman019f8512006-09-10 23:03:44 +000030#include "llvm/CodeGen/MachineJumpTableInfo.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000031#include "llvm/CodeGen/MachOWriter.h"
Nate Begeman94be2482006-09-08 22:42:09 +000032#include "llvm/ExecutionEngine/ExecutionEngine.h"
Nate Begemanbfaaaa62006-12-11 02:20:45 +000033#include "llvm/Target/TargetAsmInfo.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000034#include "llvm/Target/TargetJITInfo.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000035#include "llvm/Support/Mangler.h"
Nate Begemanf8f2c5a2006-08-25 06:36:58 +000036#include "llvm/Support/MathExtras.h"
Bill Wendling203d3e42007-01-17 22:22:31 +000037#include "llvm/Support/OutputBuffer.h"
Nate Begemanbfaaaa62006-12-11 02:20:45 +000038#include "llvm/Support/Streams.h"
Nate Begemand2030e62006-08-26 15:46:34 +000039#include <algorithm>
Bill Wendlinge9116152007-01-17 09:06:13 +000040
Nate Begemaneb883af2006-08-23 21:08:52 +000041using namespace llvm;
42
43//===----------------------------------------------------------------------===//
44// MachOCodeEmitter Implementation
45//===----------------------------------------------------------------------===//
46
47namespace llvm {
48 /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code
49 /// for functions to the Mach-O file.
50 class MachOCodeEmitter : public MachineCodeEmitter {
51 MachOWriter &MOW;
Nate Begemaneb883af2006-08-23 21:08:52 +000052
Bill Wendling203d3e42007-01-17 22:22:31 +000053 /// Target machine description.
54 TargetMachine &TM;
55
Bill Wendlingc904a5b2007-01-18 01:23:11 +000056 /// is64Bit/isLittleEndian - This information is inferred from the target
57 /// machine directly, indicating what header values and flags to set.
58 bool is64Bit, isLittleEndian;
59
Nate Begemaneb883af2006-08-23 21:08:52 +000060 /// Relocations - These are the relocations that the function needs, as
61 /// emitted.
62 std::vector<MachineRelocation> Relocations;
Nate Begeman019f8512006-09-10 23:03:44 +000063
64 /// CPLocations - This is a map of constant pool indices to offsets from the
65 /// start of the section for that constant pool index.
66 std::vector<intptr_t> CPLocations;
67
Nate Begemanbfaaaa62006-12-11 02:20:45 +000068 /// CPSections - This is a map of constant pool indices to the MachOSection
69 /// containing the constant pool entry for that index.
70 std::vector<unsigned> CPSections;
71
Nate Begeman019f8512006-09-10 23:03:44 +000072 /// JTLocations - This is a map of jump table indices to offsets from the
73 /// start of the section for that jump table index.
74 std::vector<intptr_t> JTLocations;
Nate Begemaneb883af2006-08-23 21:08:52 +000075
76 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
77 /// It is filled in by the StartMachineBasicBlock callback and queried by
78 /// the getMachineBasicBlockAddress callback.
79 std::vector<intptr_t> MBBLocations;
80
81 public:
Bill Wendlingc904a5b2007-01-18 01:23:11 +000082 MachOCodeEmitter(MachOWriter &mow) : MOW(mow), TM(MOW.TM) {
83 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
84 isLittleEndian = TM.getTargetData()->isLittleEndian();
85 }
Nate Begemaneb883af2006-08-23 21:08:52 +000086
Nate Begemanc2b2d6a2007-02-07 05:47:16 +000087 virtual void startFunction(MachineFunction &MF);
88 virtual bool finishFunction(MachineFunction &MF);
Nate Begemaneb883af2006-08-23 21:08:52 +000089
Nate Begemanbfaaaa62006-12-11 02:20:45 +000090 virtual void addRelocation(const MachineRelocation &MR) {
Nate Begemaneb883af2006-08-23 21:08:52 +000091 Relocations.push_back(MR);
92 }
93
Nate Begeman019f8512006-09-10 23:03:44 +000094 void emitConstantPool(MachineConstantPool *MCP);
95 void emitJumpTables(MachineJumpTableInfo *MJTI);
96
Nate Begemaneb883af2006-08-23 21:08:52 +000097 virtual intptr_t getConstantPoolEntryAddress(unsigned Index) const {
Nate Begemanbfaaaa62006-12-11 02:20:45 +000098 assert(CPLocations.size() > Index && "CP not emitted!");
99 return CPLocations[Index];
Nate Begemaneb883af2006-08-23 21:08:52 +0000100 }
101 virtual intptr_t getJumpTableEntryAddress(unsigned Index) const {
Nate Begeman019f8512006-09-10 23:03:44 +0000102 assert(JTLocations.size() > Index && "JT not emitted!");
103 return JTLocations[Index];
104 }
105
106 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
107 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
108 MBBLocations.resize((MBB->getNumber()+1)*2);
109 MBBLocations[MBB->getNumber()] = getCurrentPCOffset();
Nate Begemaneb883af2006-08-23 21:08:52 +0000110 }
111
112 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
113 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
114 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
115 return MBBLocations[MBB->getNumber()];
116 }
117
118 /// JIT SPECIFIC FUNCTIONS - DO NOT IMPLEMENT THESE HERE!
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000119 virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000120 assert(0 && "JIT specific function called!");
121 abort();
122 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000123 virtual void *finishFunctionStub(const Function *F) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000124 assert(0 && "JIT specific function called!");
125 abort();
126 return 0;
127 }
128 };
129}
130
131/// startFunction - This callback is invoked when a new machine function is
132/// about to be emitted.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000133void MachOCodeEmitter::startFunction(MachineFunction &MF) {
134 const TargetData *TD = TM.getTargetData();
135 const Function *F = MF.getFunction();
136
Nate Begemaneb883af2006-08-23 21:08:52 +0000137 // Align the output buffer to the appropriate alignment, power of 2.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000138 unsigned FnAlign = F->getAlignment();
139 unsigned TDAlign = TD->getTypeAlignmentPref(F->getType());
140 unsigned Align = Log2_32(std::max(FnAlign, TDAlign));
141 assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
Nate Begemaneb883af2006-08-23 21:08:52 +0000142
143 // Get the Mach-O Section that this function belongs in.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000144 MachOWriter::MachOSection *MOS = MOW.getTextSection();
Nate Begemaneb883af2006-08-23 21:08:52 +0000145
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000146 // FIXME: better memory management
Nate Begemaneb883af2006-08-23 21:08:52 +0000147 MOS->SectionData.reserve(4096);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000148 BufferBegin = &MOS->SectionData[0];
Nate Begemaneb883af2006-08-23 21:08:52 +0000149 BufferEnd = BufferBegin + MOS->SectionData.capacity();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000150
Nate Begeman6635f352007-01-26 22:39:48 +0000151 // Upgrade the section alignment if required.
152 if (MOS->align < Align) MOS->align = Align;
153
154 // Round the size up to the correct alignment for starting the new function.
155 if ((MOS->size & ((1 << Align) - 1)) != 0) {
156 MOS->size += (1 << Align);
157 MOS->size &= ~((1 << Align) - 1);
158 }
159
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000160 // FIXME: Using MOS->size directly here instead of calculating it from the
161 // output buffer size (impossible because the code emitter deals only in raw
162 // bytes) forces us to manually synchronize size and write padding zero bytes
163 // to the output buffer for all non-text sections. For text sections, we do
164 // not synchonize the output buffer, and we just blow up if anyone tries to
165 // write non-code to it. An assert should probably be added to
166 // AddSymbolToSection to prevent calling it on the text section.
Nate Begemaneb883af2006-08-23 21:08:52 +0000167 CurBufferPtr = BufferBegin + MOS->size;
168
Nate Begeman019f8512006-09-10 23:03:44 +0000169 // Clear per-function data structures.
170 CPLocations.clear();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000171 CPSections.clear();
Nate Begeman019f8512006-09-10 23:03:44 +0000172 JTLocations.clear();
Nate Begemaneb883af2006-08-23 21:08:52 +0000173 MBBLocations.clear();
174}
175
176/// finishFunction - This callback is invoked after the function is completely
177/// finished.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000178bool MachOCodeEmitter::finishFunction(MachineFunction &MF) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000179 // Get the Mach-O Section that this function belongs in.
180 MachOWriter::MachOSection *MOS = MOW.getTextSection();
181
Nate Begemaneb883af2006-08-23 21:08:52 +0000182 // Get a symbol for the function to add to the symbol table
Nate Begeman6635f352007-01-26 22:39:48 +0000183 // FIXME: it seems like we should call something like AddSymbolToSection
184 // in startFunction rather than changing the section size and symbol n_value
185 // here.
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000186 const GlobalValue *FuncV = MF.getFunction();
Bill Wendling203d3e42007-01-17 22:22:31 +0000187 MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, TM);
Nate Begeman6635f352007-01-26 22:39:48 +0000188 FnSym.n_value = MOS->size;
189 MOS->size = CurBufferPtr - BufferBegin;
190
Nate Begeman019f8512006-09-10 23:03:44 +0000191 // Emit constant pool to appropriate section(s)
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000192 emitConstantPool(MF.getConstantPool());
Nate Begeman019f8512006-09-10 23:03:44 +0000193
194 // Emit jump tables to appropriate section
Nate Begemanc2b2d6a2007-02-07 05:47:16 +0000195 emitJumpTables(MF.getJumpTableInfo());
Nate Begemaneb883af2006-08-23 21:08:52 +0000196
Nate Begeman019f8512006-09-10 23:03:44 +0000197 // If we have emitted any relocations to function-specific objects such as
198 // basic blocks, constant pools entries, or jump tables, record their
199 // addresses now so that we can rewrite them with the correct addresses
200 // later.
Nate Begemaneb883af2006-08-23 21:08:52 +0000201 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
202 MachineRelocation &MR = Relocations[i];
Nate Begeman019f8512006-09-10 23:03:44 +0000203 intptr_t Addr;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000204
Nate Begemaneb883af2006-08-23 21:08:52 +0000205 if (MR.isBasicBlock()) {
Nate Begeman019f8512006-09-10 23:03:44 +0000206 Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000207 MR.setConstantVal(MOS->Index);
208 MR.setResultPointer((void*)Addr);
209 } else if (MR.isJumpTableIndex()) {
210 Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
211 MR.setConstantVal(MOW.getJumpTableSection()->Index);
212 MR.setResultPointer((void*)Addr);
Nate Begeman019f8512006-09-10 23:03:44 +0000213 } else if (MR.isConstantPoolIndex()) {
214 Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000215 MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
216 MR.setResultPointer((void*)Addr);
217 } else if (!MR.isGlobalValue()) {
218 assert(0 && "Unhandled relocation type");
Nate Begemaneb883af2006-08-23 21:08:52 +0000219 }
Nate Begeman019f8512006-09-10 23:03:44 +0000220 MOS->Relocations.push_back(MR);
Nate Begemaneb883af2006-08-23 21:08:52 +0000221 }
222 Relocations.clear();
223
224 // Finally, add it to the symtab.
225 MOW.SymbolTable.push_back(FnSym);
226 return false;
227}
228
Nate Begeman019f8512006-09-10 23:03:44 +0000229/// emitConstantPool - For each constant pool entry, figure out which section
230/// the constant should live in, allocate space for it, and emit it to the
231/// Section data buffer.
232void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000233 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
234 if (CP.empty()) return;
235
236 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000237 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000238 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
239
240 // Although there is no strict necessity that I am aware of, we will do what
241 // gcc for OS X does and put each constant pool entry in a section of constant
242 // objects of a certain size. That means that float constants go in the
243 // literal4 section, and double objects go in literal8, etc.
244 //
245 // FIXME: revisit this decision if we ever do the "stick everything into one
246 // "giant object for PIC" optimization.
247 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
248 const Type *Ty = CP[i].getType();
Bill Wendling203d3e42007-01-17 22:22:31 +0000249 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000250
Nate Begeman1257c852007-01-29 21:20:42 +0000251 MachOWriter::MachOSection *Sec = MOW.getConstSection(CP[i].Val.ConstVal);
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000252 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000253
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000254 CPLocations.push_back(Sec->SectionData.size());
255 CPSections.push_back(Sec->Index);
256
257 // FIXME: remove when we have unified size + output buffer
258 Sec->size += Size;
259
260 // Allocate space in the section for the global.
261 // FIXME: need alignment?
262 // FIXME: share between here and AddSymbolToSection?
263 for (unsigned j = 0; j < Size; ++j)
Bill Wendling203d3e42007-01-17 22:22:31 +0000264 SecDataOut.outbyte(0);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000265
266 MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
Bill Wendling203d3e42007-01-17 22:22:31 +0000267 TM.getTargetData(), Sec->Relocations);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000268 }
Nate Begeman019f8512006-09-10 23:03:44 +0000269}
270
271/// emitJumpTables - Emit all the jump tables for a given jump table info
272/// record to the appropriate section.
273void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
274 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
275 if (JT.empty()) return;
276
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000277 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000278 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begeman019f8512006-09-10 23:03:44 +0000279 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
280
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000281 MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
282 unsigned TextSecIndex = MOW.getTextSection()->Index;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000283 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Nate Begeman019f8512006-09-10 23:03:44 +0000284
285 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
286 // For each jump table, record its offset from the start of the section,
287 // reserve space for the relocations to the MBBs, and add the relocations.
288 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000289 JTLocations.push_back(Sec->SectionData.size());
Nate Begeman019f8512006-09-10 23:03:44 +0000290 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000291 MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
Nate Begeman019f8512006-09-10 23:03:44 +0000292 MBBs[mi]));
293 MR.setResultPointer((void *)JTLocations[i]);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000294 MR.setConstantVal(TextSecIndex);
295 Sec->Relocations.push_back(MR);
Bill Wendling203d3e42007-01-17 22:22:31 +0000296 SecDataOut.outaddr(0);
Nate Begeman019f8512006-09-10 23:03:44 +0000297 }
298 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000299 // FIXME: remove when we have unified size + output buffer
300 Sec->size = Sec->SectionData.size();
Nate Begeman019f8512006-09-10 23:03:44 +0000301}
302
Nate Begemaneb883af2006-08-23 21:08:52 +0000303//===----------------------------------------------------------------------===//
304// MachOWriter Implementation
305//===----------------------------------------------------------------------===//
306
307MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000308 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
309 isLittleEndian = TM.getTargetData()->isLittleEndian();
310
311 // Create the machine code emitter object for this target.
Bill Wendlinge9116152007-01-17 09:06:13 +0000312 MCE = new MachOCodeEmitter(*this);
Nate Begemaneb883af2006-08-23 21:08:52 +0000313}
314
315MachOWriter::~MachOWriter() {
316 delete MCE;
317}
318
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000319void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000320 const Type *Ty = GV->getType()->getElementType();
321 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000322 unsigned Align = GV->getAlignment();
323 if (Align == 0)
Chris Lattner58092e32007-01-20 22:35:55 +0000324 Align = TM.getTargetData()->getTypeAlignmentPref(Ty);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000325
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000326 MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
327
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000328 // Reserve space in the .bss section for this symbol while maintaining the
329 // desired section alignment, which must be at least as much as required by
330 // this symbol.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000331 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000332
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000333 if (Align) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000334 uint64_t OrigSize = Sec->size;
335 Align = Log2_32(Align);
336 Sec->align = std::max(unsigned(Sec->align), Align);
337 Sec->size = (Sec->size + Align - 1) & ~(Align-1);
338
339 // Add alignment padding to buffer as well.
340 // FIXME: remove when we have unified size + output buffer
341 unsigned AlignedSize = Sec->size - OrigSize;
342 for (unsigned i = 0; i < AlignedSize; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000343 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000344 }
345 // Record the offset of the symbol, and then allocate space for it.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000346 // FIXME: remove when we have unified size + output buffer
347 Sym.n_value = Sec->size;
348 Sec->size += Size;
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000349 SymbolTable.push_back(Sym);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000350
351 // Now that we know what section the GlovalVariable is going to be emitted
352 // into, update our mappings.
353 // FIXME: We may also need to update this when outputting non-GlobalVariable
354 // GlobalValues such as functions.
355 GVSection[GV] = Sec;
356 GVOffset[GV] = Sec->SectionData.size();
357
358 // Allocate space in the section for the global.
359 for (unsigned i = 0; i < Size; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000360 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000361}
362
Nate Begemaneb883af2006-08-23 21:08:52 +0000363void MachOWriter::EmitGlobal(GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000364 const Type *Ty = GV->getType()->getElementType();
365 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
366 bool NoInit = !GV->hasInitializer();
Nate Begemand2030e62006-08-26 15:46:34 +0000367
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000368 // If this global has a zero initializer, it is part of the .bss or common
369 // section.
370 if (NoInit || GV->getInitializer()->isNullValue()) {
371 // If this global is part of the common block, add it now. Variables are
372 // part of the common block if they are zero initialized and allowed to be
373 // merged with other symbols.
374 if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000375 MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000376 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
377 // bytes of the symbol.
378 ExtOrCommonSym.n_value = Size;
379 // If the symbol is external, we'll put it on a list of symbols whose
380 // addition to the symbol table is being pended until we find a reference
381 if (NoInit)
382 PendingSyms.push_back(ExtOrCommonSym);
383 else
384 SymbolTable.push_back(ExtOrCommonSym);
385 return;
386 }
387 // Otherwise, this symbol is part of the .bss section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000388 MachOSection *BSS = getBSSSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000389 AddSymbolToSection(BSS, GV);
390 return;
391 }
392
393 // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
394 // 16 bytes, or a cstring. Other read only data goes into a regular const
395 // section. Read-write data goes in the data section.
Nate Begeman1257c852007-01-29 21:20:42 +0000396 MachOSection *Sec = GV->isConstant() ? getConstSection(GV->getInitializer()) :
397 getDataSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000398 AddSymbolToSection(Sec, GV);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000399 InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
400 TM.getTargetData(), Sec->Relocations);
Nate Begemaneb883af2006-08-23 21:08:52 +0000401}
402
403
404bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
405 // Nothing to do here, this is all done through the MCE object.
406 return false;
407}
408
409bool MachOWriter::doInitialization(Module &M) {
410 // Set the magic value, now that we know the pointer size and endianness
411 Header.setMagic(isLittleEndian, is64Bit);
412
413 // Set the file type
414 // FIXME: this only works for object files, we do not support the creation
415 // of dynamic libraries or executables at this time.
416 Header.filetype = MachOHeader::MH_OBJECT;
417
418 Mang = new Mangler(M);
419 return false;
420}
421
422/// doFinalization - Now that the module has been completely processed, emit
423/// the Mach-O file to 'O'.
424bool MachOWriter::doFinalization(Module &M) {
Nate Begemand2030e62006-08-26 15:46:34 +0000425 // FIXME: we don't handle debug info yet, we should probably do that.
426
Nate Begemaneb883af2006-08-23 21:08:52 +0000427 // Okay, the.text section has been completed, build the .data, .bss, and
428 // "common" sections next.
429 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
430 I != E; ++I)
431 EmitGlobal(I);
432
433 // Emit the header and load commands.
434 EmitHeaderAndLoadCommands();
435
Nate Begeman019f8512006-09-10 23:03:44 +0000436 // Emit the various sections and their relocation info.
Nate Begemaneb883af2006-08-23 21:08:52 +0000437 EmitSections();
438
Nate Begemand2030e62006-08-26 15:46:34 +0000439 // Write the symbol table and the string table to the end of the file.
440 O.write((char*)&SymT[0], SymT.size());
441 O.write((char*)&StrT[0], StrT.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000442
443 // We are done with the abstract symbols.
444 SectionList.clear();
445 SymbolTable.clear();
446 DynamicSymbolTable.clear();
447
448 // Release the name mangler object.
449 delete Mang; Mang = 0;
450 return false;
451}
452
453void MachOWriter::EmitHeaderAndLoadCommands() {
454 // Step #0: Fill in the segment load command size, since we need it to figure
455 // out the rest of the header fields
456 MachOSegment SEG("", is64Bit);
457 SEG.nsects = SectionList.size();
458 SEG.cmdsize = SEG.cmdSize(is64Bit) +
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000459 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
Nate Begemaneb883af2006-08-23 21:08:52 +0000460
461 // Step #1: calculate the number of load commands. We always have at least
462 // one, for the LC_SEGMENT load command, plus two for the normal
463 // and dynamic symbol tables, if there are any symbols.
464 Header.ncmds = SymbolTable.empty() ? 1 : 3;
465
466 // Step #2: calculate the size of the load commands
467 Header.sizeofcmds = SEG.cmdsize;
468 if (!SymbolTable.empty())
469 Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
470
471 // Step #3: write the header to the file
472 // Local alias to shortenify coming code.
473 DataBuffer &FH = Header.HeaderData;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000474 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000475
476 FHOut.outword(Header.magic);
Bill Wendling2b721822007-01-24 07:13:56 +0000477 FHOut.outword(TM.getMachOWriterInfo()->getCPUType());
478 FHOut.outword(TM.getMachOWriterInfo()->getCPUSubType());
Bill Wendling203d3e42007-01-17 22:22:31 +0000479 FHOut.outword(Header.filetype);
480 FHOut.outword(Header.ncmds);
481 FHOut.outword(Header.sizeofcmds);
482 FHOut.outword(Header.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000483 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000484 FHOut.outword(Header.reserved);
Nate Begemaneb883af2006-08-23 21:08:52 +0000485
486 // Step #4: Finish filling in the segment load command and write it out
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000487 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000488 E = SectionList.end(); I != E; ++I)
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000489 SEG.filesize += (*I)->size;
490
Nate Begemaneb883af2006-08-23 21:08:52 +0000491 SEG.vmsize = SEG.filesize;
492 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
493
Bill Wendling203d3e42007-01-17 22:22:31 +0000494 FHOut.outword(SEG.cmd);
495 FHOut.outword(SEG.cmdsize);
496 FHOut.outstring(SEG.segname, 16);
497 FHOut.outaddr(SEG.vmaddr);
498 FHOut.outaddr(SEG.vmsize);
499 FHOut.outaddr(SEG.fileoff);
500 FHOut.outaddr(SEG.filesize);
501 FHOut.outword(SEG.maxprot);
502 FHOut.outword(SEG.initprot);
503 FHOut.outword(SEG.nsects);
504 FHOut.outword(SEG.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000505
Nate Begeman94be2482006-09-08 22:42:09 +0000506 // Step #5: Finish filling in the fields of the MachOSections
507 uint64_t currentAddr = 0;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000508 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000509 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000510 MachOSection *MOS = *I;
511 MOS->addr = currentAddr;
512 MOS->offset = currentAddr + SEG.fileoff;
Nate Begeman019f8512006-09-10 23:03:44 +0000513
Nate Begeman94be2482006-09-08 22:42:09 +0000514 // FIXME: do we need to do something with alignment here?
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000515 currentAddr += MOS->size;
Nate Begeman94be2482006-09-08 22:42:09 +0000516 }
517
518 // Step #6: Calculate the number of relocations for each section and write out
519 // the section commands for each section
520 currentAddr += SEG.fileoff;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000521 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman94be2482006-09-08 22:42:09 +0000522 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000523 MachOSection *MOS = *I;
524 // Convert the relocations to target-specific relocations, and fill in the
525 // relocation offset for this section.
526 CalculateRelocations(*MOS);
527 MOS->reloff = MOS->nreloc ? currentAddr : 0;
528 currentAddr += MOS->nreloc * 8;
Nate Begeman94be2482006-09-08 22:42:09 +0000529
530 // write the finalized section command to the output buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000531 FHOut.outstring(MOS->sectname, 16);
532 FHOut.outstring(MOS->segname, 16);
533 FHOut.outaddr(MOS->addr);
534 FHOut.outaddr(MOS->size);
535 FHOut.outword(MOS->offset);
536 FHOut.outword(MOS->align);
537 FHOut.outword(MOS->reloff);
538 FHOut.outword(MOS->nreloc);
539 FHOut.outword(MOS->flags);
540 FHOut.outword(MOS->reserved1);
541 FHOut.outword(MOS->reserved2);
Nate Begemaneb883af2006-08-23 21:08:52 +0000542 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000543 FHOut.outword(MOS->reserved3);
Nate Begemaneb883af2006-08-23 21:08:52 +0000544 }
545
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000546 // Step #7: Emit the symbol table to temporary buffers, so that we know the
547 // size of the string table when we write the next load command.
548 BufferSymbolAndStringTable();
549
550 // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
Nate Begeman94be2482006-09-08 22:42:09 +0000551 SymTab.symoff = currentAddr;
Nate Begemaneb883af2006-08-23 21:08:52 +0000552 SymTab.nsyms = SymbolTable.size();
Nate Begemand2030e62006-08-26 15:46:34 +0000553 SymTab.stroff = SymTab.symoff + SymT.size();
554 SymTab.strsize = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000555 FHOut.outword(SymTab.cmd);
556 FHOut.outword(SymTab.cmdsize);
557 FHOut.outword(SymTab.symoff);
558 FHOut.outword(SymTab.nsyms);
559 FHOut.outword(SymTab.stroff);
560 FHOut.outword(SymTab.strsize);
Nate Begemaneb883af2006-08-23 21:08:52 +0000561
562 // FIXME: set DySymTab fields appropriately
Nate Begemand2030e62006-08-26 15:46:34 +0000563 // We should probably just update these in BufferSymbolAndStringTable since
564 // thats where we're partitioning up the different kinds of symbols.
Bill Wendling203d3e42007-01-17 22:22:31 +0000565 FHOut.outword(DySymTab.cmd);
566 FHOut.outword(DySymTab.cmdsize);
567 FHOut.outword(DySymTab.ilocalsym);
568 FHOut.outword(DySymTab.nlocalsym);
569 FHOut.outword(DySymTab.iextdefsym);
570 FHOut.outword(DySymTab.nextdefsym);
571 FHOut.outword(DySymTab.iundefsym);
572 FHOut.outword(DySymTab.nundefsym);
573 FHOut.outword(DySymTab.tocoff);
574 FHOut.outword(DySymTab.ntoc);
575 FHOut.outword(DySymTab.modtaboff);
576 FHOut.outword(DySymTab.nmodtab);
577 FHOut.outword(DySymTab.extrefsymoff);
578 FHOut.outword(DySymTab.nextrefsyms);
579 FHOut.outword(DySymTab.indirectsymoff);
580 FHOut.outword(DySymTab.nindirectsyms);
581 FHOut.outword(DySymTab.extreloff);
582 FHOut.outword(DySymTab.nextrel);
583 FHOut.outword(DySymTab.locreloff);
584 FHOut.outword(DySymTab.nlocrel);
Nate Begemaneb883af2006-08-23 21:08:52 +0000585
586 O.write((char*)&FH[0], FH.size());
587}
588
589/// EmitSections - Now that we have constructed the file header and load
590/// commands, emit the data for each section to the file.
591void MachOWriter::EmitSections() {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000592 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000593 E = SectionList.end(); I != E; ++I)
594 // Emit the contents of each section
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000595 O.write((char*)&(*I)->SectionData[0], (*I)->size);
596 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000597 E = SectionList.end(); I != E; ++I)
598 // Emit the relocation entry data for each section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000599 O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000600}
601
Nate Begemand2030e62006-08-26 15:46:34 +0000602/// PartitionByLocal - Simple boolean predicate that returns true if Sym is
603/// a local symbol rather than an external symbol.
604bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
Nate Begemand2030e62006-08-26 15:46:34 +0000605 return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
Nate Begemaneb883af2006-08-23 21:08:52 +0000606}
607
Nate Begemand2030e62006-08-26 15:46:34 +0000608/// PartitionByDefined - Simple boolean predicate that returns true if Sym is
609/// defined in this module.
610bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
611 // FIXME: Do N_ABS or N_INDR count as defined?
612 return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
613}
Nate Begemaneb883af2006-08-23 21:08:52 +0000614
Nate Begemand2030e62006-08-26 15:46:34 +0000615/// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
616/// each a string table index so that they appear in the correct order in the
617/// output file.
618void MachOWriter::BufferSymbolAndStringTable() {
619 // The order of the symbol table is:
620 // 1. local symbols
621 // 2. defined external symbols (sorted by name)
622 // 3. undefined external symbols (sorted by name)
623
624 // Sort the symbols by name, so that when we partition the symbols by scope
625 // of definition, we won't have to sort by name within each partition.
626 std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
627
628 // Parition the symbol table entries so that all local symbols come before
629 // all symbols with external linkage. { 1 | 2 3 }
630 std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
631
632 // Advance iterator to beginning of external symbols and partition so that
633 // all external symbols defined in this module come before all external
634 // symbols defined elsewhere. { 1 | 2 | 3 }
635 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
636 E = SymbolTable.end(); I != E; ++I) {
637 if (!PartitionByLocal(*I)) {
638 std::partition(I, E, PartitionByDefined);
639 break;
640 }
641 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000642
643 // Calculate the starting index for each of the local, extern defined, and
644 // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
645 // load command.
646 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
647 E = SymbolTable.end(); I != E; ++I) {
648 if (PartitionByLocal(*I)) {
649 ++DySymTab.nlocalsym;
650 ++DySymTab.iextdefsym;
Nate Begeman6635f352007-01-26 22:39:48 +0000651 ++DySymTab.iundefsym;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000652 } else if (PartitionByDefined(*I)) {
653 ++DySymTab.nextdefsym;
654 ++DySymTab.iundefsym;
655 } else {
656 ++DySymTab.nundefsym;
657 }
658 }
Nate Begemand2030e62006-08-26 15:46:34 +0000659
Nate Begemaneb883af2006-08-23 21:08:52 +0000660 // Write out a leading zero byte when emitting string table, for n_strx == 0
661 // which means an empty string.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000662 OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000663 StrTOut.outbyte(0);
Nate Begemaneb883af2006-08-23 21:08:52 +0000664
Nate Begemand2030e62006-08-26 15:46:34 +0000665 // The order of the string table is:
666 // 1. strings for external symbols
667 // 2. strings for local symbols
668 // Since this is the opposite order from the symbol table, which we have just
669 // sorted, we can walk the symbol table backwards to output the string table.
670 for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
671 E = SymbolTable.rend(); I != E; ++I) {
672 if (I->GVName == "") {
673 I->n_strx = 0;
674 } else {
675 I->n_strx = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000676 StrTOut.outstring(I->GVName, I->GVName.length()+1);
Nate Begemand2030e62006-08-26 15:46:34 +0000677 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000678 }
Nate Begemand2030e62006-08-26 15:46:34 +0000679
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000680 OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000681
Nate Begemand2030e62006-08-26 15:46:34 +0000682 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
683 E = SymbolTable.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000684 // Add the section base address to the section offset in the n_value field
685 // to calculate the full address.
686 // FIXME: handle symbols where the n_value field is not the address
687 GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
688 if (GV && GVSection[GV])
689 I->n_value += GVSection[GV]->addr;
690
Nate Begemand2030e62006-08-26 15:46:34 +0000691 // Emit nlist to buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000692 SymTOut.outword(I->n_strx);
693 SymTOut.outbyte(I->n_type);
694 SymTOut.outbyte(I->n_sect);
695 SymTOut.outhalf(I->n_desc);
696 SymTOut.outaddr(I->n_value);
Nate Begemand2030e62006-08-26 15:46:34 +0000697 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000698}
Nate Begeman94be2482006-09-08 22:42:09 +0000699
Nate Begeman019f8512006-09-10 23:03:44 +0000700/// CalculateRelocations - For each MachineRelocation in the current section,
701/// calculate the index of the section containing the object to be relocated,
702/// and the offset into that section. From this information, create the
703/// appropriate target-specific MachORelocation type and add buffer it to be
704/// written out after we are finished writing out sections.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000705void MachOWriter::CalculateRelocations(MachOSection &MOS) {
Nate Begeman019f8512006-09-10 23:03:44 +0000706 for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000707 MachineRelocation &MR = MOS.Relocations[i];
708 unsigned TargetSection = MR.getConstantVal();
Nate Begeman6635f352007-01-26 22:39:48 +0000709
710 // This is a scattered relocation entry if it points to a global value with
711 // a non-zero offset.
712 bool Scattered = false;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000713
714 // Since we may not have seen the GlobalValue we were interested in yet at
715 // the time we emitted the relocation for it, fix it up now so that it
716 // points to the offset into the correct section.
717 if (MR.isGlobalValue()) {
718 GlobalValue *GV = MR.getGlobalValue();
719 MachOSection *MOSPtr = GVSection[GV];
Nate Begeman6635f352007-01-26 22:39:48 +0000720 intptr_t Offset = GVOffset[GV];
721 Scattered = TargetSection != 0;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000722
Nate Begeman1257c852007-01-29 21:20:42 +0000723 if (!MOSPtr) {
724 cerr << "Trying to relocate unknown global " << *GV << '\n';
725 continue;
726 //abort();
727 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000728
729 TargetSection = MOSPtr->Index;
Nate Begeman6635f352007-01-26 22:39:48 +0000730 MR.setResultPointer((void*)Offset);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000731 }
Bill Wendling886b4122007-02-03 02:39:40 +0000732
733 OutputBuffer RelocOut(MOS.RelocBuffer, is64Bit, isLittleEndian);
734 OutputBuffer SecOut(MOS.SectionData, is64Bit, isLittleEndian);
735 MachOSection &To = *SectionList[TargetSection - 1];
736
737 MOS.nreloc += GetTargetRelocation(MR, MOS.Index, To.addr, To.Index,
738 RelocOut, SecOut, Scattered);
Nate Begeman019f8512006-09-10 23:03:44 +0000739 }
Nate Begeman019f8512006-09-10 23:03:44 +0000740}
741
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000742// InitMem - Write the value of a Constant to the specified memory location,
743// converting it into bytes and relocations.
744void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
745 const TargetData *TD,
746 std::vector<MachineRelocation> &MRs) {
747 typedef std::pair<const Constant*, intptr_t> CPair;
748 std::vector<CPair> WorkList;
749
750 WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
751
Nate Begeman6635f352007-01-26 22:39:48 +0000752 intptr_t ScatteredOffset = 0;
753
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000754 while (!WorkList.empty()) {
755 const Constant *PC = WorkList.back().first;
756 intptr_t PA = WorkList.back().second;
757 WorkList.pop_back();
758
759 if (isa<UndefValue>(PC)) {
760 continue;
761 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(PC)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000762 unsigned ElementSize = TD->getTypeSize(CP->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000763 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
764 WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
765 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
766 //
767 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
768 //
769 switch (CE->getOpcode()) {
Nate Begeman6635f352007-01-26 22:39:48 +0000770 case Instruction::GetElementPtr: {
771 std::vector<Value*> Indexes(CE->op_begin()+1, CE->op_end());
772 ScatteredOffset = TD->getIndexedOffset(CE->getOperand(0)->getType(),
773 Indexes);
774 WorkList.push_back(CPair(CE->getOperand(0), PA));
775 break;
776 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000777 case Instruction::Add:
778 default:
779 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
780 abort();
781 break;
782 }
783 } else if (PC->getType()->isFirstClassType()) {
784 unsigned char *ptr = (unsigned char *)PA;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000785 switch (PC->getType()->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000786 case Type::IntegerTyID: {
787 unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
788 uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
789 if (NumBits <= 8)
790 ptr[0] = val;
791 else if (NumBits <= 16) {
792 if (TD->isBigEndian())
793 val = ByteSwap_16(val);
794 ptr[0] = val;
795 ptr[1] = val >> 8;
796 } else if (NumBits <= 32) {
797 if (TD->isBigEndian())
798 val = ByteSwap_32(val);
799 ptr[0] = val;
800 ptr[1] = val >> 8;
801 ptr[2] = val >> 16;
802 ptr[3] = val >> 24;
803 } else if (NumBits <= 64) {
804 if (TD->isBigEndian())
805 val = ByteSwap_64(val);
806 ptr[0] = val;
807 ptr[1] = val >> 8;
808 ptr[2] = val >> 16;
809 ptr[3] = val >> 24;
810 ptr[4] = val >> 32;
811 ptr[5] = val >> 40;
812 ptr[6] = val >> 48;
813 ptr[7] = val >> 56;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000814 } else {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000815 assert(0 && "Not implemented: bit widths > 64");
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000816 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000817 break;
818 }
819 case Type::FloatTyID: {
820 uint64_t val = FloatToBits(cast<ConstantFP>(PC)->getValue());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000821 if (TD->isBigEndian())
822 val = ByteSwap_32(val);
823 ptr[0] = val;
824 ptr[1] = val >> 8;
825 ptr[2] = val >> 16;
826 ptr[3] = val >> 24;
827 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000828 }
829 case Type::DoubleTyID: {
830 uint64_t val = DoubleToBits(cast<ConstantFP>(PC)->getValue());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000831 if (TD->isBigEndian())
832 val = ByteSwap_64(val);
833 ptr[0] = val;
834 ptr[1] = val >> 8;
835 ptr[2] = val >> 16;
836 ptr[3] = val >> 24;
837 ptr[4] = val >> 32;
838 ptr[5] = val >> 40;
839 ptr[6] = val >> 48;
840 ptr[7] = val >> 56;
841 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000842 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000843 case Type::PointerTyID:
Nate Begeman6635f352007-01-26 22:39:48 +0000844 if (isa<ConstantPointerNull>(PC))
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000845 memset(ptr, 0, TD->getPointerSize());
Nate Begeman6635f352007-01-26 22:39:48 +0000846 else if (const GlobalValue* GV = dyn_cast<GlobalValue>(PC)) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000847 // FIXME: what about function stubs?
848 MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr,
849 MachineRelocation::VANILLA,
Nate Begeman6635f352007-01-26 22:39:48 +0000850 const_cast<GlobalValue*>(GV),
851 ScatteredOffset));
852 ScatteredOffset = 0;
853 } else
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000854 assert(0 && "Unknown constant pointer type!");
855 break;
856 default:
857 cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
858 abort();
859 }
860 } else if (isa<ConstantAggregateZero>(PC)) {
861 memset((void*)PA, 0, (size_t)TD->getTypeSize(PC->getType()));
862 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000863 unsigned ElementSize = TD->getTypeSize(CPA->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000864 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
865 WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
866 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
867 const StructLayout *SL =
868 TD->getStructLayout(cast<StructType>(CPS->getType()));
869 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
870 WorkList.push_back(CPair(CPS->getOperand(i), PA+SL->MemberOffsets[i]));
871 } else {
872 cerr << "Bad Type: " << *PC->getType() << "\n";
873 assert(0 && "Unknown constant type to initialize memory with!");
874 }
875 }
876}
877
878MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
879 TargetMachine &TM) :
880 GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
881 n_desc(0), n_value(0) {
882
883 const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
884
Nate Begeman94be2482006-09-08 22:42:09 +0000885 switch (GV->getLinkage()) {
886 default:
887 assert(0 && "Unexpected linkage type!");
888 break;
889 case GlobalValue::WeakLinkage:
890 case GlobalValue::LinkOnceLinkage:
891 assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
892 case GlobalValue::ExternalLinkage:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000893 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman6635f352007-01-26 22:39:48 +0000894 n_type |= GV->hasHiddenVisibility() ? N_PEXT : N_EXT;
Nate Begeman94be2482006-09-08 22:42:09 +0000895 break;
896 case GlobalValue::InternalLinkage:
Nate Begeman6635f352007-01-26 22:39:48 +0000897 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman94be2482006-09-08 22:42:09 +0000898 break;
899 }
900}