1 //===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "jit"
17 #include "JITDwarfEmitter.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/CodeGen/MachineCodeEmitter.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRelocation.h"
27 #include "llvm/ExecutionEngine/JITMemoryManager.h"
28 #include "llvm/ExecutionEngine/GenericValue.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetJITInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/MutexGuard.h"
35 #include "llvm/Support/ValueHandle.h"
36 #include "llvm/System/Disassembler.h"
37 #include "llvm/System/Memory.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/Statistic.h"
48 STATISTIC(NumBytes
, "Number of bytes of machine code compiled");
49 STATISTIC(NumRelos
, "Number of relocations applied");
50 static JIT
*TheJIT
= 0;
53 //===----------------------------------------------------------------------===//
54 // JIT lazy compilation code.
57 class JITResolverState
{
59 typedef std::map
<AssertingVH
<Function
>, void*> FunctionToStubMapTy
;
60 typedef std::map
<void*, Function
*> StubToFunctionMapTy
;
61 typedef std::map
<AssertingVH
<GlobalValue
>, void*> GlobalToIndirectSymMapTy
;
63 /// FunctionToStubMap - Keep track of the stub created for a particular
64 /// function so that we can reuse them if necessary.
65 FunctionToStubMapTy FunctionToStubMap
;
67 /// StubToFunctionMap - Keep track of the function that each stub
69 StubToFunctionMapTy StubToFunctionMap
;
71 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
72 /// particular GlobalVariable so that we can reuse them if necessary.
73 GlobalToIndirectSymMapTy GlobalToIndirectSymMap
;
76 FunctionToStubMapTy
& getFunctionToStubMap(const MutexGuard
& locked
) {
77 assert(locked
.holds(TheJIT
->lock
));
78 return FunctionToStubMap
;
81 StubToFunctionMapTy
& getStubToFunctionMap(const MutexGuard
& locked
) {
82 assert(locked
.holds(TheJIT
->lock
));
83 return StubToFunctionMap
;
86 GlobalToIndirectSymMapTy
& getGlobalToIndirectSymMap(const MutexGuard
& locked
) {
87 assert(locked
.holds(TheJIT
->lock
));
88 return GlobalToIndirectSymMap
;
92 /// JITResolver - Keep track of, and resolve, call sites for functions that
93 /// have not yet been compiled.
95 typedef JITResolverState::FunctionToStubMapTy FunctionToStubMapTy
;
96 typedef JITResolverState::StubToFunctionMapTy StubToFunctionMapTy
;
97 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy
;
99 /// LazyResolverFn - The target lazy resolver function that we actually
100 /// rewrite instructions to use.
101 TargetJITInfo::LazyResolverFn LazyResolverFn
;
103 JITResolverState state
;
105 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
106 /// external functions.
107 std::map
<void*, void*> ExternalFnToStubMap
;
109 /// revGOTMap - map addresses to indexes in the GOT
110 std::map
<void*, unsigned> revGOTMap
;
111 unsigned nextGOTIndex
;
113 static JITResolver
*TheJITResolver
;
115 explicit JITResolver(JIT
&jit
) : nextGOTIndex(0) {
118 LazyResolverFn
= jit
.getJITInfo().getLazyResolverFunction(JITCompilerFn
);
119 assert(TheJITResolver
== 0 && "Multiple JIT resolvers?");
120 TheJITResolver
= this;
127 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
128 /// if it has already been created.
129 void *getFunctionStubIfAvailable(Function
*F
);
131 /// getFunctionStub - This returns a pointer to a function stub, creating
132 /// one on demand as needed. If empty is true, create a function stub
133 /// pointing at address 0, to be filled in later.
134 void *getFunctionStub(Function
*F
);
136 /// getExternalFunctionStub - Return a stub for the function at the
137 /// specified address, created lazily on demand.
138 void *getExternalFunctionStub(void *FnAddr
);
140 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
141 /// specified GV address.
142 void *getGlobalValueIndirectSym(GlobalValue
*V
, void *GVAddress
);
144 /// AddCallbackAtLocation - If the target is capable of rewriting an
145 /// instruction without the use of a stub, record the location of the use so
146 /// we know which function is being used at the location.
147 void *AddCallbackAtLocation(Function
*F
, void *Location
) {
148 MutexGuard
locked(TheJIT
->lock
);
149 /// Get the target-specific JIT resolver function.
150 state
.getStubToFunctionMap(locked
)[Location
] = F
;
151 return (void*)(intptr_t)LazyResolverFn
;
154 void getRelocatableGVs(SmallVectorImpl
<GlobalValue
*> &GVs
,
155 SmallVectorImpl
<void*> &Ptrs
);
157 GlobalValue
*invalidateStub(void *Stub
);
159 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
160 /// an address. This function only manages slots, it does not manage the
161 /// contents of the slots or the memory associated with the GOT.
162 unsigned getGOTIndexForAddr(void *addr
);
164 /// JITCompilerFn - This function is called to resolve a stub to a compiled
165 /// address. If the LLVM Function corresponding to the stub has not yet
166 /// been compiled, this function compiles it first.
167 static void *JITCompilerFn(void *Stub
);
171 JITResolver
*JITResolver::TheJITResolver
= 0;
173 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
174 /// if it has already been created.
175 void *JITResolver::getFunctionStubIfAvailable(Function
*F
) {
176 MutexGuard
locked(TheJIT
->lock
);
178 // If we already have a stub for this function, recycle it.
179 void *&Stub
= state
.getFunctionToStubMap(locked
)[F
];
183 /// getFunctionStub - This returns a pointer to a function stub, creating
184 /// one on demand as needed.
185 void *JITResolver::getFunctionStub(Function
*F
) {
186 MutexGuard
locked(TheJIT
->lock
);
188 // If we already have a stub for this function, recycle it.
189 void *&Stub
= state
.getFunctionToStubMap(locked
)[F
];
190 if (Stub
) return Stub
;
192 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
193 // case we must resolve the symbol now.
194 void *Actual
= TheJIT
->isLazyCompilationDisabled()
195 ? (void *)0 : (void *)(intptr_t)LazyResolverFn
;
197 // If this is an external declaration, attempt to resolve the address now
198 // to place in the stub.
199 if (F
->isDeclaration() && !F
->hasNotBeenReadFromBitcode()) {
200 Actual
= TheJIT
->getPointerToFunction(F
);
202 // If we resolved the symbol to a null address (eg. a weak external)
203 // don't emit a stub. Return a null pointer to the application. If dlsym
204 // stubs are enabled, not being able to resolve the address is not
206 if (!Actual
&& !TheJIT
->areDlsymStubsEnabled()) return 0;
209 // Codegen a new stub, calling the lazy resolver or the actual address of the
210 // external function, if it was resolved.
211 Stub
= TheJIT
->getJITInfo().emitFunctionStub(F
, Actual
,
212 *TheJIT
->getCodeEmitter());
214 if (Actual
!= (void*)(intptr_t)LazyResolverFn
) {
215 // If we are getting the stub for an external function, we really want the
216 // address of the stub in the GlobalAddressMap for the JIT, not the address
217 // of the external function.
218 TheJIT
->updateGlobalMapping(F
, Stub
);
221 DOUT
<< "JIT: Stub emitted at [" << Stub
<< "] for function '"
222 << F
->getName() << "'\n";
224 // Finally, keep track of the stub-to-Function mapping so that the
225 // JITCompilerFn knows which function to compile!
226 state
.getStubToFunctionMap(locked
)[Stub
] = F
;
228 // If we are JIT'ing non-lazily but need to call a function that does not
229 // exist yet, add it to the JIT's work list so that we can fill in the stub
231 if (!Actual
&& TheJIT
->isLazyCompilationDisabled())
232 if (!F
->isDeclaration() || F
->hasNotBeenReadFromBitcode())
233 TheJIT
->addPendingFunction(F
);
238 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
240 void *JITResolver::getGlobalValueIndirectSym(GlobalValue
*GV
, void *GVAddress
) {
241 MutexGuard
locked(TheJIT
->lock
);
243 // If we already have a stub for this global variable, recycle it.
244 void *&IndirectSym
= state
.getGlobalToIndirectSymMap(locked
)[GV
];
245 if (IndirectSym
) return IndirectSym
;
247 // Otherwise, codegen a new indirect symbol.
248 IndirectSym
= TheJIT
->getJITInfo().emitGlobalValueIndirectSym(GV
, GVAddress
,
249 *TheJIT
->getCodeEmitter());
251 DOUT
<< "JIT: Indirect symbol emitted at [" << IndirectSym
<< "] for GV '"
252 << GV
->getName() << "'\n";
257 /// getExternalFunctionStub - Return a stub for the function at the
258 /// specified address, created lazily on demand.
259 void *JITResolver::getExternalFunctionStub(void *FnAddr
) {
260 // If we already have a stub for this function, recycle it.
261 void *&Stub
= ExternalFnToStubMap
[FnAddr
];
262 if (Stub
) return Stub
;
264 Stub
= TheJIT
->getJITInfo().emitFunctionStub(0, FnAddr
,
265 *TheJIT
->getCodeEmitter());
267 DOUT
<< "JIT: Stub emitted at [" << Stub
268 << "] for external function at '" << FnAddr
<< "'\n";
272 unsigned JITResolver::getGOTIndexForAddr(void* addr
) {
273 unsigned idx
= revGOTMap
[addr
];
275 idx
= ++nextGOTIndex
;
276 revGOTMap
[addr
] = idx
;
277 DOUT
<< "JIT: Adding GOT entry " << idx
<< " for addr [" << addr
<< "]\n";
282 void JITResolver::getRelocatableGVs(SmallVectorImpl
<GlobalValue
*> &GVs
,
283 SmallVectorImpl
<void*> &Ptrs
) {
284 MutexGuard
locked(TheJIT
->lock
);
286 FunctionToStubMapTy
&FM
= state
.getFunctionToStubMap(locked
);
287 GlobalToIndirectSymMapTy
&GM
= state
.getGlobalToIndirectSymMap(locked
);
289 for (FunctionToStubMapTy::iterator i
= FM
.begin(), e
= FM
.end(); i
!= e
; ++i
){
290 Function
*F
= i
->first
;
291 if (F
->isDeclaration() && F
->hasExternalLinkage()) {
292 GVs
.push_back(i
->first
);
293 Ptrs
.push_back(i
->second
);
296 for (GlobalToIndirectSymMapTy::iterator i
= GM
.begin(), e
= GM
.end();
298 GVs
.push_back(i
->first
);
299 Ptrs
.push_back(i
->second
);
303 GlobalValue
*JITResolver::invalidateStub(void *Stub
) {
304 MutexGuard
locked(TheJIT
->lock
);
306 FunctionToStubMapTy
&FM
= state
.getFunctionToStubMap(locked
);
307 StubToFunctionMapTy
&SM
= state
.getStubToFunctionMap(locked
);
308 GlobalToIndirectSymMapTy
&GM
= state
.getGlobalToIndirectSymMap(locked
);
310 // Look up the cheap way first, to see if it's a function stub we are
311 // invalidating. If so, remove it from both the forward and reverse maps.
312 if (SM
.find(Stub
) != SM
.end()) {
313 Function
*F
= SM
[Stub
];
319 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
320 for (GlobalToIndirectSymMapTy::iterator i
= GM
.begin(), e
= GM
.end();
322 if (i
->second
!= Stub
)
324 GlobalValue
*GV
= i
->first
;
329 // Lastly, check to see if it's in the ExternalFnToStubMap.
330 for (std::map
<void *, void *>::iterator i
= ExternalFnToStubMap
.begin(),
331 e
= ExternalFnToStubMap
.end(); i
!= e
; ++i
) {
332 if (i
->second
!= Stub
)
334 ExternalFnToStubMap
.erase(i
);
341 /// JITCompilerFn - This function is called when a lazy compilation stub has
342 /// been entered. It looks up which function this stub corresponds to, compiles
343 /// it if necessary, then returns the resultant function pointer.
344 void *JITResolver::JITCompilerFn(void *Stub
) {
345 JITResolver
&JR
= *TheJITResolver
;
351 // Only lock for getting the Function. The call getPointerToFunction made
352 // in this function might trigger function materializing, which requires
353 // JIT lock to be unlocked.
354 MutexGuard
locked(TheJIT
->lock
);
356 // The address given to us for the stub may not be exactly right, it might be
357 // a little bit after the stub. As such, use upper_bound to find it.
358 StubToFunctionMapTy::iterator I
=
359 JR
.state
.getStubToFunctionMap(locked
).upper_bound(Stub
);
360 assert(I
!= JR
.state
.getStubToFunctionMap(locked
).begin() &&
361 "This is not a known stub!");
363 ActualPtr
= I
->first
;
366 // If we have already code generated the function, just return the address.
367 void *Result
= TheJIT
->getPointerToGlobalIfAvailable(F
);
370 // Otherwise we don't have it, do lazy compilation now.
372 // If lazy compilation is disabled, emit a useful error message and abort.
373 if (TheJIT
->isLazyCompilationDisabled()) {
374 cerr
<< "LLVM JIT requested to do lazy compilation of function '"
375 << F
->getName() << "' when lazy compiles are disabled!\n";
379 // We might like to remove the stub from the StubToFunction map.
380 // We can't do that! Multiple threads could be stuck, waiting to acquire the
381 // lock above. As soon as the 1st function finishes compiling the function,
382 // the next one will be released, and needs to be able to find the function
384 //JR.state.getStubToFunctionMap(locked).erase(I);
386 DOUT
<< "JIT: Lazily resolving function '" << F
->getName()
387 << "' In stub ptr = " << Stub
<< " actual ptr = "
388 << ActualPtr
<< "\n";
390 Result
= TheJIT
->getPointerToFunction(F
);
393 // Reacquire the lock to erase the stub in the map.
394 MutexGuard
locked(TheJIT
->lock
);
396 // We don't need to reuse this stub in the future, as F is now compiled.
397 JR
.state
.getFunctionToStubMap(locked
).erase(F
);
399 // FIXME: We could rewrite all references to this stub if we knew them.
401 // What we will do is set the compiled function address to map to the
402 // same GOT entry as the stub so that later clients may update the GOT
403 // if they see it still using the stub address.
404 // Note: this is done so the Resolver doesn't have to manage GOT memory
405 // Do this without allocating map space if the target isn't using a GOT
406 if(JR
.revGOTMap
.find(Stub
) != JR
.revGOTMap
.end())
407 JR
.revGOTMap
[Result
] = JR
.revGOTMap
[Stub
];
412 //===----------------------------------------------------------------------===//
413 // Function Index Support
415 // On MacOS we generate an index of currently JIT'd functions so that
416 // performance tools can determine a symbol name and accurate code range for a
417 // PC value. Because performance tools are generally asynchronous, the code
418 // below is written with the hope that it could be interrupted at any time and
419 // have useful answers. However, we don't go crazy with atomic operations, we
420 // just do a "reasonable effort".
422 #define ENABLE_JIT_SYMBOL_TABLE 0
425 /// JitSymbolEntry - Each function that is JIT compiled results in one of these
426 /// being added to an array of symbols. This indicates the name of the function
427 /// as well as the address range it occupies. This allows the client to map
428 /// from a PC value to the name of the function.
429 struct JitSymbolEntry
{
430 const char *FnName
; // FnName - a strdup'd string.
436 struct JitSymbolTable
{
437 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
438 /// pointer is not used right now, but might be used in the future. Consider
439 /// it reserved for future use.
440 JitSymbolTable
*NextPtr
;
442 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
443 /// 'NumSymbols' symbols are valid.
444 JitSymbolEntry
*Symbols
;
446 /// NumSymbols - This indicates the number entries in the Symbols array that
450 /// NumAllocated - This indicates the amount of space we have in the Symbols
451 /// array. This is a private field that should not be read by external tools.
452 unsigned NumAllocated
;
455 #if ENABLE_JIT_SYMBOL_TABLE
456 JitSymbolTable
*__jitSymbolTable
;
459 static void AddFunctionToSymbolTable(const char *FnName
,
460 void *FnStart
, intptr_t FnSize
) {
461 assert(FnName
!= 0 && FnStart
!= 0 && "Bad symbol to add");
462 JitSymbolTable
**SymTabPtrPtr
= 0;
463 #if !ENABLE_JIT_SYMBOL_TABLE
466 SymTabPtrPtr
= &__jitSymbolTable
;
469 // If this is the first entry in the symbol table, add the JitSymbolTable
471 if (*SymTabPtrPtr
== 0) {
472 JitSymbolTable
*New
= new JitSymbolTable();
476 New
->NumAllocated
= 0;
480 JitSymbolTable
*SymTabPtr
= *SymTabPtrPtr
;
482 // If we have space in the table, reallocate the table.
483 if (SymTabPtr
->NumSymbols
>= SymTabPtr
->NumAllocated
) {
484 // If we don't have space, reallocate the table.
485 unsigned NewSize
= std::max(64U, SymTabPtr
->NumAllocated
*2);
486 JitSymbolEntry
*NewSymbols
= new JitSymbolEntry
[NewSize
];
487 JitSymbolEntry
*OldSymbols
= SymTabPtr
->Symbols
;
489 // Copy the old entries over.
490 memcpy(NewSymbols
, OldSymbols
, SymTabPtr
->NumSymbols
*sizeof(OldSymbols
[0]));
492 // Swap the new symbols in, delete the old ones.
493 SymTabPtr
->Symbols
= NewSymbols
;
494 SymTabPtr
->NumAllocated
= NewSize
;
495 delete [] OldSymbols
;
498 // Otherwise, we have enough space, just tack it onto the end of the array.
499 JitSymbolEntry
&Entry
= SymTabPtr
->Symbols
[SymTabPtr
->NumSymbols
];
500 Entry
.FnName
= strdup(FnName
);
501 Entry
.FnStart
= FnStart
;
502 Entry
.FnSize
= FnSize
;
503 ++SymTabPtr
->NumSymbols
;
506 static void RemoveFunctionFromSymbolTable(void *FnStart
) {
507 assert(FnStart
&& "Invalid function pointer");
508 JitSymbolTable
**SymTabPtrPtr
= 0;
509 #if !ENABLE_JIT_SYMBOL_TABLE
512 SymTabPtrPtr
= &__jitSymbolTable
;
515 JitSymbolTable
*SymTabPtr
= *SymTabPtrPtr
;
516 JitSymbolEntry
*Symbols
= SymTabPtr
->Symbols
;
518 // Scan the table to find its index. The table is not sorted, so do a linear
521 for (Index
= 0; Symbols
[Index
].FnStart
!= FnStart
; ++Index
)
522 assert(Index
!= SymTabPtr
->NumSymbols
&& "Didn't find function!");
524 // Once we have an index, we know to nuke this entry, overwrite it with the
525 // entry at the end of the array, making the last entry redundant.
526 const char *OldName
= Symbols
[Index
].FnName
;
527 Symbols
[Index
] = Symbols
[SymTabPtr
->NumSymbols
-1];
528 free((void*)OldName
);
530 // Drop the number of symbols in the table.
531 --SymTabPtr
->NumSymbols
;
533 // Finally, if we deleted the final symbol, deallocate the table itself.
534 if (SymTabPtr
->NumSymbols
!= 0)
542 //===----------------------------------------------------------------------===//
546 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
547 /// used to output functions to memory for execution.
548 class JITEmitter
: public MachineCodeEmitter
{
549 JITMemoryManager
*MemMgr
;
551 // When outputting a function stub in the context of some other function, we
552 // save BufferBegin/BufferEnd/CurBufferPtr here.
553 unsigned char *SavedBufferBegin
, *SavedBufferEnd
, *SavedCurBufferPtr
;
555 /// Relocations - These are the relocations that the function needs, as
557 std::vector
<MachineRelocation
> Relocations
;
559 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
560 /// It is filled in by the StartMachineBasicBlock callback and queried by
561 /// the getMachineBasicBlockAddress callback.
562 std::vector
<uintptr_t> MBBLocations
;
564 /// ConstantPool - The constant pool for the current function.
566 MachineConstantPool
*ConstantPool
;
568 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
570 void *ConstantPoolBase
;
572 /// ConstPoolAddresses - Addresses of individual constant pool entries.
574 SmallVector
<uintptr_t, 8> ConstPoolAddresses
;
576 /// JumpTable - The jump tables for the current function.
578 MachineJumpTableInfo
*JumpTable
;
580 /// JumpTableBase - A pointer to the first entry in the jump table.
584 /// Resolver - This contains info about the currently resolved functions.
585 JITResolver Resolver
;
587 /// DE - The dwarf emitter for the jit.
590 /// LabelLocations - This vector is a mapping from Label ID's to their
592 std::vector
<uintptr_t> LabelLocations
;
594 /// MMI - Machine module info for exception informations
595 MachineModuleInfo
* MMI
;
597 // GVSet - a set to keep track of which globals have been seen
598 SmallPtrSet
<const GlobalVariable
*, 8> GVSet
;
600 // CurFn - The llvm function being emitted. Only valid during
602 const Function
*CurFn
;
604 // CurFnStubUses - For a given Function, a vector of stubs that it
605 // references. This facilitates the JIT detecting that a stub is no
606 // longer used, so that it may be deallocated.
607 DenseMap
<const Function
*, SmallVector
<void*, 1> > CurFnStubUses
;
609 // StubFnRefs - For a given pointer to a stub, a set of Functions which
610 // reference the stub. When the count of a stub's references drops to zero,
611 // the stub is unused.
612 DenseMap
<void *, SmallPtrSet
<const Function
*, 1> > StubFnRefs
;
614 // ExtFnStubs - A map of external function names to stubs which have entries
615 // in the JITResolver's ExternalFnToStubMap.
616 StringMap
<void *> ExtFnStubs
;
619 JITEmitter(JIT
&jit
, JITMemoryManager
*JMM
) : Resolver(jit
), CurFn(0) {
620 MemMgr
= JMM
? JMM
: JITMemoryManager::CreateDefaultMemManager();
621 if (jit
.getJITInfo().needsGOT()) {
622 MemMgr
->AllocateGOT();
623 DOUT
<< "JIT is managing a GOT\n";
626 if (ExceptionHandling
) DE
= new JITDwarfEmitter(jit
);
630 if (ExceptionHandling
) delete DE
;
633 /// classof - Methods for support type inquiry through isa, cast, and
636 static inline bool classof(const JITEmitter
*) { return true; }
637 static inline bool classof(const MachineCodeEmitter
*) { return true; }
639 JITResolver
&getJITResolver() { return Resolver
; }
641 virtual void startFunction(MachineFunction
&F
);
642 virtual bool finishFunction(MachineFunction
&F
);
644 void emitConstantPool(MachineConstantPool
*MCP
);
645 void initJumpTableInfo(MachineJumpTableInfo
*MJTI
);
646 void emitJumpTableInfo(MachineJumpTableInfo
*MJTI
);
648 virtual void startGVStub(const GlobalValue
* GV
, unsigned StubSize
,
649 unsigned Alignment
= 1);
650 virtual void startGVStub(const GlobalValue
* GV
, void *Buffer
,
652 virtual void* finishGVStub(const GlobalValue
*GV
);
654 /// allocateSpace - Reserves space in the current block if any, or
655 /// allocate a new one of the given size.
656 virtual void *allocateSpace(uintptr_t Size
, unsigned Alignment
);
658 virtual void addRelocation(const MachineRelocation
&MR
) {
659 Relocations
.push_back(MR
);
662 virtual void StartMachineBasicBlock(MachineBasicBlock
*MBB
) {
663 if (MBBLocations
.size() <= (unsigned)MBB
->getNumber())
664 MBBLocations
.resize((MBB
->getNumber()+1)*2);
665 MBBLocations
[MBB
->getNumber()] = getCurrentPCValue();
666 DOUT
<< "JIT: Emitting BB" << MBB
->getNumber() << " at ["
667 << (void*) getCurrentPCValue() << "]\n";
670 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry
) const;
671 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry
) const;
673 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock
*MBB
) const {
674 assert(MBBLocations
.size() > (unsigned)MBB
->getNumber() &&
675 MBBLocations
[MBB
->getNumber()] && "MBB not emitted!");
676 return MBBLocations
[MBB
->getNumber()];
679 /// deallocateMemForFunction - Deallocate all memory for the specified
681 void deallocateMemForFunction(Function
*F
);
683 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
684 /// using the stub at the specified address. Allows
685 /// deallocateMemForFunction to also remove stubs no longer referenced.
686 void AddStubToCurrentFunction(void *Stub
);
688 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
689 /// MachineRelocations that reference external functions by name.
690 const StringMap
<void*> &getExternalFnStubs() const { return ExtFnStubs
; }
692 virtual void emitLabel(uint64_t LabelID
) {
693 if (LabelLocations
.size() <= LabelID
)
694 LabelLocations
.resize((LabelID
+1)*2);
695 LabelLocations
[LabelID
] = getCurrentPCValue();
698 virtual uintptr_t getLabelAddress(uint64_t LabelID
) const {
699 assert(LabelLocations
.size() > (unsigned)LabelID
&&
700 LabelLocations
[LabelID
] && "Label not emitted!");
701 return LabelLocations
[LabelID
];
704 virtual void setModuleInfo(MachineModuleInfo
* Info
) {
706 if (ExceptionHandling
) DE
->setModuleInfo(Info
);
709 void setMemoryExecutable(void) {
710 MemMgr
->setMemoryExecutable();
713 JITMemoryManager
*getMemMgr(void) const { return MemMgr
; }
716 void *getPointerToGlobal(GlobalValue
*GV
, void *Reference
, bool NoNeedStub
);
717 void *getPointerToGVIndirectSym(GlobalValue
*V
, void *Reference
,
719 unsigned addSizeOfGlobal(const GlobalVariable
*GV
, unsigned Size
);
720 unsigned addSizeOfGlobalsInConstantVal(const Constant
*C
, unsigned Size
);
721 unsigned addSizeOfGlobalsInInitializer(const Constant
*Init
, unsigned Size
);
722 unsigned GetSizeOfGlobalsInBytes(MachineFunction
&MF
);
726 void *JITEmitter::getPointerToGlobal(GlobalValue
*V
, void *Reference
,
727 bool DoesntNeedStub
) {
728 if (GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(V
))
729 return TheJIT
->getOrEmitGlobalVariable(GV
);
731 if (GlobalAlias
*GA
= dyn_cast
<GlobalAlias
>(V
))
732 return TheJIT
->getPointerToGlobal(GA
->resolveAliasedGlobal(false));
734 // If we have already compiled the function, return a pointer to its body.
735 Function
*F
= cast
<Function
>(V
);
737 if (!DoesntNeedStub
&& !TheJIT
->isLazyCompilationDisabled()) {
738 // Return the function stub if it's already created.
739 ResultPtr
= Resolver
.getFunctionStubIfAvailable(F
);
741 AddStubToCurrentFunction(ResultPtr
);
743 ResultPtr
= TheJIT
->getPointerToGlobalIfAvailable(F
);
745 if (ResultPtr
) return ResultPtr
;
747 // If this is an external function pointer, we can force the JIT to
748 // 'compile' it, which really just adds it to the map. In dlsym mode,
749 // external functions are forced through a stub, regardless of reloc type.
750 if (F
->isDeclaration() && !F
->hasNotBeenReadFromBitcode() &&
751 DoesntNeedStub
&& !TheJIT
->areDlsymStubsEnabled())
752 return TheJIT
->getPointerToFunction(F
);
754 // Okay, the function has not been compiled yet, if the target callback
755 // mechanism is capable of rewriting the instruction directly, prefer to do
756 // that instead of emitting a stub. This uses the lazy resolver, so is not
757 // legal if lazy compilation is disabled.
758 if (DoesntNeedStub
&& !TheJIT
->isLazyCompilationDisabled())
759 return Resolver
.AddCallbackAtLocation(F
, Reference
);
761 // Otherwise, we have to emit a stub.
762 void *StubAddr
= Resolver
.getFunctionStub(F
);
764 // Add the stub to the current function's list of referenced stubs, so we can
765 // deallocate them if the current function is ever freed. It's possible to
766 // return null from getFunctionStub in the case of a weak extern that fails
769 AddStubToCurrentFunction(StubAddr
);
774 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue
*V
, void *Reference
,
776 // Make sure GV is emitted first, and create a stub containing the fully
778 void *GVAddress
= getPointerToGlobal(V
, Reference
, true);
779 void *StubAddr
= Resolver
.getGlobalValueIndirectSym(V
, GVAddress
);
781 // Add the stub to the current function's list of referenced stubs, so we can
782 // deallocate them if the current function is ever freed.
783 AddStubToCurrentFunction(StubAddr
);
788 void JITEmitter::AddStubToCurrentFunction(void *StubAddr
) {
789 if (!TheJIT
->areDlsymStubsEnabled())
792 assert(CurFn
&& "Stub added to current function, but current function is 0!");
794 SmallVectorImpl
<void*> &StubsUsed
= CurFnStubUses
[CurFn
];
795 StubsUsed
.push_back(StubAddr
);
797 SmallPtrSet
<const Function
*, 1> &FnRefs
= StubFnRefs
[StubAddr
];
798 FnRefs
.insert(CurFn
);
801 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool
*MCP
,
802 const TargetData
*TD
) {
803 const std::vector
<MachineConstantPoolEntry
> &Constants
= MCP
->getConstants();
804 if (Constants
.empty()) return 0;
807 for (unsigned i
= 0, e
= Constants
.size(); i
!= e
; ++i
) {
808 MachineConstantPoolEntry CPE
= Constants
[i
];
809 unsigned AlignMask
= CPE
.getAlignment() - 1;
810 Size
= (Size
+ AlignMask
) & ~AlignMask
;
811 const Type
*Ty
= CPE
.getType();
812 Size
+= TD
->getTypeAllocSize(Ty
);
817 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo
*MJTI
) {
818 const std::vector
<MachineJumpTableEntry
> &JT
= MJTI
->getJumpTables();
819 if (JT
.empty()) return 0;
821 unsigned NumEntries
= 0;
822 for (unsigned i
= 0, e
= JT
.size(); i
!= e
; ++i
)
823 NumEntries
+= JT
[i
].MBBs
.size();
825 unsigned EntrySize
= MJTI
->getEntrySize();
827 return NumEntries
* EntrySize
;
830 static uintptr_t RoundUpToAlign(uintptr_t Size
, unsigned Alignment
) {
831 if (Alignment
== 0) Alignment
= 1;
832 // Since we do not know where the buffer will be allocated, be pessimistic.
833 return Size
+ Alignment
;
836 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
837 /// into the running total Size.
839 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable
*GV
, unsigned Size
) {
840 const Type
*ElTy
= GV
->getType()->getElementType();
841 size_t GVSize
= (size_t)TheJIT
->getTargetData()->getTypeAllocSize(ElTy
);
843 (size_t)TheJIT
->getTargetData()->getPreferredAlignment(GV
);
844 DOUT
<< "JIT: Adding in size " << GVSize
<< " alignment " << GVAlign
;
846 // Assume code section ends with worst possible alignment, so first
847 // variable needs maximal padding.
850 Size
= ((Size
+GVAlign
-1)/GVAlign
)*GVAlign
;
855 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
856 /// but are referenced from the constant; put them in GVSet and add their
857 /// size into the running total Size.
859 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant
*C
,
861 // If its undefined, return the garbage.
862 if (isa
<UndefValue
>(C
))
865 // If the value is a ConstantExpr
866 if (const ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(C
)) {
867 Constant
*Op0
= CE
->getOperand(0);
868 switch (CE
->getOpcode()) {
869 case Instruction::GetElementPtr
:
870 case Instruction::Trunc
:
871 case Instruction::ZExt
:
872 case Instruction::SExt
:
873 case Instruction::FPTrunc
:
874 case Instruction::FPExt
:
875 case Instruction::UIToFP
:
876 case Instruction::SIToFP
:
877 case Instruction::FPToUI
:
878 case Instruction::FPToSI
:
879 case Instruction::PtrToInt
:
880 case Instruction::IntToPtr
:
881 case Instruction::BitCast
: {
882 Size
= addSizeOfGlobalsInConstantVal(Op0
, Size
);
885 case Instruction::Add
:
886 case Instruction::Sub
:
887 case Instruction::Mul
:
888 case Instruction::UDiv
:
889 case Instruction::SDiv
:
890 case Instruction::URem
:
891 case Instruction::SRem
:
892 case Instruction::And
:
893 case Instruction::Or
:
894 case Instruction::Xor
: {
895 Size
= addSizeOfGlobalsInConstantVal(Op0
, Size
);
896 Size
= addSizeOfGlobalsInConstantVal(CE
->getOperand(1), Size
);
900 cerr
<< "ConstantExpr not handled: " << *CE
<< "\n";
906 if (C
->getType()->getTypeID() == Type::PointerTyID
)
907 if (const GlobalVariable
* GV
= dyn_cast
<GlobalVariable
>(C
))
908 if (GVSet
.insert(GV
))
909 Size
= addSizeOfGlobal(GV
, Size
);
914 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
915 /// but are referenced from the given initializer.
917 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant
*Init
,
919 if (!isa
<UndefValue
>(Init
) &&
920 !isa
<ConstantVector
>(Init
) &&
921 !isa
<ConstantAggregateZero
>(Init
) &&
922 !isa
<ConstantArray
>(Init
) &&
923 !isa
<ConstantStruct
>(Init
) &&
924 Init
->getType()->isFirstClassType())
925 Size
= addSizeOfGlobalsInConstantVal(Init
, Size
);
929 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
930 /// globals; then walk the initializers of those globals looking for more.
931 /// If their size has not been considered yet, add it into the running total
934 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction
&MF
) {
938 for (MachineFunction::iterator MBB
= MF
.begin(), E
= MF
.end();
940 for (MachineBasicBlock::const_iterator I
= MBB
->begin(), E
= MBB
->end();
942 const TargetInstrDesc
&Desc
= I
->getDesc();
943 const MachineInstr
&MI
= *I
;
944 unsigned NumOps
= Desc
.getNumOperands();
945 for (unsigned CurOp
= 0; CurOp
< NumOps
; CurOp
++) {
946 const MachineOperand
&MO
= MI
.getOperand(CurOp
);
948 GlobalValue
* V
= MO
.getGlobal();
949 const GlobalVariable
*GV
= dyn_cast
<const GlobalVariable
>(V
);
952 // If seen in previous function, it will have an entry here.
953 if (TheJIT
->getPointerToGlobalIfAvailable(GV
))
955 // If seen earlier in this function, it will have an entry here.
956 // FIXME: it should be possible to combine these tables, by
957 // assuming the addresses of the new globals in this module
958 // start at 0 (or something) and adjusting them after codegen
959 // complete. Another possibility is to grab a marker bit in GV.
960 if (GVSet
.insert(GV
))
961 // A variable as yet unseen. Add in its size.
962 Size
= addSizeOfGlobal(GV
, Size
);
967 DOUT
<< "JIT: About to look through initializers\n";
968 // Look for more globals that are referenced only from initializers.
969 // GVSet.end is computed each time because the set can grow as we go.
970 for (SmallPtrSet
<const GlobalVariable
*, 8>::iterator I
= GVSet
.begin();
971 I
!= GVSet
.end(); I
++) {
972 const GlobalVariable
* GV
= *I
;
973 if (GV
->hasInitializer())
974 Size
= addSizeOfGlobalsInInitializer(GV
->getInitializer(), Size
);
980 void JITEmitter::startFunction(MachineFunction
&F
) {
981 DOUT
<< "JIT: Starting CodeGen of Function "
982 << F
.getFunction()->getName() << "\n";
984 uintptr_t ActualSize
= 0;
985 // Set the memory writable, if it's not already
986 MemMgr
->setMemoryWritable();
987 if (MemMgr
->NeedsExactSize()) {
988 DOUT
<< "JIT: ExactSize\n";
989 const TargetInstrInfo
* TII
= F
.getTarget().getInstrInfo();
990 MachineJumpTableInfo
*MJTI
= F
.getJumpTableInfo();
991 MachineConstantPool
*MCP
= F
.getConstantPool();
993 // Ensure the constant pool/jump table info is at least 4-byte aligned.
994 ActualSize
= RoundUpToAlign(ActualSize
, 16);
996 // Add the alignment of the constant pool
997 ActualSize
= RoundUpToAlign(ActualSize
, MCP
->getConstantPoolAlignment());
999 // Add the constant pool size
1000 ActualSize
+= GetConstantPoolSizeInBytes(MCP
, TheJIT
->getTargetData());
1002 // Add the aligment of the jump table info
1003 ActualSize
= RoundUpToAlign(ActualSize
, MJTI
->getAlignment());
1005 // Add the jump table size
1006 ActualSize
+= GetJumpTableSizeInBytes(MJTI
);
1008 // Add the alignment for the function
1009 ActualSize
= RoundUpToAlign(ActualSize
,
1010 std::max(F
.getFunction()->getAlignment(), 8U));
1012 // Add the function size
1013 ActualSize
+= TII
->GetFunctionSizeInBytes(F
);
1015 DOUT
<< "JIT: ActualSize before globals " << ActualSize
<< "\n";
1016 // Add the size of the globals that will be allocated after this function.
1017 // These are all the ones referenced from this function that were not
1018 // previously allocated.
1019 ActualSize
+= GetSizeOfGlobalsInBytes(F
);
1020 DOUT
<< "JIT: ActualSize after globals " << ActualSize
<< "\n";
1023 BufferBegin
= CurBufferPtr
= MemMgr
->startFunctionBody(F
.getFunction(),
1025 BufferEnd
= BufferBegin
+ActualSize
;
1027 // Ensure the constant pool/jump table info is at least 4-byte aligned.
1030 emitConstantPool(F
.getConstantPool());
1031 initJumpTableInfo(F
.getJumpTableInfo());
1033 // About to start emitting the machine code for the function.
1034 emitAlignment(std::max(F
.getFunction()->getAlignment(), 8U));
1035 TheJIT
->updateGlobalMapping(F
.getFunction(), CurBufferPtr
);
1037 MBBLocations
.clear();
1040 bool JITEmitter::finishFunction(MachineFunction
&F
) {
1041 if (CurBufferPtr
== BufferEnd
) {
1042 // FIXME: Allocate more space, then try again.
1043 cerr
<< "JIT: Ran out of space for generated machine code!\n";
1047 emitJumpTableInfo(F
.getJumpTableInfo());
1049 // FnStart is the start of the text, not the start of the constant pool and
1050 // other per-function data.
1051 unsigned char *FnStart
=
1052 (unsigned char *)TheJIT
->getPointerToGlobalIfAvailable(F
.getFunction());
1054 // FnEnd is the end of the function's machine code.
1055 unsigned char *FnEnd
= CurBufferPtr
;
1057 if (!Relocations
.empty()) {
1058 CurFn
= F
.getFunction();
1059 NumRelos
+= Relocations
.size();
1061 // Resolve the relocations to concrete pointers.
1062 for (unsigned i
= 0, e
= Relocations
.size(); i
!= e
; ++i
) {
1063 MachineRelocation
&MR
= Relocations
[i
];
1064 void *ResultPtr
= 0;
1065 if (!MR
.letTargetResolve()) {
1066 if (MR
.isExternalSymbol()) {
1067 ResultPtr
= TheJIT
->getPointerToNamedFunction(MR
.getExternalSymbol(),
1069 DOUT
<< "JIT: Map \'" << MR
.getExternalSymbol() << "\' to ["
1070 << ResultPtr
<< "]\n";
1072 // If the target REALLY wants a stub for this function, emit it now.
1073 if (!MR
.doesntNeedStub()) {
1074 if (!TheJIT
->areDlsymStubsEnabled()) {
1075 ResultPtr
= Resolver
.getExternalFunctionStub(ResultPtr
);
1077 void *&Stub
= ExtFnStubs
[MR
.getExternalSymbol()];
1079 Stub
= Resolver
.getExternalFunctionStub((void *)&Stub
);
1080 AddStubToCurrentFunction(Stub
);
1085 } else if (MR
.isGlobalValue()) {
1086 ResultPtr
= getPointerToGlobal(MR
.getGlobalValue(),
1087 BufferBegin
+MR
.getMachineCodeOffset(),
1088 MR
.doesntNeedStub());
1089 } else if (MR
.isIndirectSymbol()) {
1090 ResultPtr
= getPointerToGVIndirectSym(MR
.getGlobalValue(),
1091 BufferBegin
+MR
.getMachineCodeOffset(),
1092 MR
.doesntNeedStub());
1093 } else if (MR
.isBasicBlock()) {
1094 ResultPtr
= (void*)getMachineBasicBlockAddress(MR
.getBasicBlock());
1095 } else if (MR
.isConstantPoolIndex()) {
1096 ResultPtr
= (void*)getConstantPoolEntryAddress(MR
.getConstantPoolIndex());
1098 assert(MR
.isJumpTableIndex());
1099 ResultPtr
=(void*)getJumpTableEntryAddress(MR
.getJumpTableIndex());
1102 MR
.setResultPointer(ResultPtr
);
1105 // if we are managing the GOT and the relocation wants an index,
1107 if (MR
.isGOTRelative() && MemMgr
->isManagingGOT()) {
1108 unsigned idx
= Resolver
.getGOTIndexForAddr(ResultPtr
);
1109 MR
.setGOTIndex(idx
);
1110 if (((void**)MemMgr
->getGOTBase())[idx
] != ResultPtr
) {
1111 DOUT
<< "JIT: GOT was out of date for " << ResultPtr
1112 << " pointing at " << ((void**)MemMgr
->getGOTBase())[idx
]
1114 ((void**)MemMgr
->getGOTBase())[idx
] = ResultPtr
;
1120 TheJIT
->getJITInfo().relocate(BufferBegin
, &Relocations
[0],
1121 Relocations
.size(), MemMgr
->getGOTBase());
1124 // Update the GOT entry for F to point to the new code.
1125 if (MemMgr
->isManagingGOT()) {
1126 unsigned idx
= Resolver
.getGOTIndexForAddr((void*)BufferBegin
);
1127 if (((void**)MemMgr
->getGOTBase())[idx
] != (void*)BufferBegin
) {
1128 DOUT
<< "JIT: GOT was out of date for " << (void*)BufferBegin
1129 << " pointing at " << ((void**)MemMgr
->getGOTBase())[idx
] << "\n";
1130 ((void**)MemMgr
->getGOTBase())[idx
] = (void*)BufferBegin
;
1134 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
1135 // global variables that were referenced in the relocations.
1136 MemMgr
->endFunctionBody(F
.getFunction(), BufferBegin
, CurBufferPtr
);
1138 if (CurBufferPtr
== BufferEnd
) {
1139 // FIXME: Allocate more space, then try again.
1140 cerr
<< "JIT: Ran out of space for generated machine code!\n";
1144 BufferBegin
= CurBufferPtr
= 0;
1145 NumBytes
+= FnEnd
-FnStart
;
1147 // Invalidate the icache if necessary.
1148 sys::Memory::InvalidateInstructionCache(FnStart
, FnEnd
-FnStart
);
1150 // Add it to the JIT symbol table if the host wants it.
1151 AddFunctionToSymbolTable(F
.getFunction()->getNameStart(),
1152 FnStart
, FnEnd
-FnStart
);
1154 DOUT
<< "JIT: Finished CodeGen of [" << (void*)FnStart
1155 << "] Function: " << F
.getFunction()->getName()
1156 << ": " << (FnEnd
-FnStart
) << " bytes of text, "
1157 << Relocations
.size() << " relocations\n";
1158 Relocations
.clear();
1159 ConstPoolAddresses
.clear();
1161 // Mark code region readable and executable if it's not so already.
1162 MemMgr
->setMemoryExecutable();
1166 if (sys::hasDisassembler()) {
1167 DOUT
<< "JIT: Disassembled code:\n";
1168 DOUT
<< sys::disassembleBuffer(FnStart
, FnEnd
-FnStart
, (uintptr_t)FnStart
);
1170 DOUT
<< "JIT: Binary code:\n";
1172 unsigned char* q
= FnStart
;
1173 for (int i
= 0; q
< FnEnd
; q
+= 4, ++i
) {
1177 DOUT
<< "JIT: " << std::setw(8) << std::setfill('0')
1178 << (long)(q
- FnStart
) << ": ";
1180 for (int j
= 3; j
>= 0; --j
) {
1184 DOUT
<< std::setw(2) << std::setfill('0') << (unsigned short)q
[j
];
1197 if (ExceptionHandling
) {
1198 uintptr_t ActualSize
= 0;
1199 SavedBufferBegin
= BufferBegin
;
1200 SavedBufferEnd
= BufferEnd
;
1201 SavedCurBufferPtr
= CurBufferPtr
;
1203 if (MemMgr
->NeedsExactSize()) {
1204 ActualSize
= DE
->GetDwarfTableSizeInBytes(F
, *this, FnStart
, FnEnd
);
1207 BufferBegin
= CurBufferPtr
= MemMgr
->startExceptionTable(F
.getFunction(),
1209 BufferEnd
= BufferBegin
+ActualSize
;
1210 unsigned char* FrameRegister
= DE
->EmitDwarfTable(F
, *this, FnStart
, FnEnd
);
1211 MemMgr
->endExceptionTable(F
.getFunction(), BufferBegin
, CurBufferPtr
,
1213 BufferBegin
= SavedBufferBegin
;
1214 BufferEnd
= SavedBufferEnd
;
1215 CurBufferPtr
= SavedCurBufferPtr
;
1217 TheJIT
->RegisterTable(FrameRegister
);
1226 /// deallocateMemForFunction - Deallocate all memory for the specified
1227 /// function body. Also drop any references the function has to stubs.
1228 void JITEmitter::deallocateMemForFunction(Function
*F
) {
1229 MemMgr
->deallocateMemForFunction(F
);
1231 // If the function did not reference any stubs, return.
1232 if (CurFnStubUses
.find(F
) == CurFnStubUses
.end())
1235 // For each referenced stub, erase the reference to this function, and then
1236 // erase the list of referenced stubs.
1237 SmallVectorImpl
<void *> &StubList
= CurFnStubUses
[F
];
1238 for (unsigned i
= 0, e
= StubList
.size(); i
!= e
; ++i
) {
1239 void *Stub
= StubList
[i
];
1241 // If we already invalidated this stub for this function, continue.
1242 if (StubFnRefs
.count(Stub
) == 0)
1245 SmallPtrSet
<const Function
*, 1> &FnRefs
= StubFnRefs
[Stub
];
1248 // If this function was the last reference to the stub, invalidate the stub
1249 // in the JITResolver. Were there a memory manager deallocateStub routine,
1250 // we could call that at this point too.
1251 if (FnRefs
.empty()) {
1252 DOUT
<< "\nJIT: Invalidated Stub at [" << Stub
<< "]\n";
1253 StubFnRefs
.erase(Stub
);
1255 // Invalidate the stub. If it is a GV stub, update the JIT's global
1256 // mapping for that GV to zero, otherwise, search the string map of
1257 // external function names to stubs and remove the entry for this stub.
1258 GlobalValue
*GV
= Resolver
.invalidateStub(Stub
);
1260 TheJIT
->updateGlobalMapping(GV
, 0);
1262 for (StringMapIterator
<void*> i
= ExtFnStubs
.begin(),
1263 e
= ExtFnStubs
.end(); i
!= e
; ++i
) {
1264 if (i
->second
== Stub
) {
1265 ExtFnStubs
.erase(i
);
1272 CurFnStubUses
.erase(F
);
1276 void* JITEmitter::allocateSpace(uintptr_t Size
, unsigned Alignment
) {
1278 return MachineCodeEmitter::allocateSpace(Size
, Alignment
);
1280 // create a new memory block if there is no active one.
1281 // care must be taken so that BufferBegin is invalidated when a
1283 BufferBegin
= CurBufferPtr
= MemMgr
->allocateSpace(Size
, Alignment
);
1284 BufferEnd
= BufferBegin
+Size
;
1285 return CurBufferPtr
;
1288 void JITEmitter::emitConstantPool(MachineConstantPool
*MCP
) {
1289 if (TheJIT
->getJITInfo().hasCustomConstantPool())
1292 const std::vector
<MachineConstantPoolEntry
> &Constants
= MCP
->getConstants();
1293 if (Constants
.empty()) return;
1295 unsigned Size
= GetConstantPoolSizeInBytes(MCP
, TheJIT
->getTargetData());
1296 unsigned Align
= MCP
->getConstantPoolAlignment();
1297 ConstantPoolBase
= allocateSpace(Size
, Align
);
1300 if (ConstantPoolBase
== 0) return; // Buffer overflow.
1302 DOUT
<< "JIT: Emitted constant pool at [" << ConstantPoolBase
1303 << "] (size: " << Size
<< ", alignment: " << Align
<< ")\n";
1305 // Initialize the memory for all of the constant pool entries.
1306 unsigned Offset
= 0;
1307 for (unsigned i
= 0, e
= Constants
.size(); i
!= e
; ++i
) {
1308 MachineConstantPoolEntry CPE
= Constants
[i
];
1309 unsigned AlignMask
= CPE
.getAlignment() - 1;
1310 Offset
= (Offset
+ AlignMask
) & ~AlignMask
;
1312 uintptr_t CAddr
= (uintptr_t)ConstantPoolBase
+ Offset
;
1313 ConstPoolAddresses
.push_back(CAddr
);
1314 if (CPE
.isMachineConstantPoolEntry()) {
1315 // FIXME: add support to lower machine constant pool values into bytes!
1316 cerr
<< "Initialize memory with machine specific constant pool entry"
1317 << " has not been implemented!\n";
1320 TheJIT
->InitializeMemory(CPE
.Val
.ConstVal
, (void*)CAddr
);
1321 DOUT
<< "JIT: CP" << i
<< " at [0x"
1322 << std::hex
<< CAddr
<< std::dec
<< "]\n";
1324 const Type
*Ty
= CPE
.Val
.ConstVal
->getType();
1325 Offset
+= TheJIT
->getTargetData()->getTypeAllocSize(Ty
);
1329 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo
*MJTI
) {
1330 if (TheJIT
->getJITInfo().hasCustomJumpTables())
1333 const std::vector
<MachineJumpTableEntry
> &JT
= MJTI
->getJumpTables();
1334 if (JT
.empty()) return;
1336 unsigned NumEntries
= 0;
1337 for (unsigned i
= 0, e
= JT
.size(); i
!= e
; ++i
)
1338 NumEntries
+= JT
[i
].MBBs
.size();
1340 unsigned EntrySize
= MJTI
->getEntrySize();
1342 // Just allocate space for all the jump tables now. We will fix up the actual
1343 // MBB entries in the tables after we emit the code for each block, since then
1344 // we will know the final locations of the MBBs in memory.
1346 JumpTableBase
= allocateSpace(NumEntries
* EntrySize
, MJTI
->getAlignment());
1349 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo
*MJTI
) {
1350 if (TheJIT
->getJITInfo().hasCustomJumpTables())
1353 const std::vector
<MachineJumpTableEntry
> &JT
= MJTI
->getJumpTables();
1354 if (JT
.empty() || JumpTableBase
== 0) return;
1356 if (TargetMachine::getRelocationModel() == Reloc::PIC_
) {
1357 assert(MJTI
->getEntrySize() == 4 && "Cross JIT'ing?");
1358 // For each jump table, place the offset from the beginning of the table
1359 // to the target address.
1360 int *SlotPtr
= (int*)JumpTableBase
;
1362 for (unsigned i
= 0, e
= JT
.size(); i
!= e
; ++i
) {
1363 const std::vector
<MachineBasicBlock
*> &MBBs
= JT
[i
].MBBs
;
1364 // Store the offset of the basic block for this jump table slot in the
1365 // memory we allocated for the jump table in 'initJumpTableInfo'
1366 uintptr_t Base
= (uintptr_t)SlotPtr
;
1367 for (unsigned mi
= 0, me
= MBBs
.size(); mi
!= me
; ++mi
) {
1368 uintptr_t MBBAddr
= getMachineBasicBlockAddress(MBBs
[mi
]);
1369 *SlotPtr
++ = TheJIT
->getJITInfo().getPICJumpTableEntry(MBBAddr
, Base
);
1373 assert(MJTI
->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1375 // For each jump table, map each target in the jump table to the address of
1376 // an emitted MachineBasicBlock.
1377 intptr_t *SlotPtr
= (intptr_t*)JumpTableBase
;
1379 for (unsigned i
= 0, e
= JT
.size(); i
!= e
; ++i
) {
1380 const std::vector
<MachineBasicBlock
*> &MBBs
= JT
[i
].MBBs
;
1381 // Store the address of the basic block for this jump table slot in the
1382 // memory we allocated for the jump table in 'initJumpTableInfo'
1383 for (unsigned mi
= 0, me
= MBBs
.size(); mi
!= me
; ++mi
)
1384 *SlotPtr
++ = getMachineBasicBlockAddress(MBBs
[mi
]);
1389 void JITEmitter::startGVStub(const GlobalValue
* GV
, unsigned StubSize
,
1390 unsigned Alignment
) {
1391 SavedBufferBegin
= BufferBegin
;
1392 SavedBufferEnd
= BufferEnd
;
1393 SavedCurBufferPtr
= CurBufferPtr
;
1395 BufferBegin
= CurBufferPtr
= MemMgr
->allocateStub(GV
, StubSize
, Alignment
);
1396 BufferEnd
= BufferBegin
+StubSize
+1;
1399 void JITEmitter::startGVStub(const GlobalValue
* GV
, void *Buffer
,
1400 unsigned StubSize
) {
1401 SavedBufferBegin
= BufferBegin
;
1402 SavedBufferEnd
= BufferEnd
;
1403 SavedCurBufferPtr
= CurBufferPtr
;
1405 BufferBegin
= CurBufferPtr
= (unsigned char *)Buffer
;
1406 BufferEnd
= BufferBegin
+StubSize
+1;
1409 void *JITEmitter::finishGVStub(const GlobalValue
* GV
) {
1410 NumBytes
+= getCurrentPCOffset();
1411 std::swap(SavedBufferBegin
, BufferBegin
);
1412 BufferEnd
= SavedBufferEnd
;
1413 CurBufferPtr
= SavedCurBufferPtr
;
1414 return SavedBufferBegin
;
1417 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1418 // in the constant pool that was last emitted with the 'emitConstantPool'
1421 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum
) const {
1422 assert(ConstantNum
< ConstantPool
->getConstants().size() &&
1423 "Invalid ConstantPoolIndex!");
1424 return ConstPoolAddresses
[ConstantNum
];
1427 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1428 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1430 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index
) const {
1431 const std::vector
<MachineJumpTableEntry
> &JT
= JumpTable
->getJumpTables();
1432 assert(Index
< JT
.size() && "Invalid jump table index!");
1434 unsigned Offset
= 0;
1435 unsigned EntrySize
= JumpTable
->getEntrySize();
1437 for (unsigned i
= 0; i
< Index
; ++i
)
1438 Offset
+= JT
[i
].MBBs
.size();
1440 Offset
*= EntrySize
;
1442 return (uintptr_t)((char *)JumpTableBase
+ Offset
);
1445 //===----------------------------------------------------------------------===//
1446 // Public interface to this file
1447 //===----------------------------------------------------------------------===//
1449 MachineCodeEmitter
*JIT::createEmitter(JIT
&jit
, JITMemoryManager
*JMM
) {
1450 return new JITEmitter(jit
, JMM
);
1453 // getPointerToNamedFunction - This function is used as a global wrapper to
1454 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1455 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1456 // need to resolve function(s) that are being mis-codegenerated, so we need to
1457 // resolve their addresses at runtime, and this is the way to do it.
1459 void *getPointerToNamedFunction(const char *Name
) {
1460 if (Function
*F
= TheJIT
->FindFunctionNamed(Name
))
1461 return TheJIT
->getPointerToFunction(F
);
1462 return TheJIT
->getPointerToNamedFunction(Name
);
1466 // getPointerToFunctionOrStub - If the specified function has been
1467 // code-gen'd, return a pointer to the function. If not, compile it, or use
1468 // a stub to implement lazy compilation if available.
1470 void *JIT::getPointerToFunctionOrStub(Function
*F
) {
1471 // If we have already code generated the function, just return the address.
1472 if (void *Addr
= getPointerToGlobalIfAvailable(F
))
1475 // Get a stub if the target supports it.
1476 assert(isa
<JITEmitter
>(MCE
) && "Unexpected MCE?");
1477 JITEmitter
*JE
= cast
<JITEmitter
>(getCodeEmitter());
1478 return JE
->getJITResolver().getFunctionStub(F
);
1481 void JIT::updateFunctionStub(Function
*F
) {
1482 // Get the empty stub we generated earlier.
1483 assert(isa
<JITEmitter
>(MCE
) && "Unexpected MCE?");
1484 JITEmitter
*JE
= cast
<JITEmitter
>(getCodeEmitter());
1485 void *Stub
= JE
->getJITResolver().getFunctionStub(F
);
1487 // Tell the target jit info to rewrite the stub at the specified address,
1488 // rather than creating a new one.
1489 void *Addr
= getPointerToGlobalIfAvailable(F
);
1490 getJITInfo().emitFunctionStubAtAddr(F
, Addr
, Stub
, *getCodeEmitter());
1493 /// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1494 /// that were emitted during code generation.
1496 void JIT::updateDlsymStubTable() {
1497 assert(isa
<JITEmitter
>(MCE
) && "Unexpected MCE?");
1498 JITEmitter
*JE
= cast
<JITEmitter
>(getCodeEmitter());
1500 SmallVector
<GlobalValue
*, 8> GVs
;
1501 SmallVector
<void*, 8> Ptrs
;
1502 const StringMap
<void *> &ExtFns
= JE
->getExternalFnStubs();
1504 JE
->getJITResolver().getRelocatableGVs(GVs
, Ptrs
);
1506 unsigned nStubs
= GVs
.size() + ExtFns
.size();
1508 // If there are no relocatable stubs, return.
1512 // If there are no new relocatable stubs, return.
1513 void *CurTable
= JE
->getMemMgr()->getDlsymTable();
1514 if (CurTable
&& (*(unsigned *)CurTable
== nStubs
))
1517 // Calculate the size of the stub info
1518 unsigned offset
= 4 + 4 * nStubs
+ sizeof(intptr_t) * nStubs
;
1520 SmallVector
<unsigned, 8> Offsets
;
1521 for (unsigned i
= 0; i
!= GVs
.size(); ++i
) {
1522 Offsets
.push_back(offset
);
1523 offset
+= GVs
[i
]->getName().length() + 1;
1525 for (StringMapConstIterator
<void*> i
= ExtFns
.begin(), e
= ExtFns
.end();
1527 Offsets
.push_back(offset
);
1528 offset
+= strlen(i
->first()) + 1;
1531 // Allocate space for the new "stub", which contains the dlsym table.
1532 JE
->startGVStub(0, offset
, 4);
1534 // Emit the number of records
1535 MCE
->emitInt32(nStubs
);
1537 // Emit the string offsets
1538 for (unsigned i
= 0; i
!= nStubs
; ++i
)
1539 MCE
->emitInt32(Offsets
[i
]);
1541 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1542 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1543 // relocation can write the relocated pointer at the appropriate place in
1545 for (unsigned i
= 0; i
!= GVs
.size(); ++i
) {
1546 intptr_t Ptr
= (intptr_t)Ptrs
[i
];
1547 assert((Ptr
& 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1549 if (isa
<Function
>(GVs
[i
]))
1552 if (sizeof(Ptr
) == 8)
1553 MCE
->emitInt64(Ptr
);
1555 MCE
->emitInt32(Ptr
);
1557 for (StringMapConstIterator
<void*> i
= ExtFns
.begin(), e
= ExtFns
.end();
1559 intptr_t Ptr
= (intptr_t)i
->second
| 1;
1561 if (sizeof(Ptr
) == 8)
1562 MCE
->emitInt64(Ptr
);
1564 MCE
->emitInt32(Ptr
);
1567 // Emit the strings.
1568 for (unsigned i
= 0; i
!= GVs
.size(); ++i
)
1569 MCE
->emitString(GVs
[i
]->getName());
1570 for (StringMapConstIterator
<void*> i
= ExtFns
.begin(), e
= ExtFns
.end();
1572 MCE
->emitString(i
->first());
1574 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1575 // deallocate space for the old one, if one existed.
1576 JE
->getMemMgr()->SetDlsymTable(JE
->finishGVStub(0));
1579 /// freeMachineCodeForFunction - release machine code memory for given Function.
1581 void JIT::freeMachineCodeForFunction(Function
*F
) {
1583 // Delete translation for this from the ExecutionEngine, so it will get
1584 // retranslated next time it is used.
1585 void *OldPtr
= updateGlobalMapping(F
, 0);
1588 RemoveFunctionFromSymbolTable(OldPtr
);
1590 // Free the actual memory for the function body and related stuff.
1591 assert(isa
<JITEmitter
>(MCE
) && "Unexpected MCE?");
1592 cast
<JITEmitter
>(MCE
)->deallocateMemForFunction(F
);