blob: 0a8825a4e4d1e2d0175422aef5a9d0e107158151 [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"
Bill Wendling157c4ee2007-01-17 03:49:21 +000035#include "llvm/Target/TargetObjInfo.h"
Nate Begemaneb883af2006-08-23 21:08:52 +000036#include "llvm/Support/Mangler.h"
Nate Begemanf8f2c5a2006-08-25 06:36:58 +000037#include "llvm/Support/MathExtras.h"
Nate Begemanbfaaaa62006-12-11 02:20:45 +000038#include "llvm/Support/Streams.h"
Nate Begemand2030e62006-08-26 15:46:34 +000039#include <algorithm>
Nate Begemaneb883af2006-08-23 21:08:52 +000040using namespace llvm;
41
42//===----------------------------------------------------------------------===//
43// MachOCodeEmitter Implementation
44//===----------------------------------------------------------------------===//
45
46namespace llvm {
47 /// MachOCodeEmitter - This class is used by the MachOWriter to emit the code
48 /// for functions to the Mach-O file.
49 class MachOCodeEmitter : public MachineCodeEmitter {
50 MachOWriter &MOW;
Nate Begemaneb883af2006-08-23 21:08:52 +000051
Bill Wendling157c4ee2007-01-17 03:49:21 +000052 /// Target machine description.
53 ///
54 TargetMachine &TM;
55
56 /// Target object writer info.
57 ///
58 const TargetObjInfo *TOI;
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 Wendling157c4ee2007-01-17 03:49:21 +000082 MachOCodeEmitter(MachOWriter &mow, TargetMachine &tm) : MOW(mow), TM(tm) {
83 // Create the target object info object for this target.
84 TOI = TM.getTargetObjInfo();
85 }
Nate Begemaneb883af2006-08-23 21:08:52 +000086
Nate Begemanbfaaaa62006-12-11 02:20:45 +000087 virtual void startFunction(MachineFunction &F);
88 virtual bool finishFunction(MachineFunction &F);
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.
133void MachOCodeEmitter::startFunction(MachineFunction &F) {
134 // Align the output buffer to the appropriate alignment, power of 2.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000135 // FIXME: MachineFunction or TargetData should probably carry an alignment
136 // field for functions that we can query here instead of hard coding 4 in both
137 // the object writer and asm printer.
Nate Begemaneb883af2006-08-23 21:08:52 +0000138 unsigned Align = 4;
139
140 // Get the Mach-O Section that this function belongs in.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000141 MachOWriter::MachOSection *MOS = MOW.getTextSection();
Nate Begemaneb883af2006-08-23 21:08:52 +0000142
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000143 // FIXME: better memory management
Nate Begemaneb883af2006-08-23 21:08:52 +0000144 MOS->SectionData.reserve(4096);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000145 BufferBegin = &MOS->SectionData[0];
Nate Begemaneb883af2006-08-23 21:08:52 +0000146 BufferEnd = BufferBegin + MOS->SectionData.capacity();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000147
148 // FIXME: Using MOS->size directly here instead of calculating it from the
149 // output buffer size (impossible because the code emitter deals only in raw
150 // bytes) forces us to manually synchronize size and write padding zero bytes
151 // to the output buffer for all non-text sections. For text sections, we do
152 // not synchonize the output buffer, and we just blow up if anyone tries to
153 // write non-code to it. An assert should probably be added to
154 // AddSymbolToSection to prevent calling it on the text section.
Nate Begemaneb883af2006-08-23 21:08:52 +0000155 CurBufferPtr = BufferBegin + MOS->size;
156
157 // Upgrade the section alignment if required.
158 if (MOS->align < Align) MOS->align = Align;
159
Nate Begeman019f8512006-09-10 23:03:44 +0000160 // Clear per-function data structures.
161 CPLocations.clear();
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000162 CPSections.clear();
Nate Begeman019f8512006-09-10 23:03:44 +0000163 JTLocations.clear();
Nate Begemaneb883af2006-08-23 21:08:52 +0000164 MBBLocations.clear();
165}
166
167/// finishFunction - This callback is invoked after the function is completely
168/// finished.
169bool MachOCodeEmitter::finishFunction(MachineFunction &F) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000170 // Get the Mach-O Section that this function belongs in.
171 MachOWriter::MachOSection *MOS = MOW.getTextSection();
172
Nate Begemaneb883af2006-08-23 21:08:52 +0000173 MOS->size += CurBufferPtr - BufferBegin;
174
175 // Get a symbol for the function to add to the symbol table
Nate Begemand2030e62006-08-26 15:46:34 +0000176 const GlobalValue *FuncV = F.getFunction();
Bill Wendling157c4ee2007-01-17 03:49:21 +0000177 MachOSym FnSym(FuncV, MOW.Mang->getValueName(FuncV), MOS->Index, TM);
Nate Begeman94be2482006-09-08 22:42:09 +0000178
Nate Begeman019f8512006-09-10 23:03:44 +0000179 // Emit constant pool to appropriate section(s)
180 emitConstantPool(F.getConstantPool());
181
182 // Emit jump tables to appropriate section
183 emitJumpTables(F.getJumpTableInfo());
Nate Begemaneb883af2006-08-23 21:08:52 +0000184
Nate Begeman019f8512006-09-10 23:03:44 +0000185 // If we have emitted any relocations to function-specific objects such as
186 // basic blocks, constant pools entries, or jump tables, record their
187 // addresses now so that we can rewrite them with the correct addresses
188 // later.
Nate Begemaneb883af2006-08-23 21:08:52 +0000189 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
190 MachineRelocation &MR = Relocations[i];
Nate Begeman019f8512006-09-10 23:03:44 +0000191 intptr_t Addr;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000192
Nate Begemaneb883af2006-08-23 21:08:52 +0000193 if (MR.isBasicBlock()) {
Nate Begeman019f8512006-09-10 23:03:44 +0000194 Addr = getMachineBasicBlockAddress(MR.getBasicBlock());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000195 MR.setConstantVal(MOS->Index);
196 MR.setResultPointer((void*)Addr);
197 } else if (MR.isJumpTableIndex()) {
198 Addr = getJumpTableEntryAddress(MR.getJumpTableIndex());
199 MR.setConstantVal(MOW.getJumpTableSection()->Index);
200 MR.setResultPointer((void*)Addr);
Nate Begeman019f8512006-09-10 23:03:44 +0000201 } else if (MR.isConstantPoolIndex()) {
202 Addr = getConstantPoolEntryAddress(MR.getConstantPoolIndex());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000203 MR.setConstantVal(CPSections[MR.getConstantPoolIndex()]);
204 MR.setResultPointer((void*)Addr);
205 } else if (!MR.isGlobalValue()) {
206 assert(0 && "Unhandled relocation type");
Nate Begemaneb883af2006-08-23 21:08:52 +0000207 }
Nate Begeman019f8512006-09-10 23:03:44 +0000208 MOS->Relocations.push_back(MR);
Nate Begemaneb883af2006-08-23 21:08:52 +0000209 }
210 Relocations.clear();
211
212 // Finally, add it to the symtab.
213 MOW.SymbolTable.push_back(FnSym);
214 return false;
215}
216
Nate Begeman019f8512006-09-10 23:03:44 +0000217/// emitConstantPool - For each constant pool entry, figure out which section
218/// the constant should live in, allocate space for it, and emit it to the
219/// Section data buffer.
220void MachOCodeEmitter::emitConstantPool(MachineConstantPool *MCP) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000221 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
222 if (CP.empty()) return;
223
224 // FIXME: handle PIC codegen
Bill Wendling157c4ee2007-01-17 03:49:21 +0000225 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000226 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
227
228 // Although there is no strict necessity that I am aware of, we will do what
229 // gcc for OS X does and put each constant pool entry in a section of constant
230 // objects of a certain size. That means that float constants go in the
231 // literal4 section, and double objects go in literal8, etc.
232 //
233 // FIXME: revisit this decision if we ever do the "stick everything into one
234 // "giant object for PIC" optimization.
235 for (unsigned i = 0, e = CP.size(); i != e; ++i) {
236 const Type *Ty = CP[i].getType();
Bill Wendling157c4ee2007-01-17 03:49:21 +0000237 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000238
239 MachOWriter::MachOSection *Sec = MOW.getConstSection(Ty);
240 CPLocations.push_back(Sec->SectionData.size());
241 CPSections.push_back(Sec->Index);
242
243 // FIXME: remove when we have unified size + output buffer
244 Sec->size += Size;
245
246 // Allocate space in the section for the global.
247 // FIXME: need alignment?
248 // FIXME: share between here and AddSymbolToSection?
249 for (unsigned j = 0; j < Size; ++j)
Bill Wendling157c4ee2007-01-17 03:49:21 +0000250 TOI->outbyte(Sec->SectionData, 0);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000251
252 MOW.InitMem(CP[i].Val.ConstVal, &Sec->SectionData[0], CPLocations[i],
Bill Wendling157c4ee2007-01-17 03:49:21 +0000253 TM.getTargetData(), Sec->Relocations);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000254 }
Nate Begeman019f8512006-09-10 23:03:44 +0000255}
256
257/// emitJumpTables - Emit all the jump tables for a given jump table info
258/// record to the appropriate section.
259void MachOCodeEmitter::emitJumpTables(MachineJumpTableInfo *MJTI) {
260 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
261 if (JT.empty()) return;
262
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000263 // FIXME: handle PIC codegen
Bill Wendling157c4ee2007-01-17 03:49:21 +0000264 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
Nate Begeman019f8512006-09-10 23:03:44 +0000265 assert(!isPIC && "PIC codegen not yet handled for mach-o jump tables!");
266
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000267 MachOWriter::MachOSection *Sec = MOW.getJumpTableSection();
268 unsigned TextSecIndex = MOW.getTextSection()->Index;
Nate Begeman019f8512006-09-10 23:03:44 +0000269
270 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
271 // For each jump table, record its offset from the start of the section,
272 // reserve space for the relocations to the MBBs, and add the relocations.
273 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000274 JTLocations.push_back(Sec->SectionData.size());
Nate Begeman019f8512006-09-10 23:03:44 +0000275 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000276 MachineRelocation MR(MOW.GetJTRelocation(Sec->SectionData.size(),
Nate Begeman019f8512006-09-10 23:03:44 +0000277 MBBs[mi]));
278 MR.setResultPointer((void *)JTLocations[i]);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000279 MR.setConstantVal(TextSecIndex);
280 Sec->Relocations.push_back(MR);
Bill Wendling157c4ee2007-01-17 03:49:21 +0000281 TOI->outaddr(Sec->SectionData, 0);
Nate Begeman019f8512006-09-10 23:03:44 +0000282 }
283 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000284 // FIXME: remove when we have unified size + output buffer
285 Sec->size = Sec->SectionData.size();
Nate Begeman019f8512006-09-10 23:03:44 +0000286}
287
Nate Begemaneb883af2006-08-23 21:08:52 +0000288//===----------------------------------------------------------------------===//
289// MachOWriter Implementation
290//===----------------------------------------------------------------------===//
291
292MachOWriter::MachOWriter(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) {
Nate Begemaneb883af2006-08-23 21:08:52 +0000293 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
294 isLittleEndian = TM.getTargetData()->isLittleEndian();
295
296 // Create the machine code emitter object for this target.
Bill Wendling157c4ee2007-01-17 03:49:21 +0000297 MCE = new MachOCodeEmitter(*this, tm);
298
299 // Create the target object info object for this target.
300 TOI = TM.getTargetObjInfo();
Nate Begemaneb883af2006-08-23 21:08:52 +0000301}
302
303MachOWriter::~MachOWriter() {
304 delete MCE;
305}
306
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000307void MachOWriter::AddSymbolToSection(MachOSection *Sec, GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000308 const Type *Ty = GV->getType()->getElementType();
309 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000310 unsigned Align = GV->getAlignment();
311 if (Align == 0)
312 Align = TM.getTargetData()->getTypeAlignment(Ty);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000313
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000314 MachOSym Sym(GV, Mang->getValueName(GV), Sec->Index, TM);
315
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000316 // Reserve space in the .bss section for this symbol while maintaining the
317 // desired section alignment, which must be at least as much as required by
318 // this symbol.
319 if (Align) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000320 uint64_t OrigSize = Sec->size;
321 Align = Log2_32(Align);
322 Sec->align = std::max(unsigned(Sec->align), Align);
323 Sec->size = (Sec->size + Align - 1) & ~(Align-1);
324
325 // Add alignment padding to buffer as well.
326 // FIXME: remove when we have unified size + output buffer
327 unsigned AlignedSize = Sec->size - OrigSize;
328 for (unsigned i = 0; i < AlignedSize; ++i)
Bill Wendling157c4ee2007-01-17 03:49:21 +0000329 TOI->outbyte(Sec->SectionData, 0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000330 }
331 // Record the offset of the symbol, and then allocate space for it.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000332 // FIXME: remove when we have unified size + output buffer
333 Sym.n_value = Sec->size;
334 Sec->size += Size;
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000335 SymbolTable.push_back(Sym);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000336
337 // Now that we know what section the GlovalVariable is going to be emitted
338 // into, update our mappings.
339 // FIXME: We may also need to update this when outputting non-GlobalVariable
340 // GlobalValues such as functions.
341 GVSection[GV] = Sec;
342 GVOffset[GV] = Sec->SectionData.size();
343
344 // Allocate space in the section for the global.
345 for (unsigned i = 0; i < Size; ++i)
Bill Wendling157c4ee2007-01-17 03:49:21 +0000346 TOI->outbyte(Sec->SectionData, 0);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000347}
348
Nate Begemaneb883af2006-08-23 21:08:52 +0000349void MachOWriter::EmitGlobal(GlobalVariable *GV) {
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000350 const Type *Ty = GV->getType()->getElementType();
351 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
352 bool NoInit = !GV->hasInitializer();
Nate Begemand2030e62006-08-26 15:46:34 +0000353
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000354 // If this global has a zero initializer, it is part of the .bss or common
355 // section.
356 if (NoInit || GV->getInitializer()->isNullValue()) {
357 // If this global is part of the common block, add it now. Variables are
358 // part of the common block if they are zero initialized and allowed to be
359 // merged with other symbols.
360 if (NoInit || GV->hasLinkOnceLinkage() || GV->hasWeakLinkage()) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000361 MachOSym ExtOrCommonSym(GV, Mang->getValueName(GV), MachOSym::NO_SECT,TM);
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000362 // For undefined (N_UNDF) external (N_EXT) types, n_value is the size in
363 // bytes of the symbol.
364 ExtOrCommonSym.n_value = Size;
365 // If the symbol is external, we'll put it on a list of symbols whose
366 // addition to the symbol table is being pended until we find a reference
367 if (NoInit)
368 PendingSyms.push_back(ExtOrCommonSym);
369 else
370 SymbolTable.push_back(ExtOrCommonSym);
371 return;
372 }
373 // Otherwise, this symbol is part of the .bss section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000374 MachOSection *BSS = getBSSSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000375 AddSymbolToSection(BSS, GV);
376 return;
377 }
378
379 // Scalar read-only data goes in a literal section if the scalar is 4, 8, or
380 // 16 bytes, or a cstring. Other read only data goes into a regular const
381 // section. Read-write data goes in the data section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000382 MachOSection *Sec = GV->isConstant() ? getConstSection(Ty) : getDataSection();
Nate Begemanf8f2c5a2006-08-25 06:36:58 +0000383 AddSymbolToSection(Sec, GV);
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000384 InitMem(GV->getInitializer(), &Sec->SectionData[0], GVOffset[GV],
385 TM.getTargetData(), Sec->Relocations);
Nate Begemaneb883af2006-08-23 21:08:52 +0000386}
387
388
389bool MachOWriter::runOnMachineFunction(MachineFunction &MF) {
390 // Nothing to do here, this is all done through the MCE object.
391 return false;
392}
393
394bool MachOWriter::doInitialization(Module &M) {
395 // Set the magic value, now that we know the pointer size and endianness
396 Header.setMagic(isLittleEndian, is64Bit);
397
398 // Set the file type
399 // FIXME: this only works for object files, we do not support the creation
400 // of dynamic libraries or executables at this time.
401 Header.filetype = MachOHeader::MH_OBJECT;
402
403 Mang = new Mangler(M);
404 return false;
405}
406
407/// doFinalization - Now that the module has been completely processed, emit
408/// the Mach-O file to 'O'.
409bool MachOWriter::doFinalization(Module &M) {
Nate Begemand2030e62006-08-26 15:46:34 +0000410 // FIXME: we don't handle debug info yet, we should probably do that.
411
Nate Begemaneb883af2006-08-23 21:08:52 +0000412 // Okay, the.text section has been completed, build the .data, .bss, and
413 // "common" sections next.
414 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
415 I != E; ++I)
416 EmitGlobal(I);
417
418 // Emit the header and load commands.
419 EmitHeaderAndLoadCommands();
420
Nate Begeman019f8512006-09-10 23:03:44 +0000421 // Emit the various sections and their relocation info.
Nate Begemaneb883af2006-08-23 21:08:52 +0000422 EmitSections();
423
Nate Begemand2030e62006-08-26 15:46:34 +0000424 // Write the symbol table and the string table to the end of the file.
425 O.write((char*)&SymT[0], SymT.size());
426 O.write((char*)&StrT[0], StrT.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000427
428 // We are done with the abstract symbols.
429 SectionList.clear();
430 SymbolTable.clear();
431 DynamicSymbolTable.clear();
432
433 // Release the name mangler object.
434 delete Mang; Mang = 0;
435 return false;
436}
437
438void MachOWriter::EmitHeaderAndLoadCommands() {
439 // Step #0: Fill in the segment load command size, since we need it to figure
440 // out the rest of the header fields
441 MachOSegment SEG("", is64Bit);
442 SEG.nsects = SectionList.size();
443 SEG.cmdsize = SEG.cmdSize(is64Bit) +
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000444 SEG.nsects * SectionList[0]->cmdSize(is64Bit);
Nate Begemaneb883af2006-08-23 21:08:52 +0000445
446 // Step #1: calculate the number of load commands. We always have at least
447 // one, for the LC_SEGMENT load command, plus two for the normal
448 // and dynamic symbol tables, if there are any symbols.
449 Header.ncmds = SymbolTable.empty() ? 1 : 3;
450
451 // Step #2: calculate the size of the load commands
452 Header.sizeofcmds = SEG.cmdsize;
453 if (!SymbolTable.empty())
454 Header.sizeofcmds += SymTab.cmdsize + DySymTab.cmdsize;
455
456 // Step #3: write the header to the file
457 // Local alias to shortenify coming code.
458 DataBuffer &FH = Header.HeaderData;
Bill Wendling157c4ee2007-01-17 03:49:21 +0000459 TOI->outword(FH, Header.magic);
460 TOI->outword(FH, Header.cputype);
461 TOI->outword(FH, Header.cpusubtype);
462 TOI->outword(FH, Header.filetype);
463 TOI->outword(FH, Header.ncmds);
464 TOI->outword(FH, Header.sizeofcmds);
465 TOI->outword(FH, Header.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000466 if (is64Bit)
Bill Wendling157c4ee2007-01-17 03:49:21 +0000467 TOI->outword(FH, Header.reserved);
Nate Begemaneb883af2006-08-23 21:08:52 +0000468
469 // Step #4: Finish filling in the segment load command and write it out
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000470 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000471 E = SectionList.end(); I != E; ++I)
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000472 SEG.filesize += (*I)->size;
473
Nate Begemaneb883af2006-08-23 21:08:52 +0000474 SEG.vmsize = SEG.filesize;
475 SEG.fileoff = Header.cmdSize(is64Bit) + Header.sizeofcmds;
476
Bill Wendling157c4ee2007-01-17 03:49:21 +0000477 TOI->outword(FH, SEG.cmd);
478 TOI->outword(FH, SEG.cmdsize);
479 TOI->outstring(FH, SEG.segname, 16);
480 TOI->outaddr(FH, SEG.vmaddr);
481 TOI->outaddr(FH, SEG.vmsize);
482 TOI->outaddr(FH, SEG.fileoff);
483 TOI->outaddr(FH, SEG.filesize);
484 TOI->outword(FH, SEG.maxprot);
485 TOI->outword(FH, SEG.initprot);
486 TOI->outword(FH, SEG.nsects);
487 TOI->outword(FH, SEG.flags);
Nate Begemaneb883af2006-08-23 21:08:52 +0000488
Nate Begeman94be2482006-09-08 22:42:09 +0000489 // Step #5: Finish filling in the fields of the MachOSections
490 uint64_t currentAddr = 0;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000491 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begemaneb883af2006-08-23 21:08:52 +0000492 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000493 MachOSection *MOS = *I;
494 MOS->addr = currentAddr;
495 MOS->offset = currentAddr + SEG.fileoff;
Nate Begeman019f8512006-09-10 23:03:44 +0000496
Nate Begeman94be2482006-09-08 22:42:09 +0000497 // FIXME: do we need to do something with alignment here?
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000498 currentAddr += MOS->size;
Nate Begeman94be2482006-09-08 22:42:09 +0000499 }
500
501 // Step #6: Calculate the number of relocations for each section and write out
502 // the section commands for each section
503 currentAddr += SEG.fileoff;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000504 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman94be2482006-09-08 22:42:09 +0000505 E = SectionList.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000506 MachOSection *MOS = *I;
507 // Convert the relocations to target-specific relocations, and fill in the
508 // relocation offset for this section.
509 CalculateRelocations(*MOS);
510 MOS->reloff = MOS->nreloc ? currentAddr : 0;
511 currentAddr += MOS->nreloc * 8;
Nate Begeman94be2482006-09-08 22:42:09 +0000512
513 // write the finalized section command to the output buffer
Bill Wendling157c4ee2007-01-17 03:49:21 +0000514 TOI->outstring(FH, MOS->sectname, 16);
515 TOI->outstring(FH, MOS->segname, 16);
516 TOI->outaddr(FH, MOS->addr);
517 TOI->outaddr(FH, MOS->size);
518 TOI->outword(FH, MOS->offset);
519 TOI->outword(FH, MOS->align);
520 TOI->outword(FH, MOS->reloff);
521 TOI->outword(FH, MOS->nreloc);
522 TOI->outword(FH, MOS->flags);
523 TOI->outword(FH, MOS->reserved1);
524 TOI->outword(FH, MOS->reserved2);
Nate Begemaneb883af2006-08-23 21:08:52 +0000525 if (is64Bit)
Bill Wendling157c4ee2007-01-17 03:49:21 +0000526 TOI->outword(FH, MOS->reserved3);
Nate Begemaneb883af2006-08-23 21:08:52 +0000527 }
528
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000529 // Step #7: Emit the symbol table to temporary buffers, so that we know the
530 // size of the string table when we write the next load command.
531 BufferSymbolAndStringTable();
532
533 // Step #8: Emit LC_SYMTAB/LC_DYSYMTAB load commands
Nate Begeman94be2482006-09-08 22:42:09 +0000534 SymTab.symoff = currentAddr;
Nate Begemaneb883af2006-08-23 21:08:52 +0000535 SymTab.nsyms = SymbolTable.size();
Nate Begemand2030e62006-08-26 15:46:34 +0000536 SymTab.stroff = SymTab.symoff + SymT.size();
537 SymTab.strsize = StrT.size();
Bill Wendling157c4ee2007-01-17 03:49:21 +0000538 TOI->outword(FH, SymTab.cmd);
539 TOI->outword(FH, SymTab.cmdsize);
540 TOI->outword(FH, SymTab.symoff);
541 TOI->outword(FH, SymTab.nsyms);
542 TOI->outword(FH, SymTab.stroff);
543 TOI->outword(FH, SymTab.strsize);
Nate Begemaneb883af2006-08-23 21:08:52 +0000544
545 // FIXME: set DySymTab fields appropriately
Nate Begemand2030e62006-08-26 15:46:34 +0000546 // We should probably just update these in BufferSymbolAndStringTable since
547 // thats where we're partitioning up the different kinds of symbols.
Bill Wendling157c4ee2007-01-17 03:49:21 +0000548 TOI->outword(FH, DySymTab.cmd);
549 TOI->outword(FH, DySymTab.cmdsize);
550 TOI->outword(FH, DySymTab.ilocalsym);
551 TOI->outword(FH, DySymTab.nlocalsym);
552 TOI->outword(FH, DySymTab.iextdefsym);
553 TOI->outword(FH, DySymTab.nextdefsym);
554 TOI->outword(FH, DySymTab.iundefsym);
555 TOI->outword(FH, DySymTab.nundefsym);
556 TOI->outword(FH, DySymTab.tocoff);
557 TOI->outword(FH, DySymTab.ntoc);
558 TOI->outword(FH, DySymTab.modtaboff);
559 TOI->outword(FH, DySymTab.nmodtab);
560 TOI->outword(FH, DySymTab.extrefsymoff);
561 TOI->outword(FH, DySymTab.nextrefsyms);
562 TOI->outword(FH, DySymTab.indirectsymoff);
563 TOI->outword(FH, DySymTab.nindirectsyms);
564 TOI->outword(FH, DySymTab.extreloff);
565 TOI->outword(FH, DySymTab.nextrel);
566 TOI->outword(FH, DySymTab.locreloff);
567 TOI->outword(FH, DySymTab.nlocrel);
Nate Begemaneb883af2006-08-23 21:08:52 +0000568
569 O.write((char*)&FH[0], FH.size());
570}
571
572/// EmitSections - Now that we have constructed the file header and load
573/// commands, emit the data for each section to the file.
574void MachOWriter::EmitSections() {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000575 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000576 E = SectionList.end(); I != E; ++I)
577 // Emit the contents of each section
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000578 O.write((char*)&(*I)->SectionData[0], (*I)->size);
579 for (std::vector<MachOSection*>::iterator I = SectionList.begin(),
Nate Begeman019f8512006-09-10 23:03:44 +0000580 E = SectionList.end(); I != E; ++I)
581 // Emit the relocation entry data for each section.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000582 O.write((char*)&(*I)->RelocBuffer[0], (*I)->RelocBuffer.size());
Nate Begemaneb883af2006-08-23 21:08:52 +0000583}
584
Nate Begemand2030e62006-08-26 15:46:34 +0000585/// PartitionByLocal - Simple boolean predicate that returns true if Sym is
586/// a local symbol rather than an external symbol.
587bool MachOWriter::PartitionByLocal(const MachOSym &Sym) {
Nate Begemand2030e62006-08-26 15:46:34 +0000588 return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
Nate Begemaneb883af2006-08-23 21:08:52 +0000589}
590
Nate Begemand2030e62006-08-26 15:46:34 +0000591/// PartitionByDefined - Simple boolean predicate that returns true if Sym is
592/// defined in this module.
593bool MachOWriter::PartitionByDefined(const MachOSym &Sym) {
594 // FIXME: Do N_ABS or N_INDR count as defined?
595 return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
596}
Nate Begemaneb883af2006-08-23 21:08:52 +0000597
Nate Begemand2030e62006-08-26 15:46:34 +0000598/// BufferSymbolAndStringTable - Sort the symbols we encountered and assign them
599/// each a string table index so that they appear in the correct order in the
600/// output file.
601void MachOWriter::BufferSymbolAndStringTable() {
602 // The order of the symbol table is:
603 // 1. local symbols
604 // 2. defined external symbols (sorted by name)
605 // 3. undefined external symbols (sorted by name)
606
607 // Sort the symbols by name, so that when we partition the symbols by scope
608 // of definition, we won't have to sort by name within each partition.
609 std::sort(SymbolTable.begin(), SymbolTable.end(), MachOSymCmp());
610
611 // Parition the symbol table entries so that all local symbols come before
612 // all symbols with external linkage. { 1 | 2 3 }
613 std::partition(SymbolTable.begin(), SymbolTable.end(), PartitionByLocal);
614
615 // Advance iterator to beginning of external symbols and partition so that
616 // all external symbols defined in this module come before all external
617 // symbols defined elsewhere. { 1 | 2 | 3 }
618 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
619 E = SymbolTable.end(); I != E; ++I) {
620 if (!PartitionByLocal(*I)) {
621 std::partition(I, E, PartitionByDefined);
622 break;
623 }
624 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000625
626 // Calculate the starting index for each of the local, extern defined, and
627 // undefined symbols, as well as the number of each to put in the LC_DYSYMTAB
628 // load command.
629 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
630 E = SymbolTable.end(); I != E; ++I) {
631 if (PartitionByLocal(*I)) {
632 ++DySymTab.nlocalsym;
633 ++DySymTab.iextdefsym;
634 } else if (PartitionByDefined(*I)) {
635 ++DySymTab.nextdefsym;
636 ++DySymTab.iundefsym;
637 } else {
638 ++DySymTab.nundefsym;
639 }
640 }
Nate Begemand2030e62006-08-26 15:46:34 +0000641
Nate Begemaneb883af2006-08-23 21:08:52 +0000642 // Write out a leading zero byte when emitting string table, for n_strx == 0
643 // which means an empty string.
Bill Wendling157c4ee2007-01-17 03:49:21 +0000644 TOI->outbyte(StrT, 0);
Nate Begemaneb883af2006-08-23 21:08:52 +0000645
Nate Begemand2030e62006-08-26 15:46:34 +0000646 // The order of the string table is:
647 // 1. strings for external symbols
648 // 2. strings for local symbols
649 // Since this is the opposite order from the symbol table, which we have just
650 // sorted, we can walk the symbol table backwards to output the string table.
651 for (std::vector<MachOSym>::reverse_iterator I = SymbolTable.rbegin(),
652 E = SymbolTable.rend(); I != E; ++I) {
653 if (I->GVName == "") {
654 I->n_strx = 0;
655 } else {
656 I->n_strx = StrT.size();
Bill Wendling157c4ee2007-01-17 03:49:21 +0000657 TOI->outstring(StrT, I->GVName, I->GVName.length()+1);
Nate Begemand2030e62006-08-26 15:46:34 +0000658 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000659 }
Nate Begemand2030e62006-08-26 15:46:34 +0000660
661 for (std::vector<MachOSym>::iterator I = SymbolTable.begin(),
662 E = SymbolTable.end(); I != E; ++I) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000663 // Add the section base address to the section offset in the n_value field
664 // to calculate the full address.
665 // FIXME: handle symbols where the n_value field is not the address
666 GlobalValue *GV = const_cast<GlobalValue*>(I->GV);
667 if (GV && GVSection[GV])
668 I->n_value += GVSection[GV]->addr;
669
Nate Begemand2030e62006-08-26 15:46:34 +0000670 // Emit nlist to buffer
Bill Wendling157c4ee2007-01-17 03:49:21 +0000671 TOI->outword(SymT, I->n_strx);
672 TOI->outbyte(SymT, I->n_type);
673 TOI->outbyte(SymT, I->n_sect);
674 TOI->outhalf(SymT, I->n_desc);
675 TOI->outaddr(SymT, I->n_value);
Nate Begemand2030e62006-08-26 15:46:34 +0000676 }
Nate Begemaneb883af2006-08-23 21:08:52 +0000677}
Nate Begeman94be2482006-09-08 22:42:09 +0000678
Nate Begeman019f8512006-09-10 23:03:44 +0000679/// CalculateRelocations - For each MachineRelocation in the current section,
680/// calculate the index of the section containing the object to be relocated,
681/// and the offset into that section. From this information, create the
682/// appropriate target-specific MachORelocation type and add buffer it to be
683/// written out after we are finished writing out sections.
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000684void MachOWriter::CalculateRelocations(MachOSection &MOS) {
Nate Begeman019f8512006-09-10 23:03:44 +0000685 for (unsigned i = 0, e = MOS.Relocations.size(); i != e; ++i) {
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000686 MachineRelocation &MR = MOS.Relocations[i];
687 unsigned TargetSection = MR.getConstantVal();
688
689 // Since we may not have seen the GlobalValue we were interested in yet at
690 // the time we emitted the relocation for it, fix it up now so that it
691 // points to the offset into the correct section.
692 if (MR.isGlobalValue()) {
693 GlobalValue *GV = MR.getGlobalValue();
694 MachOSection *MOSPtr = GVSection[GV];
695 intptr_t offset = GVOffset[GV];
696
697 assert(MOSPtr && "Trying to relocate unknown global!");
698
699 TargetSection = MOSPtr->Index;
700 MR.setResultPointer((void*)offset);
701 }
702
703 GetTargetRelocation(MR, MOS, *SectionList[TargetSection-1]);
Nate Begeman019f8512006-09-10 23:03:44 +0000704 }
Nate Begeman019f8512006-09-10 23:03:44 +0000705}
706
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000707// InitMem - Write the value of a Constant to the specified memory location,
708// converting it into bytes and relocations.
709void MachOWriter::InitMem(const Constant *C, void *Addr, intptr_t Offset,
710 const TargetData *TD,
711 std::vector<MachineRelocation> &MRs) {
712 typedef std::pair<const Constant*, intptr_t> CPair;
713 std::vector<CPair> WorkList;
714
715 WorkList.push_back(CPair(C,(intptr_t)Addr + Offset));
716
717 while (!WorkList.empty()) {
718 const Constant *PC = WorkList.back().first;
719 intptr_t PA = WorkList.back().second;
720 WorkList.pop_back();
721
722 if (isa<UndefValue>(PC)) {
723 continue;
724 } else if (const ConstantPacked *CP = dyn_cast<ConstantPacked>(PC)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000725 unsigned ElementSize = TD->getTypeSize(CP->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000726 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
727 WorkList.push_back(CPair(CP->getOperand(i), PA+i*ElementSize));
728 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(PC)) {
729 //
730 // FIXME: Handle ConstantExpression. See EE::getConstantValue()
731 //
732 switch (CE->getOpcode()) {
733 case Instruction::GetElementPtr:
734 case Instruction::Add:
735 default:
736 cerr << "ConstantExpr not handled as global var init: " << *CE << "\n";
737 abort();
738 break;
739 }
740 } else if (PC->getType()->isFirstClassType()) {
741 unsigned char *ptr = (unsigned char *)PA;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000742 switch (PC->getType()->getTypeID()) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000743 case Type::IntegerTyID: {
744 unsigned NumBits = cast<IntegerType>(PC->getType())->getBitWidth();
745 uint64_t val = cast<ConstantInt>(PC)->getZExtValue();
746 if (NumBits <= 8)
747 ptr[0] = val;
748 else if (NumBits <= 16) {
749 if (TD->isBigEndian())
750 val = ByteSwap_16(val);
751 ptr[0] = val;
752 ptr[1] = val >> 8;
753 } else if (NumBits <= 32) {
754 if (TD->isBigEndian())
755 val = ByteSwap_32(val);
756 ptr[0] = val;
757 ptr[1] = val >> 8;
758 ptr[2] = val >> 16;
759 ptr[3] = val >> 24;
760 } else if (NumBits <= 64) {
761 if (TD->isBigEndian())
762 val = ByteSwap_64(val);
763 ptr[0] = val;
764 ptr[1] = val >> 8;
765 ptr[2] = val >> 16;
766 ptr[3] = val >> 24;
767 ptr[4] = val >> 32;
768 ptr[5] = val >> 40;
769 ptr[6] = val >> 48;
770 ptr[7] = val >> 56;
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000771 } else {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000772 assert(0 && "Not implemented: bit widths > 64");
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000773 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000774 break;
775 }
776 case Type::FloatTyID: {
777 uint64_t val = FloatToBits(cast<ConstantFP>(PC)->getValue());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000778 if (TD->isBigEndian())
779 val = ByteSwap_32(val);
780 ptr[0] = val;
781 ptr[1] = val >> 8;
782 ptr[2] = val >> 16;
783 ptr[3] = val >> 24;
784 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000785 }
786 case Type::DoubleTyID: {
787 uint64_t val = DoubleToBits(cast<ConstantFP>(PC)->getValue());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000788 if (TD->isBigEndian())
789 val = ByteSwap_64(val);
790 ptr[0] = val;
791 ptr[1] = val >> 8;
792 ptr[2] = val >> 16;
793 ptr[3] = val >> 24;
794 ptr[4] = val >> 32;
795 ptr[5] = val >> 40;
796 ptr[6] = val >> 48;
797 ptr[7] = val >> 56;
798 break;
Reid Spencera54b7cb2007-01-12 07:05:14 +0000799 }
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000800 case Type::PointerTyID:
801 if (isa<ConstantPointerNull>(C))
802 memset(ptr, 0, TD->getPointerSize());
803 else if (const GlobalValue* GV = dyn_cast<GlobalValue>(C))
804 // FIXME: what about function stubs?
805 MRs.push_back(MachineRelocation::getGV(PA-(intptr_t)Addr,
806 MachineRelocation::VANILLA,
807 const_cast<GlobalValue*>(GV)));
808 else
809 assert(0 && "Unknown constant pointer type!");
810 break;
811 default:
812 cerr << "ERROR: Constant unimp for type: " << *PC->getType() << "\n";
813 abort();
814 }
815 } else if (isa<ConstantAggregateZero>(PC)) {
816 memset((void*)PA, 0, (size_t)TD->getTypeSize(PC->getType()));
817 } else if (const ConstantArray *CPA = dyn_cast<ConstantArray>(PC)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000818 unsigned ElementSize = TD->getTypeSize(CPA->getType()->getElementType());
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000819 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
820 WorkList.push_back(CPair(CPA->getOperand(i), PA+i*ElementSize));
821 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(PC)) {
822 const StructLayout *SL =
823 TD->getStructLayout(cast<StructType>(CPS->getType()));
824 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
825 WorkList.push_back(CPair(CPS->getOperand(i), PA+SL->MemberOffsets[i]));
826 } else {
827 cerr << "Bad Type: " << *PC->getType() << "\n";
828 assert(0 && "Unknown constant type to initialize memory with!");
829 }
830 }
831}
832
833MachOSym::MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
834 TargetMachine &TM) :
835 GV(gv), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), n_sect(sect),
836 n_desc(0), n_value(0) {
837
838 const TargetAsmInfo *TAI = TM.getTargetAsmInfo();
839
Nate Begeman94be2482006-09-08 22:42:09 +0000840 switch (GV->getLinkage()) {
841 default:
842 assert(0 && "Unexpected linkage type!");
843 break;
844 case GlobalValue::WeakLinkage:
845 case GlobalValue::LinkOnceLinkage:
846 assert(!isa<Function>(gv) && "Unexpected linkage type for Function!");
847 case GlobalValue::ExternalLinkage:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000848 GVName = TAI->getGlobalPrefix() + name;
Nate Begeman94be2482006-09-08 22:42:09 +0000849 n_type |= N_EXT;
850 break;
851 case GlobalValue::InternalLinkage:
Nate Begemanbfaaaa62006-12-11 02:20:45 +0000852 GVName = TAI->getPrivateGlobalPrefix() + name;
Nate Begeman94be2482006-09-08 22:42:09 +0000853 break;
854 }
855}