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/System/Disassembler.h"
36 #include "llvm/System/Memory.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/ADT/Statistic.h"
47 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
48 STATISTIC(NumRelos, "Number of relocations applied");
49 static JIT *TheJIT = 0;
52 //===----------------------------------------------------------------------===//
53 // JIT lazy compilation code.
56 class JITResolverState {
58 /// FunctionToStubMap - Keep track of the stub created for a particular
59 /// function so that we can reuse them if necessary.
60 std::map<Function*, void*> FunctionToStubMap;
62 /// StubToFunctionMap - Keep track of the function that each stub
64 std::map<void*, Function*> StubToFunctionMap;
66 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
67 /// particular GlobalVariable so that we can reuse them if necessary.
68 std::map<GlobalValue*, void*> GlobalToIndirectSymMap;
71 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
72 assert(locked.holds(TheJIT->lock));
73 return FunctionToStubMap;
76 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
77 assert(locked.holds(TheJIT->lock));
78 return StubToFunctionMap;
81 std::map<GlobalValue*, void*>&
82 getGlobalToIndirectSymMap(const MutexGuard& locked) {
83 assert(locked.holds(TheJIT->lock));
84 return GlobalToIndirectSymMap;
88 /// JITResolver - Keep track of, and resolve, call sites for functions that
89 /// have not yet been compiled.
91 /// LazyResolverFn - The target lazy resolver function that we actually
92 /// rewrite instructions to use.
93 TargetJITInfo::LazyResolverFn LazyResolverFn;
95 JITResolverState state;
97 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
98 /// external functions.
99 std::map<void*, void*> ExternalFnToStubMap;
101 //map addresses to indexes in the GOT
102 std::map<void*, unsigned> revGOTMap;
103 unsigned nextGOTIndex;
105 static JITResolver *TheJITResolver;
107 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
110 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
111 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
112 TheJITResolver = this;
119 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
120 /// if it has already been created.
121 void *getFunctionStubIfAvailable(Function *F);
123 /// getFunctionStub - This returns a pointer to a function stub, creating
124 /// one on demand as needed. If empty is true, create a function stub
125 /// pointing at address 0, to be filled in later.
126 void *getFunctionStub(Function *F, bool empty = false);
128 /// getExternalFunctionStub - Return a stub for the function at the
129 /// specified address, created lazily on demand.
130 void *getExternalFunctionStub(void *FnAddr);
132 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
133 /// specified GV address.
134 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
136 /// AddCallbackAtLocation - If the target is capable of rewriting an
137 /// instruction without the use of a stub, record the location of the use so
138 /// we know which function is being used at the location.
139 void *AddCallbackAtLocation(Function *F, void *Location) {
140 MutexGuard locked(TheJIT->lock);
141 /// Get the target-specific JIT resolver function.
142 state.getStubToFunctionMap(locked)[Location] = F;
143 return (void*)(intptr_t)LazyResolverFn;
146 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
147 SmallVectorImpl<void*> &Ptrs);
149 GlobalValue *invalidateStub(void *Stub);
151 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
152 /// an address. This function only manages slots, it does not manage the
153 /// contents of the slots or the memory associated with the GOT.
154 unsigned getGOTIndexForAddr(void *addr);
156 /// JITCompilerFn - This function is called to resolve a stub to a compiled
157 /// address. If the LLVM Function corresponding to the stub has not yet
158 /// been compiled, this function compiles it first.
159 static void *JITCompilerFn(void *Stub);
163 JITResolver *JITResolver::TheJITResolver = 0;
165 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
166 /// if it has already been created.
167 void *JITResolver::getFunctionStubIfAvailable(Function *F) {
168 MutexGuard locked(TheJIT->lock);
170 // If we already have a stub for this function, recycle it.
171 void *&Stub = state.getFunctionToStubMap(locked)[F];
175 /// getFunctionStub - This returns a pointer to a function stub, creating
176 /// one on demand as needed.
177 void *JITResolver::getFunctionStub(Function *F, bool empty) {
178 MutexGuard locked(TheJIT->lock);
180 // If we already have a stub for this function, recycle it.
181 void *&Stub = state.getFunctionToStubMap(locked)[F];
182 if (Stub) return Stub;
184 // Call the lazy resolver function unless we already KNOW it is an external
185 // function, in which case we just skip the lazy resolution step.
186 void *Actual = empty ? (void*)0 : (void*)(intptr_t)LazyResolverFn;
187 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
188 Actual = TheJIT->getPointerToFunction(F);
190 // If we resolved the symbol to a null address (eg. a weak external)
191 // don't emit a stub. Return a null pointer to the application.
192 if (!Actual) return 0;
195 // Otherwise, codegen a new stub. For now, the stub will call the lazy
196 // resolver function.
197 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
198 *TheJIT->getCodeEmitter());
200 if (Actual != (void*)(intptr_t)LazyResolverFn) {
201 // If we are getting the stub for an external function, we really want the
202 // address of the stub in the GlobalAddressMap for the JIT, not the address
203 // of the external function.
204 TheJIT->updateGlobalMapping(F, Stub);
207 cerr << "JIT: Stub emitted at [" << Stub << "] for function '"
208 << F->getName() << "'\n";
210 // Finally, keep track of the stub-to-Function mapping so that the
211 // JITCompilerFn knows which function to compile!
212 state.getStubToFunctionMap(locked)[Stub] = F;
214 // If this is an "empty" stub, then inform the JIT that it will need to
215 // JIT the function so an address can be provided.
217 TheJIT->addPendingFunction(F);
222 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
224 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
225 MutexGuard locked(TheJIT->lock);
227 // If we already have a stub for this global variable, recycle it.
228 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
229 if (IndirectSym) return IndirectSym;
231 // Otherwise, codegen a new indirect symbol.
232 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
233 *TheJIT->getCodeEmitter());
235 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
236 << GV->getName() << "'\n";
241 /// getExternalFunctionStub - Return a stub for the function at the
242 /// specified address, created lazily on demand.
243 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
244 // If we already have a stub for this function, recycle it.
245 void *&Stub = ExternalFnToStubMap[FnAddr];
246 if (Stub) return Stub;
248 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
249 *TheJIT->getCodeEmitter());
251 DOUT << "JIT: Stub emitted at [" << Stub
252 << "] for external function at '" << FnAddr << "'\n";
256 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
257 unsigned idx = revGOTMap[addr];
259 idx = ++nextGOTIndex;
260 revGOTMap[addr] = idx;
261 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
266 void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
267 SmallVectorImpl<void*> &Ptrs) {
268 MutexGuard locked(TheJIT->lock);
270 std::map<Function*,void*> &FM = state.getFunctionToStubMap(locked);
271 std::map<GlobalValue*,void*> &GM = state.getGlobalToIndirectSymMap(locked);
273 for (std::map<Function*,void*>::iterator i = FM.begin(), e = FM.end();
275 Function *F = i->first;
276 if (F->isDeclaration() && F->hasExternalLinkage()) {
277 GVs.push_back(i->first);
278 Ptrs.push_back(i->second);
281 for (std::map<GlobalValue*,void*>::iterator i = GM.begin(), e = GM.end();
283 GVs.push_back(i->first);
284 Ptrs.push_back(i->second);
288 GlobalValue *JITResolver::invalidateStub(void *Stub) {
289 MutexGuard locked(TheJIT->lock);
291 std::map<Function*,void*> &FM = state.getFunctionToStubMap(locked);
292 std::map<void*,Function*> &SM = state.getStubToFunctionMap(locked);
293 std::map<GlobalValue*,void*> &GM = state.getGlobalToIndirectSymMap(locked);
295 // Look up the cheap way first, to see if it's a function stub we are
296 // invalidating. If so, remove it from both the forward and reverse maps.
297 if (SM.find(Stub) != SM.end()) {
298 Function *F = SM[Stub];
304 // Otherwise, it must be an indirect symbol stub. Find it and remove it.
305 for (std::map<GlobalValue*,void*>::iterator i = GM.begin(), e = GM.end();
307 if (i->second != Stub)
309 GlobalValue *GV = i->first;
317 /// JITCompilerFn - This function is called when a lazy compilation stub has
318 /// been entered. It looks up which function this stub corresponds to, compiles
319 /// it if necessary, then returns the resultant function pointer.
320 void *JITResolver::JITCompilerFn(void *Stub) {
321 JITResolver &JR = *TheJITResolver;
327 // Only lock for getting the Function. The call getPointerToFunction made
328 // in this function might trigger function materializing, which requires
329 // JIT lock to be unlocked.
330 MutexGuard locked(TheJIT->lock);
332 // The address given to us for the stub may not be exactly right, it might be
333 // a little bit after the stub. As such, use upper_bound to find it.
334 std::map<void*, Function*>::iterator I =
335 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
336 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
337 "This is not a known stub!");
339 ActualPtr = I->first;
342 // If we have already code generated the function, just return the address.
343 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
346 // Otherwise we don't have it, do lazy compilation now.
348 // If lazy compilation is disabled, emit a useful error message and abort.
349 if (TheJIT->isLazyCompilationDisabled()) {
350 cerr << "LLVM JIT requested to do lazy compilation of function '"
351 << F->getName() << "' when lazy compiles are disabled!\n";
355 // We might like to remove the stub from the StubToFunction map.
356 // We can't do that! Multiple threads could be stuck, waiting to acquire the
357 // lock above. As soon as the 1st function finishes compiling the function,
358 // the next one will be released, and needs to be able to find the function
360 //JR.state.getStubToFunctionMap(locked).erase(I);
362 DOUT << "JIT: Lazily resolving function '" << F->getName()
363 << "' In stub ptr = " << Stub << " actual ptr = "
364 << ActualPtr << "\n";
366 Result = TheJIT->getPointerToFunction(F);
369 // Reacquire the lock to erase the stub in the map.
370 MutexGuard locked(TheJIT->lock);
372 // We don't need to reuse this stub in the future, as F is now compiled.
373 JR.state.getFunctionToStubMap(locked).erase(F);
375 // FIXME: We could rewrite all references to this stub if we knew them.
377 // What we will do is set the compiled function address to map to the
378 // same GOT entry as the stub so that later clients may update the GOT
379 // if they see it still using the stub address.
380 // Note: this is done so the Resolver doesn't have to manage GOT memory
381 // Do this without allocating map space if the target isn't using a GOT
382 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
383 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
388 //===----------------------------------------------------------------------===//
389 // Function Index Support
391 // On MacOS we generate an index of currently JIT'd functions so that
392 // performance tools can determine a symbol name and accurate code range for a
393 // PC value. Because performance tools are generally asynchronous, the code
394 // below is written with the hope that it could be interrupted at any time and
395 // have useful answers. However, we don't go crazy with atomic operations, we
396 // just do a "reasonable effort".
398 #define ENABLE_JIT_SYMBOL_TABLE 0
401 /// JitSymbolEntry - Each function that is JIT compiled results in one of these
402 /// being added to an array of symbols. This indicates the name of the function
403 /// as well as the address range it occupies. This allows the client to map
404 /// from a PC value to the name of the function.
405 struct JitSymbolEntry {
406 const char *FnName; // FnName - a strdup'd string.
412 struct JitSymbolTable {
413 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
414 /// pointer is not used right now, but might be used in the future. Consider
415 /// it reserved for future use.
416 JitSymbolTable *NextPtr;
418 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
419 /// 'NumSymbols' symbols are valid.
420 JitSymbolEntry *Symbols;
422 /// NumSymbols - This indicates the number entries in the Symbols array that
426 /// NumAllocated - This indicates the amount of space we have in the Symbols
427 /// array. This is a private field that should not be read by external tools.
428 unsigned NumAllocated;
431 #if ENABLE_JIT_SYMBOL_TABLE
432 JitSymbolTable *__jitSymbolTable;
435 static void AddFunctionToSymbolTable(const char *FnName,
436 void *FnStart, intptr_t FnSize) {
437 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
438 JitSymbolTable **SymTabPtrPtr = 0;
439 #if !ENABLE_JIT_SYMBOL_TABLE
442 SymTabPtrPtr = &__jitSymbolTable;
445 // If this is the first entry in the symbol table, add the JitSymbolTable
447 if (*SymTabPtrPtr == 0) {
448 JitSymbolTable *New = new JitSymbolTable();
452 New->NumAllocated = 0;
456 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
458 // If we have space in the table, reallocate the table.
459 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
460 // If we don't have space, reallocate the table.
461 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
462 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
463 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
465 // Copy the old entries over.
466 memcpy(NewSymbols, OldSymbols, SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
468 // Swap the new symbols in, delete the old ones.
469 SymTabPtr->Symbols = NewSymbols;
470 SymTabPtr->NumAllocated = NewSize;
471 delete [] OldSymbols;
474 // Otherwise, we have enough space, just tack it onto the end of the array.
475 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
476 Entry.FnName = strdup(FnName);
477 Entry.FnStart = FnStart;
478 Entry.FnSize = FnSize;
479 ++SymTabPtr->NumSymbols;
482 static void RemoveFunctionFromSymbolTable(void *FnStart) {
483 assert(FnStart && "Invalid function pointer");
484 JitSymbolTable **SymTabPtrPtr = 0;
485 #if !ENABLE_JIT_SYMBOL_TABLE
488 SymTabPtrPtr = &__jitSymbolTable;
491 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
492 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
494 // Scan the table to find its index. The table is not sorted, so do a linear
497 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
498 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
500 // Once we have an index, we know to nuke this entry, overwrite it with the
501 // entry at the end of the array, making the last entry redundant.
502 const char *OldName = Symbols[Index].FnName;
503 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
504 free((void*)OldName);
506 // Drop the number of symbols in the table.
507 --SymTabPtr->NumSymbols;
509 // Finally, if we deleted the final symbol, deallocate the table itself.
510 if (SymTabPtr->NumSymbols != 0)
518 //===----------------------------------------------------------------------===//
522 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
523 /// used to output functions to memory for execution.
524 class JITEmitter : public MachineCodeEmitter {
525 JITMemoryManager *MemMgr;
527 // When outputting a function stub in the context of some other function, we
528 // save BufferBegin/BufferEnd/CurBufferPtr here.
529 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
531 /// Relocations - These are the relocations that the function needs, as
533 std::vector<MachineRelocation> Relocations;
535 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
536 /// It is filled in by the StartMachineBasicBlock callback and queried by
537 /// the getMachineBasicBlockAddress callback.
538 std::vector<uintptr_t> MBBLocations;
540 /// ConstantPool - The constant pool for the current function.
542 MachineConstantPool *ConstantPool;
544 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
546 void *ConstantPoolBase;
548 /// JumpTable - The jump tables for the current function.
550 MachineJumpTableInfo *JumpTable;
552 /// JumpTableBase - A pointer to the first entry in the jump table.
556 /// Resolver - This contains info about the currently resolved functions.
557 JITResolver Resolver;
559 /// DE - The dwarf emitter for the jit.
562 /// LabelLocations - This vector is a mapping from Label ID's to their
564 std::vector<uintptr_t> LabelLocations;
566 /// MMI - Machine module info for exception informations
567 MachineModuleInfo* MMI;
569 // GVSet - a set to keep track of which globals have been seen
570 SmallPtrSet<const GlobalVariable*, 8> GVSet;
572 // CurFn - The llvm function being emitted. Only valid during
574 const Function *CurFn;
576 // CurFnStubUses - For a given Function, a vector of stubs that it
577 // references. This facilitates the JIT detecting that a stub is no
578 // longer used, so that it may be deallocated.
579 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
581 // StubFnRefs - For a given pointer to a stub, a set of Functions which
582 // reference the stub. When the count of a stub's references drops to zero,
583 // the stub is unused.
584 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
587 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit), CurFn(0) {
588 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
589 if (jit.getJITInfo().needsGOT()) {
590 MemMgr->AllocateGOT();
591 DOUT << "JIT is managing a GOT\n";
594 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
598 if (ExceptionHandling) delete DE;
601 /// classof - Methods for support type inquiry through isa, cast, and
604 static inline bool classof(const JITEmitter*) { return true; }
605 static inline bool classof(const MachineCodeEmitter*) { return true; }
607 JITResolver &getJITResolver() { return Resolver; }
609 virtual void startFunction(MachineFunction &F);
610 virtual bool finishFunction(MachineFunction &F);
612 void emitConstantPool(MachineConstantPool *MCP);
613 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
614 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
616 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
617 unsigned Alignment = 1);
618 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
620 virtual void* finishGVStub(const GlobalValue *GV);
622 /// allocateSpace - Reserves space in the current block if any, or
623 /// allocate a new one of the given size.
624 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
626 virtual void addRelocation(const MachineRelocation &MR) {
627 Relocations.push_back(MR);
630 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
631 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
632 MBBLocations.resize((MBB->getNumber()+1)*2);
633 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
634 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
635 << (void*) getCurrentPCValue() << "]\n";
638 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
639 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
641 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
642 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
643 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
644 return MBBLocations[MBB->getNumber()];
647 void AddStubToCurrentFunction(void *Stub);
649 /// deallocateMemForFunction - Deallocate all memory for the specified
651 void deallocateMemForFunction(Function *F);
653 virtual void emitLabel(uint64_t LabelID) {
654 if (LabelLocations.size() <= LabelID)
655 LabelLocations.resize((LabelID+1)*2);
656 LabelLocations[LabelID] = getCurrentPCValue();
659 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
660 assert(LabelLocations.size() > (unsigned)LabelID &&
661 LabelLocations[LabelID] && "Label not emitted!");
662 return LabelLocations[LabelID];
665 virtual void setModuleInfo(MachineModuleInfo* Info) {
667 if (ExceptionHandling) DE->setModuleInfo(Info);
670 void setMemoryExecutable(void) {
671 MemMgr->setMemoryExecutable();
674 JITMemoryManager *getMemMgr(void) const { return MemMgr; }
677 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
678 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
680 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
681 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
682 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
683 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
687 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
688 bool DoesntNeedStub) {
689 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
690 return TheJIT->getOrEmitGlobalVariable(GV);
692 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
693 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
695 // If we have already compiled the function, return a pointer to its body.
696 Function *F = cast<Function>(V);
698 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled()) {
699 // Return the function stub if it's already created.
700 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
702 AddStubToCurrentFunction(ResultPtr);
704 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
706 if (ResultPtr) return ResultPtr;
708 // If this is an external function pointer, we can force the JIT to
709 // 'compile' it, which really just adds it to the map.
710 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() && DoesntNeedStub)
711 return TheJIT->getPointerToFunction(F);
713 // If we are jitting non-lazily but encounter a function that has not been
714 // jitted yet, we need to allocate a blank stub to call the function
715 // once we JIT it and its address is known.
716 if (TheJIT->isLazyCompilationDisabled())
717 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
718 return Resolver.getFunctionStub(F, true);
720 // Okay, the function has not been compiled yet, if the target callback
721 // mechanism is capable of rewriting the instruction directly, prefer to do
722 // that instead of emitting a stub.
724 return Resolver.AddCallbackAtLocation(F, Reference);
726 // Otherwise, we have to emit a lazy resolving stub.
727 void *StubAddr = Resolver.getFunctionStub(F);
729 // Add the stub to the current function's list of referenced stubs, so we can
730 // deallocate them if the current function is ever freed.
731 AddStubToCurrentFunction(StubAddr);
736 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
738 // Make sure GV is emitted first, and create a stub containing the fully
740 void *GVAddress = getPointerToGlobal(V, Reference, true);
741 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
743 // Add the stub to the current function's list of referenced stubs, so we can
744 // deallocate them if the current function is ever freed.
745 AddStubToCurrentFunction(StubAddr);
750 void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
751 if (!TheJIT->areDlsymStubsEnabled())
754 assert(CurFn && "Stub added to current function, but current function is 0!");
756 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
757 StubsUsed.push_back(StubAddr);
759 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
760 FnRefs.insert(CurFn);
763 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
764 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
765 if (Constants.empty()) return 0;
767 MachineConstantPoolEntry CPE = Constants.back();
768 unsigned Size = CPE.Offset;
769 const Type *Ty = CPE.isMachineConstantPoolEntry()
770 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
771 Size += TheJIT->getTargetData()->getTypePaddedSize(Ty);
775 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
776 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
777 if (JT.empty()) return 0;
779 unsigned NumEntries = 0;
780 for (unsigned i = 0, e = JT.size(); i != e; ++i)
781 NumEntries += JT[i].MBBs.size();
783 unsigned EntrySize = MJTI->getEntrySize();
785 return NumEntries * EntrySize;
788 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
789 if (Alignment == 0) Alignment = 1;
790 // Since we do not know where the buffer will be allocated, be pessimistic.
791 return Size + Alignment;
794 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
795 /// into the running total Size.
797 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
798 const Type *ElTy = GV->getType()->getElementType();
799 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypePaddedSize(ElTy);
801 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
802 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
804 // Assume code section ends with worst possible alignment, so first
805 // variable needs maximal padding.
808 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
813 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
814 /// but are referenced from the constant; put them in GVSet and add their
815 /// size into the running total Size.
817 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
819 // If its undefined, return the garbage.
820 if (isa<UndefValue>(C))
823 // If the value is a ConstantExpr
824 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
825 Constant *Op0 = CE->getOperand(0);
826 switch (CE->getOpcode()) {
827 case Instruction::GetElementPtr:
828 case Instruction::Trunc:
829 case Instruction::ZExt:
830 case Instruction::SExt:
831 case Instruction::FPTrunc:
832 case Instruction::FPExt:
833 case Instruction::UIToFP:
834 case Instruction::SIToFP:
835 case Instruction::FPToUI:
836 case Instruction::FPToSI:
837 case Instruction::PtrToInt:
838 case Instruction::IntToPtr:
839 case Instruction::BitCast: {
840 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
843 case Instruction::Add:
844 case Instruction::Sub:
845 case Instruction::Mul:
846 case Instruction::UDiv:
847 case Instruction::SDiv:
848 case Instruction::URem:
849 case Instruction::SRem:
850 case Instruction::And:
851 case Instruction::Or:
852 case Instruction::Xor: {
853 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
854 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
858 cerr << "ConstantExpr not handled: " << *CE << "\n";
864 if (C->getType()->getTypeID() == Type::PointerTyID)
865 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
866 if (GVSet.insert(GV))
867 Size = addSizeOfGlobal(GV, Size);
872 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
873 /// but are referenced from the given initializer.
875 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
877 if (!isa<UndefValue>(Init) &&
878 !isa<ConstantVector>(Init) &&
879 !isa<ConstantAggregateZero>(Init) &&
880 !isa<ConstantArray>(Init) &&
881 !isa<ConstantStruct>(Init) &&
882 Init->getType()->isFirstClassType())
883 Size = addSizeOfGlobalsInConstantVal(Init, Size);
887 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
888 /// globals; then walk the initializers of those globals looking for more.
889 /// If their size has not been considered yet, add it into the running total
892 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
896 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
898 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
900 const TargetInstrDesc &Desc = I->getDesc();
901 const MachineInstr &MI = *I;
902 unsigned NumOps = Desc.getNumOperands();
903 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
904 const MachineOperand &MO = MI.getOperand(CurOp);
906 GlobalValue* V = MO.getGlobal();
907 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
910 // If seen in previous function, it will have an entry here.
911 if (TheJIT->getPointerToGlobalIfAvailable(GV))
913 // If seen earlier in this function, it will have an entry here.
914 // FIXME: it should be possible to combine these tables, by
915 // assuming the addresses of the new globals in this module
916 // start at 0 (or something) and adjusting them after codegen
917 // complete. Another possibility is to grab a marker bit in GV.
918 if (GVSet.insert(GV))
919 // A variable as yet unseen. Add in its size.
920 Size = addSizeOfGlobal(GV, Size);
925 DOUT << "JIT: About to look through initializers\n";
926 // Look for more globals that are referenced only from initializers.
927 // GVSet.end is computed each time because the set can grow as we go.
928 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
929 I != GVSet.end(); I++) {
930 const GlobalVariable* GV = *I;
931 if (GV->hasInitializer())
932 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
938 void JITEmitter::startFunction(MachineFunction &F) {
939 DOUT << "JIT: Starting CodeGen of Function "
940 << F.getFunction()->getName() << "\n";
942 uintptr_t ActualSize = 0;
943 // Set the memory writable, if it's not already
944 MemMgr->setMemoryWritable();
945 if (MemMgr->NeedsExactSize()) {
946 DOUT << "JIT: ExactSize\n";
947 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
948 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
949 MachineConstantPool *MCP = F.getConstantPool();
951 // Ensure the constant pool/jump table info is at least 4-byte aligned.
952 ActualSize = RoundUpToAlign(ActualSize, 16);
954 // Add the alignment of the constant pool
955 ActualSize = RoundUpToAlign(ActualSize,
956 1 << MCP->getConstantPoolAlignment());
958 // Add the constant pool size
959 ActualSize += GetConstantPoolSizeInBytes(MCP);
961 // Add the aligment of the jump table info
962 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
964 // Add the jump table size
965 ActualSize += GetJumpTableSizeInBytes(MJTI);
967 // Add the alignment for the function
968 ActualSize = RoundUpToAlign(ActualSize,
969 std::max(F.getFunction()->getAlignment(), 8U));
971 // Add the function size
972 ActualSize += TII->GetFunctionSizeInBytes(F);
974 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
975 // Add the size of the globals that will be allocated after this function.
976 // These are all the ones referenced from this function that were not
977 // previously allocated.
978 ActualSize += GetSizeOfGlobalsInBytes(F);
979 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
982 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
984 BufferEnd = BufferBegin+ActualSize;
986 // Ensure the constant pool/jump table info is at least 4-byte aligned.
989 emitConstantPool(F.getConstantPool());
990 initJumpTableInfo(F.getJumpTableInfo());
992 // About to start emitting the machine code for the function.
993 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
994 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
996 MBBLocations.clear();
999 bool JITEmitter::finishFunction(MachineFunction &F) {
1000 if (CurBufferPtr == BufferEnd) {
1001 // FIXME: Allocate more space, then try again.
1002 cerr << "JIT: Ran out of space for generated machine code!\n";
1006 emitJumpTableInfo(F.getJumpTableInfo());
1008 // FnStart is the start of the text, not the start of the constant pool and
1009 // other per-function data.
1010 unsigned char *FnStart =
1011 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
1013 if (!Relocations.empty()) {
1014 CurFn = F.getFunction();
1015 NumRelos += Relocations.size();
1017 // Resolve the relocations to concrete pointers.
1018 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1019 MachineRelocation &MR = Relocations[i];
1020 void *ResultPtr = 0;
1021 if (!MR.letTargetResolve()) {
1022 if (MR.isExternalSymbol()) {
1023 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1025 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
1026 << ResultPtr << "]\n";
1028 // If the target REALLY wants a stub for this function, emit it now.
1029 if (!MR.doesntNeedStub())
1030 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1031 } else if (MR.isGlobalValue()) {
1032 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1033 BufferBegin+MR.getMachineCodeOffset(),
1034 MR.doesntNeedStub());
1035 } else if (MR.isIndirectSymbol()) {
1036 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
1037 BufferBegin+MR.getMachineCodeOffset(),
1038 MR.doesntNeedStub());
1039 } else if (MR.isBasicBlock()) {
1040 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1041 } else if (MR.isConstantPoolIndex()) {
1042 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1044 assert(MR.isJumpTableIndex());
1045 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1048 MR.setResultPointer(ResultPtr);
1051 // if we are managing the GOT and the relocation wants an index,
1053 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
1054 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
1055 MR.setGOTIndex(idx);
1056 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
1057 DOUT << "JIT: GOT was out of date for " << ResultPtr
1058 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1060 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
1066 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
1067 Relocations.size(), MemMgr->getGOTBase());
1070 // Update the GOT entry for F to point to the new code.
1071 if (MemMgr->isManagingGOT()) {
1072 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
1073 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
1074 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
1075 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1076 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
1080 unsigned char *FnEnd = CurBufferPtr;
1082 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
1084 if (CurBufferPtr == BufferEnd) {
1085 // FIXME: Allocate more space, then try again.
1086 cerr << "JIT: Ran out of space for generated machine code!\n";
1090 BufferBegin = CurBufferPtr = 0;
1091 NumBytes += FnEnd-FnStart;
1093 // Invalidate the icache if necessary.
1094 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
1096 // Add it to the JIT symbol table if the host wants it.
1097 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
1098 FnStart, FnEnd-FnStart);
1100 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1101 << "] Function: " << F.getFunction()->getName()
1102 << ": " << (FnEnd-FnStart) << " bytes of text, "
1103 << Relocations.size() << " relocations\n";
1104 Relocations.clear();
1106 // Mark code region readable and executable if it's not so already.
1107 MemMgr->setMemoryExecutable();
1111 if (sys::hasDisassembler()) {
1112 DOUT << "JIT: Disassembled code:\n";
1113 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
1115 DOUT << "JIT: Binary code:\n";
1117 unsigned char* q = FnStart;
1118 for (int i = 0; q < FnEnd; q += 4, ++i) {
1122 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1123 << (long)(q - FnStart) << ": ";
1125 for (int j = 3; j >= 0; --j) {
1129 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1142 if (ExceptionHandling) {
1143 uintptr_t ActualSize = 0;
1144 SavedBufferBegin = BufferBegin;
1145 SavedBufferEnd = BufferEnd;
1146 SavedCurBufferPtr = CurBufferPtr;
1148 if (MemMgr->NeedsExactSize()) {
1149 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
1152 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1154 BufferEnd = BufferBegin+ActualSize;
1155 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
1156 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1158 BufferBegin = SavedBufferBegin;
1159 BufferEnd = SavedBufferEnd;
1160 CurBufferPtr = SavedCurBufferPtr;
1162 TheJIT->RegisterTable(FrameRegister);
1171 /// deallocateMemForFunction - Deallocate all memory for the specified
1172 /// function body. Also drop any references the function has to stubs.
1173 void JITEmitter::deallocateMemForFunction(Function *F) {
1174 MemMgr->deallocateMemForFunction(F);
1176 // If the function did not reference any stubs, return.
1177 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1180 // For each referenced stub, erase the reference to this function, and then
1181 // erase the list of referenced stubs.
1182 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1183 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1184 void *Stub = StubList[i];
1185 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1188 // If this function was the last reference to the stub, invalidate the stub
1189 // in the JITResolver. Were there a memory manager deallocateStub routine,
1190 // we could call that at this point too.
1191 if (FnRefs.empty()) {
1192 Resolver.invalidateStub(Stub);
1193 StubFnRefs.erase(F);
1196 CurFnStubUses.erase(F);
1200 void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
1202 return MachineCodeEmitter::allocateSpace(Size, Alignment);
1204 // create a new memory block if there is no active one.
1205 // care must be taken so that BufferBegin is invalidated when a
1207 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1208 BufferEnd = BufferBegin+Size;
1209 return CurBufferPtr;
1212 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1213 if (TheJIT->getJITInfo().hasCustomConstantPool())
1216 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1217 if (Constants.empty()) return;
1219 MachineConstantPoolEntry CPE = Constants.back();
1220 unsigned Size = CPE.Offset;
1221 const Type *Ty = CPE.isMachineConstantPoolEntry()
1222 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
1223 Size += TheJIT->getTargetData()->getTypePaddedSize(Ty);
1225 unsigned Align = 1 << MCP->getConstantPoolAlignment();
1226 ConstantPoolBase = allocateSpace(Size, Align);
1229 if (ConstantPoolBase == 0) return; // Buffer overflow.
1231 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1232 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1234 // Initialize the memory for all of the constant pool entries.
1235 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1236 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
1237 if (Constants[i].isMachineConstantPoolEntry()) {
1238 // FIXME: add support to lower machine constant pool values into bytes!
1239 cerr << "Initialize memory with machine specific constant pool entry"
1240 << " has not been implemented!\n";
1243 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
1244 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
1248 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1249 if (TheJIT->getJITInfo().hasCustomJumpTables())
1252 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1253 if (JT.empty()) return;
1255 unsigned NumEntries = 0;
1256 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1257 NumEntries += JT[i].MBBs.size();
1259 unsigned EntrySize = MJTI->getEntrySize();
1261 // Just allocate space for all the jump tables now. We will fix up the actual
1262 // MBB entries in the tables after we emit the code for each block, since then
1263 // we will know the final locations of the MBBs in memory.
1265 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1268 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1269 if (TheJIT->getJITInfo().hasCustomJumpTables())
1272 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1273 if (JT.empty() || JumpTableBase == 0) return;
1275 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1276 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1277 // For each jump table, place the offset from the beginning of the table
1278 // to the target address.
1279 int *SlotPtr = (int*)JumpTableBase;
1281 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1282 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1283 // Store the offset of the basic block for this jump table slot in the
1284 // memory we allocated for the jump table in 'initJumpTableInfo'
1285 uintptr_t Base = (uintptr_t)SlotPtr;
1286 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1287 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1288 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1292 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1294 // For each jump table, map each target in the jump table to the address of
1295 // an emitted MachineBasicBlock.
1296 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1298 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1299 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1300 // Store the address of the basic block for this jump table slot in the
1301 // memory we allocated for the jump table in 'initJumpTableInfo'
1302 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1303 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1308 void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1309 unsigned Alignment) {
1310 SavedBufferBegin = BufferBegin;
1311 SavedBufferEnd = BufferEnd;
1312 SavedCurBufferPtr = CurBufferPtr;
1314 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1315 BufferEnd = BufferBegin+StubSize+1;
1318 void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1319 unsigned StubSize) {
1320 SavedBufferBegin = BufferBegin;
1321 SavedBufferEnd = BufferEnd;
1322 SavedCurBufferPtr = CurBufferPtr;
1324 BufferBegin = CurBufferPtr = (unsigned char *)Buffer;
1325 BufferEnd = BufferBegin+StubSize+1;
1328 void *JITEmitter::finishGVStub(const GlobalValue* GV) {
1329 NumBytes += getCurrentPCOffset();
1330 std::swap(SavedBufferBegin, BufferBegin);
1331 BufferEnd = SavedBufferEnd;
1332 CurBufferPtr = SavedCurBufferPtr;
1333 return SavedBufferBegin;
1336 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1337 // in the constant pool that was last emitted with the 'emitConstantPool'
1340 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1341 assert(ConstantNum < ConstantPool->getConstants().size() &&
1342 "Invalid ConstantPoolIndex!");
1343 return (uintptr_t)ConstantPoolBase +
1344 ConstantPool->getConstants()[ConstantNum].Offset;
1347 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1348 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1350 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1351 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1352 assert(Index < JT.size() && "Invalid jump table index!");
1354 unsigned Offset = 0;
1355 unsigned EntrySize = JumpTable->getEntrySize();
1357 for (unsigned i = 0; i < Index; ++i)
1358 Offset += JT[i].MBBs.size();
1360 Offset *= EntrySize;
1362 return (uintptr_t)((char *)JumpTableBase + Offset);
1365 //===----------------------------------------------------------------------===//
1366 // Public interface to this file
1367 //===----------------------------------------------------------------------===//
1369 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1370 return new JITEmitter(jit, JMM);
1373 // getPointerToNamedFunction - This function is used as a global wrapper to
1374 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1375 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1376 // need to resolve function(s) that are being mis-codegenerated, so we need to
1377 // resolve their addresses at runtime, and this is the way to do it.
1379 void *getPointerToNamedFunction(const char *Name) {
1380 if (Function *F = TheJIT->FindFunctionNamed(Name))
1381 return TheJIT->getPointerToFunction(F);
1382 return TheJIT->getPointerToNamedFunction(Name);
1386 // getPointerToFunctionOrStub - If the specified function has been
1387 // code-gen'd, return a pointer to the function. If not, compile it, or use
1388 // a stub to implement lazy compilation if available.
1390 void *JIT::getPointerToFunctionOrStub(Function *F) {
1391 // If we have already code generated the function, just return the address.
1392 if (void *Addr = getPointerToGlobalIfAvailable(F))
1395 // Get a stub if the target supports it.
1396 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1397 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1398 return JE->getJITResolver().getFunctionStub(F);
1401 void JIT::updateFunctionStub(Function *F) {
1402 // Get the empty stub we generated earlier.
1403 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1404 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1405 void *Stub = JE->getJITResolver().getFunctionStub(F);
1407 // Tell the target jit info to rewrite the stub at the specified address,
1408 // rather than creating a new one.
1409 void *Addr = getPointerToGlobalIfAvailable(F);
1410 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1413 /// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1414 /// that were emitted during code generation.
1416 void JIT::updateDlsymStubTable() {
1417 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1418 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1420 SmallVector<GlobalValue*, 8> GVs;
1421 SmallVector<void*, 8> Ptrs;
1423 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1425 // If there are no relocatable stubs, return.
1429 // If there are no new relocatable stubs, return.
1430 void *CurTable = JE->getMemMgr()->getDlsymTable();
1431 if (CurTable && (*(unsigned *)CurTable == GVs.size()))
1434 // Calculate the size of the stub info
1435 unsigned offset = 4 + 4 * GVs.size() + sizeof(intptr_t) * GVs.size();
1437 SmallVector<unsigned, 8> Offsets;
1438 for (unsigned i = 0; i != GVs.size(); ++i) {
1439 Offsets.push_back(offset);
1440 offset += GVs[i]->getName().length() + 1;
1443 // Allocate space for the new "stub", which contains the dlsym table.
1444 JE->startGVStub(0, offset, 4);
1446 // Emit the number of records
1447 MCE->emitInt32(GVs.size());
1449 // Emit the string offsets
1450 for (unsigned i = 0; i != GVs.size(); ++i)
1451 MCE->emitInt32(Offsets[i]);
1453 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1454 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1455 // relocation can write the relocated pointer at the appropriate place in
1457 for (unsigned i = 0; i != GVs.size(); ++i) {
1458 intptr_t Ptr = (intptr_t)Ptrs[i];
1459 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1461 if (isa<Function>(GVs[i]))
1464 if (sizeof(void *) == 8)
1465 MCE->emitInt64(Ptr);
1467 MCE->emitInt32(Ptr);
1470 // Emit the strings.
1471 for (unsigned i = 0; i != GVs.size(); ++i)
1472 MCE->emitString(GVs[i]->getName());
1474 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1475 // deallocate space for the old one, if one existed.
1476 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1479 /// freeMachineCodeForFunction - release machine code memory for given Function.
1481 void JIT::freeMachineCodeForFunction(Function *F) {
1483 // Delete translation for this from the ExecutionEngine, so it will get
1484 // retranslated next time it is used.
1485 void *OldPtr = updateGlobalMapping(F, 0);
1488 RemoveFunctionFromSymbolTable(OldPtr);
1490 // Free the actual memory for the function body and related stuff.
1491 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1492 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);