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 // If we resolved the symbol to a null address (eg. a weak external)
184 // don't emit a stub. Return a null pointer to the application.
185 if (!Actual) return 0;
188 // Otherwise, codegen a new stub. For now, the stub will call the lazy
189 // resolver function.
190 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
191 *TheJIT->getCodeEmitter());
193 if (Actual != (void*)(intptr_t)LazyResolverFn) {
194 // If we are getting the stub for an external function, we really want the
195 // address of the stub in the GlobalAddressMap for the JIT, not the address
196 // of the external function.
197 TheJIT->updateGlobalMapping(F, Stub);
200 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
201 << F->getName() << "'\n";
203 // Finally, keep track of the stub-to-Function mapping so that the
204 // JITCompilerFn knows which function to compile!
205 state.getStubToFunctionMap(locked)[Stub] = F;
209 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
211 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
212 MutexGuard locked(TheJIT->lock);
214 // If we already have a stub for this global variable, recycle it.
215 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
216 if (IndirectSym) return IndirectSym;
218 // Otherwise, codegen a new indirect symbol.
219 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
220 *TheJIT->getCodeEmitter());
222 DOUT << "JIT: Indirect symbol emitted at [" << IndirectSym << "] for GV '"
223 << GV->getName() << "'\n";
228 /// getExternalFunctionStub - Return a stub for the function at the
229 /// specified address, created lazily on demand.
230 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
231 // If we already have a stub for this function, recycle it.
232 void *&Stub = ExternalFnToStubMap[FnAddr];
233 if (Stub) return Stub;
235 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
236 *TheJIT->getCodeEmitter());
238 DOUT << "JIT: Stub emitted at [" << Stub
239 << "] for external function at '" << FnAddr << "'\n";
243 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
244 unsigned idx = revGOTMap[addr];
246 idx = ++nextGOTIndex;
247 revGOTMap[addr] = idx;
248 DOUT << "JIT: Adding GOT entry " << idx << " for addr [" << addr << "]\n";
253 /// JITCompilerFn - This function is called when a lazy compilation stub has
254 /// been entered. It looks up which function this stub corresponds to, compiles
255 /// it if necessary, then returns the resultant function pointer.
256 void *JITResolver::JITCompilerFn(void *Stub) {
257 JITResolver &JR = *TheJITResolver;
263 // Only lock for getting the Function. The call getPointerToFunction made
264 // in this function might trigger function materializing, which requires
265 // JIT lock to be unlocked.
266 MutexGuard locked(TheJIT->lock);
268 // The address given to us for the stub may not be exactly right, it might be
269 // a little bit after the stub. As such, use upper_bound to find it.
270 std::map<void*, Function*>::iterator I =
271 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
272 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
273 "This is not a known stub!");
275 ActualPtr = I->first;
278 // If we have already code generated the function, just return the address.
279 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
282 // Otherwise we don't have it, do lazy compilation now.
284 // If lazy compilation is disabled, emit a useful error message and abort.
285 if (TheJIT->isLazyCompilationDisabled()) {
286 cerr << "LLVM JIT requested to do lazy compilation of function '"
287 << F->getName() << "' when lazy compiles are disabled!\n";
291 // We might like to remove the stub from the StubToFunction map.
292 // We can't do that! Multiple threads could be stuck, waiting to acquire the
293 // lock above. As soon as the 1st function finishes compiling the function,
294 // the next one will be released, and needs to be able to find the function
296 //JR.state.getStubToFunctionMap(locked).erase(I);
298 DOUT << "JIT: Lazily resolving function '" << F->getName()
299 << "' In stub ptr = " << Stub << " actual ptr = "
300 << ActualPtr << "\n";
302 Result = TheJIT->getPointerToFunction(F);
305 // Reacquire the lock to erase the stub in the map.
306 MutexGuard locked(TheJIT->lock);
308 // We don't need to reuse this stub in the future, as F is now compiled.
309 JR.state.getFunctionToStubMap(locked).erase(F);
311 // FIXME: We could rewrite all references to this stub if we knew them.
313 // What we will do is set the compiled function address to map to the
314 // same GOT entry as the stub so that later clients may update the GOT
315 // if they see it still using the stub address.
316 // Note: this is done so the Resolver doesn't have to manage GOT memory
317 // Do this without allocating map space if the target isn't using a GOT
318 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
319 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
324 //===----------------------------------------------------------------------===//
325 // Function Index Support
327 // On MacOS we generate an index of currently JIT'd functions so that
328 // performance tools can determine a symbol name and accurate code range for a
329 // PC value. Because performance tools are generally asynchronous, the code
330 // below is written with the hope that it could be interrupted at any time and
331 // have useful answers. However, we don't go crazy with atomic operations, we
332 // just do a "reasonable effort".
334 #define ENABLE_JIT_SYMBOL_TABLE 0
337 /// JitSymbolEntry - Each function that is JIT compiled results in one of these
338 /// being added to an array of symbols. This indicates the name of the function
339 /// as well as the address range it occupies. This allows the client to map
340 /// from a PC value to the name of the function.
341 struct JitSymbolEntry {
342 const char *FnName; // FnName - a strdup'd string.
348 struct JitSymbolTable {
349 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
350 /// pointer is not used right now, but might be used in the future. Consider
351 /// it reserved for future use.
352 JitSymbolTable *NextPtr;
354 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
355 /// 'NumSymbols' symbols are valid.
356 JitSymbolEntry *Symbols;
358 /// NumSymbols - This indicates the number entries in the Symbols array that
362 /// NumAllocated - This indicates the amount of space we have in the Symbols
363 /// array. This is a private field that should not be read by external tools.
364 unsigned NumAllocated;
367 #if ENABLE_JIT_SYMBOL_TABLE
368 JitSymbolTable *__jitSymbolTable;
371 static void AddFunctionToSymbolTable(const char *FnName,
372 void *FnStart, intptr_t FnSize) {
373 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
374 JitSymbolTable **SymTabPtrPtr = 0;
375 #if !ENABLE_JIT_SYMBOL_TABLE
378 SymTabPtrPtr = &__jitSymbolTable;
381 // If this is the first entry in the symbol table, add the JitSymbolTable
383 if (*SymTabPtrPtr == 0) {
384 JitSymbolTable *New = new JitSymbolTable();
388 New->NumAllocated = 0;
392 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
394 // If we have space in the table, reallocate the table.
395 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
396 // If we don't have space, reallocate the table.
397 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
398 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
399 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
401 // Copy the old entries over.
402 memcpy(NewSymbols, OldSymbols,
403 SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
405 // Swap the new symbols in, delete the old ones.
406 SymTabPtr->Symbols = NewSymbols;
407 SymTabPtr->NumAllocated = NewSize;
408 delete [] OldSymbols;
411 // Otherwise, we have enough space, just tack it onto the end of the array.
412 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
413 Entry.FnName = strdup(FnName);
414 Entry.FnStart = FnStart;
415 Entry.FnSize = FnSize;
416 ++SymTabPtr->NumSymbols;
419 static void RemoveFunctionFromSymbolTable(void *FnStart) {
420 assert(FnStart && "Invalid function pointer");
421 JitSymbolTable **SymTabPtrPtr = 0;
422 #if !ENABLE_JIT_SYMBOL_TABLE
425 SymTabPtrPtr = &__jitSymbolTable;
428 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
429 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
431 // Scan the table to find its index. The table is not sorted, so do a linear
434 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
435 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
437 // Once we have an index, we know to nuke this entry, overwrite it with the
438 // entry at the end of the array, making the last entry redundant.
439 const char *OldName = Symbols[Index].FnName;
440 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
441 free((void*)OldName);
443 // Drop the number of symbols in the table.
444 --SymTabPtr->NumSymbols;
446 // Finally, if we deleted the final symbol, deallocate the table itself.
447 if (SymTabPtr->NumSymbols != 0)
455 //===----------------------------------------------------------------------===//
459 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
460 /// used to output functions to memory for execution.
461 class JITEmitter : public MachineCodeEmitter {
462 JITMemoryManager *MemMgr;
464 // When outputting a function stub in the context of some other function, we
465 // save BufferBegin/BufferEnd/CurBufferPtr here.
466 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
468 /// Relocations - These are the relocations that the function needs, as
470 std::vector<MachineRelocation> Relocations;
472 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
473 /// It is filled in by the StartMachineBasicBlock callback and queried by
474 /// the getMachineBasicBlockAddress callback.
475 std::vector<uintptr_t> MBBLocations;
477 /// ConstantPool - The constant pool for the current function.
479 MachineConstantPool *ConstantPool;
481 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
483 void *ConstantPoolBase;
485 /// JumpTable - The jump tables for the current function.
487 MachineJumpTableInfo *JumpTable;
489 /// JumpTableBase - A pointer to the first entry in the jump table.
493 /// Resolver - This contains info about the currently resolved functions.
494 JITResolver Resolver;
496 /// DE - The dwarf emitter for the jit.
499 /// LabelLocations - This vector is a mapping from Label ID's to their
501 std::vector<uintptr_t> LabelLocations;
503 /// MMI - Machine module info for exception informations
504 MachineModuleInfo* MMI;
506 // GVSet - a set to keep track of which globals have been seen
507 SmallPtrSet<const GlobalVariable*, 8> GVSet;
510 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
511 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
512 if (jit.getJITInfo().needsGOT()) {
513 MemMgr->AllocateGOT();
514 DOUT << "JIT is managing a GOT\n";
517 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
521 if (ExceptionHandling) delete DE;
524 /// classof - Methods for support type inquiry through isa, cast, and
527 static inline bool classof(const JITEmitter*) { return true; }
528 static inline bool classof(const MachineCodeEmitter*) { return true; }
530 JITResolver &getJITResolver() { return Resolver; }
532 virtual void startFunction(MachineFunction &F);
533 virtual bool finishFunction(MachineFunction &F);
535 void emitConstantPool(MachineConstantPool *MCP);
536 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
537 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
539 virtual void startGVStub(const GlobalValue* GV, unsigned StubSize,
540 unsigned Alignment = 1);
541 virtual void* finishGVStub(const GlobalValue *GV);
543 /// allocateSpace - Reserves space in the current block if any, or
544 /// allocate a new one of the given size.
545 virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
547 virtual void addRelocation(const MachineRelocation &MR) {
548 Relocations.push_back(MR);
551 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
552 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
553 MBBLocations.resize((MBB->getNumber()+1)*2);
554 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
555 DOUT << "JIT: Emitting BB" << MBB->getNumber() << " at ["
556 << (void*) getCurrentPCValue() << "]\n";
559 virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
560 virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
562 virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
563 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
564 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
565 return MBBLocations[MBB->getNumber()];
568 /// deallocateMemForFunction - Deallocate all memory for the specified
570 void deallocateMemForFunction(Function *F) {
571 MemMgr->deallocateMemForFunction(F);
574 virtual void emitLabel(uint64_t LabelID) {
575 if (LabelLocations.size() <= LabelID)
576 LabelLocations.resize((LabelID+1)*2);
577 LabelLocations[LabelID] = getCurrentPCValue();
580 virtual uintptr_t getLabelAddress(uint64_t LabelID) const {
581 assert(LabelLocations.size() > (unsigned)LabelID &&
582 LabelLocations[LabelID] && "Label not emitted!");
583 return LabelLocations[LabelID];
586 virtual void setModuleInfo(MachineModuleInfo* Info) {
588 if (ExceptionHandling) DE->setModuleInfo(Info);
591 void setMemoryExecutable(void) {
592 MemMgr->setMemoryExecutable();
596 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
597 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
599 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
600 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
601 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
602 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
606 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
607 bool DoesntNeedStub) {
608 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
609 /// FIXME: If we straightened things out, this could actually emit the
610 /// global immediately instead of queuing it for codegen later!
611 return TheJIT->getOrEmitGlobalVariable(GV);
613 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
614 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
616 // If we have already compiled the function, return a pointer to its body.
617 Function *F = cast<Function>(V);
619 if (!DoesntNeedStub && !TheJIT->isLazyCompilationDisabled())
620 // Return the function stub if it's already created.
621 ResultPtr = Resolver.getFunctionStubIfAvailable(F);
623 ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
624 if (ResultPtr) return ResultPtr;
626 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
627 // If this is an external function pointer, we can force the JIT to
628 // 'compile' it, which really just adds it to the map.
630 return TheJIT->getPointerToFunction(F);
632 return Resolver.getFunctionStub(F);
635 // Okay, the function has not been compiled yet, if the target callback
636 // mechanism is capable of rewriting the instruction directly, prefer to do
637 // that instead of emitting a stub.
639 return Resolver.AddCallbackAtLocation(F, Reference);
641 // Otherwise, we have to emit a lazy resolving stub.
642 return Resolver.getFunctionStub(F);
645 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference,
647 // Make sure GV is emitted first.
648 // FIXME: For now, if the GV is an external function we force the JIT to
649 // compile it so the indirect symbol will contain the fully resolved address.
650 void *GVAddress = getPointerToGlobal(V, Reference, true);
651 return Resolver.getGlobalValueIndirectSym(V, GVAddress);
654 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
655 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
656 if (Constants.empty()) return 0;
658 MachineConstantPoolEntry CPE = Constants.back();
659 unsigned Size = CPE.Offset;
660 const Type *Ty = CPE.isMachineConstantPoolEntry()
661 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
662 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
666 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
667 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
668 if (JT.empty()) return 0;
670 unsigned NumEntries = 0;
671 for (unsigned i = 0, e = JT.size(); i != e; ++i)
672 NumEntries += JT[i].MBBs.size();
674 unsigned EntrySize = MJTI->getEntrySize();
676 return NumEntries * EntrySize;
679 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
680 if (Alignment == 0) Alignment = 1;
681 // Since we do not know where the buffer will be allocated, be pessimistic.
682 return Size + Alignment;
685 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
686 /// into the running total Size.
688 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
689 const Type *ElTy = GV->getType()->getElementType();
690 size_t GVSize = (size_t)TheJIT->getTargetData()->getABITypeSize(ElTy);
692 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
693 DOUT << "JIT: Adding in size " << GVSize << " alignment " << GVAlign;
695 // Assume code section ends with worst possible alignment, so first
696 // variable needs maximal padding.
699 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
704 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
705 /// but are referenced from the constant; put them in GVSet and add their
706 /// size into the running total Size.
708 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
710 // If its undefined, return the garbage.
711 if (isa<UndefValue>(C))
714 // If the value is a ConstantExpr
715 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
716 Constant *Op0 = CE->getOperand(0);
717 switch (CE->getOpcode()) {
718 case Instruction::GetElementPtr:
719 case Instruction::Trunc:
720 case Instruction::ZExt:
721 case Instruction::SExt:
722 case Instruction::FPTrunc:
723 case Instruction::FPExt:
724 case Instruction::UIToFP:
725 case Instruction::SIToFP:
726 case Instruction::FPToUI:
727 case Instruction::FPToSI:
728 case Instruction::PtrToInt:
729 case Instruction::IntToPtr:
730 case Instruction::BitCast: {
731 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
734 case Instruction::Add:
735 case Instruction::Sub:
736 case Instruction::Mul:
737 case Instruction::UDiv:
738 case Instruction::SDiv:
739 case Instruction::URem:
740 case Instruction::SRem:
741 case Instruction::And:
742 case Instruction::Or:
743 case Instruction::Xor: {
744 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
745 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
749 cerr << "ConstantExpr not handled: " << *CE << "\n";
755 if (C->getType()->getTypeID() == Type::PointerTyID)
756 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
757 if (GVSet.insert(GV))
758 Size = addSizeOfGlobal(GV, Size);
763 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
764 /// but are referenced from the given initializer.
766 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
768 if (!isa<UndefValue>(Init) &&
769 !isa<ConstantVector>(Init) &&
770 !isa<ConstantAggregateZero>(Init) &&
771 !isa<ConstantArray>(Init) &&
772 !isa<ConstantStruct>(Init) &&
773 Init->getType()->isFirstClassType())
774 Size = addSizeOfGlobalsInConstantVal(Init, Size);
778 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
779 /// globals; then walk the initializers of those globals looking for more.
780 /// If their size has not been considered yet, add it into the running total
783 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
787 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
789 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
791 const TargetInstrDesc &Desc = I->getDesc();
792 const MachineInstr &MI = *I;
793 unsigned NumOps = Desc.getNumOperands();
794 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
795 const MachineOperand &MO = MI.getOperand(CurOp);
797 GlobalValue* V = MO.getGlobal();
798 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
801 // If seen in previous function, it will have an entry here.
802 if (TheJIT->getPointerToGlobalIfAvailable(GV))
804 // If seen earlier in this function, it will have an entry here.
805 // FIXME: it should be possible to combine these tables, by
806 // assuming the addresses of the new globals in this module
807 // start at 0 (or something) and adjusting them after codegen
808 // complete. Another possibility is to grab a marker bit in GV.
809 if (GVSet.insert(GV))
810 // A variable as yet unseen. Add in its size.
811 Size = addSizeOfGlobal(GV, Size);
816 DOUT << "JIT: About to look through initializers\n";
817 // Look for more globals that are referenced only from initializers.
818 // GVSet.end is computed each time because the set can grow as we go.
819 for (SmallPtrSet<const GlobalVariable *, 8>::iterator I = GVSet.begin();
820 I != GVSet.end(); I++) {
821 const GlobalVariable* GV = *I;
822 if (GV->hasInitializer())
823 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
829 void JITEmitter::startFunction(MachineFunction &F) {
830 DOUT << "JIT: Starting CodeGen of Function "
831 << F.getFunction()->getName() << "\n";
833 uintptr_t ActualSize = 0;
834 // Set the memory writable, if it's not already
835 MemMgr->setMemoryWritable();
836 if (MemMgr->NeedsExactSize()) {
837 DOUT << "JIT: ExactSize\n";
838 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
839 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
840 MachineConstantPool *MCP = F.getConstantPool();
842 // Ensure the constant pool/jump table info is at least 4-byte aligned.
843 ActualSize = RoundUpToAlign(ActualSize, 16);
845 // Add the alignment of the constant pool
846 ActualSize = RoundUpToAlign(ActualSize,
847 1 << MCP->getConstantPoolAlignment());
849 // Add the constant pool size
850 ActualSize += GetConstantPoolSizeInBytes(MCP);
852 // Add the aligment of the jump table info
853 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
855 // Add the jump table size
856 ActualSize += GetJumpTableSizeInBytes(MJTI);
858 // Add the alignment for the function
859 ActualSize = RoundUpToAlign(ActualSize,
860 std::max(F.getFunction()->getAlignment(), 8U));
862 // Add the function size
863 ActualSize += TII->GetFunctionSizeInBytes(F);
865 DOUT << "JIT: ActualSize before globals " << ActualSize << "\n";
866 // Add the size of the globals that will be allocated after this function.
867 // These are all the ones referenced from this function that were not
868 // previously allocated.
869 ActualSize += GetSizeOfGlobalsInBytes(F);
870 DOUT << "JIT: ActualSize after globals " << ActualSize << "\n";
873 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
875 BufferEnd = BufferBegin+ActualSize;
877 // Ensure the constant pool/jump table info is at least 4-byte aligned.
880 emitConstantPool(F.getConstantPool());
881 initJumpTableInfo(F.getJumpTableInfo());
883 // About to start emitting the machine code for the function.
884 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
885 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
887 MBBLocations.clear();
890 bool JITEmitter::finishFunction(MachineFunction &F) {
891 if (CurBufferPtr == BufferEnd) {
892 // FIXME: Allocate more space, then try again.
893 cerr << "JIT: Ran out of space for generated machine code!\n";
897 emitJumpTableInfo(F.getJumpTableInfo());
899 // FnStart is the start of the text, not the start of the constant pool and
900 // other per-function data.
901 unsigned char *FnStart =
902 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
904 if (!Relocations.empty()) {
905 NumRelos += Relocations.size();
907 // Resolve the relocations to concrete pointers.
908 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
909 MachineRelocation &MR = Relocations[i];
911 if (!MR.letTargetResolve()) {
912 if (MR.isExternalSymbol()) {
913 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
915 DOUT << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
916 << ResultPtr << "]\n";
918 // If the target REALLY wants a stub for this function, emit it now.
919 if (!MR.doesntNeedStub())
920 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
921 } else if (MR.isGlobalValue()) {
922 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
923 BufferBegin+MR.getMachineCodeOffset(),
924 MR.doesntNeedStub());
925 } else if (MR.isIndirectSymbol()) {
926 ResultPtr = getPointerToGVIndirectSym(MR.getGlobalValue(),
927 BufferBegin+MR.getMachineCodeOffset(),
928 MR.doesntNeedStub());
929 } else if (MR.isBasicBlock()) {
930 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
931 } else if (MR.isConstantPoolIndex()) {
932 ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
934 assert(MR.isJumpTableIndex());
935 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
938 MR.setResultPointer(ResultPtr);
941 // if we are managing the GOT and the relocation wants an index,
943 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
944 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
946 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
947 DOUT << "JIT: GOT was out of date for " << ResultPtr
948 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
950 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
955 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
956 Relocations.size(), MemMgr->getGOTBase());
959 // Update the GOT entry for F to point to the new code.
960 if (MemMgr->isManagingGOT()) {
961 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
962 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
963 DOUT << "JIT: GOT was out of date for " << (void*)BufferBegin
964 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
965 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
969 unsigned char *FnEnd = CurBufferPtr;
971 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
973 if (CurBufferPtr == BufferEnd) {
974 // FIXME: Allocate more space, then try again.
975 cerr << "JIT: Ran out of space for generated machine code!\n";
979 BufferBegin = CurBufferPtr = 0;
980 NumBytes += FnEnd-FnStart;
982 // Invalidate the icache if necessary.
983 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
985 // Add it to the JIT symbol table if the host wants it.
986 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
987 FnStart, FnEnd-FnStart);
989 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
990 << "] Function: " << F.getFunction()->getName()
991 << ": " << (FnEnd-FnStart) << " bytes of text, "
992 << Relocations.size() << " relocations\n";
995 // Mark code region readable and executable if it's not so already.
996 MemMgr->setMemoryExecutable();
1000 if (sys::hasDisassembler()) {
1001 DOUT << "JIT: Disassembled code:\n";
1002 DOUT << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
1004 DOUT << "JIT: Binary code:\n";
1006 unsigned char* q = FnStart;
1007 for (int i = 0; q < FnEnd; q += 4, ++i) {
1011 DOUT << "JIT: " << std::setw(8) << std::setfill('0')
1012 << (long)(q - FnStart) << ": ";
1014 for (int j = 3; j >= 0; --j) {
1018 DOUT << std::setw(2) << std::setfill('0') << (unsigned short)q[j];
1031 if (ExceptionHandling) {
1032 uintptr_t ActualSize = 0;
1033 SavedBufferBegin = BufferBegin;
1034 SavedBufferEnd = BufferEnd;
1035 SavedCurBufferPtr = CurBufferPtr;
1037 if (MemMgr->NeedsExactSize()) {
1038 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
1041 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
1043 BufferEnd = BufferBegin+ActualSize;
1044 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
1045 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
1047 BufferBegin = SavedBufferBegin;
1048 BufferEnd = SavedBufferEnd;
1049 CurBufferPtr = SavedCurBufferPtr;
1051 TheJIT->RegisterTable(FrameRegister);
1060 void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
1062 return MachineCodeEmitter::allocateSpace(Size, Alignment);
1064 // create a new memory block if there is no active one.
1065 // care must be taken so that BufferBegin is invalidated when a
1067 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
1068 BufferEnd = BufferBegin+Size;
1069 return CurBufferPtr;
1072 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1073 if (TheJIT->getJITInfo().hasCustomConstantPool())
1076 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1077 if (Constants.empty()) return;
1079 MachineConstantPoolEntry CPE = Constants.back();
1080 unsigned Size = CPE.Offset;
1081 const Type *Ty = CPE.isMachineConstantPoolEntry()
1082 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
1083 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
1085 unsigned Align = 1 << MCP->getConstantPoolAlignment();
1086 ConstantPoolBase = allocateSpace(Size, Align);
1089 if (ConstantPoolBase == 0) return; // Buffer overflow.
1091 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1092 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1094 // Initialize the memory for all of the constant pool entries.
1095 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1096 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
1097 if (Constants[i].isMachineConstantPoolEntry()) {
1098 // FIXME: add support to lower machine constant pool values into bytes!
1099 cerr << "Initialize memory with machine specific constant pool entry"
1100 << " has not been implemented!\n";
1103 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
1104 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
1108 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1109 if (TheJIT->getJITInfo().hasCustomJumpTables())
1112 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1113 if (JT.empty()) return;
1115 unsigned NumEntries = 0;
1116 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1117 NumEntries += JT[i].MBBs.size();
1119 unsigned EntrySize = MJTI->getEntrySize();
1121 // Just allocate space for all the jump tables now. We will fix up the actual
1122 // MBB entries in the tables after we emit the code for each block, since then
1123 // we will know the final locations of the MBBs in memory.
1125 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1128 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1129 if (TheJIT->getJITInfo().hasCustomJumpTables())
1132 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1133 if (JT.empty() || JumpTableBase == 0) return;
1135 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1136 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1137 // For each jump table, place the offset from the beginning of the table
1138 // to the target address.
1139 int *SlotPtr = (int*)JumpTableBase;
1141 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1142 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1143 // Store the offset of the basic block for this jump table slot in the
1144 // memory we allocated for the jump table in 'initJumpTableInfo'
1145 uintptr_t Base = (uintptr_t)SlotPtr;
1146 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1147 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1148 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1152 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1154 // For each jump table, map each target in the jump table to the address of
1155 // an emitted MachineBasicBlock.
1156 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1158 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1159 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1160 // Store the address of the basic block for this jump table slot in the
1161 // memory we allocated for the jump table in 'initJumpTableInfo'
1162 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1163 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1168 void JITEmitter::startGVStub(const GlobalValue* GV, unsigned StubSize,
1169 unsigned Alignment) {
1170 SavedBufferBegin = BufferBegin;
1171 SavedBufferEnd = BufferEnd;
1172 SavedCurBufferPtr = CurBufferPtr;
1174 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1175 BufferEnd = BufferBegin+StubSize+1;
1178 void *JITEmitter::finishGVStub(const GlobalValue* GV) {
1179 NumBytes += getCurrentPCOffset();
1180 std::swap(SavedBufferBegin, BufferBegin);
1181 BufferEnd = SavedBufferEnd;
1182 CurBufferPtr = SavedCurBufferPtr;
1183 return SavedBufferBegin;
1186 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1187 // in the constant pool that was last emitted with the 'emitConstantPool'
1190 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1191 assert(ConstantNum < ConstantPool->getConstants().size() &&
1192 "Invalid ConstantPoolIndex!");
1193 return (uintptr_t)ConstantPoolBase +
1194 ConstantPool->getConstants()[ConstantNum].Offset;
1197 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1198 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1200 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1201 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1202 assert(Index < JT.size() && "Invalid jump table index!");
1204 unsigned Offset = 0;
1205 unsigned EntrySize = JumpTable->getEntrySize();
1207 for (unsigned i = 0; i < Index; ++i)
1208 Offset += JT[i].MBBs.size();
1210 Offset *= EntrySize;
1212 return (uintptr_t)((char *)JumpTableBase + Offset);
1215 //===----------------------------------------------------------------------===//
1216 // Public interface to this file
1217 //===----------------------------------------------------------------------===//
1219 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1220 return new JITEmitter(jit, JMM);
1223 // getPointerToNamedFunction - This function is used as a global wrapper to
1224 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1225 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1226 // need to resolve function(s) that are being mis-codegenerated, so we need to
1227 // resolve their addresses at runtime, and this is the way to do it.
1229 void *getPointerToNamedFunction(const char *Name) {
1230 if (Function *F = TheJIT->FindFunctionNamed(Name))
1231 return TheJIT->getPointerToFunction(F);
1232 return TheJIT->getPointerToNamedFunction(Name);
1236 // getPointerToFunctionOrStub - If the specified function has been
1237 // code-gen'd, return a pointer to the function. If not, compile it, or use
1238 // a stub to implement lazy compilation if available.
1240 void *JIT::getPointerToFunctionOrStub(Function *F) {
1241 // If we have already code generated the function, just return the address.
1242 if (void *Addr = getPointerToGlobalIfAvailable(F))
1245 // Get a stub if the target supports it.
1246 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1247 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1248 return JE->getJITResolver().getFunctionStub(F);
1251 /// freeMachineCodeForFunction - release machine code memory for given Function.
1253 void JIT::freeMachineCodeForFunction(Function *F) {
1255 // Delete translation for this from the ExecutionEngine, so it will get
1256 // retranslated next time it is used.
1257 void *OldPtr = updateGlobalMapping(F, 0);
1260 RemoveFunctionFromSymbolTable(OldPtr);
1262 // Free the actual memory for the function body and related stuff.
1263 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1264 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);