blob: 049b3bc4a368061a5b4089e074fba9dea3e3e59f [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines a MachineCodeEmitter object that is used by the JIT to
11// write machine code to memory and remember where relocatable values are.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "jit"
16#include "JIT.h"
17#include "llvm/Constant.h"
18#include "llvm/Module.h"
19#include "llvm/Type.h"
20#include "llvm/CodeGen/MachineCodeEmitter.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineConstantPool.h"
23#include "llvm/CodeGen/MachineJumpTableInfo.h"
24#include "llvm/CodeGen/MachineRelocation.h"
Chris Lattnerc8ad39c2007-12-05 23:39:57 +000025#include "llvm/ExecutionEngine/JITMemoryManager.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000026#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetJITInfo.h"
28#include "llvm/Target/TargetMachine.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/MutexGuard.h"
31#include "llvm/System/Disassembler.h"
32#include "llvm/ADT/Statistic.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include <algorithm>
34using namespace llvm;
35
36STATISTIC(NumBytes, "Number of bytes of machine code compiled");
37STATISTIC(NumRelos, "Number of relocations applied");
38static JIT *TheJIT = 0;
39
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040
41//===----------------------------------------------------------------------===//
42// JIT lazy compilation code.
43//
44namespace {
45 class JITResolverState {
46 private:
47 /// FunctionToStubMap - Keep track of the stub created for a particular
48 /// function so that we can reuse them if necessary.
49 std::map<Function*, void*> FunctionToStubMap;
50
51 /// StubToFunctionMap - Keep track of the function that each stub
52 /// corresponds to.
53 std::map<void*, Function*> StubToFunctionMap;
54
Evan Cheng28e7e162008-01-04 10:46:51 +000055 /// GlobalToLazyPtrMap - Keep track of the lazy pointer created for a
56 /// particular GlobalVariable so that we can reuse them if necessary.
57 std::map<GlobalValue*, void*> GlobalToLazyPtrMap;
58
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059 public:
60 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
61 assert(locked.holds(TheJIT->lock));
62 return FunctionToStubMap;
63 }
64
65 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
66 assert(locked.holds(TheJIT->lock));
67 return StubToFunctionMap;
68 }
Evan Cheng28e7e162008-01-04 10:46:51 +000069
70 std::map<GlobalValue*, void*>&
71 getGlobalToLazyPtrMap(const MutexGuard& locked) {
72 assert(locked.holds(TheJIT->lock));
73 return GlobalToLazyPtrMap;
74 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000075 };
76
77 /// JITResolver - Keep track of, and resolve, call sites for functions that
78 /// have not yet been compiled.
79 class JITResolver {
80 /// LazyResolverFn - The target lazy resolver function that we actually
81 /// rewrite instructions to use.
82 TargetJITInfo::LazyResolverFn LazyResolverFn;
83
84 JITResolverState state;
85
86 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
87 /// external functions.
88 std::map<void*, void*> ExternalFnToStubMap;
89
90 //map addresses to indexes in the GOT
91 std::map<void*, unsigned> revGOTMap;
92 unsigned nextGOTIndex;
93
94 static JITResolver *TheJITResolver;
95 public:
96 JITResolver(JIT &jit) : nextGOTIndex(0) {
97 TheJIT = &jit;
98
99 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
100 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
101 TheJITResolver = this;
102 }
103
104 ~JITResolver() {
105 TheJITResolver = 0;
106 }
107
108 /// getFunctionStub - This returns a pointer to a function stub, creating
109 /// one on demand as needed.
110 void *getFunctionStub(Function *F);
111
112 /// getExternalFunctionStub - Return a stub for the function at the
113 /// specified address, created lazily on demand.
114 void *getExternalFunctionStub(void *FnAddr);
115
Evan Cheng28e7e162008-01-04 10:46:51 +0000116 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
117 /// GV address.
118 void *getGlobalValueLazyPtr(GlobalValue *V, void *GVAddress);
119
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120 /// AddCallbackAtLocation - If the target is capable of rewriting an
121 /// instruction without the use of a stub, record the location of the use so
122 /// we know which function is being used at the location.
123 void *AddCallbackAtLocation(Function *F, void *Location) {
124 MutexGuard locked(TheJIT->lock);
125 /// Get the target-specific JIT resolver function.
126 state.getStubToFunctionMap(locked)[Location] = F;
127 return (void*)(intptr_t)LazyResolverFn;
128 }
129
130 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000131 /// an address. This function only manages slots, it does not manage the
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132 /// contents of the slots or the memory associated with the GOT.
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000133 unsigned getGOTIndexForAddr(void *addr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000134
135 /// JITCompilerFn - This function is called to resolve a stub to a compiled
136 /// address. If the LLVM Function corresponding to the stub has not yet
137 /// been compiled, this function compiles it first.
138 static void *JITCompilerFn(void *Stub);
139 };
140}
141
142JITResolver *JITResolver::TheJITResolver = 0;
143
144#if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
145 defined(__APPLE__)
146extern "C" void sys_icache_invalidate(const void *Addr, size_t len);
147#endif
148
149/// synchronizeICache - On some targets, the JIT emitted code must be
150/// explicitly refetched to ensure correct execution.
151static void synchronizeICache(const void *Addr, size_t len) {
152#if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \
153 defined(__APPLE__)
154 sys_icache_invalidate(Addr, len);
155#endif
156}
157
158/// getFunctionStub - This returns a pointer to a function stub, creating
159/// one on demand as needed.
160void *JITResolver::getFunctionStub(Function *F) {
161 MutexGuard locked(TheJIT->lock);
162
163 // If we already have a stub for this function, recycle it.
164 void *&Stub = state.getFunctionToStubMap(locked)[F];
165 if (Stub) return Stub;
166
167 // Call the lazy resolver function unless we already KNOW it is an external
168 // function, in which case we just skip the lazy resolution step.
169 void *Actual = (void*)(intptr_t)LazyResolverFn;
170 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode())
171 Actual = TheJIT->getPointerToFunction(F);
172
173 // Otherwise, codegen a new stub. For now, the stub will call the lazy
174 // resolver function.
175 Stub = TheJIT->getJITInfo().emitFunctionStub(Actual,
176 *TheJIT->getCodeEmitter());
177
178 if (Actual != (void*)(intptr_t)LazyResolverFn) {
179 // If we are getting the stub for an external function, we really want the
180 // address of the stub in the GlobalAddressMap for the JIT, not the address
181 // of the external function.
182 TheJIT->updateGlobalMapping(F, Stub);
183 }
184
185 // Invalidate the icache if necessary.
186 synchronizeICache(Stub, TheJIT->getCodeEmitter()->getCurrentPCValue() -
187 (intptr_t)Stub);
188
189 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
190 << F->getName() << "'\n";
191
192 // Finally, keep track of the stub-to-Function mapping so that the
193 // JITCompilerFn knows which function to compile!
194 state.getStubToFunctionMap(locked)[Stub] = F;
195 return Stub;
196}
197
Evan Cheng28e7e162008-01-04 10:46:51 +0000198/// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
199/// GV address.
200void *JITResolver::getGlobalValueLazyPtr(GlobalValue *GV, void *GVAddress) {
201 MutexGuard locked(TheJIT->lock);
202
203 // If we already have a stub for this global variable, recycle it.
204 void *&LazyPtr = state.getGlobalToLazyPtrMap(locked)[GV];
205 if (LazyPtr) return LazyPtr;
206
207 // Otherwise, codegen a new lazy pointer.
208 LazyPtr = TheJIT->getJITInfo().emitGlobalValueLazyPtr(GVAddress,
209 *TheJIT->getCodeEmitter());
210
211 DOUT << "JIT: Stub emitted at [" << LazyPtr << "] for GV '"
212 << GV->getName() << "'\n";
213
214 return LazyPtr;
215}
216
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217/// getExternalFunctionStub - Return a stub for the function at the
218/// specified address, created lazily on demand.
219void *JITResolver::getExternalFunctionStub(void *FnAddr) {
220 // If we already have a stub for this function, recycle it.
221 void *&Stub = ExternalFnToStubMap[FnAddr];
222 if (Stub) return Stub;
223
224 Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr,
225 *TheJIT->getCodeEmitter());
226
227 // Invalidate the icache if necessary.
228 synchronizeICache(Stub, TheJIT->getCodeEmitter()->getCurrentPCValue() -
229 (intptr_t)Stub);
230
231 DOUT << "JIT: Stub emitted at [" << Stub
232 << "] for external function at '" << FnAddr << "'\n";
233 return Stub;
234}
235
236unsigned JITResolver::getGOTIndexForAddr(void* addr) {
237 unsigned idx = revGOTMap[addr];
238 if (!idx) {
239 idx = ++nextGOTIndex;
240 revGOTMap[addr] = idx;
241 DOUT << "Adding GOT entry " << idx
242 << " for addr " << addr << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000243 }
244 return idx;
245}
246
247/// JITCompilerFn - This function is called when a lazy compilation stub has
248/// been entered. It looks up which function this stub corresponds to, compiles
249/// it if necessary, then returns the resultant function pointer.
250void *JITResolver::JITCompilerFn(void *Stub) {
251 JITResolver &JR = *TheJITResolver;
252
253 MutexGuard locked(TheJIT->lock);
254
255 // The address given to us for the stub may not be exactly right, it might be
256 // a little bit after the stub. As such, use upper_bound to find it.
257 std::map<void*, Function*>::iterator I =
258 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
259 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
260 "This is not a known stub!");
261 Function *F = (--I)->second;
262
263 // If we have already code generated the function, just return the address.
264 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
265
266 if (!Result) {
267 // Otherwise we don't have it, do lazy compilation now.
268
269 // If lazy compilation is disabled, emit a useful error message and abort.
270 if (TheJIT->isLazyCompilationDisabled()) {
271 cerr << "LLVM JIT requested to do lazy compilation of function '"
272 << F->getName() << "' when lazy compiles are disabled!\n";
273 abort();
274 }
275
276 // We might like to remove the stub from the StubToFunction map.
277 // We can't do that! Multiple threads could be stuck, waiting to acquire the
278 // lock above. As soon as the 1st function finishes compiling the function,
279 // the next one will be released, and needs to be able to find the function
280 // it needs to call.
281 //JR.state.getStubToFunctionMap(locked).erase(I);
282
283 DOUT << "JIT: Lazily resolving function '" << F->getName()
284 << "' In stub ptr = " << Stub << " actual ptr = "
285 << I->first << "\n";
286
287 Result = TheJIT->getPointerToFunction(F);
288 }
289
290 // We don't need to reuse this stub in the future, as F is now compiled.
291 JR.state.getFunctionToStubMap(locked).erase(F);
292
293 // FIXME: We could rewrite all references to this stub if we knew them.
294
295 // What we will do is set the compiled function address to map to the
296 // same GOT entry as the stub so that later clients may update the GOT
297 // if they see it still using the stub address.
298 // Note: this is done so the Resolver doesn't have to manage GOT memory
299 // Do this without allocating map space if the target isn't using a GOT
300 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
301 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
302
303 return Result;
304}
305
306
307//===----------------------------------------------------------------------===//
308// JITEmitter code.
309//
310namespace {
311 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
312 /// used to output functions to memory for execution.
313 class JITEmitter : public MachineCodeEmitter {
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000314 JITMemoryManager *MemMgr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315
316 // When outputting a function stub in the context of some other function, we
317 // save BufferBegin/BufferEnd/CurBufferPtr here.
318 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
319
320 /// Relocations - These are the relocations that the function needs, as
321 /// emitted.
322 std::vector<MachineRelocation> Relocations;
323
324 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
325 /// It is filled in by the StartMachineBasicBlock callback and queried by
326 /// the getMachineBasicBlockAddress callback.
327 std::vector<intptr_t> MBBLocations;
328
329 /// ConstantPool - The constant pool for the current function.
330 ///
331 MachineConstantPool *ConstantPool;
332
333 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
334 ///
335 void *ConstantPoolBase;
336
337 /// JumpTable - The jump tables for the current function.
338 ///
339 MachineJumpTableInfo *JumpTable;
340
341 /// JumpTableBase - A pointer to the first entry in the jump table.
342 ///
343 void *JumpTableBase;
Evan Chengaf743252008-01-05 02:26:58 +0000344
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345 /// Resolver - This contains info about the currently resolved functions.
346 JITResolver Resolver;
347 public:
Chris Lattnere44be002007-12-06 01:08:09 +0000348 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
349 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000350 if (jit.getJITInfo().needsGOT()) {
351 MemMgr->AllocateGOT();
352 DOUT << "JIT is managing a GOT\n";
353 }
354 }
355 ~JITEmitter() {
356 delete MemMgr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357 }
358
359 JITResolver &getJITResolver() { return Resolver; }
360
361 virtual void startFunction(MachineFunction &F);
362 virtual bool finishFunction(MachineFunction &F);
363
364 void emitConstantPool(MachineConstantPool *MCP);
365 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
366 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
367
368 virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1);
369 virtual void* finishFunctionStub(const Function *F);
370
371 virtual void addRelocation(const MachineRelocation &MR) {
372 Relocations.push_back(MR);
373 }
374
375 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
376 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
377 MBBLocations.resize((MBB->getNumber()+1)*2);
378 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
379 }
380
381 virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
382 virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Chengaf743252008-01-05 02:26:58 +0000383
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
385 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
386 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
387 return MBBLocations[MBB->getNumber()];
388 }
389
390 /// deallocateMemForFunction - Deallocate all memory for the specified
391 /// function body.
392 void deallocateMemForFunction(Function *F) {
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000393 MemMgr->deallocateMemForFunction(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000394 }
395 private:
396 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Cheng28e7e162008-01-04 10:46:51 +0000397 void *getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
398 bool NoNeedStub);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399 };
400}
401
402void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
403 bool DoesntNeedStub) {
404 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
405 /// FIXME: If we straightened things out, this could actually emit the
406 /// global immediately instead of queuing it for codegen later!
407 return TheJIT->getOrEmitGlobalVariable(GV);
408 }
409
410 // If we have already compiled the function, return a pointer to its body.
411 Function *F = cast<Function>(V);
412 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
413 if (ResultPtr) return ResultPtr;
414
415 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
416 // If this is an external function pointer, we can force the JIT to
417 // 'compile' it, which really just adds it to the map.
418 if (DoesntNeedStub)
419 return TheJIT->getPointerToFunction(F);
420
421 return Resolver.getFunctionStub(F);
422 }
423
424 // Okay, the function has not been compiled yet, if the target callback
425 // mechanism is capable of rewriting the instruction directly, prefer to do
426 // that instead of emitting a stub.
427 if (DoesntNeedStub)
428 return Resolver.AddCallbackAtLocation(F, Reference);
429
430 // Otherwise, we have to emit a lazy resolving stub.
431 return Resolver.getFunctionStub(F);
432}
433
Evan Cheng28e7e162008-01-04 10:46:51 +0000434void *JITEmitter::getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
435 bool DoesntNeedStub) {
436 // Make sure GV is emitted first.
437 // FIXME: For now, if the GV is an external function we force the JIT to
438 // compile it so the lazy pointer will contain the fully resolved address.
439 void *GVAddress = getPointerToGlobal(V, Reference, true);
440 return Resolver.getGlobalValueLazyPtr(V, GVAddress);
441}
442
443
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000444void JITEmitter::startFunction(MachineFunction &F) {
445 uintptr_t ActualSize;
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000446 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
447 ActualSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000448 BufferEnd = BufferBegin+ActualSize;
449
450 // Ensure the constant pool/jump table info is at least 4-byte aligned.
451 emitAlignment(16);
452
453 emitConstantPool(F.getConstantPool());
454 initJumpTableInfo(F.getJumpTableInfo());
455
456 // About to start emitting the machine code for the function.
457 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
458 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
459
460 MBBLocations.clear();
461}
462
463bool JITEmitter::finishFunction(MachineFunction &F) {
464 if (CurBufferPtr == BufferEnd) {
465 // FIXME: Allocate more space, then try again.
466 cerr << "JIT: Ran out of space for generated machine code!\n";
467 abort();
468 }
469
470 emitJumpTableInfo(F.getJumpTableInfo());
471
472 // FnStart is the start of the text, not the start of the constant pool and
473 // other per-function data.
474 unsigned char *FnStart =
475 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
476 unsigned char *FnEnd = CurBufferPtr;
477
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000478 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000479 NumBytes += FnEnd-FnStart;
480
481 if (!Relocations.empty()) {
482 NumRelos += Relocations.size();
483
484 // Resolve the relocations to concrete pointers.
485 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
486 MachineRelocation &MR = Relocations[i];
487 void *ResultPtr;
488 if (MR.isString()) {
489 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
490
491 // If the target REALLY wants a stub for this function, emit it now.
Evan Chengf0123872008-01-03 02:56:28 +0000492 if (!MR.doesntNeedStub())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000493 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
494 } else if (MR.isGlobalValue()) {
495 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
496 BufferBegin+MR.getMachineCodeOffset(),
Evan Chengf0123872008-01-03 02:56:28 +0000497 MR.doesntNeedStub());
Evan Cheng28e7e162008-01-04 10:46:51 +0000498 } else if (MR.isGlobalValueLazyPtr()) {
499 ResultPtr = getPointerToGVLazyPtr(MR.getGlobalValue(),
500 BufferBegin+MR.getMachineCodeOffset(),
501 MR.doesntNeedStub());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000502 } else if (MR.isBasicBlock()) {
503 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
504 } else if (MR.isConstantPoolIndex()) {
505 ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
506 } else {
507 assert(MR.isJumpTableIndex());
508 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
509 }
510
511 MR.setResultPointer(ResultPtr);
512
513 // if we are managing the GOT and the relocation wants an index,
514 // give it one
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000515 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000516 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
517 MR.setGOTIndex(idx);
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000518 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000519 DOUT << "GOT was out of date for " << ResultPtr
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000520 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000521 << "\n";
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000522 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000523 }
524 }
525 }
526
527 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000528 Relocations.size(), MemMgr->getGOTBase());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000529 }
530
531 // Update the GOT entry for F to point to the new code.
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000532 if (MemMgr->isManagingGOT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000533 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000534 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000535 DOUT << "GOT was out of date for " << (void*)BufferBegin
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000536 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
537 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000538 }
539 }
540
541 // Invalidate the icache if necessary.
542 synchronizeICache(FnStart, FnEnd-FnStart);
543
544 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
545 << "] Function: " << F.getFunction()->getName()
546 << ": " << (FnEnd-FnStart) << " bytes of text, "
547 << Relocations.size() << " relocations\n";
548 Relocations.clear();
549
550#ifndef NDEBUG
551 if (sys::hasDisassembler())
552 DOUT << "Disassembled code:\n"
553 << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
554#endif
555
556 return false;
557}
558
559void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
560 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
561 if (Constants.empty()) return;
562
563 MachineConstantPoolEntry CPE = Constants.back();
564 unsigned Size = CPE.Offset;
565 const Type *Ty = CPE.isMachineConstantPoolEntry()
566 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
Duncan Sandsf99fdc62007-11-01 20:53:16 +0000567 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000568
569 ConstantPoolBase = allocateSpace(Size, 1 << MCP->getConstantPoolAlignment());
570 ConstantPool = MCP;
571
572 if (ConstantPoolBase == 0) return; // Buffer overflow.
573
574 // Initialize the memory for all of the constant pool entries.
575 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
576 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
577 if (Constants[i].isMachineConstantPoolEntry()) {
578 // FIXME: add support to lower machine constant pool values into bytes!
579 cerr << "Initialize memory with machine specific constant pool entry"
580 << " has not been implemented!\n";
581 abort();
582 }
583 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
584 }
585}
586
587void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
588 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
589 if (JT.empty()) return;
590
591 unsigned NumEntries = 0;
592 for (unsigned i = 0, e = JT.size(); i != e; ++i)
593 NumEntries += JT[i].MBBs.size();
594
595 unsigned EntrySize = MJTI->getEntrySize();
596
597 // Just allocate space for all the jump tables now. We will fix up the actual
598 // MBB entries in the tables after we emit the code for each block, since then
599 // we will know the final locations of the MBBs in memory.
600 JumpTable = MJTI;
601 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
602}
603
604void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
605 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
606 if (JT.empty() || JumpTableBase == 0) return;
607
608 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
609 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
610 // For each jump table, place the offset from the beginning of the table
611 // to the target address.
612 int *SlotPtr = (int*)JumpTableBase;
613
614 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
615 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
616 // Store the offset of the basic block for this jump table slot in the
617 // memory we allocated for the jump table in 'initJumpTableInfo'
618 intptr_t Base = (intptr_t)SlotPtr;
Evan Chengaf743252008-01-05 02:26:58 +0000619 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
620 intptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
621 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
622 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000623 }
624 } else {
625 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
626
627 // For each jump table, map each target in the jump table to the address of
628 // an emitted MachineBasicBlock.
629 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
630
631 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
632 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
633 // Store the address of the basic block for this jump table slot in the
634 // memory we allocated for the jump table in 'initJumpTableInfo'
635 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
636 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
637 }
638 }
639}
640
641void JITEmitter::startFunctionStub(unsigned StubSize, unsigned Alignment) {
642 SavedBufferBegin = BufferBegin;
643 SavedBufferEnd = BufferEnd;
644 SavedCurBufferPtr = CurBufferPtr;
645
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000646 BufferBegin = CurBufferPtr = MemMgr->allocateStub(StubSize, Alignment);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000647 BufferEnd = BufferBegin+StubSize+1;
648}
649
650void *JITEmitter::finishFunctionStub(const Function *F) {
651 NumBytes += getCurrentPCOffset();
652 std::swap(SavedBufferBegin, BufferBegin);
653 BufferEnd = SavedBufferEnd;
654 CurBufferPtr = SavedCurBufferPtr;
655 return SavedBufferBegin;
656}
657
658// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
659// in the constant pool that was last emitted with the 'emitConstantPool'
660// method.
661//
662intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
663 assert(ConstantNum < ConstantPool->getConstants().size() &&
664 "Invalid ConstantPoolIndex!");
665 return (intptr_t)ConstantPoolBase +
666 ConstantPool->getConstants()[ConstantNum].Offset;
667}
668
669// getJumpTableEntryAddress - Return the address of the JumpTable with index
670// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
671//
672intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
673 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
674 assert(Index < JT.size() && "Invalid jump table index!");
675
676 unsigned Offset = 0;
677 unsigned EntrySize = JumpTable->getEntrySize();
678
679 for (unsigned i = 0; i < Index; ++i)
680 Offset += JT[i].MBBs.size();
681
682 Offset *= EntrySize;
683
684 return (intptr_t)((char *)JumpTableBase + Offset);
685}
686
687//===----------------------------------------------------------------------===//
688// Public interface to this file
689//===----------------------------------------------------------------------===//
690
Chris Lattnere44be002007-12-06 01:08:09 +0000691MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
692 return new JITEmitter(jit, JMM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000693}
694
695// getPointerToNamedFunction - This function is used as a global wrapper to
696// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
697// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
698// need to resolve function(s) that are being mis-codegenerated, so we need to
699// resolve their addresses at runtime, and this is the way to do it.
700extern "C" {
701 void *getPointerToNamedFunction(const char *Name) {
702 if (Function *F = TheJIT->FindFunctionNamed(Name))
703 return TheJIT->getPointerToFunction(F);
704 return TheJIT->getPointerToNamedFunction(Name);
705 }
706}
707
708// getPointerToFunctionOrStub - If the specified function has been
709// code-gen'd, return a pointer to the function. If not, compile it, or use
710// a stub to implement lazy compilation if available.
711//
712void *JIT::getPointerToFunctionOrStub(Function *F) {
713 // If we have already code generated the function, just return the address.
714 if (void *Addr = getPointerToGlobalIfAvailable(F))
715 return Addr;
716
717 // Get a stub if the target supports it.
718 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
719 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
720 return JE->getJITResolver().getFunctionStub(F);
721}
722
723/// freeMachineCodeForFunction - release machine code memory for given Function.
724///
725void JIT::freeMachineCodeForFunction(Function *F) {
726 // Delete translation for this from the ExecutionEngine, so it will get
727 // retranslated next time it is used.
728 updateGlobalMapping(F, 0);
729
730 // Free the actual memory for the function body and related stuff.
731 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?");
732 static_cast<JITEmitter*>(MCE)->deallocateMemForFunction(F);
733}
734