blob: 4a69ac7fa81692846e3e481e0cb0e5e393119cce [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 Lattner4d326fa2003-12-20 01:46:27 +000019#include "JIT.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 Lattnerc19aade2003-12-08 08:06:28 +000030using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000031
Chris Lattnerbd199fb2002-12-24 00:01:05 +000032namespace {
Chris Lattnere7386562003-10-20 05:45:49 +000033 Statistic<> NumBytes("jit", "Number of bytes of machine code compiled");
Chris Lattner4d326fa2003-12-20 01:46:27 +000034 JIT *TheJIT = 0;
Chris Lattnerbd199fb2002-12-24 00:01:05 +000035
Chris Lattner688506d2003-08-14 18:35:27 +000036 /// JITMemoryManager - Manage memory for the JIT code generation in a logical,
37 /// sane way. This splits a large block of MAP_NORESERVE'd memory into two
38 /// sections, one for function stubs, one for the functions themselves. We
39 /// have to do this because we may need to emit a function stub while in the
40 /// middle of emitting a function, and we don't know how large the function we
41 /// are emitting is. This never bothers to release the memory, because when
42 /// we are ready to destroy the JIT, the program exits.
43 class JITMemoryManager {
44 unsigned char *MemBase; // Base of block of memory, start of stub mem
45 unsigned char *FunctionBase; // Start of the function body area
46 unsigned char *CurStubPtr, *CurFunctionPtr;
47 public:
48 JITMemoryManager();
49
50 inline unsigned char *allocateStub(unsigned StubSize);
51 inline unsigned char *startFunctionBody();
52 inline void endFunctionBody(unsigned char *FunctionEnd);
53 };
54}
55
Chris Lattner688506d2003-08-14 18:35:27 +000056// getMemory - Return a pointer to the specified number of bytes, which is
57// mapped as executable readable and writable.
58static void *getMemory(unsigned NumBytes) {
59 if (NumBytes == 0) return 0;
60 static const long pageSize = sysconf(_SC_PAGESIZE);
61 unsigned NumPages = (NumBytes+pageSize-1)/pageSize;
62
Chris Lattnerc52663c2004-05-27 18:03:56 +000063/* FIXME: This should use the proper autoconf flags */
Chris Lattner688506d2003-08-14 18:35:27 +000064#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();
Chris Lattnerc52663c2004-05-27 18:03:56 +000074 return 0;
Chris Lattner688506d2003-08-14 18:35:27 +000075#endif
Brian Gaeke364f86d2003-10-11 03:51:18 +000076
Chris Lattnerc52663c2004-05-27 18:03:56 +000077#ifdef HAVE_MMAP
Chris Lattner6c0398e2004-02-08 19:33:07 +000078 int fd = -1;
Brian Gaeke364f86d2003-10-11 03:51:18 +000079#if defined(__linux__)
Chris Lattner6c0398e2004-02-08 19:33:07 +000080 fd = 0;
Brian Gaeke364f86d2003-10-11 03:51:18 +000081#endif
Chris Lattner688506d2003-08-14 18:35:27 +000082
83 unsigned mmapFlags = MAP_PRIVATE|MAP_ANONYMOUS;
84#ifdef MAP_NORESERVE
85 mmapFlags |= MAP_NORESERVE;
86#endif
87
88 void *pa = mmap(0, pageSize*NumPages, PROT_READ|PROT_WRITE|PROT_EXEC,
Chris Lattner011efae2003-10-06 19:07:41 +000089 mmapFlags, fd, 0);
Chris Lattner688506d2003-08-14 18:35:27 +000090 if (pa == MAP_FAILED) {
91 perror("mmap");
92 abort();
93 }
94 return pa;
Chris Lattnerc52663c2004-05-27 18:03:56 +000095#else
96 std::cerr << "Do not know how to allocate mem for the JIT without mmap!\n";
97 abort();
98 return 0;
99#endif
Chris Lattner688506d2003-08-14 18:35:27 +0000100}
101
102JITMemoryManager::JITMemoryManager() {
103 // Allocate a 16M block of memory...
104 MemBase = (unsigned char*)getMemory(16 << 20);
105 FunctionBase = MemBase + 512*1024; // Use 512k for stubs
106
107 // Allocate stubs backwards from the function base, allocate functions forward
108 // from the function base.
109 CurStubPtr = CurFunctionPtr = FunctionBase;
110}
111
112unsigned char *JITMemoryManager::allocateStub(unsigned StubSize) {
113 CurStubPtr -= StubSize;
114 if (CurStubPtr < MemBase) {
115 std::cerr << "JIT ran out of memory for function stubs!\n";
116 abort();
117 }
118 return CurStubPtr;
119}
120
121unsigned char *JITMemoryManager::startFunctionBody() {
122 // Round up to an even multiple of 4 bytes, this should eventually be target
123 // specific.
124 return (unsigned char*)(((intptr_t)CurFunctionPtr + 3) & ~3);
125}
126
127void JITMemoryManager::endFunctionBody(unsigned char *FunctionEnd) {
128 assert(FunctionEnd > CurFunctionPtr);
129 CurFunctionPtr = FunctionEnd;
130}
131
132
133
134namespace {
Brian Gaeke6020ddd2003-10-16 23:33:38 +0000135 /// Emitter - The JIT implementation of the MachineCodeEmitter, which is used
Chris Lattner688506d2003-08-14 18:35:27 +0000136 /// to output functions to memory for execution.
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000137 class Emitter : public MachineCodeEmitter {
Chris Lattner688506d2003-08-14 18:35:27 +0000138 JITMemoryManager MemMgr;
139
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000140 // CurBlock - The start of the current block of memory. CurByte - The
141 // current byte being emitted to.
Chris Lattner6125fdd2003-05-09 03:30:07 +0000142 unsigned char *CurBlock, *CurByte;
143
144 // When outputting a function stub in the context of some other function, we
145 // save CurBlock and CurByte here.
146 unsigned char *SavedCurBlock, *SavedCurByte;
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000147
148 // ConstantPoolAddresses - Contains the location for each entry in the
149 // constant pool.
Chris Lattner1cc08382003-01-13 01:00:12 +0000150 std::vector<void*> ConstantPoolAddresses;
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000151 public:
Chris Lattner4d326fa2003-12-20 01:46:27 +0000152 Emitter(JIT &jit) { TheJIT = &jit; }
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000153
154 virtual void startFunction(MachineFunction &F);
155 virtual void finishFunction(MachineFunction &F);
Chris Lattner1cc08382003-01-13 01:00:12 +0000156 virtual void emitConstantPool(MachineConstantPool *MCP);
Chris Lattner6125fdd2003-05-09 03:30:07 +0000157 virtual void startFunctionStub(const Function &F, unsigned StubSize);
158 virtual void* finishFunctionStub(const Function &F);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000159 virtual void emitByte(unsigned char B);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000160 virtual void emitWord(unsigned W);
Brian Gaekeaea1b582004-04-23 17:11:14 +0000161 virtual void emitWordAt(unsigned W, unsigned *Ptr);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000162
163 virtual uint64_t getGlobalValueAddress(GlobalValue *V);
164 virtual uint64_t getGlobalValueAddress(const std::string &Name);
165 virtual uint64_t getConstantPoolEntryAddress(unsigned Entry);
166 virtual uint64_t getCurrentPCValue();
167
168 // forceCompilationOf - Force the compilation of the specified function, and
169 // return its address, because we REALLY need the address now.
170 //
171 // FIXME: This is JIT specific!
172 //
173 virtual uint64_t forceCompilationOf(Function *F);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000174 };
175}
176
Chris Lattner4d326fa2003-12-20 01:46:27 +0000177MachineCodeEmitter *JIT::createEmitter(JIT &jit) {
178 return new Emitter(jit);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000179}
180
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000181void Emitter::startFunction(MachineFunction &F) {
Chris Lattner688506d2003-08-14 18:35:27 +0000182 CurByte = CurBlock = MemMgr.startFunctionBody();
Chris Lattner4d326fa2003-12-20 01:46:27 +0000183 TheJIT->addGlobalMapping(F.getFunction(), CurBlock);
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000184}
185
186void Emitter::finishFunction(MachineFunction &F) {
Chris Lattner688506d2003-08-14 18:35:27 +0000187 MemMgr.endFunctionBody(CurByte);
Chris Lattner1cc08382003-01-13 01:00:12 +0000188 ConstantPoolAddresses.clear();
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000189 NumBytes += CurByte-CurBlock;
190
Brian Gaeke02c26b62003-06-30 18:06:20 +0000191 DEBUG(std::cerr << "Finished CodeGen of [" << (void*)CurBlock
Misha Brukman1d440852003-06-06 06:52:35 +0000192 << "] Function: " << F.getFunction()->getName()
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000193 << ": " << CurByte-CurBlock << " bytes of text\n");
194}
195
Chris Lattner1cc08382003-01-13 01:00:12 +0000196void Emitter::emitConstantPool(MachineConstantPool *MCP) {
197 const std::vector<Constant*> &Constants = MCP->getConstants();
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000198 if (Constants.empty()) return;
199
200 std::vector<unsigned> ConstantOffset;
201 ConstantOffset.reserve(Constants.size());
202
203 // Calculate how much space we will need for all the constants, and the offset
204 // each one will live in.
205 unsigned TotalSize = 0;
Chris Lattner1cc08382003-01-13 01:00:12 +0000206 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000207 const Type *Ty = Constants[i]->getType();
Chris Lattner4d326fa2003-12-20 01:46:27 +0000208 unsigned Size = TheJIT->getTargetData().getTypeSize(Ty);
209 unsigned Alignment = TheJIT->getTargetData().getTypeAlignment(Ty);
Chris Lattner2c0a6a12003-11-30 04:23:21 +0000210 // Make sure to take into account the alignment requirements of the type.
211 TotalSize = (TotalSize + Alignment-1) & ~(Alignment-1);
212
213 // Remember the offset this element lives at.
214 ConstantOffset.push_back(TotalSize);
215 TotalSize += Size; // Reserve space for the constant.
216 }
217
218 // Now that we know how much memory to allocate, do so.
219 char *Pool = new char[TotalSize];
220
221 // Actually output all of the constants, and remember their addresses.
222 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
223 void *Addr = Pool + ConstantOffset[i];
Chris Lattner4d326fa2003-12-20 01:46:27 +0000224 TheJIT->InitializeMemory(Constants[i], Addr);
Misha Brukman91de3522003-11-30 00:50:53 +0000225 ConstantPoolAddresses.push_back(Addr);
Chris Lattner1cc08382003-01-13 01:00:12 +0000226 }
227}
228
Chris Lattner6125fdd2003-05-09 03:30:07 +0000229void Emitter::startFunctionStub(const Function &F, unsigned StubSize) {
230 SavedCurBlock = CurBlock; SavedCurByte = CurByte;
Chris Lattner688506d2003-08-14 18:35:27 +0000231 CurByte = CurBlock = MemMgr.allocateStub(StubSize);
Chris Lattner6125fdd2003-05-09 03:30:07 +0000232}
233
234void *Emitter::finishFunctionStub(const Function &F) {
235 NumBytes += CurByte-CurBlock;
236 DEBUG(std::cerr << "Finished CodeGen of [0x" << std::hex
237 << (unsigned)(intptr_t)CurBlock
238 << std::dec << "] Function stub for: " << F.getName()
239 << ": " << CurByte-CurBlock << " bytes of text\n");
240 std::swap(CurBlock, SavedCurBlock);
241 CurByte = SavedCurByte;
242 return SavedCurBlock;
243}
244
Chris Lattnerbd199fb2002-12-24 00:01:05 +0000245void Emitter::emitByte(unsigned char B) {
246 *CurByte++ = B; // Write the byte to memory
247}
248
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000249void Emitter::emitWord(unsigned W) {
Chris Lattner688506d2003-08-14 18:35:27 +0000250 // This won't work if the endianness of the host and target don't agree! (For
251 // a JIT this can't happen though. :)
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000252 *(unsigned*)CurByte = W;
253 CurByte += sizeof(unsigned);
254}
255
Brian Gaekeaea1b582004-04-23 17:11:14 +0000256void Emitter::emitWordAt(unsigned W, unsigned *Ptr) {
257 *Ptr = W;
258}
259
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000260uint64_t Emitter::getGlobalValueAddress(GlobalValue *V) {
261 // Try looking up the function to see if it is already compiled, if not return
262 // 0.
Chris Lattnerc07ed132003-12-20 03:36:47 +0000263 if (isa<Function>(V))
264 return (intptr_t)TheJIT->getPointerToGlobalIfAvailable(V);
265 else {
266 return (intptr_t)TheJIT->getOrEmitGlobalVariable(cast<GlobalVariable>(V));
267 }
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000268}
269uint64_t Emitter::getGlobalValueAddress(const std::string &Name) {
Chris Lattner4d326fa2003-12-20 01:46:27 +0000270 return (intptr_t)TheJIT->getPointerToNamedFunction(Name);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000271}
272
273// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
274// in the constant pool that was last emitted with the 'emitConstantPool'
275// method.
276//
277uint64_t Emitter::getConstantPoolEntryAddress(unsigned ConstantNum) {
278 assert(ConstantNum < ConstantPoolAddresses.size() &&
279 "Invalid ConstantPoolIndex!");
280 return (intptr_t)ConstantPoolAddresses[ConstantNum];
281}
282
283// getCurrentPCValue - This returns the address that the next emitted byte
284// will be output to.
285//
286uint64_t Emitter::getCurrentPCValue() {
287 return (intptr_t)CurByte;
288}
289
290uint64_t Emitter::forceCompilationOf(Function *F) {
Chris Lattner4d326fa2003-12-20 01:46:27 +0000291 return (intptr_t)TheJIT->getPointerToFunction(F);
Chris Lattnerbba1b6d2003-06-01 23:24:36 +0000292}
293
Misha Brukmand69c1e62003-07-28 19:09:06 +0000294// getPointerToNamedFunction - This function is used as a global wrapper to
Chris Lattner4d326fa2003-12-20 01:46:27 +0000295// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
Misha Brukmand69c1e62003-07-28 19:09:06 +0000296// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
297// need to resolve function(s) that are being mis-codegenerated, so we need to
298// resolve their addresses at runtime, and this is the way to do it.
299extern "C" {
300 void *getPointerToNamedFunction(const char *Name) {
Chris Lattner4d326fa2003-12-20 01:46:27 +0000301 Module &M = TheJIT->getModule();
Misha Brukmand69c1e62003-07-28 19:09:06 +0000302 if (Function *F = M.getNamedFunction(Name))
Chris Lattner4d326fa2003-12-20 01:46:27 +0000303 return TheJIT->getPointerToFunction(F);
304 return TheJIT->getPointerToNamedFunction(Name);
Misha Brukmand69c1e62003-07-28 19:09:06 +0000305 }
306}