blob: 87013471074b5e068c177ad9f0b256deeec3eaa7 [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!");
110 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);
228 } else if (!MR.isGlobalValue()) {
229 assert(0 && "Unhandled relocation type");
Nate Begemaneb883af2006-08-23 21:08:52 +0000230 }
Nate Begeman019f8512006-09-10 23:03:44 +0000231 MOS->Relocations.push_back(MR);
Nate Begemaneb883af2006-08-23 21:08:52 +0000232 }
233 Relocations.clear();
234
235 // Finally, add it to the symtab.
236 MOW.SymbolTable.push_back(FnSym);
237 return false;
238}
239
Nate Begeman019f8512006-09-10 23:03:44 +0000240/// emitConstantPool - For each constant pool entry, figure out which section
241/// the constant should live in, allocate space for it, and emit it to the
242/// Section data buffer.
243void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000244 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
245 if (CP.empty()) return;
246
247 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000248 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000249 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
250
251 // Although there is no strict necessity that I am aware of, we will do what
252 // gcc for OS X does and put each constant pool entry in a section of constant
253 // objects of a certain size. That means that float constants go in the
254 // literal4 section, and double objects go in literal8, etc.
255 //
256 // FIXME: revisit this decision if we ever do the "stick everything into one
257 // "giant object for PIC" optimization.
258 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
259 const Type *Ty = CP[i].getType();
Bill Wendling203d3e42007-01-17 22:22:31 +0000260 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000261
Nate Begeman1257c852007-01-29 21:20:42 +0000262 MachOWriter::MachOSection *Sec = MOW.getConstSection(CP[i].Val.ConstVal);
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000263 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000264
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000265 CPLocations.push_back(Sec->SectionData.size());
266 CPSections.push_back(Sec->Index);
267
268 // FIXME: remove when we have unified size + output buffer
269 Sec->size += Size;
270
271 // Allocate space in the section for the global.
272 // FIXME: need alignment?
273 // FIXME: share between here and AddSymbolToSection?
274 for (unsigned j = 0; j < Size; ++j)
Bill Wendling203d3e42007-01-17 22:22:31 +0000275 SecDataOut.outbyte(0);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000276
277 MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
Bill Wendling203d3e42007-01-17 22:22:31 +0000278 TM.getTargetData(), Sec->Relocations);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000279 }
Nate Begeman019f8512006-09-10 23:03:44 +0000280}
281
282/// emitJumpTables - Emit all the jump tables for a given jump table info
283/// record to the appropriate section.
284void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
285 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
286 if (JT.empty()) return;
287
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000288 // FIXME: handle PIC codegen
Bill Wendling203d3e42007-01-17 22:22:31 +0000289 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begeman019f8512006-09-10 23:03:44 +0000290 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
291
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000292 MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
293 unsigned TextSecIndex = MOW.getTextSection()->Index;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000294 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Nate Begeman019f8512006-09-10 23:03:44 +0000295
296 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
297 // For each jump table, record its offset from the start of the section,
298 // reserve space for the relocations to the MBBs, and add the relocations.
299 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000300 JTLocations.push_back(Sec->SectionData.size());
Nate Begeman019f8512006-09-10 23:03:44 +0000301 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000302 MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
Nate Begeman019f8512006-09-10 23:03:44 +0000303 MBBs[mi]));
304 MR.setResultPointer((void *)JTLocations[i]);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000305 MR.setConstantVal(TextSecIndex);
306 Sec->Relocations.push_back(MR);
Bill Wendling203d3e42007-01-17 22:22:31 +0000307 SecDataOut.outaddr(0);
Nate Begeman019f8512006-09-10 23:03:44 +0000308 }
309 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000310 // FIXME: remove when we have unified size + output buffer
311 Sec->size = Sec->SectionData.size();
Nate Begeman019f8512006-09-10 23:03:44 +0000312}
313
Nate Begemaneb883af2006-08-23 21:08:52 +0000314//===----------------------------------------------------------------------===//
315// MachOWriter Implementation
316//===----------------------------------------------------------------------===//
317
318MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000319 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
320 isLittleEndian = TM.getTargetData()->isLittleEndian();
321
322 // Create the machine code emitter object for this target.
Bill Wendlinge9116152007-01-17 09:06:13 +0000323 MCE = new MachOCodeEmitter(*this);
Nate Begemaneb883af2006-08-23 21:08:52 +0000324}
325
326MachOWriter::~MachOWriter() {
327 delete MCE;
328}
329
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000330void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000331 const Type *Ty = GV->getType()->getElementType();
332 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000333 unsigned Align = GV->getAlignment();
334 if (Align == 0)
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000335 Align = TM.getTargetData()->getPrefTypeAlignment(Ty);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000336
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000337 MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
338
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000339 // Reserve space in the .bss section for this symbol while maintaining the
340 // desired section alignment, which must be at least as much as required by
341 // this symbol.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000342 OutputBuffer SecDataOut(Sec->SectionData, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000343
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000344 if (Align) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000345 uint64_t OrigSize = Sec->size;
346 Align = Log2_32(Align);
347 Sec->align = std::max(unsigned(Sec->align), Align);
348 Sec->size = (Sec->size + Align - 1) & ~(Align-1);
349
350 // Add alignment padding to buffer as well.
351 // FIXME: remove when we have unified size + output buffer
352 unsigned AlignedSize = Sec->size - OrigSize;
353 for (unsigned i = 0; i < AlignedSize; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000354 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000355 }
356 // Record the offset of the symbol, and then allocate space for it.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000357 // FIXME: remove when we have unified size + output buffer
358 Sym.n_value = Sec->size;
359 Sec->size += Size;
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000360 SymbolTable.push_back(Sym);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000361
362 // Now that we know what section the GlovalVariable is going to be emitted
363 // into, update our mappings.
364 // FIXME: We may also need to update this when outputting non-GlobalVariable
365 // GlobalValues such as functions.
366 GVSection[GV] = Sec;
367 GVOffset[GV] = Sec->SectionData.size();
368
369 // Allocate space in the section for the global.
370 for (unsigned i = 0; i < Size; ++i)
Bill Wendling203d3e42007-01-17 22:22:31 +0000371 SecDataOut.outbyte(0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000372}
373
Nate Begemaneb883af2006-08-23 21:08:52 +0000374void MachOWriter::EmitGlobal(GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000375 const Type *Ty = GV->getType()->getElementType();
376 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
377 bool NoInit = !GV->hasInitializer();
Nate Begemand2030e62006-08-26 15:46:34 +0000378
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000379 // If this global has a zero initializer, it is part of the .bss or common
380 // section.
381 if (NoInit || GV->getInitializer()->isNullValue()) {
382 // If this global is part of the common block, add it now. Variables are
383 // part of the common block if they are zero initialized and allowed to be
384 // merged with other symbols.
385 if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000386 MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000387 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
388 // bytes of the symbol.
389 ExtOrCommonSym.n_value = Size;
390 // If the symbol is external, we'll put it on a list of symbols whose
391 // addition to the symbol table is being pended until we find a reference
392 if (NoInit)
393 PendingSyms.push_back(ExtOrCommonSym);
394 else
395 SymbolTable.push_back(ExtOrCommonSym);
396 return;
397 }
398 // Otherwise, this symbol is part of the .bss section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000399 MachOSection *BSS = getBSSSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000400 AddSymbolToSection(BSS, GV);
401 return;
402 }
403
404 // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
405 // 16 bytes, or a cstring. Other read only data goes into a regular const
406 // section. Read-write data goes in the data section.
Nate Begeman1257c852007-01-29 21:20:42 +0000407 MachOSection *Sec = GV->isConstant() ? getConstSection(GV->getInitializer()) :
408 getDataSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000409 AddSymbolToSection(Sec, GV);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000410 InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
411 TM.getTargetData(), Sec->Relocations);
Nate Begemaneb883af2006-08-23 21:08:52 +0000412}
413
414
415bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
416 // Nothing to do here, this is all done through the MCE object.
417 return false;
418}
419
420bool MachOWriter::doInitialization(Module &M) {
421 // Set the magic value, now that we know the pointer size and endianness
422 Header.setMagic(isLittleEndian, is64Bit);
423
424 // Set the file type
425 // FIXME: this only works for object files, we do not support the creation
426 // of dynamic libraries or executables at this time.
427 Header.filetype = MachOHeader::MH_OBJECT;
428
429 Mang = new Mangler(M);
430 return false;
431}
432
433/// doFinalization - Now that the module has been completely processed, emit
434/// the Mach-O file to 'O'.
435bool MachOWriter::doFinalization(Module &M) {
Nate Begemand2030e62006-08-26 15:46:34 +0000436 // FIXME: we don't handle debug info yet, we should probably do that.
437
Nate Begemaneb883af2006-08-23 21:08:52 +0000438 // Okay, the.text section has been completed, build the .data, .bss, and
439 // "common" sections next.
440 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
441 I != E; ++I)
442 EmitGlobal(I);
443
444 // Emit the header and load commands.
445 EmitHeaderAndLoadCommands();
446
Nate Begeman019f8512006-09-10 23:03:44 +0000447 // Emit the various sections and their relocation info.
Nate Begemaneb883af2006-08-23 21:08:52 +0000448 EmitSections();
449
Nate Begemand2030e62006-08-26 15:46:34 +0000450 // Write the symbol table and the string table to the end of the file.
451 O.write((char*)&SymT[0], SymT.size());
452 O.write((char*)&StrT[0], StrT.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000453
454 // We are done with the abstract symbols.
455 SectionList.clear();
456 SymbolTable.clear();
457 DynamicSymbolTable.clear();
458
459 // Release the name mangler object.
460 delete Mang; Mang = 0;
461 return false;
462}
463
464void MachOWriter::EmitHeaderAndLoadCommands() {
465 // Step #0: Fill in the segment load command size, since we need it to figure
466 // out the rest of the header fields
467 MachOSegment SEG("", is64Bit);
468 SEG.nsects = SectionList.size();
469 SEG.cmdsize = SEG.cmdSize(is64Bit) +
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000470 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
Nate Begemaneb883af2006-08-23 21:08:52 +0000471
472 // Step #1: calculate the number of load commands. We always have at least
473 // one, for the LC_SEGMENT load command, plus two for the normal
474 // and dynamic symbol tables, if there are any symbols.
475 Header.ncmds = SymbolTable.empty() ? 1 : 3;
476
477 // Step #2: calculate the size of the load commands
478 Header.sizeofcmds = SEG.cmdsize;
479 if (!SymbolTable.empty())
480 Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
481
482 // Step #3: write the header to the file
483 // Local alias to shortenify coming code.
484 DataBuffer &FH = Header.HeaderData;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000485 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000486
487 FHOut.outword(Header.magic);
Bill Wendling2b721822007-01-24 07:13:56 +0000488 FHOut.outword(TM.getMachOWriterInfo()->getCPUType());
489 FHOut.outword(TM.getMachOWriterInfo()->getCPUSubType());
Bill Wendling203d3e42007-01-17 22:22:31 +0000490 FHOut.outword(Header.filetype);
491 FHOut.outword(Header.ncmds);
492 FHOut.outword(Header.sizeofcmds);
493 FHOut.outword(Header.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000494 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000495 FHOut.outword(Header.reserved);
Nate Begemaneb883af2006-08-23 21:08:52 +0000496
497 // Step #4: Finish filling in the segment load command and write it out
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000498 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000499 E = SectionList.end(); I != E; ++I)
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000500 SEG.filesize += (*I)->size;
501
Nate Begemaneb883af2006-08-23 21:08:52 +0000502 SEG.vmsize = SEG.filesize;
503 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
504
Bill Wendling203d3e42007-01-17 22:22:31 +0000505 FHOut.outword(SEG.cmd);
506 FHOut.outword(SEG.cmdsize);
507 FHOut.outstring(SEG.segname, 16);
508 FHOut.outaddr(SEG.vmaddr);
509 FHOut.outaddr(SEG.vmsize);
510 FHOut.outaddr(SEG.fileoff);
511 FHOut.outaddr(SEG.filesize);
512 FHOut.outword(SEG.maxprot);
513 FHOut.outword(SEG.initprot);
514 FHOut.outword(SEG.nsects);
515 FHOut.outword(SEG.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000516
Nate Begeman94be2482006-09-08 22:42:09 +0000517 // Step #5: Finish filling in the fields of the MachOSections
518 uint64_t currentAddr = 0;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000519 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000520 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000521 MachOSection *MOS = *I;
522 MOS->addr = currentAddr;
523 MOS->offset = currentAddr + SEG.fileoff;
Nate Begeman019f8512006-09-10 23:03:44 +0000524
Nate Begeman94be2482006-09-08 22:42:09 +0000525 // FIXME: do we need to do something with alignment here?
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000526 currentAddr += MOS->size;
Nate Begeman94be2482006-09-08 22:42:09 +0000527 }
528
529 // Step #6: Calculate the number of relocations for each section and write out
530 // the section commands for each section
531 currentAddr += SEG.fileoff;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000532 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman94be2482006-09-08 22:42:09 +0000533 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000534 MachOSection *MOS = *I;
535 // Convert the relocations to target-specific relocations, and fill in the
536 // relocation offset for this section.
537 CalculateRelocations(*MOS);
538 MOS->reloff = MOS->nreloc ? currentAddr : 0;
539 currentAddr += MOS->nreloc * 8;
Nate Begeman94be2482006-09-08 22:42:09 +0000540
541 // write the finalized section command to the output buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000542 FHOut.outstring(MOS->sectname, 16);
543 FHOut.outstring(MOS->segname, 16);
544 FHOut.outaddr(MOS->addr);
545 FHOut.outaddr(MOS->size);
546 FHOut.outword(MOS->offset);
547 FHOut.outword(MOS->align);
548 FHOut.outword(MOS->reloff);
549 FHOut.outword(MOS->nreloc);
550 FHOut.outword(MOS->flags);
551 FHOut.outword(MOS->reserved1);
552 FHOut.outword(MOS->reserved2);
Nate Begemaneb883af2006-08-23 21:08:52 +0000553 if (is64Bit)
Bill Wendling203d3e42007-01-17 22:22:31 +0000554 FHOut.outword(MOS->reserved3);
Nate Begemaneb883af2006-08-23 21:08:52 +0000555 }
556
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000557 // Step #7: Emit the symbol table to temporary buffers, so that we know the
558 // size of the string table when we write the next load command.
559 BufferSymbolAndStringTable();
560
561 // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
Nate Begeman94be2482006-09-08 22:42:09 +0000562 SymTab.symoff = currentAddr;
Nate Begemaneb883af2006-08-23 21:08:52 +0000563 SymTab.nsyms = SymbolTable.size();
Nate Begemand2030e62006-08-26 15:46:34 +0000564 SymTab.stroff = SymTab.symoff + SymT.size();
565 SymTab.strsize = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000566 FHOut.outword(SymTab.cmd);
567 FHOut.outword(SymTab.cmdsize);
568 FHOut.outword(SymTab.symoff);
569 FHOut.outword(SymTab.nsyms);
570 FHOut.outword(SymTab.stroff);
571 FHOut.outword(SymTab.strsize);
Nate Begemaneb883af2006-08-23 21:08:52 +0000572
573 // FIXME: set DySymTab fields appropriately
Nate Begemand2030e62006-08-26 15:46:34 +0000574 // We should probably just update these in BufferSymbolAndStringTable since
575 // thats where we're partitioning up the different kinds of symbols.
Bill Wendling203d3e42007-01-17 22:22:31 +0000576 FHOut.outword(DySymTab.cmd);
577 FHOut.outword(DySymTab.cmdsize);
578 FHOut.outword(DySymTab.ilocalsym);
579 FHOut.outword(DySymTab.nlocalsym);
580 FHOut.outword(DySymTab.iextdefsym);
581 FHOut.outword(DySymTab.nextdefsym);
582 FHOut.outword(DySymTab.iundefsym);
583 FHOut.outword(DySymTab.nundefsym);
584 FHOut.outword(DySymTab.tocoff);
585 FHOut.outword(DySymTab.ntoc);
586 FHOut.outword(DySymTab.modtaboff);
587 FHOut.outword(DySymTab.nmodtab);
588 FHOut.outword(DySymTab.extrefsymoff);
589 FHOut.outword(DySymTab.nextrefsyms);
590 FHOut.outword(DySymTab.indirectsymoff);
591 FHOut.outword(DySymTab.nindirectsyms);
592 FHOut.outword(DySymTab.extreloff);
593 FHOut.outword(DySymTab.nextrel);
594 FHOut.outword(DySymTab.locreloff);
595 FHOut.outword(DySymTab.nlocrel);
Nate Begemaneb883af2006-08-23 21:08:52 +0000596
597 O.write((char*)&FH[0], FH.size());
598}
599
600/// EmitSections - Now that we have constructed the file header and load
601/// commands, emit the data for each section to the file.
602void MachOWriter::EmitSections() {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000603 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000604 E = SectionList.end(); I != E; ++I)
605 // Emit the contents of each section
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000606 O.write((char*)&(*I)->SectionData[0], (*I)->size);
607 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000608 E = SectionList.end(); I != E; ++I)
609 // Emit the relocation entry data for each section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000610 O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000611}
612
Nate Begemand2030e62006-08-26 15:46:34 +0000613/// PartitionByLocal - Simple boolean predicate that returns true if Sym is
614/// a local symbol rather than an external symbol.
615bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
Nate Begemand2030e62006-08-26 15:46:34 +0000616 return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
Nate Begemaneb883af2006-08-23 21:08:52 +0000617}
618
Nate Begemand2030e62006-08-26 15:46:34 +0000619/// PartitionByDefined - Simple boolean predicate that returns true if Sym is
620/// defined in this module.
621bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
622 // FIXME: Do N_ABS or N_INDR count as defined?
623 return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
624}
Nate Begemaneb883af2006-08-23 21:08:52 +0000625
Nate Begemand2030e62006-08-26 15:46:34 +0000626/// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
627/// each a string table index so that they appear in the correct order in the
628/// output file.
629void MachOWriter::BufferSymbolAndStringTable() {
630 // The order of the symbol table is:
631 // 1. local symbols
632 // 2. defined external symbols (sorted by name)
633 // 3. undefined external symbols (sorted by name)
634
635 // Sort the symbols by name, so that when we partition the symbols by scope
636 // of definition, we won't have to sort by name within each partition.
637 std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
638
639 // Parition the symbol table entries so that all local symbols come before
640 // all symbols with external linkage. { 1 | 2 3 }
641 std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
642
643 // Advance iterator to beginning of external symbols and partition so that
644 // all external symbols defined in this module come before all external
645 // symbols defined elsewhere. { 1 | 2 | 3 }
646 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
647 E = SymbolTable.end(); I != E; ++I) {
648 if (!PartitionByLocal(*I)) {
649 std::partition(I, E, PartitionByDefined);
650 break;
651 }
652 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000653
654 // Calculate the starting index for each of the local, extern defined, and
655 // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
656 // load command.
657 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
658 E = SymbolTable.end(); I != E; ++I) {
659 if (PartitionByLocal(*I)) {
660 ++DySymTab.nlocalsym;
661 ++DySymTab.iextdefsym;
Nate Begeman6635f352007-01-26 22:39:48 +0000662 ++DySymTab.iundefsym;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000663 } else if (PartitionByDefined(*I)) {
664 ++DySymTab.nextdefsym;
665 ++DySymTab.iundefsym;
666 } else {
667 ++DySymTab.nundefsym;
668 }
669 }
Nate Begemand2030e62006-08-26 15:46:34 +0000670
Nate Begemaneb883af2006-08-23 21:08:52 +0000671 // Write out a leading zero byte when emitting string table, for n_strx == 0
672 // which means an empty string.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000673 OutputBuffer StrTOut(StrT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000674 StrTOut.outbyte(0);
Nate Begemaneb883af2006-08-23 21:08:52 +0000675
Nate Begemand2030e62006-08-26 15:46:34 +0000676 // The order of the string table is:
677 // 1. strings for external symbols
678 // 2. strings for local symbols
679 // Since this is the opposite order from the symbol table, which we have just
680 // sorted, we can walk the symbol table backwards to output the string table.
681 for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
682 E = SymbolTable.rend(); I != E; ++I) {
683 if (I->GVName == "") {
684 I->n_strx = 0;
685 } else {
686 I->n_strx = StrT.size();
Bill Wendling203d3e42007-01-17 22:22:31 +0000687 StrTOut.outstring(I->GVName, I->GVName.length()+1);
Nate Begemand2030e62006-08-26 15:46:34 +0000688 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000689 }
Nate Begemand2030e62006-08-26 15:46:34 +0000690
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000691 OutputBuffer SymTOut(SymT, is64Bit, isLittleEndian);
Bill Wendling203d3e42007-01-17 22:22:31 +0000692
Nate Begemand2030e62006-08-26 15:46:34 +0000693 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
694 E = SymbolTable.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000695 // Add the section base address to the section offset in the n_value field
696 // to calculate the full address.
697 // FIXME: handle symbols where the n_value field is not the address
698 GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
699 if (GV && GVSection[GV])
700 I->n_value += GVSection[GV]->addr;
701
Nate Begemand2030e62006-08-26 15:46:34 +0000702 // Emit nlist to buffer
Bill Wendling203d3e42007-01-17 22:22:31 +0000703 SymTOut.outword(I->n_strx);
704 SymTOut.outbyte(I->n_type);
705 SymTOut.outbyte(I->n_sect);
706 SymTOut.outhalf(I->n_desc);
707 SymTOut.outaddr(I->n_value);
Nate Begemand2030e62006-08-26 15:46:34 +0000708 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000709}
Nate Begeman94be2482006-09-08 22:42:09 +0000710
Nate Begeman019f8512006-09-10 23:03:44 +0000711/// CalculateRelocations - For each MachineRelocation in the current section,
712/// calculate the index of the section containing the object to be relocated,
713/// and the offset into that section. From this information, create the
714/// appropriate target-specific MachORelocation type and add buffer it to be
715/// written out after we are finished writing out sections.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000716void MachOWriter::CalculateRelocations(MachOSection &MOS) {
Nate Begeman019f8512006-09-10 23:03:44 +0000717 for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000718 MachineRelocation &MR = MOS.Relocations[i];
719 unsigned TargetSection = MR.getConstantVal();
Nate Begeman6635f352007-01-26 22:39:48 +0000720
721 // This is a scattered relocation entry if it points to a global value with
722 // a non-zero offset.
723 bool Scattered = false;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000724
725 // Since we may not have seen the GlobalValue we were interested in yet at
726 // the time we emitted the relocation for it, fix it up now so that it
727 // points to the offset into the correct section.
728 if (MR.isGlobalValue()) {
729 GlobalValue *GV = MR.getGlobalValue();
730 MachOSection *MOSPtr = GVSection[GV];
Nate Begeman6635f352007-01-26 22:39:48 +0000731 intptr_t Offset = GVOffset[GV];
732 Scattered = TargetSection != 0;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000733
Nate Begeman1257c852007-01-29 21:20:42 +0000734 if (!MOSPtr) {
735 cerr << "Trying to relocate unknown global " << *GV << '\n';
736 continue;
737 //abort();
738 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000739
740 TargetSection = MOSPtr->Index;
Nate Begeman6635f352007-01-26 22:39:48 +0000741 MR.setResultPointer((void*)Offset);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000742 }
Bill Wendling886b4122007-02-03 02:39:40 +0000743
744 OutputBuffer RelocOut(MOS.RelocBuffer, is64Bit, isLittleEndian);
745 OutputBuffer SecOut(MOS.SectionData, is64Bit, isLittleEndian);
746 MachOSection &To = *SectionList[TargetSection - 1];
747
748 MOS.nreloc += GetTargetRelocation(MR, MOS.Index, To.addr, To.Index,
749 RelocOut, SecOut, Scattered);
Nate Begeman019f8512006-09-10 23:03:44 +0000750 }
Nate Begeman019f8512006-09-10 23:03:44 +0000751}
752
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000753// InitMem - Write the value of a Constant to the specified memory location,
754// converting it into bytes and relocations.
755void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
756 const TargetData *TD,
757 std::vector<MachineRelocation> &MRs) {
758 typedef std::pair<const Constant*, intptr_t> CPair;
759 std::vector<CPair> WorkList;
760
761 WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
762
Nate Begeman6635f352007-01-26 22:39:48 +0000763 intptr_t ScatteredOffset = 0;
764
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000765 while (!WorkList.empty()) {
766 const Constant *PC = WorkList.back().first;
767 intptr_t PA = WorkList.back().second;
768 WorkList.pop_back();
769
770 if (isa<UndefValue>(PC)) {
771 continue;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000772 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(PC)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000773 unsigned ElementSize = TD->getTypeSize(CP->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000774 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
775 WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
776 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
777 //
778 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
779 //
780 switch (CE->getOpcode()) {
Nate Begeman6635f352007-01-26 22:39:48 +0000781 case Instruction::GetElementPtr: {
Chris Lattner7f6b9d22007-02-10 20:31:59 +0000782 SmallVector<Value*, 8> Indices(CE->op_begin()+1, CE->op_end());
Nate Begeman6635f352007-01-26 22:39:48 +0000783 ScatteredOffset = TD->getIndexedOffset(CE->getOperand(0)->getType(),
Chris Lattner7f6b9d22007-02-10 20:31:59 +0000784 &Indices[0], Indices.size());
Nate Begeman6635f352007-01-26 22:39:48 +0000785 WorkList.push_back(CPair(CE->getOperand(0), PA));
786 break;
787 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000788 case Instruction::Add:
789 default:
790 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
791 abort();
792 break;
793 }
794 } else if (PC->getType()->isFirstClassType()) {
795 unsigned char *ptr = (unsigned char *)PA;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000796 switch (PC->getType()->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000797 case Type::IntegerTyID: {
798 unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
799 uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
800 if (NumBits <= 8)
801 ptr[0] = val;
802 else if (NumBits <= 16) {
803 if (TD->isBigEndian())
804 val = ByteSwap_16(val);
805 ptr[0] = val;
806 ptr[1] = val >> 8;
807 } else if (NumBits <= 32) {
808 if (TD->isBigEndian())
809 val = ByteSwap_32(val);
810 ptr[0] = val;
811 ptr[1] = val >> 8;
812 ptr[2] = val >> 16;
813 ptr[3] = val >> 24;
814 } else if (NumBits <= 64) {
815 if (TD->isBigEndian())
816 val = ByteSwap_64(val);
817 ptr[0] = val;
818 ptr[1] = val >> 8;
819 ptr[2] = val >> 16;
820 ptr[3] = val >> 24;
821 ptr[4] = val >> 32;
822 ptr[5] = val >> 40;
823 ptr[6] = val >> 48;
824 ptr[7] = val >> 56;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000825 } else {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000826 assert(0 && "Not implemented: bit widths > 64");
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000827 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000828 break;
829 }
830 case Type::FloatTyID: {
831 uint64_t val = FloatToBits(cast<ConstantFP>(PC)->getValue());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000832 if (TD->isBigEndian())
833 val = ByteSwap_32(val);
834 ptr[0] = val;
835 ptr[1] = val >> 8;
836 ptr[2] = val >> 16;
837 ptr[3] = val >> 24;
838 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000839 }
840 case Type::DoubleTyID: {
841 uint64_t val = DoubleToBits(cast<ConstantFP>(PC)->getValue());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000842 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;
852 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000853 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000854 case Type::PointerTyID:
Nate Begeman6635f352007-01-26 22:39:48 +0000855 if (isa<ConstantPointerNull>(PC))
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000856 memset(ptr, 0, TD->getPointerSize());
Nate Begeman6635f352007-01-26 22:39:48 +0000857 else if (const GlobalValue* GV = dyn_cast<GlobalValue>(PC)) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000858 // FIXME: what about function stubs?
859 MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr,
860 MachineRelocation::VANILLA,
Nate Begeman6635f352007-01-26 22:39:48 +0000861 const_cast<GlobalValue*>(GV),
862 ScatteredOffset));
863 ScatteredOffset = 0;
864 } else
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000865 assert(0 && "Unknown constant pointer type!");
866 break;
867 default:
868 cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
869 abort();
870 }
871 } else if (isa<ConstantAggregateZero>(PC)) {
872 memset((void*)PA, 0, (size_t)TD->getTypeSize(PC->getType()));
873 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000874 unsigned ElementSize = TD->getTypeSize(CPA->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000875 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
876 WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
877 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
878 const StructLayout *SL =
879 TD->getStructLayout(cast<StructType>(CPS->getType()));
880 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
Chris Lattnerb1919e22007-02-10 19:55:17 +0000881 WorkList.push_back(CPair(CPS->getOperand(i),
882 PA+SL->getElementOffset(i)));
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000883 } else {
884 cerr << "Bad Type: " << *PC->getType() << "\n";
885 assert(0 && "Unknown constant type to initialize memory with!");
886 }
887 }
888}
889
890MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
891 TargetMachine &TM) :
892 GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
893 n_desc(0), n_value(0) {
894
895 const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
896
Nate Begeman94be2482006-09-08 22:42:09 +0000897 switch (GV->getLinkage()) {
898 default:
899 assert(0 && "Unexpected linkage type!");
900 break;
901 case GlobalValue::WeakLinkage:
902 case GlobalValue::LinkOnceLinkage:
903 assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
904 case GlobalValue::ExternalLinkage:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000905 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman6635f352007-01-26 22:39:48 +0000906 n_type |= GV->hasHiddenVisibility() ? N_PEXT : N_EXT;
Nate Begeman94be2482006-09-08 22:42:09 +0000907 break;
908 case GlobalValue::InternalLinkage:
Nate Begeman6635f352007-01-26 22:39:48 +0000909 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman94be2482006-09-08 22:42:09 +0000910 break;
911 }
912}