blob: a90a6a52fa9ab61717f4f4aa8e6898a3b6c46e24 [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"
Nicolas Geoffray0e757e12008-02-13 18:39:37 +000017#include "JITDwarfEmitter.h"
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +000018#include "llvm/Constants.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000019#include "llvm/Module.h"
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +000020#include "llvm/DerivedTypes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/CodeGen/MachineCodeEmitter.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/CodeGen/MachineConstantPool.h"
24#include "llvm/CodeGen/MachineJumpTableInfo.h"
Nicolas Geoffray0e757e12008-02-13 18:39:37 +000025#include "llvm/CodeGen/MachineModuleInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000026#include "llvm/CodeGen/MachineRelocation.h"
Chris Lattnerc8ad39c2007-12-05 23:39:57 +000027#include "llvm/ExecutionEngine/JITMemoryManager.h"
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +000028#include "llvm/ExecutionEngine/GenericValue.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029#include "llvm/Target/TargetData.h"
30#include "llvm/Target/TargetJITInfo.h"
31#include "llvm/Target/TargetMachine.h"
Nicolas Geoffray0e757e12008-02-13 18:39:37 +000032#include "llvm/Target/TargetOptions.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include "llvm/Support/Debug.h"
34#include "llvm/Support/MutexGuard.h"
35#include "llvm/System/Disassembler.h"
Chris Lattner88f51632008-06-25 17:18:44 +000036#include "llvm/System/Memory.h"
Nicolas Geoffray68847972008-04-18 20:59:31 +000037#include "llvm/Target/TargetInstrInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000038#include "llvm/ADT/Statistic.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#include <algorithm>
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +000040#include <set>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041using namespace llvm;
42
43STATISTIC(NumBytes, "Number of bytes of machine code compiled");
44STATISTIC(NumRelos, "Number of relocations applied");
45static JIT *TheJIT = 0;
46
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047
48//===----------------------------------------------------------------------===//
49// JIT lazy compilation code.
50//
51namespace {
52 class JITResolverState {
53 private:
54 /// FunctionToStubMap - Keep track of the stub created for a particular
55 /// function so that we can reuse them if necessary.
56 std::map<Function*, void*> FunctionToStubMap;
57
58 /// StubToFunctionMap - Keep track of the function that each stub
59 /// corresponds to.
60 std::map<void*, Function*> StubToFunctionMap;
61
Evan Cheng28e7e162008-01-04 10:46:51 +000062 /// GlobalToLazyPtrMap - Keep track of the lazy pointer created for a
63 /// particular GlobalVariable so that we can reuse them if necessary.
64 std::map<GlobalValue*, void*> GlobalToLazyPtrMap;
65
Dan Gohmanf17a25c2007-07-18 16:29:46 +000066 public:
67 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
68 assert(locked.holds(TheJIT->lock));
69 return FunctionToStubMap;
70 }
71
72 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
73 assert(locked.holds(TheJIT->lock));
74 return StubToFunctionMap;
75 }
Evan Cheng28e7e162008-01-04 10:46:51 +000076
77 std::map<GlobalValue*, void*>&
78 getGlobalToLazyPtrMap(const MutexGuard& locked) {
79 assert(locked.holds(TheJIT->lock));
80 return GlobalToLazyPtrMap;
81 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082 };
83
84 /// JITResolver - Keep track of, and resolve, call sites for functions that
85 /// have not yet been compiled.
86 class JITResolver {
87 /// LazyResolverFn - The target lazy resolver function that we actually
88 /// rewrite instructions to use.
89 TargetJITInfo::LazyResolverFn LazyResolverFn;
90
91 JITResolverState state;
92
93 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
94 /// external functions.
95 std::map<void*, void*> ExternalFnToStubMap;
96
97 //map addresses to indexes in the GOT
98 std::map<void*, unsigned> revGOTMap;
99 unsigned nextGOTIndex;
100
101 static JITResolver *TheJITResolver;
102 public:
Dan Gohman40bd38e2008-03-25 22:06:05 +0000103 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104 TheJIT = &jit;
105
106 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
107 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
108 TheJITResolver = this;
109 }
110
111 ~JITResolver() {
112 TheJITResolver = 0;
113 }
114
115 /// getFunctionStub - This returns a pointer to a function stub, creating
116 /// one on demand as needed.
117 void *getFunctionStub(Function *F);
118
119 /// getExternalFunctionStub - Return a stub for the function at the
120 /// specified address, created lazily on demand.
121 void *getExternalFunctionStub(void *FnAddr);
122
Evan Cheng28e7e162008-01-04 10:46:51 +0000123 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
124 /// GV address.
125 void *getGlobalValueLazyPtr(GlobalValue *V, void *GVAddress);
126
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127 /// AddCallbackAtLocation - If the target is capable of rewriting an
128 /// instruction without the use of a stub, record the location of the use so
129 /// we know which function is being used at the location.
130 void *AddCallbackAtLocation(Function *F, void *Location) {
131 MutexGuard locked(TheJIT->lock);
132 /// Get the target-specific JIT resolver function.
133 state.getStubToFunctionMap(locked)[Location] = F;
134 return (void*)(intptr_t)LazyResolverFn;
135 }
136
137 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000138 /// an address. This function only manages slots, it does not manage the
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000139 /// contents of the slots or the memory associated with the GOT.
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000140 unsigned getGOTIndexForAddr(void *addr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141
142 /// JITCompilerFn - This function is called to resolve a stub to a compiled
143 /// address. If the LLVM Function corresponding to the stub has not yet
144 /// been compiled, this function compiles it first.
145 static void *JITCompilerFn(void *Stub);
146 };
147}
148
149JITResolver *JITResolver::TheJITResolver = 0;
150
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151/// getFunctionStub - This returns a pointer to a function stub, creating
152/// one on demand as needed.
153void *JITResolver::getFunctionStub(Function *F) {
154 MutexGuard locked(TheJIT->lock);
155
156 // If we already have a stub for this function, recycle it.
157 void *&Stub = state.getFunctionToStubMap(locked)[F];
158 if (Stub) return Stub;
159
160 // Call the lazy resolver function unless we already KNOW it is an external
161 // function, in which case we just skip the lazy resolution step.
162 void *Actual = (void*)(intptr_t)LazyResolverFn;
163 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode())
164 Actual = TheJIT->getPointerToFunction(F);
165
166 // Otherwise, codegen a new stub. For now, the stub will call the lazy
167 // resolver function.
Nicolas Geoffray2b483b52008-04-16 20:46:05 +0000168 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169 *TheJIT->getCodeEmitter());
170
171 if (Actual != (void*)(intptr_t)LazyResolverFn) {
172 // If we are getting the stub for an external function, we really want the
173 // address of the stub in the GlobalAddressMap for the JIT, not the address
174 // of the external function.
175 TheJIT->updateGlobalMapping(F, Stub);
176 }
177
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000178 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
179 << F->getName() << "'\n";
180
181 // Finally, keep track of the stub-to-Function mapping so that the
182 // JITCompilerFn knows which function to compile!
183 state.getStubToFunctionMap(locked)[Stub] = F;
184 return Stub;
185}
186
Evan Cheng28e7e162008-01-04 10:46:51 +0000187/// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
188/// GV address.
189void *JITResolver::getGlobalValueLazyPtr(GlobalValue *GV, void *GVAddress) {
190 MutexGuard locked(TheJIT->lock);
191
192 // If we already have a stub for this global variable, recycle it.
193 void *&LazyPtr = state.getGlobalToLazyPtrMap(locked)[GV];
194 if (LazyPtr) return LazyPtr;
195
196 // Otherwise, codegen a new lazy pointer.
Nicolas Geoffray2b483b52008-04-16 20:46:05 +0000197 LazyPtr = TheJIT->getJITInfo().emitGlobalValueLazyPtr(GV, GVAddress,
Evan Cheng28e7e162008-01-04 10:46:51 +0000198 *TheJIT->getCodeEmitter());
199
200 DOUT << "JIT: Stub emitted at [" << LazyPtr << "] for GV '"
201 << GV->getName() << "'\n";
202
203 return LazyPtr;
204}
205
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206/// getExternalFunctionStub - Return a stub for the function at the
207/// specified address, created lazily on demand.
208void *JITResolver::getExternalFunctionStub(void *FnAddr) {
209 // If we already have a stub for this function, recycle it.
210 void *&Stub = ExternalFnToStubMap[FnAddr];
211 if (Stub) return Stub;
212
Nicolas Geoffray2b483b52008-04-16 20:46:05 +0000213 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 *TheJIT->getCodeEmitter());
215
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216 DOUT << "JIT: Stub emitted at [" << Stub
217 << "] for external function at '" << FnAddr << "'\n";
218 return Stub;
219}
220
221unsigned JITResolver::getGOTIndexForAddr(void* addr) {
222 unsigned idx = revGOTMap[addr];
223 if (!idx) {
224 idx = ++nextGOTIndex;
225 revGOTMap[addr] = idx;
Evan Cheng71c58872008-04-12 00:22:01 +0000226 DOUT << "Adding GOT entry " << idx << " for addr " << addr << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227 }
228 return idx;
229}
230
231/// JITCompilerFn - This function is called when a lazy compilation stub has
232/// been entered. It looks up which function this stub corresponds to, compiles
233/// it if necessary, then returns the resultant function pointer.
234void *JITResolver::JITCompilerFn(void *Stub) {
235 JITResolver &JR = *TheJITResolver;
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000236
237 Function* F = 0;
238 void* ActualPtr = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000240 {
241 // Only lock for getting the Function. The call getPointerToFunction made
242 // in this function might trigger function materializing, which requires
243 // JIT lock to be unlocked.
244 MutexGuard locked(TheJIT->lock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000246 // The address given to us for the stub may not be exactly right, it might be
247 // a little bit after the stub. As such, use upper_bound to find it.
248 std::map<void*, Function*>::iterator I =
249 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
250 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
251 "This is not a known stub!");
252 F = (--I)->second;
253 ActualPtr = I->first;
254 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255
256 // If we have already code generated the function, just return the address.
257 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
258
259 if (!Result) {
260 // Otherwise we don't have it, do lazy compilation now.
261
262 // If lazy compilation is disabled, emit a useful error message and abort.
263 if (TheJIT->isLazyCompilationDisabled()) {
264 cerr << "LLVM JIT requested to do lazy compilation of function '"
265 << F->getName() << "' when lazy compiles are disabled!\n";
266 abort();
267 }
268
269 // We might like to remove the stub from the StubToFunction map.
270 // We can't do that! Multiple threads could be stuck, waiting to acquire the
271 // lock above. As soon as the 1st function finishes compiling the function,
272 // the next one will be released, and needs to be able to find the function
273 // it needs to call.
274 //JR.state.getStubToFunctionMap(locked).erase(I);
275
276 DOUT << "JIT: Lazily resolving function '" << F->getName()
277 << "' In stub ptr = " << Stub << " actual ptr = "
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000278 << ActualPtr << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000279
280 Result = TheJIT->getPointerToFunction(F);
281 }
Nicolas Geoffray7bf33432008-10-03 07:27:08 +0000282
283 // Reacquire the lock to erase the stub in the map.
284 MutexGuard locked(TheJIT->lock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000285
286 // We don't need to reuse this stub in the future, as F is now compiled.
287 JR.state.getFunctionToStubMap(locked).erase(F);
288
289 // FIXME: We could rewrite all references to this stub if we knew them.
290
291 // What we will do is set the compiled function address to map to the
292 // same GOT entry as the stub so that later clients may update the GOT
293 // if they see it still using the stub address.
294 // Note: this is done so the Resolver doesn't have to manage GOT memory
295 // Do this without allocating map space if the target isn't using a GOT
296 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
297 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
298
299 return Result;
300}
301
Chris Lattnerf50e3572008-04-04 05:51:42 +0000302//===----------------------------------------------------------------------===//
303// Function Index Support
304
305// On MacOS we generate an index of currently JIT'd functions so that
306// performance tools can determine a symbol name and accurate code range for a
307// PC value. Because performance tools are generally asynchronous, the code
308// below is written with the hope that it could be interrupted at any time and
309// have useful answers. However, we don't go crazy with atomic operations, we
310// just do a "reasonable effort".
311#ifdef __APPLE__
Evan Cheng4481f762008-05-15 17:31:35 +0000312#define ENABLE_JIT_SYMBOL_TABLE 0
Chris Lattnerf50e3572008-04-04 05:51:42 +0000313#endif
314
315/// JitSymbolEntry - Each function that is JIT compiled results in one of these
316/// being added to an array of symbols. This indicates the name of the function
317/// as well as the address range it occupies. This allows the client to map
318/// from a PC value to the name of the function.
319struct JitSymbolEntry {
320 const char *FnName; // FnName - a strdup'd string.
321 void *FnStart;
322 intptr_t FnSize;
323};
324
325
326struct JitSymbolTable {
327 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
328 /// pointer is not used right now, but might be used in the future. Consider
329 /// it reserved for future use.
330 JitSymbolTable *NextPtr;
331
332 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
333 /// 'NumSymbols' symbols are valid.
334 JitSymbolEntry *Symbols;
335
336 /// NumSymbols - This indicates the number entries in the Symbols array that
337 /// are valid.
338 unsigned NumSymbols;
339
340 /// NumAllocated - This indicates the amount of space we have in the Symbols
341 /// array. This is a private field that should not be read by external tools.
342 unsigned NumAllocated;
343};
344
345#if ENABLE_JIT_SYMBOL_TABLE
346JitSymbolTable *__jitSymbolTable;
347#endif
348
349static void AddFunctionToSymbolTable(const char *FnName,
350 void *FnStart, intptr_t FnSize) {
351 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
352 JitSymbolTable **SymTabPtrPtr = 0;
353#if !ENABLE_JIT_SYMBOL_TABLE
354 return;
355#else
356 SymTabPtrPtr = &__jitSymbolTable;
357#endif
358
359 // If this is the first entry in the symbol table, add the JitSymbolTable
360 // index.
361 if (*SymTabPtrPtr == 0) {
362 JitSymbolTable *New = new JitSymbolTable();
363 New->NextPtr = 0;
364 New->Symbols = 0;
365 New->NumSymbols = 0;
366 New->NumAllocated = 0;
367 *SymTabPtrPtr = New;
368 }
369
370 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
371
372 // If we have space in the table, reallocate the table.
373 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
374 // If we don't have space, reallocate the table.
Chris Lattnerea0cb7c2008-04-13 07:04:56 +0000375 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
Chris Lattnerf50e3572008-04-04 05:51:42 +0000376 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
377 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
378
379 // Copy the old entries over.
380 memcpy(NewSymbols, OldSymbols,
Chris Lattnerea0cb7c2008-04-13 07:04:56 +0000381 SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
Chris Lattnerf50e3572008-04-04 05:51:42 +0000382
383 // Swap the new symbols in, delete the old ones.
384 SymTabPtr->Symbols = NewSymbols;
Chris Lattnerea0cb7c2008-04-13 07:04:56 +0000385 SymTabPtr->NumAllocated = NewSize;
Chris Lattnerf50e3572008-04-04 05:51:42 +0000386 delete [] OldSymbols;
387 }
388
389 // Otherwise, we have enough space, just tack it onto the end of the array.
390 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
391 Entry.FnName = strdup(FnName);
392 Entry.FnStart = FnStart;
393 Entry.FnSize = FnSize;
394 ++SymTabPtr->NumSymbols;
395}
396
397static void RemoveFunctionFromSymbolTable(void *FnStart) {
398 assert(FnStart && "Invalid function pointer");
399 JitSymbolTable **SymTabPtrPtr = 0;
400#if !ENABLE_JIT_SYMBOL_TABLE
401 return;
402#else
403 SymTabPtrPtr = &__jitSymbolTable;
404#endif
405
406 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
407 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
408
409 // Scan the table to find its index. The table is not sorted, so do a linear
410 // scan.
411 unsigned Index;
412 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
413 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
414
415 // Once we have an index, we know to nuke this entry, overwrite it with the
416 // entry at the end of the array, making the last entry redundant.
417 const char *OldName = Symbols[Index].FnName;
418 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
419 free((void*)OldName);
420
421 // Drop the number of symbols in the table.
422 --SymTabPtr->NumSymbols;
423
424 // Finally, if we deleted the final symbol, deallocate the table itself.
Nate Begeman0751db22008-05-18 19:09:10 +0000425 if (SymTabPtr->NumSymbols != 0)
Chris Lattnerf50e3572008-04-04 05:51:42 +0000426 return;
427
428 *SymTabPtrPtr = 0;
429 delete [] Symbols;
430 delete SymTabPtr;
431}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432
433//===----------------------------------------------------------------------===//
434// JITEmitter code.
435//
436namespace {
437 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
438 /// used to output functions to memory for execution.
439 class JITEmitter : public MachineCodeEmitter {
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000440 JITMemoryManager *MemMgr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000441
442 // When outputting a function stub in the context of some other function, we
443 // save BufferBegin/BufferEnd/CurBufferPtr here.
444 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
445
446 /// Relocations - These are the relocations that the function needs, as
447 /// emitted.
448 std::vector<MachineRelocation> Relocations;
449
450 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
451 /// It is filled in by the StartMachineBasicBlock callback and queried by
452 /// the getMachineBasicBlockAddress callback.
453 std::vector<intptr_t> MBBLocations;
454
455 /// ConstantPool - The constant pool for the current function.
456 ///
457 MachineConstantPool *ConstantPool;
458
459 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
460 ///
461 void *ConstantPoolBase;
462
463 /// JumpTable - The jump tables for the current function.
464 ///
465 MachineJumpTableInfo *JumpTable;
466
467 /// JumpTableBase - A pointer to the first entry in the jump table.
468 ///
469 void *JumpTableBase;
Evan Chengaf743252008-01-05 02:26:58 +0000470
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000471 /// Resolver - This contains info about the currently resolved functions.
472 JITResolver Resolver;
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000473
474 /// DE - The dwarf emitter for the jit.
475 JITDwarfEmitter *DE;
476
477 /// LabelLocations - This vector is a mapping from Label ID's to their
478 /// address.
479 std::vector<intptr_t> LabelLocations;
480
481 /// MMI - Machine module info for exception informations
482 MachineModuleInfo* MMI;
483
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000484 // GVSet - a set to keep track of which globals have been seen
485 std::set<const GlobalVariable*> GVSet;
486
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000487 public:
Chris Lattnere44be002007-12-06 01:08:09 +0000488 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
489 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000490 if (jit.getJITInfo().needsGOT()) {
491 MemMgr->AllocateGOT();
492 DOUT << "JIT is managing a GOT\n";
493 }
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000494
495 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000496 }
497 ~JITEmitter() {
498 delete MemMgr;
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000499 if (ExceptionHandling) delete DE;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000500 }
Evan Cheng89b29a12008-08-20 00:28:12 +0000501
502 /// classof - Methods for support type inquiry through isa, cast, and
503 /// dyn_cast:
504 ///
505 static inline bool classof(const JITEmitter*) { return true; }
506 static inline bool classof(const MachineCodeEmitter*) { return true; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000507
508 JITResolver &getJITResolver() { return Resolver; }
509
510 virtual void startFunction(MachineFunction &F);
511 virtual bool finishFunction(MachineFunction &F);
512
513 void emitConstantPool(MachineConstantPool *MCP);
514 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
515 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
516
Nicolas Geoffray2b483b52008-04-16 20:46:05 +0000517 virtual void startFunctionStub(const GlobalValue* F, unsigned StubSize,
518 unsigned Alignment = 1);
519 virtual void* finishFunctionStub(const GlobalValue *F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000520
521 virtual void addRelocation(const MachineRelocation &MR) {
522 Relocations.push_back(MR);
523 }
524
525 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
526 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
527 MBBLocations.resize((MBB->getNumber()+1)*2);
528 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
529 }
530
531 virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
532 virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
Evan Chengaf743252008-01-05 02:26:58 +0000533
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000534 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
535 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
536 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
537 return MBBLocations[MBB->getNumber()];
538 }
539
540 /// deallocateMemForFunction - Deallocate all memory for the specified
541 /// function body.
542 void deallocateMemForFunction(Function *F) {
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000543 MemMgr->deallocateMemForFunction(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000544 }
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000545
546 virtual void emitLabel(uint64_t LabelID) {
547 if (LabelLocations.size() <= LabelID)
548 LabelLocations.resize((LabelID+1)*2);
549 LabelLocations[LabelID] = getCurrentPCValue();
550 }
551
552 virtual intptr_t getLabelAddress(uint64_t LabelID) const {
553 assert(LabelLocations.size() > (unsigned)LabelID &&
554 LabelLocations[LabelID] && "Label not emitted!");
555 return LabelLocations[LabelID];
556 }
557
558 virtual void setModuleInfo(MachineModuleInfo* Info) {
559 MMI = Info;
560 if (ExceptionHandling) DE->setModuleInfo(Info);
561 }
562
Jim Grosbach724b1812008-10-03 16:17:20 +0000563 void setMemoryExecutable(void) {
564 MemMgr->setMemoryExecutable();
565 }
566
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000567 private:
568 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
Evan Cheng28e7e162008-01-04 10:46:51 +0000569 void *getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
570 bool NoNeedStub);
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000571 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
572 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
573 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
574 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000575 };
576}
577
578void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
579 bool DoesntNeedStub) {
580 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
581 /// FIXME: If we straightened things out, this could actually emit the
582 /// global immediately instead of queuing it for codegen later!
583 return TheJIT->getOrEmitGlobalVariable(GV);
584 }
Chris Lattner44d8ea72008-06-25 20:21:35 +0000585 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Anton Korobeynikovc7b90912008-09-09 20:05:04 +0000586 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000587
588 // If we have already compiled the function, return a pointer to its body.
589 Function *F = cast<Function>(V);
590 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
591 if (ResultPtr) return ResultPtr;
592
593 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
594 // If this is an external function pointer, we can force the JIT to
595 // 'compile' it, which really just adds it to the map.
596 if (DoesntNeedStub)
597 return TheJIT->getPointerToFunction(F);
598
599 return Resolver.getFunctionStub(F);
600 }
601
602 // Okay, the function has not been compiled yet, if the target callback
603 // mechanism is capable of rewriting the instruction directly, prefer to do
604 // that instead of emitting a stub.
605 if (DoesntNeedStub)
606 return Resolver.AddCallbackAtLocation(F, Reference);
607
608 // Otherwise, we have to emit a lazy resolving stub.
609 return Resolver.getFunctionStub(F);
610}
611
Evan Cheng28e7e162008-01-04 10:46:51 +0000612void *JITEmitter::getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
613 bool DoesntNeedStub) {
614 // Make sure GV is emitted first.
615 // FIXME: For now, if the GV is an external function we force the JIT to
616 // compile it so the lazy pointer will contain the fully resolved address.
617 void *GVAddress = getPointerToGlobal(V, Reference, true);
618 return Resolver.getGlobalValueLazyPtr(V, GVAddress);
619}
620
Nicolas Geoffray68847972008-04-18 20:59:31 +0000621static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
622 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
623 if (Constants.empty()) return 0;
624
625 MachineConstantPoolEntry CPE = Constants.back();
626 unsigned Size = CPE.Offset;
627 const Type *Ty = CPE.isMachineConstantPoolEntry()
628 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
629 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
630 return Size;
631}
632
633static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
634 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
635 if (JT.empty()) return 0;
636
637 unsigned NumEntries = 0;
638 for (unsigned i = 0, e = JT.size(); i != e; ++i)
639 NumEntries += JT[i].MBBs.size();
640
641 unsigned EntrySize = MJTI->getEntrySize();
642
643 return NumEntries * EntrySize;
644}
645
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000646static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
Nicolas Geoffray68847972008-04-18 20:59:31 +0000647 if (Alignment == 0) Alignment = 1;
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000648 // Since we do not know where the buffer will be allocated, be pessimistic.
649 return Size + Alignment;
Nicolas Geoffray68847972008-04-18 20:59:31 +0000650}
Evan Cheng28e7e162008-01-04 10:46:51 +0000651
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000652/// addSizeOfGlobal - add the size of the global (plus any alignment padding)
653/// into the running total Size.
654
655unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
656 const Type *ElTy = GV->getType()->getElementType();
657 size_t GVSize = (size_t)TheJIT->getTargetData()->getABITypeSize(ElTy);
658 size_t GVAlign =
659 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
660 DOUT << "Adding in size " << GVSize << " alignment " << GVAlign;
661 DEBUG(GV->dump());
662 // Assume code section ends with worst possible alignment, so first
663 // variable needs maximal padding.
664 if (Size==0)
665 Size = 1;
666 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
667 Size += GVSize;
668 return Size;
669}
670
671/// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
672/// but are referenced from the constant; put them in GVSet and add their
673/// size into the running total Size.
674
675unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
676 unsigned Size) {
677 // If its undefined, return the garbage.
678 if (isa<UndefValue>(C))
679 return Size;
680
681 // If the value is a ConstantExpr
682 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
683 Constant *Op0 = CE->getOperand(0);
684 switch (CE->getOpcode()) {
685 case Instruction::GetElementPtr:
686 case Instruction::Trunc:
687 case Instruction::ZExt:
688 case Instruction::SExt:
689 case Instruction::FPTrunc:
690 case Instruction::FPExt:
691 case Instruction::UIToFP:
692 case Instruction::SIToFP:
693 case Instruction::FPToUI:
694 case Instruction::FPToSI:
695 case Instruction::PtrToInt:
696 case Instruction::IntToPtr:
697 case Instruction::BitCast: {
698 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
699 break;
700 }
701 case Instruction::Add:
702 case Instruction::Sub:
703 case Instruction::Mul:
704 case Instruction::UDiv:
705 case Instruction::SDiv:
706 case Instruction::URem:
707 case Instruction::SRem:
708 case Instruction::And:
709 case Instruction::Or:
710 case Instruction::Xor: {
711 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
712 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
713 break;
714 }
715 default: {
716 cerr << "ConstantExpr not handled: " << *CE << "\n";
717 abort();
718 }
719 }
720 }
721
722 if (C->getType()->getTypeID() == Type::PointerTyID)
723 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
724 if (GVSet.insert(GV).second)
725 Size = addSizeOfGlobal(GV, Size);
726
727 return Size;
728}
729
730/// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
731/// but are referenced from the given initializer.
732
733unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
734 unsigned Size) {
735 if (!isa<UndefValue>(Init) &&
736 !isa<ConstantVector>(Init) &&
737 !isa<ConstantAggregateZero>(Init) &&
738 !isa<ConstantArray>(Init) &&
739 !isa<ConstantStruct>(Init) &&
740 Init->getType()->isFirstClassType())
741 Size = addSizeOfGlobalsInConstantVal(Init, Size);
742 return Size;
743}
744
745/// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
746/// globals; then walk the initializers of those globals looking for more.
747/// If their size has not been considered yet, add it into the running total
748/// Size.
749
750unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
751 unsigned Size = 0;
752 GVSet.clear();
753
754 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
755 MBB != E; ++MBB) {
756 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
757 I != E; ++I) {
758 const TargetInstrDesc &Desc = I->getDesc();
759 const MachineInstr &MI = *I;
760 unsigned NumOps = Desc.getNumOperands();
761 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
762 const MachineOperand &MO = MI.getOperand(CurOp);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000763 if (MO.isGlobal()) {
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000764 GlobalValue* V = MO.getGlobal();
765 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
766 if (!GV)
767 continue;
768 // If seen in previous function, it will have an entry here.
769 if (TheJIT->getPointerToGlobalIfAvailable(GV))
770 continue;
771 // If seen earlier in this function, it will have an entry here.
772 // FIXME: it should be possible to combine these tables, by
773 // assuming the addresses of the new globals in this module
774 // start at 0 (or something) and adjusting them after codegen
775 // complete. Another possibility is to grab a marker bit in GV.
776 if (GVSet.insert(GV).second)
777 // A variable as yet unseen. Add in its size.
778 Size = addSizeOfGlobal(GV, Size);
779 }
780 }
781 }
782 }
783 DOUT << "About to look through initializers\n";
784 // Look for more globals that are referenced only from initializers.
785 // GVSet.end is computed each time because the set can grow as we go.
786 for (std::set<const GlobalVariable *>::iterator I = GVSet.begin();
787 I != GVSet.end(); I++) {
788 const GlobalVariable* GV = *I;
789 if (GV->hasInitializer())
790 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
791 }
792
793 return Size;
794}
795
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000796void JITEmitter::startFunction(MachineFunction &F) {
Nicolas Geoffray68847972008-04-18 20:59:31 +0000797 uintptr_t ActualSize = 0;
Jim Grosbach724b1812008-10-03 16:17:20 +0000798 // Set the memory writable, if it's not already
799 MemMgr->setMemoryWritable();
Nicolas Geoffrayf748af22008-04-20 17:44:19 +0000800 if (MemMgr->NeedsExactSize()) {
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000801 DOUT << "ExactSize\n";
Nicolas Geoffray68847972008-04-18 20:59:31 +0000802 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
803 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
804 MachineConstantPool *MCP = F.getConstantPool();
805
806 // Ensure the constant pool/jump table info is at least 4-byte aligned.
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000807 ActualSize = RoundUpToAlign(ActualSize, 16);
Nicolas Geoffray68847972008-04-18 20:59:31 +0000808
809 // Add the alignment of the constant pool
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000810 ActualSize = RoundUpToAlign(ActualSize,
811 1 << MCP->getConstantPoolAlignment());
Nicolas Geoffray68847972008-04-18 20:59:31 +0000812
813 // Add the constant pool size
814 ActualSize += GetConstantPoolSizeInBytes(MCP);
815
816 // Add the aligment of the jump table info
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000817 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
Nicolas Geoffray68847972008-04-18 20:59:31 +0000818
819 // Add the jump table size
820 ActualSize += GetJumpTableSizeInBytes(MJTI);
821
822 // Add the alignment for the function
Nicolas Geoffray5a80b292008-04-20 23:39:44 +0000823 ActualSize = RoundUpToAlign(ActualSize,
824 std::max(F.getFunction()->getAlignment(), 8U));
Nicolas Geoffray68847972008-04-18 20:59:31 +0000825
826 // Add the function size
827 ActualSize += TII->GetFunctionSizeInBytes(F);
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000828
829 DOUT << "ActualSize before globals " << ActualSize << "\n";
830 // Add the size of the globals that will be allocated after this function.
831 // These are all the ones referenced from this function that were not
832 // previously allocated.
833 ActualSize += GetSizeOfGlobalsInBytes(F);
834 DOUT << "ActualSize after globals " << ActualSize << "\n";
Nicolas Geoffray68847972008-04-18 20:59:31 +0000835 }
836
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000837 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
838 ActualSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839 BufferEnd = BufferBegin+ActualSize;
840
841 // Ensure the constant pool/jump table info is at least 4-byte aligned.
842 emitAlignment(16);
843
844 emitConstantPool(F.getConstantPool());
845 initJumpTableInfo(F.getJumpTableInfo());
846
847 // About to start emitting the machine code for the function.
848 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
849 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
850
851 MBBLocations.clear();
852}
853
854bool JITEmitter::finishFunction(MachineFunction &F) {
855 if (CurBufferPtr == BufferEnd) {
856 // FIXME: Allocate more space, then try again.
857 cerr << "JIT: Ran out of space for generated machine code!\n";
858 abort();
859 }
860
861 emitJumpTableInfo(F.getJumpTableInfo());
862
863 // FnStart is the start of the text, not the start of the constant pool and
864 // other per-function data.
865 unsigned char *FnStart =
866 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867
868 if (!Relocations.empty()) {
869 NumRelos += Relocations.size();
870
871 // Resolve the relocations to concrete pointers.
872 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
873 MachineRelocation &MR = Relocations[i];
874 void *ResultPtr;
875 if (MR.isString()) {
876 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
877
878 // If the target REALLY wants a stub for this function, emit it now.
Evan Chengf0123872008-01-03 02:56:28 +0000879 if (!MR.doesntNeedStub())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000880 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
881 } else if (MR.isGlobalValue()) {
882 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
883 BufferBegin+MR.getMachineCodeOffset(),
Evan Chengf0123872008-01-03 02:56:28 +0000884 MR.doesntNeedStub());
Evan Cheng28e7e162008-01-04 10:46:51 +0000885 } else if (MR.isGlobalValueLazyPtr()) {
886 ResultPtr = getPointerToGVLazyPtr(MR.getGlobalValue(),
887 BufferBegin+MR.getMachineCodeOffset(),
888 MR.doesntNeedStub());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000889 } else if (MR.isBasicBlock()) {
890 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
891 } else if (MR.isConstantPoolIndex()) {
892 ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
893 } else {
894 assert(MR.isJumpTableIndex());
895 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
896 }
897
898 MR.setResultPointer(ResultPtr);
899
900 // if we are managing the GOT and the relocation wants an index,
901 // give it one
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000902 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
904 MR.setGOTIndex(idx);
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000905 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000906 DOUT << "GOT was out of date for " << ResultPtr
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000907 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000908 << "\n";
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000909 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000910 }
911 }
912 }
913
914 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000915 Relocations.size(), MemMgr->getGOTBase());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000916 }
917
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +0000918 unsigned char *FnEnd = CurBufferPtr;
919
920 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
921 NumBytes += FnEnd-FnStart;
922
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000923 // Update the GOT entry for F to point to the new code.
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000924 if (MemMgr->isManagingGOT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000925 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000926 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000927 DOUT << "GOT was out of date for " << (void*)BufferBegin
Chris Lattnerc8ad39c2007-12-05 23:39:57 +0000928 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
929 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000930 }
931 }
932
933 // Invalidate the icache if necessary.
Chris Lattner88f51632008-06-25 17:18:44 +0000934 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
Chris Lattnerf50e3572008-04-04 05:51:42 +0000935
936 // Add it to the JIT symbol table if the host wants it.
937 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
938 FnStart, FnEnd-FnStart);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000939
940 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
941 << "] Function: " << F.getFunction()->getName()
942 << ": " << (FnEnd-FnStart) << " bytes of text, "
943 << Relocations.size() << " relocations\n";
944 Relocations.clear();
945
Evan Chengb83f6972008-09-18 07:54:21 +0000946 // Mark code region readable and executable if it's not so already.
Jim Grosbach724b1812008-10-03 16:17:20 +0000947 MemMgr->setMemoryExecutable();
Evan Chengb83f6972008-09-18 07:54:21 +0000948
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000949#ifndef NDEBUG
Dale Johannesenc501c082008-08-11 23:46:25 +0000950 {
951 DOUT << std::hex;
952 int i;
953 unsigned char* q = FnStart;
954 for (i=1; q!=FnEnd; q++, i++) {
955 if (i%8==1)
956 DOUT << "0x" << (long)q << ": ";
957 DOUT<< (unsigned short)*q << " ";
958 if (i%8==0)
959 DOUT<<"\n";
960 }
961 DOUT << std::dec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000962 if (sys::hasDisassembler())
963 DOUT << "Disassembled code:\n"
964 << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
Dale Johannesenc501c082008-08-11 23:46:25 +0000965 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966#endif
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000967 if (ExceptionHandling) {
Nicolas Geoffray68847972008-04-18 20:59:31 +0000968 uintptr_t ActualSize = 0;
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000969 SavedBufferBegin = BufferBegin;
970 SavedBufferEnd = BufferEnd;
971 SavedCurBufferPtr = CurBufferPtr;
Nicolas Geoffray68847972008-04-18 20:59:31 +0000972
Nicolas Geoffrayf748af22008-04-20 17:44:19 +0000973 if (MemMgr->NeedsExactSize()) {
974 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
Nicolas Geoffray68847972008-04-18 20:59:31 +0000975 }
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000976
977 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
978 ActualSize);
979 BufferEnd = BufferBegin+ActualSize;
980 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
Chris Lattner3d46fe02008-03-07 20:05:43 +0000981 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
982 FrameRegister);
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000983 BufferBegin = SavedBufferBegin;
984 BufferEnd = SavedBufferEnd;
985 CurBufferPtr = SavedCurBufferPtr;
986
987 TheJIT->RegisterTable(FrameRegister);
988 }
Evan Chengca346e62008-09-02 08:14:01 +0000989
990 if (MMI)
991 MMI->EndFunction();
Nicolas Geoffray0e757e12008-02-13 18:39:37 +0000992
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993 return false;
994}
995
996void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
997 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
998 if (Constants.empty()) return;
999
1000 MachineConstantPoolEntry CPE = Constants.back();
1001 unsigned Size = CPE.Offset;
1002 const Type *Ty = CPE.isMachineConstantPoolEntry()
1003 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
Duncan Sandsf99fdc62007-11-01 20:53:16 +00001004 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001005
Evan Cheng71c58872008-04-12 00:22:01 +00001006 unsigned Align = 1 << MCP->getConstantPoolAlignment();
1007 ConstantPoolBase = allocateSpace(Size, Align);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001008 ConstantPool = MCP;
1009
1010 if (ConstantPoolBase == 0) return; // Buffer overflow.
1011
Evan Cheng71c58872008-04-12 00:22:01 +00001012 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1013 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1014
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001015 // Initialize the memory for all of the constant pool entries.
1016 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1017 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
1018 if (Constants[i].isMachineConstantPoolEntry()) {
1019 // FIXME: add support to lower machine constant pool values into bytes!
1020 cerr << "Initialize memory with machine specific constant pool entry"
1021 << " has not been implemented!\n";
1022 abort();
1023 }
1024 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
Evan Cheng71c58872008-04-12 00:22:01 +00001025 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001026 }
1027}
1028
1029void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1030 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1031 if (JT.empty()) return;
1032
1033 unsigned NumEntries = 0;
1034 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1035 NumEntries += JT[i].MBBs.size();
1036
1037 unsigned EntrySize = MJTI->getEntrySize();
1038
1039 // Just allocate space for all the jump tables now. We will fix up the actual
1040 // MBB entries in the tables after we emit the code for each block, since then
1041 // we will know the final locations of the MBBs in memory.
1042 JumpTable = MJTI;
1043 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1044}
1045
1046void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1047 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1048 if (JT.empty() || JumpTableBase == 0) return;
1049
1050 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1051 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1052 // For each jump table, place the offset from the beginning of the table
1053 // to the target address.
1054 int *SlotPtr = (int*)JumpTableBase;
1055
1056 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1057 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1058 // Store the offset of the basic block for this jump table slot in the
1059 // memory we allocated for the jump table in 'initJumpTableInfo'
1060 intptr_t Base = (intptr_t)SlotPtr;
Evan Chengaf743252008-01-05 02:26:58 +00001061 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1062 intptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1063 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1064 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001065 }
1066 } else {
1067 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1068
1069 // For each jump table, map each target in the jump table to the address of
1070 // an emitted MachineBasicBlock.
1071 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1072
1073 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1074 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1075 // Store the address of the basic block for this jump table slot in the
1076 // memory we allocated for the jump table in 'initJumpTableInfo'
1077 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1078 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1079 }
1080 }
1081}
1082
Nicolas Geoffray2b483b52008-04-16 20:46:05 +00001083void JITEmitter::startFunctionStub(const GlobalValue* F, unsigned StubSize,
1084 unsigned Alignment) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001085 SavedBufferBegin = BufferBegin;
1086 SavedBufferEnd = BufferEnd;
1087 SavedCurBufferPtr = CurBufferPtr;
1088
Nicolas Geoffray2b483b52008-04-16 20:46:05 +00001089 BufferBegin = CurBufferPtr = MemMgr->allocateStub(F, StubSize, Alignment);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001090 BufferEnd = BufferBegin+StubSize+1;
1091}
1092
Nicolas Geoffray2b483b52008-04-16 20:46:05 +00001093void *JITEmitter::finishFunctionStub(const GlobalValue* F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001094 NumBytes += getCurrentPCOffset();
Jim Grosbach724b1812008-10-03 16:17:20 +00001095
1096 // Invalidate the icache if necessary.
1097 sys::Memory::InvalidateInstructionCache(BufferBegin, NumBytes);
1098
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001099 std::swap(SavedBufferBegin, BufferBegin);
1100 BufferEnd = SavedBufferEnd;
1101 CurBufferPtr = SavedCurBufferPtr;
1102 return SavedBufferBegin;
1103}
1104
1105// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1106// in the constant pool that was last emitted with the 'emitConstantPool'
1107// method.
1108//
1109intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1110 assert(ConstantNum < ConstantPool->getConstants().size() &&
1111 "Invalid ConstantPoolIndex!");
1112 return (intptr_t)ConstantPoolBase +
1113 ConstantPool->getConstants()[ConstantNum].Offset;
1114}
1115
1116// getJumpTableEntryAddress - Return the address of the JumpTable with index
1117// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1118//
1119intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1120 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1121 assert(Index < JT.size() && "Invalid jump table index!");
1122
1123 unsigned Offset = 0;
1124 unsigned EntrySize = JumpTable->getEntrySize();
1125
1126 for (unsigned i = 0; i < Index; ++i)
1127 Offset += JT[i].MBBs.size();
1128
1129 Offset *= EntrySize;
1130
1131 return (intptr_t)((char *)JumpTableBase + Offset);
1132}
1133
1134//===----------------------------------------------------------------------===//
1135// Public interface to this file
1136//===----------------------------------------------------------------------===//
1137
Chris Lattnere44be002007-12-06 01:08:09 +00001138MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1139 return new JITEmitter(jit, JMM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140}
1141
1142// getPointerToNamedFunction - This function is used as a global wrapper to
1143// JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1144// bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1145// need to resolve function(s) that are being mis-codegenerated, so we need to
1146// resolve their addresses at runtime, and this is the way to do it.
1147extern "C" {
1148 void *getPointerToNamedFunction(const char *Name) {
1149 if (Function *F = TheJIT->FindFunctionNamed(Name))
1150 return TheJIT->getPointerToFunction(F);
1151 return TheJIT->getPointerToNamedFunction(Name);
1152 }
1153}
1154
1155// getPointerToFunctionOrStub - If the specified function has been
1156// code-gen'd, return a pointer to the function. If not, compile it, or use
1157// a stub to implement lazy compilation if available.
1158//
1159void *JIT::getPointerToFunctionOrStub(Function *F) {
1160 // If we have already code generated the function, just return the address.
1161 if (void *Addr = getPointerToGlobalIfAvailable(F))
1162 return Addr;
1163
1164 // Get a stub if the target supports it.
Evan Cheng89b29a12008-08-20 00:28:12 +00001165 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1166 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001167 return JE->getJITResolver().getFunctionStub(F);
1168}
1169
1170/// freeMachineCodeForFunction - release machine code memory for given Function.
1171///
1172void JIT::freeMachineCodeForFunction(Function *F) {
Dale Johannesen0ba4a0e2008-08-07 01:30:15 +00001173
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001174 // Delete translation for this from the ExecutionEngine, so it will get
1175 // retranslated next time it is used.
Chris Lattnerf50e3572008-04-04 05:51:42 +00001176 void *OldPtr = updateGlobalMapping(F, 0);
1177
1178 if (OldPtr)
1179 RemoveFunctionFromSymbolTable(OldPtr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001180
1181 // Free the actual memory for the function body and related stuff.
Evan Cheng89b29a12008-08-20 00:28:12 +00001182 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1183 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001184}
1185