1 //===-- JITEmitter.cpp - Write machine code to executable memory ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a MachineCodeEmitter object that is used by the JIT to
11 // write machine code to memory and remember where relocatable values are.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "jit"
17 #include "JITDwarfEmitter.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/CodeGen/MachineCodeEmitter.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRelocation.h"
27 #include "llvm/ExecutionEngine/JITMemoryManager.h"
28 #include "llvm/ExecutionEngine/GenericValue.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetJITInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/MutexGuard.h"
35 #include "llvm/Support/ValueHandle.h"
36 #include "llvm/System/Disassembler.h"
37 #include "llvm/System/Memory.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/Statistic.h"
48 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
49 STATISTIC(NumRelos, "Number of relocations applied");
50 static JIT *TheJIT = 0;
53 //===----------------------------------------------------------------------===//
54 // JIT lazy compilation code.
57 class JITResolverState {
59 /// FunctionToStubMap - Keep track of the stub created for a particular
60 /// function so that we can reuse them if necessary.
61 std::map<AssertingVH<Function>, void*> FunctionToStubMap;
63 /// StubToFunctionMap - Keep track of the function that each stub
65 std::map<void*, AssertingVH<Function> > StubToFunctionMap;
67 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
68 /// particular GlobalVariable so that we can reuse them if necessary.
69 std::map<GlobalValue*, void*> GlobalToIndirectSymMap;
72 std::map<AssertingVH<Function>, void*>& getFunctionToStubMap(const MutexGuard& locked) {
73 assert(locked.holds(TheJIT->lock));
74 return FunctionToStubMap;
77 std::map<void*, AssertingVH<Function> >& getStubToFunctionMap(const MutexGuard& locked) {
78 assert(locked.holds(TheJIT->lock));
79 return StubToFunctionMap;
82 std::map<GlobalValue*, void*>&
83 getGlobalToIndirectSymMap(const MutexGuard& locked) {
84 assert(locked.holds(TheJIT->lock));
85 return GlobalToIndirectSymMap;
89 /// JITResolver - Keep track of, and resolve, call sites for functions that
90 /// have not yet been compiled.
92 /// LazyResolverFn - The target lazy resolver function that we actually
93 /// rewrite instructions to use.
94 TargetJITInfo::LazyResolverFn LazyResolverFn;
96 JITResolverState state;
98 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
99 /// external functions.
100 std::map<void*, void*> ExternalFnToStubMap;
102 /// revGOTMap - map addresses to indexes in the GOT
103 std::map<void*, unsigned> revGOTMap;
104 unsigned nextGOTIndex;
106 static JITResolver *TheJITResolver;
108 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
111 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
112 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
113 TheJITResolver = this;
120 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
121 /// if it has already been created.
122 void *getFunctionStubIfAvailable(Function *F);
124 /// getFunctionStub - This returns a pointer to a function stub, creating
125 /// one on demand as needed. If empty is true, create a function stub
126 /// pointing at address 0, to be filled in later.
127 void *getFunctionStub(Function *F);
129 /// getExternalFunctionStub - Return a stub for the function at the
130 /// specified address, created lazily on demand.
131 void *getExternalFunctionStub(void *FnAddr);
133 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
134 /// specified GV address.
135 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
137 /// AddCallbackAtLocation - If the target is capable of rewriting an
138 /// instruction without the use of a stub, record the location of the use so
139 /// we know which function is being used at the location.
140 void *AddCallbackAtLocation(Function *F, void *Location) {
141 MutexGuard locked(TheJIT->lock);
142 /// Get the target-specific JIT resolver function.
143 state.getStubToFunctionMap(locked)[Location] = F;
144 return (void*)(intptr_t)LazyResolverFn;
147 void getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
148 SmallVectorImpl<void*> &Ptrs);
150 GlobalValue *invalidateStub(void *Stub);
152 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
153 /// an address. This function only manages slots, it does not manage the
154 /// contents of the slots or the memory associated with the GOT.
155 unsigned getGOTIndexForAddr(void *addr);
157 /// JITCompilerFn - This function is called to resolve a stub to a compiled
158 /// address. If the LLVM Function corresponding to the stub has not yet
159 /// been compiled, this function compiles it first.
160 static void *JITCompilerFn(void *Stub);
164 JITResolver *JITResolver::TheJITResolver = 0;
166 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
167 /// if it has already been created.
168 void *JITResolver::getFunctionStubIfAvailable(Function *F) {
169 MutexGuard locked(TheJIT->lock);
171 // If we already have a stub for this function, recycle it.
172 void *&Stub = state.getFunctionToStubMap(locked)[F];
176 /// getFunctionStub - This returns a pointer to a function stub, creating
177 /// one on demand as needed.
178 void *JITResolver::getFunctionStub(Function *F) {
179 MutexGuard locked(TheJIT->lock);
181 // If we already have a stub for this function, recycle it.
182 void *&Stub = state.getFunctionToStubMap(locked)[F];
183 if (Stub) return Stub;
185 // Call the lazy resolver function unless we are JIT'ing non-lazily, in which
186 // case we must resolve the symbol now.
187 void *Actual = TheJIT->isLazyCompilationDisabled()
188 ? (void *)0 : (void *)(intptr_t)LazyResolverFn;
190 // If this is an external declaration, attempt to resolve the address now
191 // to place in the stub.
192 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
193 Actual = TheJIT->getPointerToFunction(F);
195 // If we resolved the symbol to a null address (eg. a weak external)
196 // don't emit a stub. Return a null pointer to the application. If dlsym
197 // stubs are enabled, not being able to resolve the address is not
199 if (!Actual && !TheJIT->areDlsymStubsEnabled()) return 0;
202 // Codegen a new stub, calling the lazy resolver or the actual address of the
203 // external function, if it was resolved.
204 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
205 *TheJIT->getCodeEmitter());
207 if (Actual != (void*)(intptr_t)LazyResolverFn) {
208 // If we are getting the stub for an external function, we really want the
209 // address of the stub in the GlobalAddressMap for the JIT, not the address
210 // of the external function.
211 TheJIT->updateGlobalMapping(F, Stub);
214 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
215 << F->getName() << "'\n";
217 // Finally, keep track of the stub-to-Function mapping so that the
218 // JITCompilerFn knows which function to compile!
219 state.getStubToFunctionMap(locked)[Stub] = F;
221 // If we are JIT'ing non-lazily but need to call a function that does not
222 // exist yet, add it to the JIT's work list so that we can fill in the stub
224 if (!Actual && TheJIT->isLazyCompilationDisabled())
225 if (!F->isDeclaration() || F->hasNotBeenReadFromBitcode())
226 TheJIT->addPendingFunction(F);
231 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
233 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
234 MutexGuard locked(TheJIT->lock);
236 // If we already have a stub for this global variable, recycle it.
237 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
238 if (IndirectSym) return IndirectSym;
240 // Otherwise, codegen a new indirect symbol.
241 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
242 *TheJIT->getCodeEmitter());
244 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
245 << GV->getName() << "'\n";
250 /// getExternalFunctionStub - Return a stub for the function at the
251 /// specified address, created lazily on demand.
252 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
253 // If we already have a stub for this function, recycle it.
254 void *&Stub = ExternalFnToStubMap[FnAddr];
255 if (Stub) return Stub;
257 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
258 *TheJIT->getCodeEmitter());
260 DOUT << "JIT: Stub emitted at [" << Stub
261 << "] for external function at '" << FnAddr << "'\n";
265 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
266 unsigned idx = revGOTMap[addr];
268 idx = ++nextGOTIndex;
269 revGOTMap[addr] = idx;
270 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
275 void JITResolver::getRelocatableGVs(SmallVectorImpl<GlobalValue*> &GVs,
276 SmallVectorImpl<void*> &Ptrs) {
277 MutexGuard locked(TheJIT->lock);
279 std::map<AssertingVH<Function>,void*> &FM =state.getFunctionToStubMap(locked);
280 std::map<GlobalValue*,void*> &GM = state.getGlobalToIndirectSymMap(locked);
282 for (std::map<AssertingVH<Function>,void*>::iterator i = FM.begin(),
283 e = FM.end(); i != e; ++i) {
284 Function *F = i->first;
285 if (F->isDeclaration() && F->hasExternalLinkage()) {
286 GVs.push_back(i->first);
287 Ptrs.push_back(i->second);
290 for (std::map<GlobalValue*,void*>::iterator i = GM.begin(), e = GM.end();
292 GVs.push_back(i->first);
293 Ptrs.push_back(i->second);
297 GlobalValue *JITResolver::invalidateStub(void *Stub) {
298 MutexGuard locked(TheJIT->lock);
300 std::map<AssertingVH<Function>,void*> &FM =state.getFunctionToStubMap(locked);
301 std::map<void*,AssertingVH<Function> > &SM=state.getStubToFunctionMap(locked);
302 std::map<GlobalValue*,void*> &GM = state.getGlobalToIndirectSymMap(locked);
304 // Look up the cheap way first, to see if it's a function stub we are
305 // invalidating. If so, remove it from both the forward and reverse maps.
306 if (SM.find(Stub) != SM.end()) {
307 Function *F = SM[Stub];
313 // Otherwise, it might be an indirect symbol stub. Find it and remove it.
314 for (std::map<GlobalValue*,void*>::iterator i = GM.begin(), e = GM.end();
316 if (i->second != Stub)
318 GlobalValue *GV = i->first;
323 // Lastly, check to see if it's in the ExternalFnToStubMap.
324 for (std::map<void *, void *>::iterator i = ExternalFnToStubMap.begin(),
325 e = ExternalFnToStubMap.end(); i != e; ++i) {
326 if (i->second != Stub)
328 ExternalFnToStubMap.erase(i);
335 /// JITCompilerFn - This function is called when a lazy compilation stub has
336 /// been entered. It looks up which function this stub corresponds to, compiles
337 /// it if necessary, then returns the resultant function pointer.
338 void *JITResolver::JITCompilerFn(void *Stub) {
339 JITResolver &JR = *TheJITResolver;
345 // Only lock for getting the Function. The call getPointerToFunction made
346 // in this function might trigger function materializing, which requires
347 // JIT lock to be unlocked.
348 MutexGuard locked(TheJIT->lock);
350 // The address given to us for the stub may not be exactly right, it might be
351 // a little bit after the stub. As such, use upper_bound to find it.
352 std::map<void*, AssertingVH<Function> >::iterator I =
353 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
354 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
355 "This is not a known stub!");
357 ActualPtr = I->first;
360 // If we have already code generated the function, just return the address.
361 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
364 // Otherwise we don't have it, do lazy compilation now.
366 // If lazy compilation is disabled, emit a useful error message and abort.
367 if (TheJIT->isLazyCompilationDisabled()) {
368 cerr << "LLVM JIT requested to do lazy compilation of function '"
369 << F->getName() << "' when lazy compiles are disabled!\n";
373 // We might like to remove the stub from the StubToFunction map.
374 // We can't do that! Multiple threads could be stuck, waiting to acquire the
375 // lock above. As soon as the 1st function finishes compiling the function,
376 // the next one will be released, and needs to be able to find the function
378 //JR.state.getStubToFunctionMap(locked).erase(I);
380 DOUT << "JIT: Lazily resolving function '" << F->getName()
381 << "' In stub ptr = " << Stub << " actual ptr = "
382 << ActualPtr << "\n";
384 Result = TheJIT->getPointerToFunction(F);
387 // Reacquire the lock to erase the stub in the map.
388 MutexGuard locked(TheJIT->lock);
390 // We don't need to reuse this stub in the future, as F is now compiled.
391 JR.state.getFunctionToStubMap(locked).erase(F);
393 // FIXME: We could rewrite all references to this stub if we knew them.
395 // What we will do is set the compiled function address to map to the
396 // same GOT entry as the stub so that later clients may update the GOT
397 // if they see it still using the stub address.
398 // Note: this is done so the Resolver doesn't have to manage GOT memory
399 // Do this without allocating map space if the target isn't using a GOT
400 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
401 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
406 //===----------------------------------------------------------------------===//
407 // Function Index Support
409 // On MacOS we generate an index of currently JIT'd functions so that
410 // performance tools can determine a symbol name and accurate code range for a
411 // PC value. Because performance tools are generally asynchronous, the code
412 // below is written with the hope that it could be interrupted at any time and
413 // have useful answers. However, we don't go crazy with atomic operations, we
414 // just do a "reasonable effort".
416 #define ENABLE_JIT_SYMBOL_TABLE 0
419 /// JitSymbolEntry - Each function that is JIT compiled results in one of these
420 /// being added to an array of symbols. This indicates the name of the function
421 /// as well as the address range it occupies. This allows the client to map
422 /// from a PC value to the name of the function.
423 struct JitSymbolEntry {
424 const char *FnName; // FnName - a strdup'd string.
430 struct JitSymbolTable {
431 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
432 /// pointer is not used right now, but might be used in the future. Consider
433 /// it reserved for future use.
434 JitSymbolTable *NextPtr;
436 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
437 /// 'NumSymbols' symbols are valid.
438 JitSymbolEntry *Symbols;
440 /// NumSymbols - This indicates the number entries in the Symbols array that
444 /// NumAllocated - This indicates the amount of space we have in the Symbols
445 /// array. This is a private field that should not be read by external tools.
446 unsigned NumAllocated;
449 #if ENABLE_JIT_SYMBOL_TABLE
450 JitSymbolTable *__jitSymbolTable;
453 static void AddFunctionToSymbolTable(const char *FnName,
454 void *FnStart, intptr_t FnSize) {
455 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
456 JitSymbolTable **SymTabPtrPtr = 0;
457 #if !ENABLE_JIT_SYMBOL_TABLE
460 SymTabPtrPtr = &__jitSymbolTable;
463 // If this is the first entry in the symbol table, add the JitSymbolTable
465 if (*SymTabPtrPtr == 0) {
466 JitSymbolTable *New = new JitSymbolTable();
470 New->NumAllocated = 0;
474 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
476 // If we have space in the table, reallocate the table.
477 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
478 // If we don't have space, reallocate the table.
479 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
480 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
481 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
483 // Copy the old entries over.
484 memcpy(NewSymbols, OldSymbols, SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
486 // Swap the new symbols in, delete the old ones.
487 SymTabPtr->Symbols = NewSymbols;
488 SymTabPtr->NumAllocated = NewSize;
489 delete [] OldSymbols;
492 // Otherwise, we have enough space, just tack it onto the end of the array.
493 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
494 Entry.FnName = strdup(FnName);
495 Entry.FnStart = FnStart;
496 Entry.FnSize = FnSize;
497 ++SymTabPtr->NumSymbols;
500 static void RemoveFunctionFromSymbolTable(void *FnStart) {
501 assert(FnStart && "Invalid function pointer");
502 JitSymbolTable **SymTabPtrPtr = 0;
503 #if !ENABLE_JIT_SYMBOL_TABLE
506 SymTabPtrPtr = &__jitSymbolTable;
509 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
510 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
512 // Scan the table to find its index. The table is not sorted, so do a linear
515 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
516 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
518 // Once we have an index, we know to nuke this entry, overwrite it with the
519 // entry at the end of the array, making the last entry redundant.
520 const char *OldName = Symbols[Index].FnName;
521 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
522 free((void*)OldName);
524 // Drop the number of symbols in the table.
525 --SymTabPtr->NumSymbols;
527 // Finally, if we deleted the final symbol, deallocate the table itself.
528 if (SymTabPtr->NumSymbols != 0)
536 //===----------------------------------------------------------------------===//
540 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
541 /// used to output functions to memory for execution.
542 class JITEmitter : public MachineCodeEmitter {
543 JITMemoryManager *MemMgr;
545 // When outputting a function stub in the context of some other function, we
546 // save BufferBegin/BufferEnd/CurBufferPtr here.
547 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
549 /// Relocations - These are the relocations that the function needs, as
551 std::vector<MachineRelocation> Relocations;
553 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
554 /// It is filled in by the StartMachineBasicBlock callback and queried by
555 /// the getMachineBasicBlockAddress callback.
556 std::vector<uintptr_t> MBBLocations;
558 /// ConstantPool - The constant pool for the current function.
560 MachineConstantPool *ConstantPool;
562 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
564 void *ConstantPoolBase;
566 /// ConstPoolAddresses - Addresses of individual constant pool entries.
568 SmallVector<uintptr_t, 8> ConstPoolAddresses;
570 /// JumpTable - The jump tables for the current function.
572 MachineJumpTableInfo *JumpTable;
574 /// JumpTableBase - A pointer to the first entry in the jump table.
578 /// Resolver - This contains info about the currently resolved functions.
579 JITResolver Resolver;
581 /// DE - The dwarf emitter for the jit.
584 /// LabelLocations - This vector is a mapping from Label ID's to their
586 std::vector<uintptr_t> LabelLocations;
588 /// MMI - Machine module info for exception informations
589 MachineModuleInfo* MMI;
591 // GVSet - a set to keep track of which globals have been seen
592 SmallPtrSet<const GlobalVariable*, 8> GVSet;
594 // CurFn - The llvm function being emitted. Only valid during
596 const Function *CurFn;
598 // CurFnStubUses - For a given Function, a vector of stubs that it
599 // references. This facilitates the JIT detecting that a stub is no
600 // longer used, so that it may be deallocated.
601 DenseMap<const Function *, SmallVector<void*, 1> > CurFnStubUses;
603 // StubFnRefs - For a given pointer to a stub, a set of Functions which
604 // reference the stub. When the count of a stub's references drops to zero,
605 // the stub is unused.
606 DenseMap<void *, SmallPtrSet<const Function*, 1> > StubFnRefs;
608 // ExtFnStubs - A map of external function names to stubs which have entries
609 // in the JITResolver's ExternalFnToStubMap.
610 StringMap<void *> ExtFnStubs;
613 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit), CurFn(0) {
614 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
615 if (jit.getJITInfo().needsGOT()) {
616 MemMgr->AllocateGOT();
617 DOUT << "JIT is managing a GOT\n";
620 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
624 if (ExceptionHandling) delete DE;
627 /// classof - Methods for support type inquiry through isa, cast, and
630 static inline bool classof(const JITEmitter*) { return true; }
631 static inline bool classof(const MachineCodeEmitter*) { return true; }
633 JITResolver &getJITResolver() { return Resolver; }
635 virtual void startFunction(MachineFunction &F);
636 virtual bool finishFunction(MachineFunction &F);
638 void emitConstantPool(MachineConstantPool *MCP);
639 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
640 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
642 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
643 unsigned Alignment = 1);
644 virtual void startGVStub(const GlobalValue* GV, void *Buffer,
646 virtual void* finishGVStub(const GlobalValue *GV);
648 /// allocateSpace - Reserves space in the current block if any, or
649 /// allocate a new one of the given size.
650 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
652 virtual void addRelocation(const MachineRelocation &MR) {
653 Relocations.push_back(MR);
656 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
657 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
658 MBBLocations.resize((MBB->getNumber()+1)*2);
659 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
660 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
661 << (void*) getCurrentPCValue() << "]\n";
664 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
665 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
667 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
668 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
669 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
670 return MBBLocations[MBB->getNumber()];
673 /// deallocateMemForFunction - Deallocate all memory for the specified
675 void deallocateMemForFunction(Function *F);
677 /// AddStubToCurrentFunction - Mark the current function being JIT'd as
678 /// using the stub at the specified address. Allows
679 /// deallocateMemForFunction to also remove stubs no longer referenced.
680 void AddStubToCurrentFunction(void *Stub);
682 /// getExternalFnStubs - Accessor for the JIT to find stubs emitted for
683 /// MachineRelocations that reference external functions by name.
684 const StringMap<void*> &getExternalFnStubs() const { return ExtFnStubs; }
686 virtual void emitLabel(uint64_t LabelID) {
687 if (LabelLocations.size() <= LabelID)
688 LabelLocations.resize((LabelID+1)*2);
689 LabelLocations[LabelID] = getCurrentPCValue();
692 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
693 assert(LabelLocations.size() > (unsigned)LabelID &&
694 LabelLocations[LabelID] && "Label not emitted!");
695 return LabelLocations[LabelID];
698 virtual void setModuleInfo(MachineModuleInfo* Info) {
700 if (ExceptionHandling) DE->setModuleInfo(Info);
703 void setMemoryExecutable(void) {
704 MemMgr->setMemoryExecutable();
707 JITMemoryManager *getMemMgr(void) const { return MemMgr; }
710 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
711 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
713 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
714 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
715 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
716 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
720 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
721 bool DoesntNeedStub) {
722 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
723 return TheJIT->getOrEmitGlobalVariable(GV);
725 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
726 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
728 // If we have already compiled the function, return a pointer to its body.
729 Function *F = cast<Function>(V);
731 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled()) {
732 // Return the function stub if it's already created.
733 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
735 AddStubToCurrentFunction(ResultPtr);
737 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
739 if (ResultPtr) return ResultPtr;
741 // If this is an external function pointer, we can force the JIT to
742 // 'compile' it, which really just adds it to the map. In dlsym mode,
743 // external functions are forced through a stub, regardless of reloc type.
744 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode() &&
745 DoesntNeedStub && !TheJIT->areDlsymStubsEnabled())
746 return TheJIT->getPointerToFunction(F);
748 // Okay, the function has not been compiled yet, if the target callback
749 // mechanism is capable of rewriting the instruction directly, prefer to do
750 // that instead of emitting a stub. This uses the lazy resolver, so is not
751 // legal if lazy compilation is disabled.
752 if (DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
753 return Resolver.AddCallbackAtLocation(F, Reference);
755 // Otherwise, we have to emit a stub.
756 void *StubAddr = Resolver.getFunctionStub(F);
758 // Add the stub to the current function's list of referenced stubs, so we can
759 // deallocate them if the current function is ever freed. It's possible to
760 // return null from getFunctionStub in the case of a weak extern that fails
763 AddStubToCurrentFunction(StubAddr);
768 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
770 // Make sure GV is emitted first, and create a stub containing the fully
772 void *GVAddress = getPointerToGlobal(V, Reference, true);
773 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
775 // Add the stub to the current function's list of referenced stubs, so we can
776 // deallocate them if the current function is ever freed.
777 AddStubToCurrentFunction(StubAddr);
782 void JITEmitter::AddStubToCurrentFunction(void *StubAddr) {
783 if (!TheJIT->areDlsymStubsEnabled())
786 assert(CurFn && "Stub added to current function, but current function is 0!");
788 SmallVectorImpl<void*> &StubsUsed = CurFnStubUses[CurFn];
789 StubsUsed.push_back(StubAddr);
791 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[StubAddr];
792 FnRefs.insert(CurFn);
795 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
796 const TargetData *TD) {
797 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
798 if (Constants.empty()) return 0;
801 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
802 MachineConstantPoolEntry CPE = Constants[i];
803 unsigned AlignMask = CPE.getAlignment() - 1;
804 Size = (Size + AlignMask) & ~AlignMask;
805 const Type *Ty = CPE.getType();
806 Size += TD->getTypePaddedSize(Ty);
811 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
812 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
813 if (JT.empty()) return 0;
815 unsigned NumEntries = 0;
816 for (unsigned i = 0, e = JT.size(); i != e; ++i)
817 NumEntries += JT[i].MBBs.size();
819 unsigned EntrySize = MJTI->getEntrySize();
821 return NumEntries * EntrySize;
824 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
825 if (Alignment == 0) Alignment = 1;
826 // Since we do not know where the buffer will be allocated, be pessimistic.
827 return Size + Alignment;
830 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
831 /// into the running total Size.
833 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
834 const Type *ElTy = GV->getType()->getElementType();
835 size_t GVSize = (size_t)TheJIT->getTargetData()->getTypePaddedSize(ElTy);
837 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
838 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
840 // Assume code section ends with worst possible alignment, so first
841 // variable needs maximal padding.
844 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
849 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
850 /// but are referenced from the constant; put them in GVSet and add their
851 /// size into the running total Size.
853 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
855 // If its undefined, return the garbage.
856 if (isa<UndefValue>(C))
859 // If the value is a ConstantExpr
860 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
861 Constant *Op0 = CE->getOperand(0);
862 switch (CE->getOpcode()) {
863 case Instruction::GetElementPtr:
864 case Instruction::Trunc:
865 case Instruction::ZExt:
866 case Instruction::SExt:
867 case Instruction::FPTrunc:
868 case Instruction::FPExt:
869 case Instruction::UIToFP:
870 case Instruction::SIToFP:
871 case Instruction::FPToUI:
872 case Instruction::FPToSI:
873 case Instruction::PtrToInt:
874 case Instruction::IntToPtr:
875 case Instruction::BitCast: {
876 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
879 case Instruction::Add:
880 case Instruction::Sub:
881 case Instruction::Mul:
882 case Instruction::UDiv:
883 case Instruction::SDiv:
884 case Instruction::URem:
885 case Instruction::SRem:
886 case Instruction::And:
887 case Instruction::Or:
888 case Instruction::Xor: {
889 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
890 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
894 cerr << "ConstantExpr not handled: " << *CE << "\n";
900 if (C->getType()->getTypeID() == Type::PointerTyID)
901 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
902 if (GVSet.insert(GV))
903 Size = addSizeOfGlobal(GV, Size);
908 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
909 /// but are referenced from the given initializer.
911 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
913 if (!isa<UndefValue>(Init) &&
914 !isa<ConstantVector>(Init) &&
915 !isa<ConstantAggregateZero>(Init) &&
916 !isa<ConstantArray>(Init) &&
917 !isa<ConstantStruct>(Init) &&
918 Init->getType()->isFirstClassType())
919 Size = addSizeOfGlobalsInConstantVal(Init, Size);
923 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
924 /// globals; then walk the initializers of those globals looking for more.
925 /// If their size has not been considered yet, add it into the running total
928 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
932 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
934 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
936 const TargetInstrDesc &Desc = I->getDesc();
937 const MachineInstr &MI = *I;
938 unsigned NumOps = Desc.getNumOperands();
939 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
940 const MachineOperand &MO = MI.getOperand(CurOp);
942 GlobalValue* V = MO.getGlobal();
943 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
946 // If seen in previous function, it will have an entry here.
947 if (TheJIT->getPointerToGlobalIfAvailable(GV))
949 // If seen earlier in this function, it will have an entry here.
950 // FIXME: it should be possible to combine these tables, by
951 // assuming the addresses of the new globals in this module
952 // start at 0 (or something) and adjusting them after codegen
953 // complete. Another possibility is to grab a marker bit in GV.
954 if (GVSet.insert(GV))
955 // A variable as yet unseen. Add in its size.
956 Size = addSizeOfGlobal(GV, Size);
961 DOUT << "JIT: About to look through initializers\n";
962 // Look for more globals that are referenced only from initializers.
963 // GVSet.end is computed each time because the set can grow as we go.
964 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
965 I != GVSet.end(); I++) {
966 const GlobalVariable* GV = *I;
967 if (GV->hasInitializer())
968 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
974 void JITEmitter::startFunction(MachineFunction &F) {
975 DOUT << "JIT: Starting CodeGen of Function "
976 << F.getFunction()->getName() << "\n";
978 uintptr_t ActualSize = 0;
979 // Set the memory writable, if it's not already
980 MemMgr->setMemoryWritable();
981 if (MemMgr->NeedsExactSize()) {
982 DOUT << "JIT: ExactSize\n";
983 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
984 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
985 MachineConstantPool *MCP = F.getConstantPool();
987 // Ensure the constant pool/jump table info is at least 4-byte aligned.
988 ActualSize = RoundUpToAlign(ActualSize, 16);
990 // Add the alignment of the constant pool
991 ActualSize = RoundUpToAlign(ActualSize, MCP->getConstantPoolAlignment());
993 // Add the constant pool size
994 ActualSize += GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
996 // Add the aligment of the jump table info
997 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
999 // Add the jump table size
1000 ActualSize += GetJumpTableSizeInBytes(MJTI);
1002 // Add the alignment for the function
1003 ActualSize = RoundUpToAlign(ActualSize,
1004 std::max(F.getFunction()->getAlignment(), 8U));
1006 // Add the function size
1007 ActualSize += TII->GetFunctionSizeInBytes(F);
1009 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
1010 // Add the size of the globals that will be allocated after this function.
1011 // These are all the ones referenced from this function that were not
1012 // previously allocated.
1013 ActualSize += GetSizeOfGlobalsInBytes(F);
1014 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
1017 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
1019 BufferEnd = BufferBegin+ActualSize;
1021 // Ensure the constant pool/jump table info is at least 4-byte aligned.
1024 emitConstantPool(F.getConstantPool());
1025 initJumpTableInfo(F.getJumpTableInfo());
1027 // About to start emitting the machine code for the function.
1028 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
1029 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
1031 MBBLocations.clear();
1034 bool JITEmitter::finishFunction(MachineFunction &F) {
1035 if (CurBufferPtr == BufferEnd) {
1036 // FIXME: Allocate more space, then try again.
1037 cerr << "JIT: Ran out of space for generated machine code!\n";
1041 emitJumpTableInfo(F.getJumpTableInfo());
1043 // FnStart is the start of the text, not the start of the constant pool and
1044 // other per-function data.
1045 unsigned char *FnStart =
1046 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
1048 if (!Relocations.empty()) {
1049 CurFn = F.getFunction();
1050 NumRelos += Relocations.size();
1052 // Resolve the relocations to concrete pointers.
1053 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
1054 MachineRelocation &MR = Relocations[i];
1055 void *ResultPtr = 0;
1056 if (!MR.letTargetResolve()) {
1057 if (MR.isExternalSymbol()) {
1058 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
1060 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
1061 << ResultPtr << "]\n";
1063 // If the target REALLY wants a stub for this function, emit it now.
1064 if (!MR.doesntNeedStub()) {
1065 if (!TheJIT->areDlsymStubsEnabled()) {
1066 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
1068 void *&Stub = ExtFnStubs[MR.getExternalSymbol()];
1070 Stub = Resolver.getExternalFunctionStub((void *)&Stub);
1071 AddStubToCurrentFunction(Stub);
1076 } else if (MR.isGlobalValue()) {
1077 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
1078 BufferBegin+MR.getMachineCodeOffset(),
1079 MR.doesntNeedStub());
1080 } else if (MR.isIndirectSymbol()) {
1081 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
1082 BufferBegin+MR.getMachineCodeOffset(),
1083 MR.doesntNeedStub());
1084 } else if (MR.isBasicBlock()) {
1085 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
1086 } else if (MR.isConstantPoolIndex()) {
1087 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
1089 assert(MR.isJumpTableIndex());
1090 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
1093 MR.setResultPointer(ResultPtr);
1096 // if we are managing the GOT and the relocation wants an index,
1098 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
1099 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
1100 MR.setGOTIndex(idx);
1101 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
1102 DOUT << "JIT: GOT was out of date for " << ResultPtr
1103 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
1105 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
1111 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
1112 Relocations.size(), MemMgr->getGOTBase());
1115 // Update the GOT entry for F to point to the new code.
1116 if (MemMgr->isManagingGOT()) {
1117 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
1118 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
1119 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
1120 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
1121 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
1125 unsigned char *FnEnd = CurBufferPtr;
1127 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
1129 if (CurBufferPtr == BufferEnd) {
1130 // FIXME: Allocate more space, then try again.
1131 cerr << "JIT: Ran out of space for generated machine code!\n";
1135 BufferBegin = CurBufferPtr = 0;
1136 NumBytes += FnEnd-FnStart;
1138 // Invalidate the icache if necessary.
1139 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
1141 // Add it to the JIT symbol table if the host wants it.
1142 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
1143 FnStart, FnEnd-FnStart);
1145 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
1146 << "] Function: " << F.getFunction()->getName()
1147 << ": " << (FnEnd-FnStart) << " bytes of text, "
1148 << Relocations.size() << " relocations\n";
1149 Relocations.clear();
1150 ConstPoolAddresses.clear();
1152 // Mark code region readable and executable if it's not so already.
1153 MemMgr->setMemoryExecutable();
1157 if (sys::hasDisassembler()) {
1158 DOUT << "JIT: Disassembled code:\n";
1159 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
1161 DOUT << "JIT: Binary code:\n";
1163 unsigned char* q = FnStart;
1164 for (int i = 0; q < FnEnd; q += 4, ++i) {
1168 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1169 << (long)(q - FnStart) << ": ";
1171 for (int j = 3; j >= 0; --j) {
1175 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1188 if (ExceptionHandling) {
1189 uintptr_t ActualSize = 0;
1190 SavedBufferBegin = BufferBegin;
1191 SavedBufferEnd = BufferEnd;
1192 SavedCurBufferPtr = CurBufferPtr;
1194 if (MemMgr->NeedsExactSize()) {
1195 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
1198 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1200 BufferEnd = BufferBegin+ActualSize;
1201 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
1202 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1204 BufferBegin = SavedBufferBegin;
1205 BufferEnd = SavedBufferEnd;
1206 CurBufferPtr = SavedCurBufferPtr;
1208 TheJIT->RegisterTable(FrameRegister);
1217 /// deallocateMemForFunction - Deallocate all memory for the specified
1218 /// function body. Also drop any references the function has to stubs.
1219 void JITEmitter::deallocateMemForFunction(Function *F) {
1220 MemMgr->deallocateMemForFunction(F);
1222 // If the function did not reference any stubs, return.
1223 if (CurFnStubUses.find(F) == CurFnStubUses.end())
1226 // For each referenced stub, erase the reference to this function, and then
1227 // erase the list of referenced stubs.
1228 SmallVectorImpl<void *> &StubList = CurFnStubUses[F];
1229 for (unsigned i = 0, e = StubList.size(); i != e; ++i) {
1230 void *Stub = StubList[i];
1232 // If we already invalidated this stub for this function, continue.
1233 if (StubFnRefs.count(Stub) == 0)
1236 SmallPtrSet<const Function *, 1> &FnRefs = StubFnRefs[Stub];
1239 // If this function was the last reference to the stub, invalidate the stub
1240 // in the JITResolver. Were there a memory manager deallocateStub routine,
1241 // we could call that at this point too.
1242 if (FnRefs.empty()) {
1243 DOUT << "\nJIT: Invalidated Stub at [" << Stub << "]\n";
1244 StubFnRefs.erase(Stub);
1246 // Invalidate the stub. If it is a GV stub, update the JIT's global
1247 // mapping for that GV to zero, otherwise, search the string map of
1248 // external function names to stubs and remove the entry for this stub.
1249 GlobalValue *GV = Resolver.invalidateStub(Stub);
1251 TheJIT->updateGlobalMapping(GV, 0);
1253 for (StringMapIterator<void*> i = ExtFnStubs.begin(),
1254 e = ExtFnStubs.end(); i != e; ++i) {
1255 if (i->second == Stub) {
1256 ExtFnStubs.erase(i);
1263 CurFnStubUses.erase(F);
1267 void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
1269 return MachineCodeEmitter::allocateSpace(Size, Alignment);
1271 // create a new memory block if there is no active one.
1272 // care must be taken so that BufferBegin is invalidated when a
1274 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1275 BufferEnd = BufferBegin+Size;
1276 return CurBufferPtr;
1279 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1280 if (TheJIT->getJITInfo().hasCustomConstantPool())
1283 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1284 if (Constants.empty()) return;
1286 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
1287 unsigned Align = MCP->getConstantPoolAlignment();
1288 ConstantPoolBase = allocateSpace(Size, Align);
1291 if (ConstantPoolBase == 0) return; // Buffer overflow.
1293 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1294 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1296 // Initialize the memory for all of the constant pool entries.
1297 unsigned Offset = 0;
1298 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1299 MachineConstantPoolEntry CPE = Constants[i];
1300 unsigned AlignMask = CPE.getAlignment() - 1;
1301 Offset = (Offset + AlignMask) & ~AlignMask;
1303 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1304 ConstPoolAddresses.push_back(CAddr);
1305 if (CPE.isMachineConstantPoolEntry()) {
1306 // FIXME: add support to lower machine constant pool values into bytes!
1307 cerr << "Initialize memory with machine specific constant pool entry"
1308 << " has not been implemented!\n";
1311 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1312 DOUT << "JIT: CP" << i << " at [0x"
1313 << std::hex << CAddr << std::dec << "]\n";
1315 const Type *Ty = CPE.Val.ConstVal->getType();
1316 Offset += TheJIT->getTargetData()->getTypePaddedSize(Ty);
1320 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1321 if (TheJIT->getJITInfo().hasCustomJumpTables())
1324 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1325 if (JT.empty()) return;
1327 unsigned NumEntries = 0;
1328 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1329 NumEntries += JT[i].MBBs.size();
1331 unsigned EntrySize = MJTI->getEntrySize();
1333 // Just allocate space for all the jump tables now. We will fix up the actual
1334 // MBB entries in the tables after we emit the code for each block, since then
1335 // we will know the final locations of the MBBs in memory.
1337 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1340 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1341 if (TheJIT->getJITInfo().hasCustomJumpTables())
1344 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1345 if (JT.empty() || JumpTableBase == 0) return;
1347 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1348 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1349 // For each jump table, place the offset from the beginning of the table
1350 // to the target address.
1351 int *SlotPtr = (int*)JumpTableBase;
1353 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1354 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1355 // Store the offset of the basic block for this jump table slot in the
1356 // memory we allocated for the jump table in 'initJumpTableInfo'
1357 uintptr_t Base = (uintptr_t)SlotPtr;
1358 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1359 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1360 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1364 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1366 // For each jump table, map each target in the jump table to the address of
1367 // an emitted MachineBasicBlock.
1368 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1370 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1371 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1372 // Store the address of the basic block for this jump table slot in the
1373 // memory we allocated for the jump table in 'initJumpTableInfo'
1374 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1375 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1380 void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1381 unsigned Alignment) {
1382 SavedBufferBegin = BufferBegin;
1383 SavedBufferEnd = BufferEnd;
1384 SavedCurBufferPtr = CurBufferPtr;
1386 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1387 BufferEnd = BufferBegin+StubSize+1;
1390 void JITEmitter::startGVStub(const GlobalValue* GV, void *Buffer,
1391 unsigned StubSize) {
1392 SavedBufferBegin = BufferBegin;
1393 SavedBufferEnd = BufferEnd;
1394 SavedCurBufferPtr = CurBufferPtr;
1396 BufferBegin = CurBufferPtr = (unsigned char *)Buffer;
1397 BufferEnd = BufferBegin+StubSize+1;
1400 void *JITEmitter::finishGVStub(const GlobalValue* GV) {
1401 NumBytes += getCurrentPCOffset();
1402 std::swap(SavedBufferBegin, BufferBegin);
1403 BufferEnd = SavedBufferEnd;
1404 CurBufferPtr = SavedCurBufferPtr;
1405 return SavedBufferBegin;
1408 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1409 // in the constant pool that was last emitted with the 'emitConstantPool'
1412 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1413 assert(ConstantNum < ConstantPool->getConstants().size() &&
1414 "Invalid ConstantPoolIndex!");
1415 return ConstPoolAddresses[ConstantNum];
1418 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1419 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1421 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1422 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1423 assert(Index < JT.size() && "Invalid jump table index!");
1425 unsigned Offset = 0;
1426 unsigned EntrySize = JumpTable->getEntrySize();
1428 for (unsigned i = 0; i < Index; ++i)
1429 Offset += JT[i].MBBs.size();
1431 Offset *= EntrySize;
1433 return (uintptr_t)((char *)JumpTableBase + Offset);
1436 //===----------------------------------------------------------------------===//
1437 // Public interface to this file
1438 //===----------------------------------------------------------------------===//
1440 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1441 return new JITEmitter(jit, JMM);
1444 // getPointerToNamedFunction - This function is used as a global wrapper to
1445 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1446 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1447 // need to resolve function(s) that are being mis-codegenerated, so we need to
1448 // resolve their addresses at runtime, and this is the way to do it.
1450 void *getPointerToNamedFunction(const char *Name) {
1451 if (Function *F = TheJIT->FindFunctionNamed(Name))
1452 return TheJIT->getPointerToFunction(F);
1453 return TheJIT->getPointerToNamedFunction(Name);
1457 // getPointerToFunctionOrStub - If the specified function has been
1458 // code-gen'd, return a pointer to the function. If not, compile it, or use
1459 // a stub to implement lazy compilation if available.
1461 void *JIT::getPointerToFunctionOrStub(Function *F) {
1462 // If we have already code generated the function, just return the address.
1463 if (void *Addr = getPointerToGlobalIfAvailable(F))
1466 // Get a stub if the target supports it.
1467 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1468 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1469 return JE->getJITResolver().getFunctionStub(F);
1472 void JIT::updateFunctionStub(Function *F) {
1473 // Get the empty stub we generated earlier.
1474 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1475 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1476 void *Stub = JE->getJITResolver().getFunctionStub(F);
1478 // Tell the target jit info to rewrite the stub at the specified address,
1479 // rather than creating a new one.
1480 void *Addr = getPointerToGlobalIfAvailable(F);
1481 getJITInfo().emitFunctionStubAtAddr(F, Addr, Stub, *getCodeEmitter());
1484 /// updateDlsymStubTable - Emit the data necessary to relocate the stubs
1485 /// that were emitted during code generation.
1487 void JIT::updateDlsymStubTable() {
1488 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1489 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1491 SmallVector<GlobalValue*, 8> GVs;
1492 SmallVector<void*, 8> Ptrs;
1493 const StringMap<void *> &ExtFns = JE->getExternalFnStubs();
1495 JE->getJITResolver().getRelocatableGVs(GVs, Ptrs);
1497 unsigned nStubs = GVs.size() + ExtFns.size();
1499 // If there are no relocatable stubs, return.
1503 // If there are no new relocatable stubs, return.
1504 void *CurTable = JE->getMemMgr()->getDlsymTable();
1505 if (CurTable && (*(unsigned *)CurTable == nStubs))
1508 // Calculate the size of the stub info
1509 unsigned offset = 4 + 4 * nStubs + sizeof(intptr_t) * nStubs;
1511 SmallVector<unsigned, 8> Offsets;
1512 for (unsigned i = 0; i != GVs.size(); ++i) {
1513 Offsets.push_back(offset);
1514 offset += GVs[i]->getName().length() + 1;
1516 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1518 Offsets.push_back(offset);
1519 offset += strlen(i->first()) + 1;
1522 // Allocate space for the new "stub", which contains the dlsym table.
1523 JE->startGVStub(0, offset, 4);
1525 // Emit the number of records
1526 MCE->emitInt32(nStubs);
1528 // Emit the string offsets
1529 for (unsigned i = 0; i != nStubs; ++i)
1530 MCE->emitInt32(Offsets[i]);
1532 // Emit the pointers. Verify that they are at least 2-byte aligned, and set
1533 // the low bit to 0 == GV, 1 == Function, so that the client code doing the
1534 // relocation can write the relocated pointer at the appropriate place in
1536 for (unsigned i = 0; i != GVs.size(); ++i) {
1537 intptr_t Ptr = (intptr_t)Ptrs[i];
1538 assert((Ptr & 1) == 0 && "Stub pointers must be at least 2-byte aligned!");
1540 if (isa<Function>(GVs[i]))
1543 if (sizeof(Ptr) == 8)
1544 MCE->emitInt64(Ptr);
1546 MCE->emitInt32(Ptr);
1548 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1550 intptr_t Ptr = (intptr_t)i->second | 1;
1552 if (sizeof(Ptr) == 8)
1553 MCE->emitInt64(Ptr);
1555 MCE->emitInt32(Ptr);
1558 // Emit the strings.
1559 for (unsigned i = 0; i != GVs.size(); ++i)
1560 MCE->emitString(GVs[i]->getName());
1561 for (StringMapConstIterator<void*> i = ExtFns.begin(), e = ExtFns.end();
1563 MCE->emitString(i->first());
1565 // Tell the JIT memory manager where it is. The JIT Memory Manager will
1566 // deallocate space for the old one, if one existed.
1567 JE->getMemMgr()->SetDlsymTable(JE->finishGVStub(0));
1570 /// freeMachineCodeForFunction - release machine code memory for given Function.
1572 void JIT::freeMachineCodeForFunction(Function *F) {
1574 // Delete translation for this from the ExecutionEngine, so it will get
1575 // retranslated next time it is used.
1576 void *OldPtr = updateGlobalMapping(F, 0);
1579 RemoveFunctionFromSymbolTable(OldPtr);
1581 // Free the actual memory for the function body and related stuff.
1582 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1583 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);