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 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
150 /// an address. This function only manages slots, it does not manage the
151 /// contents of the slots or the memory associated with the GOT.
152 unsigned getGOTIndexForAddr(void *addr);
154 /// JITCompilerFn - This function is called to resolve a stub to a compiled
155 /// address. If the LLVM Function corresponding to the stub has not yet
156 /// been compiled, this function compiles it first.
157 static void *JITCompilerFn(void *Stub);
161 JITResolver *JITResolver::TheJITResolver = 0;
163 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
164 /// if it has already been created.
165 void *JITResolver::getFunctionStubIfAvailable(Function *F) {
166 MutexGuard locked(TheJIT->lock);
168 // If we already have a stub for this function, recycle it.
169 void *&Stub = state.getFunctionToStubMap(locked)[F];
173 /// getFunctionStub - This returns a pointer to a function stub, creating
174 /// one on demand as needed.
175 void *JITResolver::getFunctionStub(Function *F, bool empty) {
176 MutexGuard locked(TheJIT->lock);
178 // If we already have a stub for this function, recycle it.
179 void *&Stub = state.getFunctionToStubMap(locked)[F];
180 if (Stub) return Stub;
182 // Call the lazy resolver function unless we already KNOW it is an external
183 // function, in which case we just skip the lazy resolution step.
184 void *Actual = empty ? (void*)0 : (void*)(intptr_t)LazyResolverFn;
185 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
186 Actual = TheJIT->getPointerToFunction(F);
188 // If we resolved the symbol to a null address (eg. a weak external)
189 // don't emit a stub. Return a null pointer to the application.
190 if (!Actual) return 0;
193 // Otherwise, codegen a new stub. For now, the stub will call the lazy
194 // resolver function.
195 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
196 *TheJIT->getCodeEmitter());
198 if (Actual != (void*)(intptr_t)LazyResolverFn) {
199 // If we are getting the stub for an external function, we really want the
200 // address of the stub in the GlobalAddressMap for the JIT, not the address
201 // of the external function.
202 TheJIT->updateGlobalMapping(F, Stub);
205 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
206 << F->getName() << "'\n";
208 // Finally, keep track of the stub-to-Function mapping so that the
209 // JITCompilerFn knows which function to compile!
210 state.getStubToFunctionMap(locked)[Stub] = F;
212 // If this is an "empty" stub, then inform the JIT that it will need to
213 // JIT the function so an address can be provided.
215 TheJIT->addPendingFunction(F);
220 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
222 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
223 MutexGuard locked(TheJIT->lock);
225 // If we already have a stub for this global variable, recycle it.
226 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
227 if (IndirectSym) return IndirectSym;
229 // Otherwise, codegen a new indirect symbol.
230 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
231 *TheJIT->getCodeEmitter());
233 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
234 << GV->getName() << "'\n";
239 /// getExternalFunctionStub - Return a stub for the function at the
240 /// specified address, created lazily on demand.
241 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
242 // If we already have a stub for this function, recycle it.
243 void *&Stub = ExternalFnToStubMap[FnAddr];
244 if (Stub) return Stub;
246 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
247 *TheJIT->getCodeEmitter());
249 DOUT << "JIT: Stub emitted at [" << Stub
250 << "] for external function at '" << FnAddr << "'\n";
254 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
255 unsigned idx = revGOTMap[addr];
257 idx = ++nextGOTIndex;
258 revGOTMap[addr] = idx;
259 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
264 void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
265 SmallVectorImpl<void*> &Ptrs) {
266 MutexGuard locked(TheJIT->lock);
268 std::map<Function*,void*> &FM = state.getFunctionToStubMap(locked);
269 std::map<GlobalValue*,void*> &GM = state.getGlobalToIndirectSymMap(locked);
271 for (std::map<Function*,void*>::iterator i = FM.begin(), e = FM.end();
273 Function *F = i->first;
274 if (F->isDeclaration() && F->hasExternalLinkage()) {
275 GVs.push_back(i->first);
276 Ptrs.push_back(i->second);
279 for (std::map<GlobalValue*,void*>::iterator i = GM.begin(), e = GM.end();
281 GVs.push_back(i->first);
282 Ptrs.push_back(i->second);
286 /// JITCompilerFn - This function is called when a lazy compilation stub has
287 /// been entered. It looks up which function this stub corresponds to, compiles
288 /// it if necessary, then returns the resultant function pointer.
289 void *JITResolver::JITCompilerFn(void *Stub) {
290 JITResolver &JR = *TheJITResolver;
296 // Only lock for getting the Function. The call getPointerToFunction made
297 // in this function might trigger function materializing, which requires
298 // JIT lock to be unlocked.
299 MutexGuard locked(TheJIT->lock);
301 // The address given to us for the stub may not be exactly right, it might be
302 // a little bit after the stub. As such, use upper_bound to find it.
303 std::map<void*, Function*>::iterator I =
304 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
305 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
306 "This is not a known stub!");
308 ActualPtr = I->first;
311 // If we have already code generated the function, just return the address.
312 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
315 // Otherwise we don't have it, do lazy compilation now.
317 // If lazy compilation is disabled, emit a useful error message and abort.
318 if (TheJIT->isLazyCompilationDisabled()) {
319 cerr << "LLVM JIT requested to do lazy compilation of function '"
320 << F->getName() << "' when lazy compiles are disabled!\n";
324 // We might like to remove the stub from the StubToFunction map.
325 // We can't do that! Multiple threads could be stuck, waiting to acquire the
326 // lock above. As soon as the 1st function finishes compiling the function,
327 // the next one will be released, and needs to be able to find the function
329 //JR.state.getStubToFunctionMap(locked).erase(I);
331 DOUT << "JIT: Lazily resolving function '" << F->getName()
332 << "' In stub ptr = " << Stub << " actual ptr = "
333 << ActualPtr << "\n";
335 Result = TheJIT->getPointerToFunction(F);
338 // Reacquire the lock to erase the stub in the map.
339 MutexGuard locked(TheJIT->lock);
341 // We don't need to reuse this stub in the future, as F is now compiled.
342 JR.state.getFunctionToStubMap(locked).erase(F);
344 // FIXME: We could rewrite all references to this stub if we knew them.
346 // What we will do is set the compiled function address to map to the
347 // same GOT entry as the stub so that later clients may update the GOT
348 // if they see it still using the stub address.
349 // Note: this is done so the Resolver doesn't have to manage GOT memory
350 // Do this without allocating map space if the target isn't using a GOT
351 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
352 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
357 //===----------------------------------------------------------------------===//
358 // Function Index Support
360 // On MacOS we generate an index of currently JIT'd functions so that
361 // performance tools can determine a symbol name and accurate code range for a
362 // PC value. Because performance tools are generally asynchronous, the code
363 // below is written with the hope that it could be interrupted at any time and
364 // have useful answers. However, we don't go crazy with atomic operations, we
365 // just do a "reasonable effort".
367 #define ENABLE_JIT_SYMBOL_TABLE 0
370 /// JitSymbolEntry - Each function that is JIT compiled results in one of these
371 /// being added to an array of symbols. This indicates the name of the function
372 /// as well as the address range it occupies. This allows the client to map
373 /// from a PC value to the name of the function.
374 struct JitSymbolEntry {
375 const char *FnName; // FnName - a strdup'd string.
381 struct JitSymbolTable {
382 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
383 /// pointer is not used right now, but might be used in the future. Consider
384 /// it reserved for future use.
385 JitSymbolTable *NextPtr;
387 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
388 /// 'NumSymbols' symbols are valid.
389 JitSymbolEntry *Symbols;
391 /// NumSymbols - This indicates the number entries in the Symbols array that
395 /// NumAllocated - This indicates the amount of space we have in the Symbols
396 /// array. This is a private field that should not be read by external tools.
397 unsigned NumAllocated;
400 #if ENABLE_JIT_SYMBOL_TABLE
401 JitSymbolTable *__jitSymbolTable;
404 static void AddFunctionToSymbolTable(const char *FnName,
405 void *FnStart, intptr_t FnSize) {
406 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
407 JitSymbolTable **SymTabPtrPtr = 0;
408 #if !ENABLE_JIT_SYMBOL_TABLE
411 SymTabPtrPtr = &__jitSymbolTable;
414 // If this is the first entry in the symbol table, add the JitSymbolTable
416 if (*SymTabPtrPtr == 0) {
417 JitSymbolTable *New = new JitSymbolTable();
421 New->NumAllocated = 0;
425 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
427 // If we have space in the table, reallocate the table.
428 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
429 // If we don't have space, reallocate the table.
430 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
431 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
432 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
434 // Copy the old entries over.
435 memcpy(NewSymbols, OldSymbols, SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
437 // Swap the new symbols in, delete the old ones.
438 SymTabPtr->Symbols = NewSymbols;
439 SymTabPtr->NumAllocated = NewSize;
440 delete [] OldSymbols;
443 // Otherwise, we have enough space, just tack it onto the end of the array.
444 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
445 Entry.FnName = strdup(FnName);
446 Entry.FnStart = FnStart;
447 Entry.FnSize = FnSize;
448 ++SymTabPtr->NumSymbols;
451 static void RemoveFunctionFromSymbolTable(void *FnStart) {
452 assert(FnStart && "Invalid function pointer");
453 JitSymbolTable **SymTabPtrPtr = 0;
454 #if !ENABLE_JIT_SYMBOL_TABLE
457 SymTabPtrPtr = &__jitSymbolTable;
460 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
461 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
463 // Scan the table to find its index. The table is not sorted, so do a linear
466 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
467 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
469 // Once we have an index, we know to nuke this entry, overwrite it with the
470 // entry at the end of the array, making the last entry redundant.
471 const char *OldName = Symbols[Index].FnName;
472 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
473 free((void*)OldName);
475 // Drop the number of symbols in the table.
476 --SymTabPtr->NumSymbols;
478 // Finally, if we deleted the final symbol, deallocate the table itself.
479 if (SymTabPtr->NumSymbols != 0)
487 //===----------------------------------------------------------------------===//
491 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
492 /// used to output functions to memory for execution.
493 class JITEmitter : public MachineCodeEmitter {
494 JITMemoryManager *MemMgr;
496 // When outputting a function stub in the context of some other function, we
497 // save BufferBegin/BufferEnd/CurBufferPtr here.
498 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
500 /// Relocations - These are the relocations that the function needs, as
502 std::vector<MachineRelocation> Relocations;
504 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
505 /// It is filled in by the StartMachineBasicBlock callback and queried by
506 /// the getMachineBasicBlockAddress callback.
507 std::vector<uintptr_t> MBBLocations;
509 /// ConstantPool - The constant pool for the current function.
511 MachineConstantPool *ConstantPool;
513 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
515 void *ConstantPoolBase;
517 /// JumpTable - The jump tables for the current function.
519 MachineJumpTableInfo *JumpTable;
521 /// JumpTableBase - A pointer to the first entry in the jump table.
525 /// Resolver - This contains info about the currently resolved functions.
526 JITResolver Resolver;
528 /// DE - The dwarf emitter for the jit.
531 /// LabelLocations - This vector is a mapping from Label ID's to their
533 std::vector<uintptr_t> LabelLocations;
535 /// MMI - Machine module info for exception informations
536 MachineModuleInfo* MMI;
538 // GVSet - a set to keep track of which globals have been seen
539 SmallPtrSet<const GlobalVariable*, 8> GVSet;
542 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
543 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
544 if (jit.getJITInfo().needsGOT()) {
545 MemMgr->AllocateGOT();
546 DOUT << "JIT is managing a GOT\n";
549 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
553 if (ExceptionHandling) delete DE;
556 /// classof - Methods for support type inquiry through isa, cast, and
559 static inline bool classof(const JITEmitter*) { return true; }
560 static inline bool classof(const MachineCodeEmitter*) { return true; }
562 JITResolver &getJITResolver() { return Resolver; }
564 virtual void startFunction(MachineFunction &F);
565 virtual bool finishFunction(MachineFunction &F);
567 void emitConstantPool(MachineConstantPool *MCP);
568 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
569 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
571 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
572 unsigned Alignment = 1);
573 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
575 virtual void* finishGVStub(const GlobalValue *GV);
577 /// allocateSpace - Reserves space in the current block if any, or
578 /// allocate a new one of the given size.
579 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
581 virtual void addRelocation(const MachineRelocation &MR) {
582 Relocations.push_back(MR);
585 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
586 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
587 MBBLocations.resize((MBB->getNumber()+1)*2);
588 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
589 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
590 << (void*) getCurrentPCValue() << "]\n";
593 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
594 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
596 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
597 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
598 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
599 return MBBLocations[MBB->getNumber()];
602 /// deallocateMemForFunction - Deallocate all memory for the specified
604 void deallocateMemForFunction(Function *F) {
605 MemMgr->deallocateMemForFunction(F);
608 virtual void emitLabel(uint64_t LabelID) {
609 if (LabelLocations.size() <= LabelID)
610 LabelLocations.resize((LabelID+1)*2);
611 LabelLocations[LabelID] = getCurrentPCValue();
614 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
615 assert(LabelLocations.size() > (unsigned)LabelID &&
616 LabelLocations[LabelID] && "Label not emitted!");
617 return LabelLocations[LabelID];
620 virtual void setModuleInfo(MachineModuleInfo* Info) {
622 if (ExceptionHandling) DE->setModuleInfo(Info);
625 void setMemoryExecutable(void) {
626 MemMgr->setMemoryExecutable();
629 JITMemoryManager *getMemMgr(void) const { return MemMgr; }
632 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
633 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
635 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
636 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
637 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
638 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
642 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
643 bool DoesntNeedStub) {
644 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
645 return TheJIT->getOrEmitGlobalVariable(GV);
647 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
648 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
650 // If we have already compiled the function, return a pointer to its body.
651 Function *F = cast<Function>(V);
653 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
654 // Return the function stub if it's already created.
655 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
657 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
658 if (ResultPtr) return ResultPtr;
660 // If this is an external function pointer, we can force the JIT to
661 // 'compile' it, which really just adds it to the map.
662 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() && DoesntNeedStub)
663 return TheJIT->getPointerToFunction(F);
665 // If we are jitting non-lazily but encounter a function that has not been
666 // jitted yet, we need to allocate a blank stub to call the function
667 // once we JIT it and its address is known.
668 if (TheJIT->isLazyCompilationDisabled())
669 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
670 return Resolver.getFunctionStub(F, true);
672 // Okay, the function has not been compiled yet, if the target callback
673 // mechanism is capable of rewriting the instruction directly, prefer to do
674 // that instead of emitting a stub.
676 return Resolver.AddCallbackAtLocation(F, Reference);
678 // Otherwise, we have to emit a lazy resolving stub.
679 return Resolver.getFunctionStub(F);
682 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
684 // Make sure GV is emitted first.
685 // FIXME: For now, if the GV is an external function we force the JIT to
686 // compile it so the indirect symbol will contain the fully resolved address.
687 void *GVAddress = getPointerToGlobal(V, Reference, true);
688 return Resolver.getGlobalValueIndirectSym(V, GVAddress);
691 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
692 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
693 if (Constants.empty()) return 0;
695 MachineConstantPoolEntry CPE = Constants.back();
696 unsigned Size = CPE.Offset;
697 const Type *Ty = CPE.isMachineConstantPoolEntry()
698 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
699 Size += TheJIT->getTargetData()->getTypePaddedSize(Ty);
703 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
704 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
705 if (JT.empty()) return 0;
707 unsigned NumEntries = 0;
708 for (unsigned i = 0, e = JT.size(); i != e; ++i)
709 NumEntries += JT[i].MBBs.size();
711 unsigned EntrySize = MJTI->getEntrySize();
713 return NumEntries * EntrySize;
716 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
717 if (Alignment == 0) Alignment = 1;
718 // Since we do not know where the buffer will be allocated, be pessimistic.
719 return Size + Alignment;
722 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
723 /// into the running total Size.
725 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
726 const Type *ElTy = GV->getType()->getElementType();
727 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypePaddedSize(ElTy);
729 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
730 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
732 // Assume code section ends with worst possible alignment, so first
733 // variable needs maximal padding.
736 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
741 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
742 /// but are referenced from the constant; put them in GVSet and add their
743 /// size into the running total Size.
745 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
747 // If its undefined, return the garbage.
748 if (isa<UndefValue>(C))
751 // If the value is a ConstantExpr
752 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
753 Constant *Op0 = CE->getOperand(0);
754 switch (CE->getOpcode()) {
755 case Instruction::GetElementPtr:
756 case Instruction::Trunc:
757 case Instruction::ZExt:
758 case Instruction::SExt:
759 case Instruction::FPTrunc:
760 case Instruction::FPExt:
761 case Instruction::UIToFP:
762 case Instruction::SIToFP:
763 case Instruction::FPToUI:
764 case Instruction::FPToSI:
765 case Instruction::PtrToInt:
766 case Instruction::IntToPtr:
767 case Instruction::BitCast: {
768 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
771 case Instruction::Add:
772 case Instruction::Sub:
773 case Instruction::Mul:
774 case Instruction::UDiv:
775 case Instruction::SDiv:
776 case Instruction::URem:
777 case Instruction::SRem:
778 case Instruction::And:
779 case Instruction::Or:
780 case Instruction::Xor: {
781 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
782 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
786 cerr << "ConstantExpr not handled: " << *CE << "\n";
792 if (C->getType()->getTypeID() == Type::PointerTyID)
793 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
794 if (GVSet.insert(GV))
795 Size = addSizeOfGlobal(GV, Size);
800 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
801 /// but are referenced from the given initializer.
803 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
805 if (!isa<UndefValue>(Init) &&
806 !isa<ConstantVector>(Init) &&
807 !isa<ConstantAggregateZero>(Init) &&
808 !isa<ConstantArray>(Init) &&
809 !isa<ConstantStruct>(Init) &&
810 Init->getType()->isFirstClassType())
811 Size = addSizeOfGlobalsInConstantVal(Init, Size);
815 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
816 /// globals; then walk the initializers of those globals looking for more.
817 /// If their size has not been considered yet, add it into the running total
820 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
824 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
826 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
828 const TargetInstrDesc &Desc = I->getDesc();
829 const MachineInstr &MI = *I;
830 unsigned NumOps = Desc.getNumOperands();
831 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
832 const MachineOperand &MO = MI.getOperand(CurOp);
834 GlobalValue* V = MO.getGlobal();
835 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
838 // If seen in previous function, it will have an entry here.
839 if (TheJIT->getPointerToGlobalIfAvailable(GV))
841 // If seen earlier in this function, it will have an entry here.
842 // FIXME: it should be possible to combine these tables, by
843 // assuming the addresses of the new globals in this module
844 // start at 0 (or something) and adjusting them after codegen
845 // complete. Another possibility is to grab a marker bit in GV.
846 if (GVSet.insert(GV))
847 // A variable as yet unseen. Add in its size.
848 Size = addSizeOfGlobal(GV, Size);
853 DOUT << "JIT: About to look through initializers\n";
854 // Look for more globals that are referenced only from initializers.
855 // GVSet.end is computed each time because the set can grow as we go.
856 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
857 I != GVSet.end(); I++) {
858 const GlobalVariable* GV = *I;
859 if (GV->hasInitializer())
860 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
866 void JITEmitter::startFunction(MachineFunction &F) {
867 DOUT << "JIT: Starting CodeGen of Function "
868 << F.getFunction()->getName() << "\n";
870 uintptr_t ActualSize = 0;
871 // Set the memory writable, if it's not already
872 MemMgr->setMemoryWritable();
873 if (MemMgr->NeedsExactSize()) {
874 DOUT << "JIT: ExactSize\n";
875 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
876 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
877 MachineConstantPool *MCP = F.getConstantPool();
879 // Ensure the constant pool/jump table info is at least 4-byte aligned.
880 ActualSize = RoundUpToAlign(ActualSize, 16);
882 // Add the alignment of the constant pool
883 ActualSize = RoundUpToAlign(ActualSize,
884 1 << MCP->getConstantPoolAlignment());
886 // Add the constant pool size
887 ActualSize += GetConstantPoolSizeInBytes(MCP);
889 // Add the aligment of the jump table info
890 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
892 // Add the jump table size
893 ActualSize += GetJumpTableSizeInBytes(MJTI);
895 // Add the alignment for the function
896 ActualSize = RoundUpToAlign(ActualSize,
897 std::max(F.getFunction()->getAlignment(), 8U));
899 // Add the function size
900 ActualSize += TII->GetFunctionSizeInBytes(F);
902 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
903 // Add the size of the globals that will be allocated after this function.
904 // These are all the ones referenced from this function that were not
905 // previously allocated.
906 ActualSize += GetSizeOfGlobalsInBytes(F);
907 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
910 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
912 BufferEnd = BufferBegin+ActualSize;
914 // Ensure the constant pool/jump table info is at least 4-byte aligned.
917 emitConstantPool(F.getConstantPool());
918 initJumpTableInfo(F.getJumpTableInfo());
920 // About to start emitting the machine code for the function.
921 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
922 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
924 MBBLocations.clear();
927 bool JITEmitter::finishFunction(MachineFunction &F) {
928 if (CurBufferPtr == BufferEnd) {
929 // FIXME: Allocate more space, then try again.
930 cerr << "JIT: Ran out of space for generated machine code!\n";
934 emitJumpTableInfo(F.getJumpTableInfo());
936 // FnStart is the start of the text, not the start of the constant pool and
937 // other per-function data.
938 unsigned char *FnStart =
939 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
941 if (!Relocations.empty()) {
942 NumRelos += Relocations.size();
944 // Resolve the relocations to concrete pointers.
945 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
946 MachineRelocation &MR = Relocations[i];
948 if (!MR.letTargetResolve()) {
949 if (MR.isExternalSymbol()) {
950 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
952 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
953 << ResultPtr << "]\n";
955 // If the target REALLY wants a stub for this function, emit it now.
956 if (!MR.doesntNeedStub())
957 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
958 } else if (MR.isGlobalValue()) {
959 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
960 BufferBegin+MR.getMachineCodeOffset(),
961 MR.doesntNeedStub());
962 } else if (MR.isIndirectSymbol()) {
963 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
964 BufferBegin+MR.getMachineCodeOffset(),
965 MR.doesntNeedStub());
966 } else if (MR.isBasicBlock()) {
967 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
968 } else if (MR.isConstantPoolIndex()) {
969 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
971 assert(MR.isJumpTableIndex());
972 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
975 MR.setResultPointer(ResultPtr);
978 // if we are managing the GOT and the relocation wants an index,
980 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
981 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
983 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
984 DOUT << "JIT: GOT was out of date for " << ResultPtr
985 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
987 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
992 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
993 Relocations.size(), MemMgr->getGOTBase());
996 // Update the GOT entry for F to point to the new code.
997 if (MemMgr->isManagingGOT()) {
998 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
999 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
1000 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
1001 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1002 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
1006 unsigned char *FnEnd = CurBufferPtr;
1008 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
1010 if (CurBufferPtr == BufferEnd) {
1011 // FIXME: Allocate more space, then try again.
1012 cerr << "JIT: Ran out of space for generated machine code!\n";
1016 BufferBegin = CurBufferPtr = 0;
1017 NumBytes += FnEnd-FnStart;
1019 // Invalidate the icache if necessary.
1020 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
1022 // Add it to the JIT symbol table if the host wants it.
1023 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
1024 FnStart, FnEnd-FnStart);
1026 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1027 << "] Function: " << F.getFunction()->getName()
1028 << ": " << (FnEnd-FnStart) << " bytes of text, "
1029 << Relocations.size() << " relocations\n";
1030 Relocations.clear();
1032 // Mark code region readable and executable if it's not so already.
1033 MemMgr->setMemoryExecutable();
1037 if (sys::hasDisassembler()) {
1038 DOUT << "JIT: Disassembled code:\n";
1039 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
1041 DOUT << "JIT: Binary code:\n";
1043 unsigned char* q = FnStart;
1044 for (int i = 0; q < FnEnd; q += 4, ++i) {
1048 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1049 << (long)(q - FnStart) << ": ";
1051 for (int j = 3; j >= 0; --j) {
1055 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1068 if (ExceptionHandling) {
1069 uintptr_t ActualSize = 0;
1070 SavedBufferBegin = BufferBegin;
1071 SavedBufferEnd = BufferEnd;
1072 SavedCurBufferPtr = CurBufferPtr;
1074 if (MemMgr->NeedsExactSize()) {
1075 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
1078 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1080 BufferEnd = BufferBegin+ActualSize;
1081 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
1082 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1084 BufferBegin = SavedBufferBegin;
1085 BufferEnd = SavedBufferEnd;
1086 CurBufferPtr = SavedCurBufferPtr;
1088 TheJIT->RegisterTable(FrameRegister);
1097 void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
1099 return MachineCodeEmitter::allocateSpace(Size, Alignment);
1101 // create a new memory block if there is no active one.
1102 // care must be taken so that BufferBegin is invalidated when a
1104 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1105 BufferEnd = BufferBegin+Size;
1106 return CurBufferPtr;
1109 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1110 if (TheJIT->getJITInfo().hasCustomConstantPool())
1113 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1114 if (Constants.empty()) return;
1116 MachineConstantPoolEntry CPE = Constants.back();
1117 unsigned Size = CPE.Offset;
1118 const Type *Ty = CPE.isMachineConstantPoolEntry()
1119 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
1120 Size += TheJIT->getTargetData()->getTypePaddedSize(Ty);
1122 unsigned Align = 1 << MCP->getConstantPoolAlignment();
1123 ConstantPoolBase = allocateSpace(Size, Align);
1126 if (ConstantPoolBase == 0) return; // Buffer overflow.
1128 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1129 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1131 // Initialize the memory for all of the constant pool entries.
1132 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1133 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
1134 if (Constants[i].isMachineConstantPoolEntry()) {
1135 // FIXME: add support to lower machine constant pool values into bytes!
1136 cerr << "Initialize memory with machine specific constant pool entry"
1137 << " has not been implemented!\n";
1140 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
1141 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
1145 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1146 if (TheJIT->getJITInfo().hasCustomJumpTables())
1149 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1150 if (JT.empty()) return;
1152 unsigned NumEntries = 0;
1153 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1154 NumEntries += JT[i].MBBs.size();
1156 unsigned EntrySize = MJTI->getEntrySize();
1158 // Just allocate space for all the jump tables now. We will fix up the actual
1159 // MBB entries in the tables after we emit the code for each block, since then
1160 // we will know the final locations of the MBBs in memory.
1162 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1165 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1166 if (TheJIT->getJITInfo().hasCustomJumpTables())
1169 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1170 if (JT.empty() || JumpTableBase == 0) return;
1172 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1173 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1174 // For each jump table, place the offset from the beginning of the table
1175 // to the target address.
1176 int *SlotPtr = (int*)JumpTableBase;
1178 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1179 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1180 // Store the offset of the basic block for this jump table slot in the
1181 // memory we allocated for the jump table in 'initJumpTableInfo'
1182 uintptr_t Base = (uintptr_t)SlotPtr;
1183 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1184 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1185 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1189 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1191 // For each jump table, map each target in the jump table to the address of
1192 // an emitted MachineBasicBlock.
1193 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1195 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1196 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1197 // Store the address of the basic block for this jump table slot in the
1198 // memory we allocated for the jump table in 'initJumpTableInfo'
1199 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1200 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1205 void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1206 unsigned Alignment) {
1207 SavedBufferBegin = BufferBegin;
1208 SavedBufferEnd = BufferEnd;
1209 SavedCurBufferPtr = CurBufferPtr;
1211 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1212 BufferEnd = BufferBegin+StubSize+1;
1215 void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1216 unsigned StubSize) {
1217 SavedBufferBegin = BufferBegin;
1218 SavedBufferEnd = BufferEnd;
1219 SavedCurBufferPtr = CurBufferPtr;
1221 BufferBegin = CurBufferPtr = (unsigned char *)Buffer;
1222 BufferEnd = BufferBegin+StubSize+1;
1225 void *JITEmitter::finishGVStub(const GlobalValue* GV) {
1226 NumBytes += getCurrentPCOffset();
1227 std::swap(SavedBufferBegin, BufferBegin);
1228 BufferEnd = SavedBufferEnd;
1229 CurBufferPtr = SavedCurBufferPtr;
1230 return SavedBufferBegin;
1233 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1234 // in the constant pool that was last emitted with the 'emitConstantPool'
1237 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1238 assert(ConstantNum < ConstantPool->getConstants().size() &&
1239 "Invalid ConstantPoolIndex!");
1240 return (uintptr_t)ConstantPoolBase +
1241 ConstantPool->getConstants()[ConstantNum].Offset;
1244 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1245 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1247 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1248 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1249 assert(Index < JT.size() && "Invalid jump table index!");
1251 unsigned Offset = 0;
1252 unsigned EntrySize = JumpTable->getEntrySize();
1254 for (unsigned i = 0; i < Index; ++i)
1255 Offset += JT[i].MBBs.size();
1257 Offset *= EntrySize;
1259 return (uintptr_t)((char *)JumpTableBase + Offset);
1262 //===----------------------------------------------------------------------===//
1263 // Public interface to this file
1264 //===----------------------------------------------------------------------===//
1266 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1267 return new JITEmitter(jit, JMM);
1270 // getPointerToNamedFunction - This function is used as a global wrapper to
1271 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1272 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1273 // need to resolve function(s) that are being mis-codegenerated, so we need to
1274 // resolve their addresses at runtime, and this is the way to do it.
1276 void *getPointerToNamedFunction(const char *Name) {
1277 if (Function *F = TheJIT->FindFunctionNamed(Name))
1278 return TheJIT->getPointerToFunction(F);
1279 return TheJIT->getPointerToNamedFunction(Name);
1283 // getPointerToFunctionOrStub - If the specified function has been
1284 // code-gen'd, return a pointer to the function. If not, compile it, or use
1285 // a stub to implement lazy compilation if available.
1287 void *JIT::getPointerToFunctionOrStub(Function *F) {
1288 // If we have already code generated the function, just return the address.
1289 if (void *Addr = getPointerToGlobalIfAvailable(F))
1292 // Get a stub if the target supports it.
1293 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1294 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1295 return JE->getJITResolver().getFunctionStub(F);
1298 void JIT::updateFunctionStub(Function *F) {
1299 // Get the empty stub we generated earlier.
1300 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1301 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1302 void *Stub = JE->getJITResolver().getFunctionStub(F);
1304 // Tell the target jit info to rewrite the stub at the specified address,
1305 // rather than creating a new one.
1306 void *Addr = getPointerToGlobalIfAvailable(F);
1307 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1310 /// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1311 /// that were emitted during code generation.
1313 void JIT::updateDlsymStubTable() {
1314 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1315 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1317 SmallVector<GlobalValue*, 8> GVs;
1318 SmallVector<void*, 8> Ptrs;
1320 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1322 // If there are no relocatable stubs, return.
1326 // If there are no new relocatable stubs, return.
1327 void *CurTable = JE->getMemMgr()->getDlsymTable();
1328 if (CurTable && (*(unsigned *)CurTable == GVs.size()))
1331 // Calculate the size of the stub info
1332 unsigned offset = 4 + 4 * GVs.size() + sizeof(intptr_t) * GVs.size();
1334 SmallVector<unsigned, 8> Offsets;
1335 for (unsigned i = 0; i != GVs.size(); ++i) {
1336 Offsets.push_back(offset);
1337 offset += GVs[i]->getName().length() + 1;
1340 // FIXME: This currently allocates new space every time it's called. A
1341 // different data structure could be used to make this unnecessary.
1342 JE->startGVStub(0, offset, 4);
1344 // Emit the number of records
1345 MCE->emitInt32(GVs.size());
1347 // Emit the string offsets
1348 for (unsigned i = 0; i != GVs.size(); ++i)
1349 MCE->emitInt32(Offsets[i]);
1351 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1352 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1353 // relocation can write the relocated pointer at the appropriate place in
1355 for (unsigned i = 0; i != GVs.size(); ++i) {
1356 intptr_t Ptr = (intptr_t)Ptrs[i];
1357 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1359 if (isa<Function>(GVs[i]))
1362 if (sizeof(void *) == 8)
1363 MCE->emitInt64(Ptr);
1365 MCE->emitInt32(Ptr);
1369 for (unsigned i = 0; i != GVs.size(); ++i)
1370 MCE->emitString(GVs[i]->getName());
1372 // Tell the JIT memory manager where it is.
1373 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1376 /// freeMachineCodeForFunction - release machine code memory for given Function.
1378 void JIT::freeMachineCodeForFunction(Function *F) {
1380 // Delete translation for this from the ExecutionEngine, so it will get
1381 // retranslated next time it is used.
1382 void *OldPtr = updateGlobalMapping(F, 0);
1385 RemoveFunctionFromSymbolTable(OldPtr);
1387 // Free the actual memory for the function body and related stuff.
1388 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1389 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);