blob: 1d04f9920a2dafcf1c758bbe7161dc1aecfedbf0 [file] [log] [blame]
Chris Lattnerbd199fb2002-12-24 00:01:05 +00001//===-- Emitter.cpp - Write machine code to executable memory -------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerbd199fb2002-12-24 00:01:05 +00009//
10// This file defines a MachineCodeEmitter object that is used by Jello to write
11// machine code to memory and remember where relocatable values lie.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner3785fad2003-08-05 17:00:32 +000015#define DEBUG_TYPE "jit"
Misha Brukman36d10ef2003-09-10 20:52:05 +000016#ifndef _POSIX_MAPPED_FILES
17#define _POSIX_MAPPED_FILES
18#endif
Chris Lattnerbd199fb2002-12-24 00:01:05 +000019#include "VM.h"
Chris Lattner2c0a6a12003-11-30 04:23:21 +000020#include "llvm/Constant.h"
21#include "llvm/Module.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000022#include "llvm/CodeGen/MachineCodeEmitter.h"
23#include "llvm/CodeGen/MachineFunction.h"
Chris Lattner1cc08382003-01-13 01:00:12 +000024#include "llvm/CodeGen/MachineConstantPool.h"
25#include "llvm/Target/TargetData.h"
Chris Lattnerc648dab2003-08-01 22:13:59 +000026#include "Support/Debug.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000027#include "Support/Statistic.h"
Misha Brukman36d10ef2003-09-10 20:52:05 +000028#include "Config/unistd.h"
29#include "Config/sys/mman.h"
Chris Lattnerbd199fb2002-12-24 00:01:05 +000030
Brian Gaeked0fde302003-11-11 22:41:34 +000031namespace llvm {
32
Chris Lattnerbd199fb2002-12-24 00:01:05 +000033namespace {
Chris Lattnere7386562003-10-20 05:45:49 +000034 Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
Misha Brukmand69c1e62003-07-28 19:09:06 +000035 VM *TheVM = 0;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000036
Chris Lattner688506d2003-08-14 18:35:27 +000037 /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
38 /// sane way. This splits a large block of MAP_NORESERVE'd memory into two
39 /// sections, one for function stubs, one for the functions themselves. We
40 /// have to do this because we may need to emit a function stub while in the
41 /// middle of emitting a function, and we don't know how large the function we
42 /// are emitting is. This never bothers to release the memory, because when
43 /// we are ready to destroy the JIT, the program exits.
44 class JITMemoryManager {
45 unsigned char *MemBase; // Base of block of memory, start of stub mem
46 unsigned char *FunctionBase; // Start of the function body area
47 unsigned char *CurStubPtr, *CurFunctionPtr;
48 public:
49 JITMemoryManager();
50
51 inline unsigned char *allocateStub(unsigned StubSize);
52 inline unsigned char *startFunctionBody();
53 inline void endFunctionBody(unsigned char *FunctionEnd);
54 };
55}
56
Chris Lattner688506d2003-08-14 18:35:27 +000057// getMemory - Return a pointer to the specified number of bytes, which is
58// mapped as executable readable and writable.
59static void *getMemory(unsigned NumBytes) {
60 if (NumBytes == 0) return 0;
61 static const long pageSize = sysconf(_SC_PAGESIZE);
62 unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
63
64#if defined(i386) || defined(__i386__) || defined(__x86__)
65 /* Linux and *BSD tend to have these flags named differently. */
66#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
67# define MAP_ANONYMOUS MAP_ANON
68#endif /* defined(MAP_ANON) && !defined(MAP_ANONYMOUS) */
Chris Lattner688506d2003-08-14 18:35:27 +000069#elif defined(sparc) || defined(__sparc__) || defined(__sparcv9)
Brian Gaeke364f86d2003-10-11 03:51:18 +000070/* nothing */
Chris Lattner688506d2003-08-14 18:35:27 +000071#else
72 std::cerr << "This architecture is not supported by the JIT!\n";
73 abort();
74#endif
Brian Gaeke364f86d2003-10-11 03:51:18 +000075
76#if defined(__linux__)
77#define fd 0
78#else
79#define fd -1
80#endif
Chris Lattner688506d2003-08-14 18:35:27 +000081
82 unsigned mmapFlags = MAP_PRIVATE|MAP_ANONYMOUS;
83#ifdef MAP_NORESERVE
84 mmapFlags |= MAP_NORESERVE;
85#endif
86
87 void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
Chris Lattner011efae2003-10-06 19:07:41 +000088 mmapFlags, fd, 0);
Chris Lattner688506d2003-08-14 18:35:27 +000089 if (pa == MAP_FAILED) {
90 perror("mmap");
91 abort();
92 }
93 return pa;
94}
95
96JITMemoryManager::JITMemoryManager() {
97 // Allocate a 16M block of memory...
98 MemBase = (unsigned char*)getMemory(16 << 20);
99 FunctionBase = MemBase + 512*1024; // Use 512k for stubs
100
101 // Allocate stubs backwards from the function base, allocate functions forward
102 // from the function base.
103 CurStubPtr = CurFunctionPtr = FunctionBase;
104}
105
106unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
107 CurStubPtr -= StubSize;
108 if (CurStubPtr < MemBase) {
109 std::cerr << "JIT ran out of memory for function stubs!\n";
110 abort();
111 }
112 return CurStubPtr;
113}
114
115unsigned char *JITMemoryManager::startFunctionBody() {
116 // Round up to an even multiple of 4 bytes, this should eventually be target
117 // specific.
118 return (unsigned char*)(((intptr_t)CurFunctionPtr + 3) & ~3);
119}
120
121void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
122 assert(FunctionEnd > CurFunctionPtr);
123 CurFunctionPtr = FunctionEnd;
124}
125
126
127
128namespace {
Brian Gaeke6020ddd2003-10-16 23:33:38 +0000129 /// Emitter - The JIT implementation of the MachineCodeEmitter, which is used
Chris Lattner688506d2003-08-14 18:35:27 +0000130 /// to output functions to memory for execution.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000131 class Emitter : public MachineCodeEmitter {
Chris Lattner688506d2003-08-14 18:35:27 +0000132 JITMemoryManager MemMgr;
133
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000134 // CurBlock - The start of the current block of memory. CurByte - The
135 // current byte being emitted to.
Chris Lattner6125fdd2003-05-09 03:30:07 +0000136 unsigned char *CurBlock, *CurByte;
137
138 // When outputting a function stub in the context of some other function, we
139 // save CurBlock and CurByte here.
140 unsigned char *SavedCurBlock, *SavedCurByte;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000141
142 // ConstantPoolAddresses - Contains the location for each entry in the
143 // constant pool.
Chris Lattner1cc08382003-01-13 01:00:12 +0000144 std::vector<void*> ConstantPoolAddresses;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000145 public:
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000146 Emitter(VM &vm) { TheVM = &vm; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000147
148 virtual void startFunction(MachineFunction &F);
149 virtual void finishFunction(MachineFunction &F);
Chris Lattner1cc08382003-01-13 01:00:12 +0000150 virtual void emitConstantPool(MachineConstantPool *MCP);
Chris Lattner6125fdd2003-05-09 03:30:07 +0000151 virtual void startFunctionStub(const Function &F, unsigned StubSize);
152 virtual void* finishFunctionStub(const Function &F);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000153 virtual void emitByte(unsigned char B);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000154 virtual void emitWord(unsigned W);
155
156 virtual uint64_t getGlobalValueAddress(GlobalValue *V);
157 virtual uint64_t getGlobalValueAddress(const std::string &Name);
158 virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
159 virtual uint64_t getCurrentPCValue();
160
161 // forceCompilationOf - Force the compilation of the specified function, and
162 // return its address, because we REALLY need the address now.
163 //
164 // FIXME: This is JIT specific!
165 //
166 virtual uint64_t forceCompilationOf(Function *F);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000167 };
168}
169
Misha Brukman906f5fa2003-06-02 03:23:16 +0000170MachineCodeEmitter *VM::createEmitter(VM &V) {
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000171 return new Emitter(V);
172}
173
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000174void Emitter::startFunction(MachineFunction &F) {
Chris Lattner688506d2003-08-14 18:35:27 +0000175 CurByte = CurBlock = MemMgr.startFunctionBody();
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000176 TheVM->addGlobalMapping(F.getFunction(), CurBlock);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000177}
178
179void Emitter::finishFunction(MachineFunction &F) {
Chris Lattner688506d2003-08-14 18:35:27 +0000180 MemMgr.endFunctionBody(CurByte);
Chris Lattner1cc08382003-01-13 01:00:12 +0000181 ConstantPoolAddresses.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000182 NumBytes += CurByte-CurBlock;
183
Brian Gaeke02c26b62003-06-30 18:06:20 +0000184 DEBUG(std::cerr << "Finished CodeGen of [" << (void*)CurBlock
Misha Brukman1d440852003-06-06 06:52:35 +0000185 << "] Function: " << F.getFunction()->getName()
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000186 << ": " << CurByte-CurBlock << " bytes of text\n");
187}
188
Chris Lattner1cc08382003-01-13 01:00:12 +0000189void Emitter::emitConstantPool(MachineConstantPool *MCP) {
190 const std::vector<Constant*> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000191 if (Constants.empty()) return;
192
193 std::vector<unsigned> ConstantOffset;
194 ConstantOffset.reserve(Constants.size());
195
196 // Calculate how much space we will need for all the constants, and the offset
197 // each one will live in.
198 unsigned TotalSize = 0;
Chris Lattner1cc08382003-01-13 01:00:12 +0000199 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000200 const Type *Ty = Constants[i]->getType();
201 unsigned Size = TheVM->getTargetData().getTypeSize(Ty);
202 unsigned Alignment = TheVM->getTargetData().getTypeAlignment(Ty);
203 // Make sure to take into account the alignment requirements of the type.
204 TotalSize = (TotalSize + Alignment-1) & ~(Alignment-1);
205
206 // Remember the offset this element lives at.
207 ConstantOffset.push_back(TotalSize);
208 TotalSize += Size; // Reserve space for the constant.
209 }
210
211 // Now that we know how much memory to allocate, do so.
212 char *Pool = new char[TotalSize];
213
214 // Actually output all of the constants, and remember their addresses.
215 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
216 void *Addr = Pool + ConstantOffset[i];
Misha Brukman91de3522003-11-30 00:50:53 +0000217 TheVM->InitializeMemory(Constants[i], Addr);
218 ConstantPoolAddresses.push_back(Addr);
Chris Lattner1cc08382003-01-13 01:00:12 +0000219 }
220}
221
Chris Lattner6125fdd2003-05-09 03:30:07 +0000222void Emitter::startFunctionStub(const Function &F, unsigned StubSize) {
223 SavedCurBlock = CurBlock; SavedCurByte = CurByte;
Chris Lattner688506d2003-08-14 18:35:27 +0000224 CurByte = CurBlock = MemMgr.allocateStub(StubSize);
Chris Lattner6125fdd2003-05-09 03:30:07 +0000225}
226
227void *Emitter::finishFunctionStub(const Function &F) {
228 NumBytes += CurByte-CurBlock;
229 DEBUG(std::cerr << "Finished CodeGen of [0x" << std::hex
230 << (unsigned)(intptr_t)CurBlock
231 << std::dec << "] Function stub for: " << F.getName()
232 << ": " << CurByte-CurBlock << " bytes of text\n");
233 std::swap(CurBlock, SavedCurBlock);
234 CurByte = SavedCurByte;
235 return SavedCurBlock;
236}
237
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000238void Emitter::emitByte(unsigned char B) {
239 *CurByte++ = B; // Write the byte to memory
240}
241
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000242void Emitter::emitWord(unsigned W) {
Chris Lattner688506d2003-08-14 18:35:27 +0000243 // This won't work if the endianness of the host and target don't agree! (For
244 // a JIT this can't happen though. :)
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000245 *(unsigned*)CurByte = W;
246 CurByte += sizeof(unsigned);
247}
248
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000249uint64_t Emitter::getGlobalValueAddress(GlobalValue *V) {
250 // Try looking up the function to see if it is already compiled, if not return
251 // 0.
252 return (intptr_t)TheVM->getPointerToGlobalIfAvailable(V);
253}
254uint64_t Emitter::getGlobalValueAddress(const std::string &Name) {
255 return (intptr_t)TheVM->getPointerToNamedFunction(Name);
256}
257
258// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
259// in the constant pool that was last emitted with the 'emitConstantPool'
260// method.
261//
262uint64_t Emitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
263 assert(ConstantNum < ConstantPoolAddresses.size() &&
264 "Invalid ConstantPoolIndex!");
265 return (intptr_t)ConstantPoolAddresses[ConstantNum];
266}
267
268// getCurrentPCValue - This returns the address that the next emitted byte
269// will be output to.
270//
271uint64_t Emitter::getCurrentPCValue() {
272 return (intptr_t)CurByte;
273}
274
275uint64_t Emitter::forceCompilationOf(Function *F) {
276 return (intptr_t)TheVM->getPointerToFunction(F);
277}
278
Misha Brukmand69c1e62003-07-28 19:09:06 +0000279// getPointerToNamedFunction - This function is used as a global wrapper to
280// VM::getPointerToNamedFunction for the purpose of resolving symbols when
281// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
282// need to resolve function(s) that are being mis-codegenerated, so we need to
283// resolve their addresses at runtime, and this is the way to do it.
284extern "C" {
285 void *getPointerToNamedFunction(const char *Name) {
286 Module &M = TheVM->getModule();
287 if (Function *F = M.getNamedFunction(Name))
288 return TheVM->getPointerToFunction(F);
289 return TheVM->getPointerToNamedFunction(Name);
290 }
291}
Brian Gaeked0fde302003-11-11 22:41:34 +0000292
293} // End llvm namespace