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/Statistic.h"
46 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
47 STATISTIC(NumRelos, "Number of relocations applied");
48 static JIT *TheJIT = 0;
51 //===----------------------------------------------------------------------===//
52 // JIT lazy compilation code.
55 class JITResolverState {
57 /// FunctionToStubMap - Keep track of the stub created for a particular
58 /// function so that we can reuse them if necessary.
59 std::map<Function*, void*> FunctionToStubMap;
61 /// StubToFunctionMap - Keep track of the function that each stub
63 std::map<void*, Function*> StubToFunctionMap;
65 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
66 /// particular GlobalVariable so that we can reuse them if necessary.
67 std::map<GlobalValue*, void*> GlobalToIndirectSymMap;
70 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
71 assert(locked.holds(TheJIT->lock));
72 return FunctionToStubMap;
75 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
76 assert(locked.holds(TheJIT->lock));
77 return StubToFunctionMap;
80 std::map<GlobalValue*, void*>&
81 getGlobalToIndirectSymMap(const MutexGuard& locked) {
82 assert(locked.holds(TheJIT->lock));
83 return GlobalToIndirectSymMap;
87 /// JITResolver - Keep track of, and resolve, call sites for functions that
88 /// have not yet been compiled.
90 /// LazyResolverFn - The target lazy resolver function that we actually
91 /// rewrite instructions to use.
92 TargetJITInfo::LazyResolverFn LazyResolverFn;
94 JITResolverState state;
96 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
97 /// external functions.
98 std::map<void*, void*> ExternalFnToStubMap;
100 //map addresses to indexes in the GOT
101 std::map<void*, unsigned> revGOTMap;
102 unsigned nextGOTIndex;
104 static JITResolver *TheJITResolver;
106 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
109 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
110 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
111 TheJITResolver = this;
118 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
119 /// if it has already been created.
120 void *getFunctionStubIfAvailable(Function *F);
122 /// getFunctionStub - This returns a pointer to a function stub, creating
123 /// one on demand as needed.
124 void *getFunctionStub(Function *F);
126 /// getExternalFunctionStub - Return a stub for the function at the
127 /// specified address, created lazily on demand.
128 void *getExternalFunctionStub(void *FnAddr);
130 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
131 /// specified GV address.
132 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
134 /// AddCallbackAtLocation - If the target is capable of rewriting an
135 /// instruction without the use of a stub, record the location of the use so
136 /// we know which function is being used at the location.
137 void *AddCallbackAtLocation(Function *F, void *Location) {
138 MutexGuard locked(TheJIT->lock);
139 /// Get the target-specific JIT resolver function.
140 state.getStubToFunctionMap(locked)[Location] = F;
141 return (void*)(intptr_t)LazyResolverFn;
144 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
145 /// an address. This function only manages slots, it does not manage the
146 /// contents of the slots or the memory associated with the GOT.
147 unsigned getGOTIndexForAddr(void *addr);
149 /// JITCompilerFn - This function is called to resolve a stub to a compiled
150 /// address. If the LLVM Function corresponding to the stub has not yet
151 /// been compiled, this function compiles it first.
152 static void *JITCompilerFn(void *Stub);
156 JITResolver *JITResolver::TheJITResolver = 0;
158 /// getFunctionStubIfAvailable - This returns a pointer to a function stub
159 /// if it has already been created.
160 void *JITResolver::getFunctionStubIfAvailable(Function *F) {
161 MutexGuard locked(TheJIT->lock);
163 // If we already have a stub for this function, recycle it.
164 void *&Stub = state.getFunctionToStubMap(locked)[F];
168 /// getFunctionStub - This returns a pointer to a function stub, creating
169 /// one on demand as needed.
170 void *JITResolver::getFunctionStub(Function *F) {
171 MutexGuard locked(TheJIT->lock);
173 // If we already have a stub for this function, recycle it.
174 void *&Stub = state.getFunctionToStubMap(locked)[F];
175 if (Stub) return Stub;
177 // Call the lazy resolver function unless we already KNOW it is an external
178 // function, in which case we just skip the lazy resolution step.
179 void *Actual = (void*)(intptr_t)LazyResolverFn;
180 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode())
181 Actual = TheJIT->getPointerToFunction(F);
183 // Otherwise, codegen a new stub. For now, the stub will call the lazy
184 // resolver function.
185 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
186 *TheJIT->getCodeEmitter());
188 if (Actual != (void*)(intptr_t)LazyResolverFn) {
189 // If we are getting the stub for an external function, we really want the
190 // address of the stub in the GlobalAddressMap for the JIT, not the address
191 // of the external function.
192 TheJIT->updateGlobalMapping(F, Stub);
195 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
196 << F->getName() << "'\n";
198 // Finally, keep track of the stub-to-Function mapping so that the
199 // JITCompilerFn knows which function to compile!
200 state.getStubToFunctionMap(locked)[Stub] = F;
204 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
206 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
207 MutexGuard locked(TheJIT->lock);
209 // If we already have a stub for this global variable, recycle it.
210 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
211 if (IndirectSym) return IndirectSym;
213 // Otherwise, codegen a new indirect symbol.
214 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
215 *TheJIT->getCodeEmitter());
217 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
218 << GV->getName() << "'\n";
223 /// getExternalFunctionStub - Return a stub for the function at the
224 /// specified address, created lazily on demand.
225 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
226 // If we already have a stub for this function, recycle it.
227 void *&Stub = ExternalFnToStubMap[FnAddr];
228 if (Stub) return Stub;
230 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
231 *TheJIT->getCodeEmitter());
233 DOUT << "JIT: Stub emitted at [" << Stub
234 << "] for external function at '" << FnAddr << "'\n";
238 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
239 unsigned idx = revGOTMap[addr];
241 idx = ++nextGOTIndex;
242 revGOTMap[addr] = idx;
243 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
248 /// JITCompilerFn - This function is called when a lazy compilation stub has
249 /// been entered. It looks up which function this stub corresponds to, compiles
250 /// it if necessary, then returns the resultant function pointer.
251 void *JITResolver::JITCompilerFn(void *Stub) {
252 JITResolver &JR = *TheJITResolver;
258 // Only lock for getting the Function. The call getPointerToFunction made
259 // in this function might trigger function materializing, which requires
260 // JIT lock to be unlocked.
261 MutexGuard locked(TheJIT->lock);
263 // The address given to us for the stub may not be exactly right, it might be
264 // a little bit after the stub. As such, use upper_bound to find it.
265 std::map<void*, Function*>::iterator I =
266 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
267 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
268 "This is not a known stub!");
270 ActualPtr = I->first;
273 // If we have already code generated the function, just return the address.
274 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
277 // Otherwise we don't have it, do lazy compilation now.
279 // If lazy compilation is disabled, emit a useful error message and abort.
280 if (TheJIT->isLazyCompilationDisabled()) {
281 cerr << "LLVM JIT requested to do lazy compilation of function '"
282 << F->getName() << "' when lazy compiles are disabled!\n";
286 // We might like to remove the stub from the StubToFunction map.
287 // We can't do that! Multiple threads could be stuck, waiting to acquire the
288 // lock above. As soon as the 1st function finishes compiling the function,
289 // the next one will be released, and needs to be able to find the function
291 //JR.state.getStubToFunctionMap(locked).erase(I);
293 DOUT << "JIT: Lazily resolving function '" << F->getName()
294 << "' In stub ptr = " << Stub << " actual ptr = "
295 << ActualPtr << "\n";
297 Result = TheJIT->getPointerToFunction(F);
300 // Reacquire the lock to erase the stub in the map.
301 MutexGuard locked(TheJIT->lock);
303 // We don't need to reuse this stub in the future, as F is now compiled.
304 JR.state.getFunctionToStubMap(locked).erase(F);
306 // FIXME: We could rewrite all references to this stub if we knew them.
308 // What we will do is set the compiled function address to map to the
309 // same GOT entry as the stub so that later clients may update the GOT
310 // if they see it still using the stub address.
311 // Note: this is done so the Resolver doesn't have to manage GOT memory
312 // Do this without allocating map space if the target isn't using a GOT
313 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
314 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
319 //===----------------------------------------------------------------------===//
320 // Function Index Support
322 // On MacOS we generate an index of currently JIT'd functions so that
323 // performance tools can determine a symbol name and accurate code range for a
324 // PC value. Because performance tools are generally asynchronous, the code
325 // below is written with the hope that it could be interrupted at any time and
326 // have useful answers. However, we don't go crazy with atomic operations, we
327 // just do a "reasonable effort".
329 #define ENABLE_JIT_SYMBOL_TABLE 0
332 /// JitSymbolEntry - Each function that is JIT compiled results in one of these
333 /// being added to an array of symbols. This indicates the name of the function
334 /// as well as the address range it occupies. This allows the client to map
335 /// from a PC value to the name of the function.
336 struct JitSymbolEntry {
337 const char *FnName; // FnName - a strdup'd string.
343 struct JitSymbolTable {
344 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
345 /// pointer is not used right now, but might be used in the future. Consider
346 /// it reserved for future use.
347 JitSymbolTable *NextPtr;
349 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
350 /// 'NumSymbols' symbols are valid.
351 JitSymbolEntry *Symbols;
353 /// NumSymbols - This indicates the number entries in the Symbols array that
357 /// NumAllocated - This indicates the amount of space we have in the Symbols
358 /// array. This is a private field that should not be read by external tools.
359 unsigned NumAllocated;
362 #if ENABLE_JIT_SYMBOL_TABLE
363 JitSymbolTable *__jitSymbolTable;
366 static void AddFunctionToSymbolTable(const char *FnName,
367 void *FnStart, intptr_t FnSize) {
368 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
369 JitSymbolTable **SymTabPtrPtr = 0;
370 #if !ENABLE_JIT_SYMBOL_TABLE
373 SymTabPtrPtr = &__jitSymbolTable;
376 // If this is the first entry in the symbol table, add the JitSymbolTable
378 if (*SymTabPtrPtr == 0) {
379 JitSymbolTable *New = new JitSymbolTable();
383 New->NumAllocated = 0;
387 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
389 // If we have space in the table, reallocate the table.
390 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
391 // If we don't have space, reallocate the table.
392 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
393 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
394 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
396 // Copy the old entries over.
397 memcpy(NewSymbols, OldSymbols,
398 SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
400 // Swap the new symbols in, delete the old ones.
401 SymTabPtr->Symbols = NewSymbols;
402 SymTabPtr->NumAllocated = NewSize;
403 delete [] OldSymbols;
406 // Otherwise, we have enough space, just tack it onto the end of the array.
407 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
408 Entry.FnName = strdup(FnName);
409 Entry.FnStart = FnStart;
410 Entry.FnSize = FnSize;
411 ++SymTabPtr->NumSymbols;
414 static void RemoveFunctionFromSymbolTable(void *FnStart) {
415 assert(FnStart && "Invalid function pointer");
416 JitSymbolTable **SymTabPtrPtr = 0;
417 #if !ENABLE_JIT_SYMBOL_TABLE
420 SymTabPtrPtr = &__jitSymbolTable;
423 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
424 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
426 // Scan the table to find its index. The table is not sorted, so do a linear
429 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
430 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
432 // Once we have an index, we know to nuke this entry, overwrite it with the
433 // entry at the end of the array, making the last entry redundant.
434 const char *OldName = Symbols[Index].FnName;
435 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
436 free((void*)OldName);
438 // Drop the number of symbols in the table.
439 --SymTabPtr->NumSymbols;
441 // Finally, if we deleted the final symbol, deallocate the table itself.
442 if (SymTabPtr->NumSymbols != 0)
450 //===----------------------------------------------------------------------===//
454 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
455 /// used to output functions to memory for execution.
456 class JITEmitter : public MachineCodeEmitter {
457 JITMemoryManager *MemMgr;
459 // When outputting a function stub in the context of some other function, we
460 // save BufferBegin/BufferEnd/CurBufferPtr here.
461 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
463 /// Relocations - These are the relocations that the function needs, as
465 std::vector<MachineRelocation> Relocations;
467 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
468 /// It is filled in by the StartMachineBasicBlock callback and queried by
469 /// the getMachineBasicBlockAddress callback.
470 std::vector<intptr_t> MBBLocations;
472 /// ConstantPool - The constant pool for the current function.
474 MachineConstantPool *ConstantPool;
476 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
478 void *ConstantPoolBase;
480 /// JumpTable - The jump tables for the current function.
482 MachineJumpTableInfo *JumpTable;
484 /// JumpTableBase - A pointer to the first entry in the jump table.
488 /// Resolver - This contains info about the currently resolved functions.
489 JITResolver Resolver;
491 /// DE - The dwarf emitter for the jit.
494 /// LabelLocations - This vector is a mapping from Label ID's to their
496 std::vector<intptr_t> LabelLocations;
498 /// MMI - Machine module info for exception informations
499 MachineModuleInfo* MMI;
501 // GVSet - a set to keep track of which globals have been seen
502 SmallPtrSet<const GlobalVariable*, 8> GVSet;
505 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
506 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
507 if (jit.getJITInfo().needsGOT()) {
508 MemMgr->AllocateGOT();
509 DOUT << "JIT is managing a GOT\n";
512 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
516 if (ExceptionHandling) delete DE;
519 /// classof - Methods for support type inquiry through isa, cast, and
522 static inline bool classof(const JITEmitter*) { return true; }
523 static inline bool classof(const MachineCodeEmitter*) { return true; }
525 JITResolver &getJITResolver() { return Resolver; }
527 virtual void startFunction(MachineFunction &F);
528 virtual bool finishFunction(MachineFunction &F);
530 void emitConstantPool(MachineConstantPool *MCP);
531 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
532 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
534 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
535 unsigned Alignment = 1);
536 virtual void* finishGVStub(const GlobalValue *GV);
538 /// allocateSpace - Reserves space in the current block if any, or
539 /// allocate a new one of the given size.
540 virtual void *allocateSpace(intptr_t Size, unsigned Alignment);
542 virtual void addRelocation(const MachineRelocation &MR) {
543 Relocations.push_back(MR);
546 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
547 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
548 MBBLocations.resize((MBB->getNumber()+1)*2);
549 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
550 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
551 << (void*) getCurrentPCValue() << "]\n";
554 virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
555 virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
557 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
558 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
559 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
560 return MBBLocations[MBB->getNumber()];
563 /// deallocateMemForFunction - Deallocate all memory for the specified
565 void deallocateMemForFunction(Function *F) {
566 MemMgr->deallocateMemForFunction(F);
569 virtual void emitLabel(uint64_t LabelID) {
570 if (LabelLocations.size() <= LabelID)
571 LabelLocations.resize((LabelID+1)*2);
572 LabelLocations[LabelID] = getCurrentPCValue();
575 virtual intptr_t getLabelAddress(uint64_t LabelID) const {
576 assert(LabelLocations.size() > (unsigned)LabelID &&
577 LabelLocations[LabelID] && "Label not emitted!");
578 return LabelLocations[LabelID];
581 virtual void setModuleInfo(MachineModuleInfo* Info) {
583 if (ExceptionHandling) DE->setModuleInfo(Info);
586 void setMemoryExecutable(void) {
587 MemMgr->setMemoryExecutable();
591 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
592 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
594 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
595 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
596 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
597 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
601 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
602 bool DoesntNeedStub) {
603 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
604 /// FIXME: If we straightened things out, this could actually emit the
605 /// global immediately instead of queuing it for codegen later!
606 return TheJIT->getOrEmitGlobalVariable(GV);
608 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
609 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
611 // If we have already compiled the function, return a pointer to its body.
612 Function *F = cast<Function>(V);
615 // Return the function stub if it's already created.
616 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
618 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
619 if (ResultPtr) return ResultPtr;
621 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
622 // If this is an external function pointer, we can force the JIT to
623 // 'compile' it, which really just adds it to the map.
625 return TheJIT->getPointerToFunction(F);
627 return Resolver.getFunctionStub(F);
630 // Okay, the function has not been compiled yet, if the target callback
631 // mechanism is capable of rewriting the instruction directly, prefer to do
632 // that instead of emitting a stub.
634 return Resolver.AddCallbackAtLocation(F, Reference);
636 // Otherwise, we have to emit a lazy resolving stub.
637 return Resolver.getFunctionStub(F);
640 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
642 // Make sure GV is emitted first.
643 // FIXME: For now, if the GV is an external function we force the JIT to
644 // compile it so the indirect symbol will contain the fully resolved address.
645 void *GVAddress = getPointerToGlobal(V, Reference, true);
646 return Resolver.getGlobalValueIndirectSym(V, GVAddress);
649 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
650 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
651 if (Constants.empty()) return 0;
653 MachineConstantPoolEntry CPE = Constants.back();
654 unsigned Size = CPE.Offset;
655 const Type *Ty = CPE.isMachineConstantPoolEntry()
656 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
657 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
661 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
662 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
663 if (JT.empty()) return 0;
665 unsigned NumEntries = 0;
666 for (unsigned i = 0, e = JT.size(); i != e; ++i)
667 NumEntries += JT[i].MBBs.size();
669 unsigned EntrySize = MJTI->getEntrySize();
671 return NumEntries * EntrySize;
674 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
675 if (Alignment == 0) Alignment = 1;
676 // Since we do not know where the buffer will be allocated, be pessimistic.
677 return Size + Alignment;
680 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
681 /// into the running total Size.
683 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
684 const Type *ElTy = GV->getType()->getElementType();
685 size_t GVSize = (size_t)TheJIT->getTargetData()->getABITypeSize(ElTy);
687 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
688 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
690 // Assume code section ends with worst possible alignment, so first
691 // variable needs maximal padding.
694 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
699 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
700 /// but are referenced from the constant; put them in GVSet and add their
701 /// size into the running total Size.
703 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
705 // If its undefined, return the garbage.
706 if (isa<UndefValue>(C))
709 // If the value is a ConstantExpr
710 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
711 Constant *Op0 = CE->getOperand(0);
712 switch (CE->getOpcode()) {
713 case Instruction::GetElementPtr:
714 case Instruction::Trunc:
715 case Instruction::ZExt:
716 case Instruction::SExt:
717 case Instruction::FPTrunc:
718 case Instruction::FPExt:
719 case Instruction::UIToFP:
720 case Instruction::SIToFP:
721 case Instruction::FPToUI:
722 case Instruction::FPToSI:
723 case Instruction::PtrToInt:
724 case Instruction::IntToPtr:
725 case Instruction::BitCast: {
726 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
729 case Instruction::Add:
730 case Instruction::Sub:
731 case Instruction::Mul:
732 case Instruction::UDiv:
733 case Instruction::SDiv:
734 case Instruction::URem:
735 case Instruction::SRem:
736 case Instruction::And:
737 case Instruction::Or:
738 case Instruction::Xor: {
739 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
740 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
744 cerr << "ConstantExpr not handled: " << *CE << "\n";
750 if (C->getType()->getTypeID() == Type::PointerTyID)
751 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
752 if (GVSet.insert(GV))
753 Size = addSizeOfGlobal(GV, Size);
758 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
759 /// but are referenced from the given initializer.
761 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
763 if (!isa<UndefValue>(Init) &&
764 !isa<ConstantVector>(Init) &&
765 !isa<ConstantAggregateZero>(Init) &&
766 !isa<ConstantArray>(Init) &&
767 !isa<ConstantStruct>(Init) &&
768 Init->getType()->isFirstClassType())
769 Size = addSizeOfGlobalsInConstantVal(Init, Size);
773 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
774 /// globals; then walk the initializers of those globals looking for more.
775 /// If their size has not been considered yet, add it into the running total
778 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
782 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
784 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
786 const TargetInstrDesc &Desc = I->getDesc();
787 const MachineInstr &MI = *I;
788 unsigned NumOps = Desc.getNumOperands();
789 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
790 const MachineOperand &MO = MI.getOperand(CurOp);
792 GlobalValue* V = MO.getGlobal();
793 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
796 // If seen in previous function, it will have an entry here.
797 if (TheJIT->getPointerToGlobalIfAvailable(GV))
799 // If seen earlier in this function, it will have an entry here.
800 // FIXME: it should be possible to combine these tables, by
801 // assuming the addresses of the new globals in this module
802 // start at 0 (or something) and adjusting them after codegen
803 // complete. Another possibility is to grab a marker bit in GV.
804 if (GVSet.insert(GV))
805 // A variable as yet unseen. Add in its size.
806 Size = addSizeOfGlobal(GV, Size);
811 DOUT << "JIT: About to look through initializers\n";
812 // Look for more globals that are referenced only from initializers.
813 // GVSet.end is computed each time because the set can grow as we go.
814 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
815 I != GVSet.end(); I++) {
816 const GlobalVariable* GV = *I;
817 if (GV->hasInitializer())
818 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
824 void JITEmitter::startFunction(MachineFunction &F) {
825 DOUT << "JIT: Starting CodeGen of Function "
826 << F.getFunction()->getName() << "\n";
828 uintptr_t ActualSize = 0;
829 // Set the memory writable, if it's not already
830 MemMgr->setMemoryWritable();
831 if (MemMgr->NeedsExactSize()) {
832 DOUT << "JIT: ExactSize\n";
833 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
834 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
835 MachineConstantPool *MCP = F.getConstantPool();
837 // Ensure the constant pool/jump table info is at least 4-byte aligned.
838 ActualSize = RoundUpToAlign(ActualSize, 16);
840 // Add the alignment of the constant pool
841 ActualSize = RoundUpToAlign(ActualSize,
842 1 << MCP->getConstantPoolAlignment());
844 // Add the constant pool size
845 ActualSize += GetConstantPoolSizeInBytes(MCP);
847 // Add the aligment of the jump table info
848 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
850 // Add the jump table size
851 ActualSize += GetJumpTableSizeInBytes(MJTI);
853 // Add the alignment for the function
854 ActualSize = RoundUpToAlign(ActualSize,
855 std::max(F.getFunction()->getAlignment(), 8U));
857 // Add the function size
858 ActualSize += TII->GetFunctionSizeInBytes(F);
860 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
861 // Add the size of the globals that will be allocated after this function.
862 // These are all the ones referenced from this function that were not
863 // previously allocated.
864 ActualSize += GetSizeOfGlobalsInBytes(F);
865 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
868 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
870 BufferEnd = BufferBegin+ActualSize;
872 // Ensure the constant pool/jump table info is at least 4-byte aligned.
875 emitConstantPool(F.getConstantPool());
876 initJumpTableInfo(F.getJumpTableInfo());
878 // About to start emitting the machine code for the function.
879 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
880 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
882 MBBLocations.clear();
885 bool JITEmitter::finishFunction(MachineFunction &F) {
886 if (CurBufferPtr == BufferEnd) {
887 // FIXME: Allocate more space, then try again.
888 cerr << "JIT: Ran out of space for generated machine code!\n";
892 emitJumpTableInfo(F.getJumpTableInfo());
894 // FnStart is the start of the text, not the start of the constant pool and
895 // other per-function data.
896 unsigned char *FnStart =
897 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
899 if (!Relocations.empty()) {
900 NumRelos += Relocations.size();
902 // Resolve the relocations to concrete pointers.
903 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
904 MachineRelocation &MR = Relocations[i];
906 if (!MR.letTargetResolve()) {
907 if (MR.isExternalSymbol()) {
908 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol());
909 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
910 << ResultPtr << "]\n";
912 // If the target REALLY wants a stub for this function, emit it now.
913 if (!MR.doesntNeedStub())
914 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
915 } else if (MR.isGlobalValue()) {
916 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
917 BufferBegin+MR.getMachineCodeOffset(),
918 MR.doesntNeedStub());
919 } else if (MR.isIndirectSymbol()) {
920 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
921 BufferBegin+MR.getMachineCodeOffset(),
922 MR.doesntNeedStub());
923 } else if (MR.isBasicBlock()) {
924 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
925 } else if (MR.isConstantPoolIndex()) {
926 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
928 assert(MR.isJumpTableIndex());
929 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
932 MR.setResultPointer(ResultPtr);
935 // if we are managing the GOT and the relocation wants an index,
937 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
938 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
940 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
941 DOUT << "JIT: GOT was out of date for " << ResultPtr
942 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
944 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
949 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
950 Relocations.size(), MemMgr->getGOTBase());
953 // Update the GOT entry for F to point to the new code.
954 if (MemMgr->isManagingGOT()) {
955 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
956 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
957 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
958 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
959 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
963 unsigned char *FnEnd = CurBufferPtr;
965 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
966 BufferBegin = CurBufferPtr = 0;
967 NumBytes += FnEnd-FnStart;
969 // Invalidate the icache if necessary.
970 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
972 // Add it to the JIT symbol table if the host wants it.
973 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
974 FnStart, FnEnd-FnStart);
976 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
977 << "] Function: " << F.getFunction()->getName()
978 << ": " << (FnEnd-FnStart) << " bytes of text, "
979 << Relocations.size() << " relocations\n";
982 // Mark code region readable and executable if it's not so already.
983 MemMgr->setMemoryExecutable();
987 if (sys::hasDisassembler()) {
988 DOUT << "JIT: Disassembled code:\n";
989 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
991 DOUT << "JIT: Binary code:\n";
993 unsigned char* q = FnStart;
994 for (int i = 0; q < FnEnd; q += 4, ++i) {
998 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
999 << (long)(q - FnStart) << ": ";
1001 for (int j = 3; j >= 0; --j) {
1005 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1018 if (ExceptionHandling) {
1019 uintptr_t ActualSize = 0;
1020 SavedBufferBegin = BufferBegin;
1021 SavedBufferEnd = BufferEnd;
1022 SavedCurBufferPtr = CurBufferPtr;
1024 if (MemMgr->NeedsExactSize()) {
1025 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
1028 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1030 BufferEnd = BufferBegin+ActualSize;
1031 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
1032 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1034 BufferBegin = SavedBufferBegin;
1035 BufferEnd = SavedBufferEnd;
1036 CurBufferPtr = SavedCurBufferPtr;
1038 TheJIT->RegisterTable(FrameRegister);
1047 void* JITEmitter::allocateSpace(intptr_t Size, unsigned Alignment) {
1049 return MachineCodeEmitter::allocateSpace(Size, Alignment);
1051 // create a new memory block if there is no active one.
1052 // care must be taken so that BufferBegin is invalidated when a
1054 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1055 BufferEnd = BufferBegin+Size;
1056 return CurBufferPtr;
1059 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1060 if (TheJIT->getJITInfo().hasCustomConstantPool())
1063 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1064 if (Constants.empty()) return;
1066 MachineConstantPoolEntry CPE = Constants.back();
1067 unsigned Size = CPE.Offset;
1068 const Type *Ty = CPE.isMachineConstantPoolEntry()
1069 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
1070 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
1072 unsigned Align = 1 << MCP->getConstantPoolAlignment();
1073 ConstantPoolBase = allocateSpace(Size, Align);
1076 if (ConstantPoolBase == 0) return; // Buffer overflow.
1078 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1079 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1081 // Initialize the memory for all of the constant pool entries.
1082 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1083 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
1084 if (Constants[i].isMachineConstantPoolEntry()) {
1085 // FIXME: add support to lower machine constant pool values into bytes!
1086 cerr << "Initialize memory with machine specific constant pool entry"
1087 << " has not been implemented!\n";
1090 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
1091 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
1095 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1096 if (TheJIT->getJITInfo().hasCustomJumpTables())
1099 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1100 if (JT.empty()) return;
1102 unsigned NumEntries = 0;
1103 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1104 NumEntries += JT[i].MBBs.size();
1106 unsigned EntrySize = MJTI->getEntrySize();
1108 // Just allocate space for all the jump tables now. We will fix up the actual
1109 // MBB entries in the tables after we emit the code for each block, since then
1110 // we will know the final locations of the MBBs in memory.
1112 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1115 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1116 if (TheJIT->getJITInfo().hasCustomJumpTables())
1119 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1120 if (JT.empty() || JumpTableBase == 0) return;
1122 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1123 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1124 // For each jump table, place the offset from the beginning of the table
1125 // to the target address.
1126 int *SlotPtr = (int*)JumpTableBase;
1128 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1129 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1130 // Store the offset of the basic block for this jump table slot in the
1131 // memory we allocated for the jump table in 'initJumpTableInfo'
1132 intptr_t Base = (intptr_t)SlotPtr;
1133 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1134 intptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1135 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1139 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1141 // For each jump table, map each target in the jump table to the address of
1142 // an emitted MachineBasicBlock.
1143 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1145 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1146 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1147 // Store the address of the basic block for this jump table slot in the
1148 // memory we allocated for the jump table in 'initJumpTableInfo'
1149 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1150 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1155 void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1156 unsigned Alignment) {
1157 SavedBufferBegin = BufferBegin;
1158 SavedBufferEnd = BufferEnd;
1159 SavedCurBufferPtr = CurBufferPtr;
1161 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1162 BufferEnd = BufferBegin+StubSize+1;
1165 void *JITEmitter::finishGVStub(const GlobalValue* GV) {
1166 NumBytes += getCurrentPCOffset();
1167 std::swap(SavedBufferBegin, BufferBegin);
1168 BufferEnd = SavedBufferEnd;
1169 CurBufferPtr = SavedCurBufferPtr;
1170 return SavedBufferBegin;
1173 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1174 // in the constant pool that was last emitted with the 'emitConstantPool'
1177 intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1178 assert(ConstantNum < ConstantPool->getConstants().size() &&
1179 "Invalid ConstantPoolIndex!");
1180 return (intptr_t)ConstantPoolBase +
1181 ConstantPool->getConstants()[ConstantNum].Offset;
1184 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1185 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1187 intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1188 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1189 assert(Index < JT.size() && "Invalid jump table index!");
1191 unsigned Offset = 0;
1192 unsigned EntrySize = JumpTable->getEntrySize();
1194 for (unsigned i = 0; i < Index; ++i)
1195 Offset += JT[i].MBBs.size();
1197 Offset *= EntrySize;
1199 return (intptr_t)((char *)JumpTableBase + Offset);
1202 //===----------------------------------------------------------------------===//
1203 // Public interface to this file
1204 //===----------------------------------------------------------------------===//
1206 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1207 return new JITEmitter(jit, JMM);
1210 // getPointerToNamedFunction - This function is used as a global wrapper to
1211 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1212 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1213 // need to resolve function(s) that are being mis-codegenerated, so we need to
1214 // resolve their addresses at runtime, and this is the way to do it.
1216 void *getPointerToNamedFunction(const char *Name) {
1217 if (Function *F = TheJIT->FindFunctionNamed(Name))
1218 return TheJIT->getPointerToFunction(F);
1219 return TheJIT->getPointerToNamedFunction(Name);
1223 // getPointerToFunctionOrStub - If the specified function has been
1224 // code-gen'd, return a pointer to the function. If not, compile it, or use
1225 // a stub to implement lazy compilation if available.
1227 void *JIT::getPointerToFunctionOrStub(Function *F) {
1228 // If we have already code generated the function, just return the address.
1229 if (void *Addr = getPointerToGlobalIfAvailable(F))
1232 // Get a stub if the target supports it.
1233 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1234 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1235 return JE->getJITResolver().getFunctionStub(F);
1238 /// freeMachineCodeForFunction - release machine code memory for given Function.
1240 void JIT::freeMachineCodeForFunction(Function *F) {
1242 // Delete translation for this from the ExecutionEngine, so it will get
1243 // retranslated next time it is used.
1244 void *OldPtr = updateGlobalMapping(F, 0);
1247 RemoveFunctionFromSymbolTable(OldPtr);
1249 // Free the actual memory for the function body and related stuff.
1250 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1251 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);