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/Statistic.h"
43 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
44 STATISTIC(NumRelos, "Number of relocations applied");
45 static JIT *TheJIT = 0;
48 //===----------------------------------------------------------------------===//
49 // JIT lazy compilation code.
52 class JITResolverState {
54 /// FunctionToStubMap - Keep track of the stub created for a particular
55 /// function so that we can reuse them if necessary.
56 std::map<Function*, void*> FunctionToStubMap;
58 /// StubToFunctionMap - Keep track of the function that each stub
60 std::map<void*, Function*> StubToFunctionMap;
62 /// GlobalToLazyPtrMap - Keep track of the lazy pointer created for a
63 /// particular GlobalVariable so that we can reuse them if necessary.
64 std::map<GlobalValue*, void*> GlobalToLazyPtrMap;
67 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) {
68 assert(locked.holds(TheJIT->lock));
69 return FunctionToStubMap;
72 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) {
73 assert(locked.holds(TheJIT->lock));
74 return StubToFunctionMap;
77 std::map<GlobalValue*, void*>&
78 getGlobalToLazyPtrMap(const MutexGuard& locked) {
79 assert(locked.holds(TheJIT->lock));
80 return GlobalToLazyPtrMap;
84 /// JITResolver - Keep track of, and resolve, call sites for functions that
85 /// have not yet been compiled.
87 /// LazyResolverFn - The target lazy resolver function that we actually
88 /// rewrite instructions to use.
89 TargetJITInfo::LazyResolverFn LazyResolverFn;
91 JITResolverState state;
93 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for
94 /// external functions.
95 std::map<void*, void*> ExternalFnToStubMap;
97 //map addresses to indexes in the GOT
98 std::map<void*, unsigned> revGOTMap;
99 unsigned nextGOTIndex;
101 static JITResolver *TheJITResolver;
103 explicit JITResolver(JIT &jit) : nextGOTIndex(0) {
106 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
107 assert(TheJITResolver == 0 && "Multiple JIT resolvers?");
108 TheJITResolver = this;
115 /// getFunctionStub - This returns a pointer to a function stub, creating
116 /// one on demand as needed.
117 void *getFunctionStub(Function *F);
119 /// getExternalFunctionStub - Return a stub for the function at the
120 /// specified address, created lazily on demand.
121 void *getExternalFunctionStub(void *FnAddr);
123 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
125 void *getGlobalValueLazyPtr(GlobalValue *V, void *GVAddress);
127 /// AddCallbackAtLocation - If the target is capable of rewriting an
128 /// instruction without the use of a stub, record the location of the use so
129 /// we know which function is being used at the location.
130 void *AddCallbackAtLocation(Function *F, void *Location) {
131 MutexGuard locked(TheJIT->lock);
132 /// Get the target-specific JIT resolver function.
133 state.getStubToFunctionMap(locked)[Location] = F;
134 return (void*)(intptr_t)LazyResolverFn;
137 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
138 /// an address. This function only manages slots, it does not manage the
139 /// contents of the slots or the memory associated with the GOT.
140 unsigned getGOTIndexForAddr(void *addr);
142 /// JITCompilerFn - This function is called to resolve a stub to a compiled
143 /// address. If the LLVM Function corresponding to the stub has not yet
144 /// been compiled, this function compiles it first.
145 static void *JITCompilerFn(void *Stub);
149 JITResolver *JITResolver::TheJITResolver = 0;
151 /// getFunctionStub - This returns a pointer to a function stub, creating
152 /// one on demand as needed.
153 void *JITResolver::getFunctionStub(Function *F) {
154 MutexGuard locked(TheJIT->lock);
156 // If we already have a stub for this function, recycle it.
157 void *&Stub = state.getFunctionToStubMap(locked)[F];
158 if (Stub) return Stub;
160 // Call the lazy resolver function unless we already KNOW it is an external
161 // function, in which case we just skip the lazy resolution step.
162 void *Actual = (void*)(intptr_t)LazyResolverFn;
163 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode())
164 Actual = TheJIT->getPointerToFunction(F);
166 // Otherwise, codegen a new stub. For now, the stub will call the lazy
167 // resolver function.
168 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual,
169 *TheJIT->getCodeEmitter());
171 if (Actual != (void*)(intptr_t)LazyResolverFn) {
172 // If we are getting the stub for an external function, we really want the
173 // address of the stub in the GlobalAddressMap for the JIT, not the address
174 // of the external function.
175 TheJIT->updateGlobalMapping(F, Stub);
178 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '"
179 << F->getName() << "'\n";
181 // Finally, keep track of the stub-to-Function mapping so that the
182 // JITCompilerFn knows which function to compile!
183 state.getStubToFunctionMap(locked)[Stub] = F;
187 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified
189 void *JITResolver::getGlobalValueLazyPtr(GlobalValue *GV, void *GVAddress) {
190 MutexGuard locked(TheJIT->lock);
192 // If we already have a stub for this global variable, recycle it.
193 void *&LazyPtr = state.getGlobalToLazyPtrMap(locked)[GV];
194 if (LazyPtr) return LazyPtr;
196 // Otherwise, codegen a new lazy pointer.
197 LazyPtr = TheJIT->getJITInfo().emitGlobalValueLazyPtr(GV, GVAddress,
198 *TheJIT->getCodeEmitter());
200 DOUT << "JIT: Stub emitted at [" << LazyPtr << "] for GV '"
201 << GV->getName() << "'\n";
206 /// getExternalFunctionStub - Return a stub for the function at the
207 /// specified address, created lazily on demand.
208 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
209 // If we already have a stub for this function, recycle it.
210 void *&Stub = ExternalFnToStubMap[FnAddr];
211 if (Stub) return Stub;
213 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr,
214 *TheJIT->getCodeEmitter());
216 DOUT << "JIT: Stub emitted at [" << Stub
217 << "] for external function at '" << FnAddr << "'\n";
221 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
222 unsigned idx = revGOTMap[addr];
224 idx = ++nextGOTIndex;
225 revGOTMap[addr] = idx;
226 DOUT << "Adding GOT entry " << idx << " for addr " << addr << "\n";
231 /// JITCompilerFn - This function is called when a lazy compilation stub has
232 /// been entered. It looks up which function this stub corresponds to, compiles
233 /// it if necessary, then returns the resultant function pointer.
234 void *JITResolver::JITCompilerFn(void *Stub) {
235 JITResolver &JR = *TheJITResolver;
241 // Only lock for getting the Function. The call getPointerToFunction made
242 // in this function might trigger function materializing, which requires
243 // JIT lock to be unlocked.
244 MutexGuard locked(TheJIT->lock);
246 // The address given to us for the stub may not be exactly right, it might be
247 // a little bit after the stub. As such, use upper_bound to find it.
248 std::map<void*, Function*>::iterator I =
249 JR.state.getStubToFunctionMap(locked).upper_bound(Stub);
250 assert(I != JR.state.getStubToFunctionMap(locked).begin() &&
251 "This is not a known stub!");
253 ActualPtr = I->first;
256 // If we have already code generated the function, just return the address.
257 void *Result = TheJIT->getPointerToGlobalIfAvailable(F);
260 // Otherwise we don't have it, do lazy compilation now.
262 // If lazy compilation is disabled, emit a useful error message and abort.
263 if (TheJIT->isLazyCompilationDisabled()) {
264 cerr << "LLVM JIT requested to do lazy compilation of function '"
265 << F->getName() << "' when lazy compiles are disabled!\n";
269 // We might like to remove the stub from the StubToFunction map.
270 // We can't do that! Multiple threads could be stuck, waiting to acquire the
271 // lock above. As soon as the 1st function finishes compiling the function,
272 // the next one will be released, and needs to be able to find the function
274 //JR.state.getStubToFunctionMap(locked).erase(I);
276 DOUT << "JIT: Lazily resolving function '" << F->getName()
277 << "' In stub ptr = " << Stub << " actual ptr = "
278 << ActualPtr << "\n";
280 Result = TheJIT->getPointerToFunction(F);
283 // Reacquire the lock to erase the stub in the map.
284 MutexGuard locked(TheJIT->lock);
286 // We don't need to reuse this stub in the future, as F is now compiled.
287 JR.state.getFunctionToStubMap(locked).erase(F);
289 // FIXME: We could rewrite all references to this stub if we knew them.
291 // What we will do is set the compiled function address to map to the
292 // same GOT entry as the stub so that later clients may update the GOT
293 // if they see it still using the stub address.
294 // Note: this is done so the Resolver doesn't have to manage GOT memory
295 // Do this without allocating map space if the target isn't using a GOT
296 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end())
297 JR.revGOTMap[Result] = JR.revGOTMap[Stub];
302 //===----------------------------------------------------------------------===//
303 // Function Index Support
305 // On MacOS we generate an index of currently JIT'd functions so that
306 // performance tools can determine a symbol name and accurate code range for a
307 // PC value. Because performance tools are generally asynchronous, the code
308 // below is written with the hope that it could be interrupted at any time and
309 // have useful answers. However, we don't go crazy with atomic operations, we
310 // just do a "reasonable effort".
312 #define ENABLE_JIT_SYMBOL_TABLE 0
315 /// JitSymbolEntry - Each function that is JIT compiled results in one of these
316 /// being added to an array of symbols. This indicates the name of the function
317 /// as well as the address range it occupies. This allows the client to map
318 /// from a PC value to the name of the function.
319 struct JitSymbolEntry {
320 const char *FnName; // FnName - a strdup'd string.
326 struct JitSymbolTable {
327 /// NextPtr - This forms a linked list of JitSymbolTable entries. This
328 /// pointer is not used right now, but might be used in the future. Consider
329 /// it reserved for future use.
330 JitSymbolTable *NextPtr;
332 /// Symbols - This is an array of JitSymbolEntry entries. Only the first
333 /// 'NumSymbols' symbols are valid.
334 JitSymbolEntry *Symbols;
336 /// NumSymbols - This indicates the number entries in the Symbols array that
340 /// NumAllocated - This indicates the amount of space we have in the Symbols
341 /// array. This is a private field that should not be read by external tools.
342 unsigned NumAllocated;
345 #if ENABLE_JIT_SYMBOL_TABLE
346 JitSymbolTable *__jitSymbolTable;
349 static void AddFunctionToSymbolTable(const char *FnName,
350 void *FnStart, intptr_t FnSize) {
351 assert(FnName != 0 && FnStart != 0 && "Bad symbol to add");
352 JitSymbolTable **SymTabPtrPtr = 0;
353 #if !ENABLE_JIT_SYMBOL_TABLE
356 SymTabPtrPtr = &__jitSymbolTable;
359 // If this is the first entry in the symbol table, add the JitSymbolTable
361 if (*SymTabPtrPtr == 0) {
362 JitSymbolTable *New = new JitSymbolTable();
366 New->NumAllocated = 0;
370 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
372 // If we have space in the table, reallocate the table.
373 if (SymTabPtr->NumSymbols >= SymTabPtr->NumAllocated) {
374 // If we don't have space, reallocate the table.
375 unsigned NewSize = std::max(64U, SymTabPtr->NumAllocated*2);
376 JitSymbolEntry *NewSymbols = new JitSymbolEntry[NewSize];
377 JitSymbolEntry *OldSymbols = SymTabPtr->Symbols;
379 // Copy the old entries over.
380 memcpy(NewSymbols, OldSymbols,
381 SymTabPtr->NumSymbols*sizeof(OldSymbols[0]));
383 // Swap the new symbols in, delete the old ones.
384 SymTabPtr->Symbols = NewSymbols;
385 SymTabPtr->NumAllocated = NewSize;
386 delete [] OldSymbols;
389 // Otherwise, we have enough space, just tack it onto the end of the array.
390 JitSymbolEntry &Entry = SymTabPtr->Symbols[SymTabPtr->NumSymbols];
391 Entry.FnName = strdup(FnName);
392 Entry.FnStart = FnStart;
393 Entry.FnSize = FnSize;
394 ++SymTabPtr->NumSymbols;
397 static void RemoveFunctionFromSymbolTable(void *FnStart) {
398 assert(FnStart && "Invalid function pointer");
399 JitSymbolTable **SymTabPtrPtr = 0;
400 #if !ENABLE_JIT_SYMBOL_TABLE
403 SymTabPtrPtr = &__jitSymbolTable;
406 JitSymbolTable *SymTabPtr = *SymTabPtrPtr;
407 JitSymbolEntry *Symbols = SymTabPtr->Symbols;
409 // Scan the table to find its index. The table is not sorted, so do a linear
412 for (Index = 0; Symbols[Index].FnStart != FnStart; ++Index)
413 assert(Index != SymTabPtr->NumSymbols && "Didn't find function!");
415 // Once we have an index, we know to nuke this entry, overwrite it with the
416 // entry at the end of the array, making the last entry redundant.
417 const char *OldName = Symbols[Index].FnName;
418 Symbols[Index] = Symbols[SymTabPtr->NumSymbols-1];
419 free((void*)OldName);
421 // Drop the number of symbols in the table.
422 --SymTabPtr->NumSymbols;
424 // Finally, if we deleted the final symbol, deallocate the table itself.
425 if (SymTabPtr->NumSymbols != 0)
433 //===----------------------------------------------------------------------===//
437 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
438 /// used to output functions to memory for execution.
439 class JITEmitter : public MachineCodeEmitter {
440 JITMemoryManager *MemMgr;
442 // When outputting a function stub in the context of some other function, we
443 // save BufferBegin/BufferEnd/CurBufferPtr here.
444 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
446 /// Relocations - These are the relocations that the function needs, as
448 std::vector<MachineRelocation> Relocations;
450 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
451 /// It is filled in by the StartMachineBasicBlock callback and queried by
452 /// the getMachineBasicBlockAddress callback.
453 std::vector<intptr_t> MBBLocations;
455 /// ConstantPool - The constant pool for the current function.
457 MachineConstantPool *ConstantPool;
459 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
461 void *ConstantPoolBase;
463 /// JumpTable - The jump tables for the current function.
465 MachineJumpTableInfo *JumpTable;
467 /// JumpTableBase - A pointer to the first entry in the jump table.
471 /// Resolver - This contains info about the currently resolved functions.
472 JITResolver Resolver;
474 /// DE - The dwarf emitter for the jit.
477 /// LabelLocations - This vector is a mapping from Label ID's to their
479 std::vector<intptr_t> LabelLocations;
481 /// MMI - Machine module info for exception informations
482 MachineModuleInfo* MMI;
484 // GVSet - a set to keep track of which globals have been seen
485 std::set<const GlobalVariable*> GVSet;
488 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) {
489 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
490 if (jit.getJITInfo().needsGOT()) {
491 MemMgr->AllocateGOT();
492 DOUT << "JIT is managing a GOT\n";
495 if (ExceptionHandling) DE = new JITDwarfEmitter(jit);
499 if (ExceptionHandling) delete DE;
502 /// classof - Methods for support type inquiry through isa, cast, and
505 static inline bool classof(const JITEmitter*) { return true; }
506 static inline bool classof(const MachineCodeEmitter*) { return true; }
508 JITResolver &getJITResolver() { return Resolver; }
510 virtual void startFunction(MachineFunction &F);
511 virtual bool finishFunction(MachineFunction &F);
513 void emitConstantPool(MachineConstantPool *MCP);
514 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
515 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
517 virtual void startFunctionStub(const GlobalValue* F, unsigned StubSize,
518 unsigned Alignment = 1);
519 virtual void* finishFunctionStub(const GlobalValue *F);
521 virtual void addRelocation(const MachineRelocation &MR) {
522 Relocations.push_back(MR);
525 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
526 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
527 MBBLocations.resize((MBB->getNumber()+1)*2);
528 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
531 virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const;
532 virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const;
534 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const {
535 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
536 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
537 return MBBLocations[MBB->getNumber()];
540 /// deallocateMemForFunction - Deallocate all memory for the specified
542 void deallocateMemForFunction(Function *F) {
543 MemMgr->deallocateMemForFunction(F);
546 virtual void emitLabel(uint64_t LabelID) {
547 if (LabelLocations.size() <= LabelID)
548 LabelLocations.resize((LabelID+1)*2);
549 LabelLocations[LabelID] = getCurrentPCValue();
552 virtual intptr_t getLabelAddress(uint64_t LabelID) const {
553 assert(LabelLocations.size() > (unsigned)LabelID &&
554 LabelLocations[LabelID] && "Label not emitted!");
555 return LabelLocations[LabelID];
558 virtual void setModuleInfo(MachineModuleInfo* Info) {
560 if (ExceptionHandling) DE->setModuleInfo(Info);
564 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub);
565 void *getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
567 unsigned addSizeOfGlobal(const GlobalVariable *GV, unsigned Size);
568 unsigned addSizeOfGlobalsInConstantVal(const Constant *C, unsigned Size);
569 unsigned addSizeOfGlobalsInInitializer(const Constant *Init, unsigned Size);
570 unsigned GetSizeOfGlobalsInBytes(MachineFunction &MF);
574 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
575 bool DoesntNeedStub) {
576 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
577 /// FIXME: If we straightened things out, this could actually emit the
578 /// global immediately instead of queuing it for codegen later!
579 return TheJIT->getOrEmitGlobalVariable(GV);
581 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
582 return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
584 // If we have already compiled the function, return a pointer to its body.
585 Function *F = cast<Function>(V);
586 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
587 if (ResultPtr) return ResultPtr;
589 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) {
590 // If this is an external function pointer, we can force the JIT to
591 // 'compile' it, which really just adds it to the map.
593 return TheJIT->getPointerToFunction(F);
595 return Resolver.getFunctionStub(F);
598 // Okay, the function has not been compiled yet, if the target callback
599 // mechanism is capable of rewriting the instruction directly, prefer to do
600 // that instead of emitting a stub.
602 return Resolver.AddCallbackAtLocation(F, Reference);
604 // Otherwise, we have to emit a lazy resolving stub.
605 return Resolver.getFunctionStub(F);
608 void *JITEmitter::getPointerToGVLazyPtr(GlobalValue *V, void *Reference,
609 bool DoesntNeedStub) {
610 // Make sure GV is emitted first.
611 // FIXME: For now, if the GV is an external function we force the JIT to
612 // compile it so the lazy pointer will contain the fully resolved address.
613 void *GVAddress = getPointerToGlobal(V, Reference, true);
614 return Resolver.getGlobalValueLazyPtr(V, GVAddress);
617 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP) {
618 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
619 if (Constants.empty()) return 0;
621 MachineConstantPoolEntry CPE = Constants.back();
622 unsigned Size = CPE.Offset;
623 const Type *Ty = CPE.isMachineConstantPoolEntry()
624 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
625 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
629 static unsigned GetJumpTableSizeInBytes(MachineJumpTableInfo *MJTI) {
630 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
631 if (JT.empty()) return 0;
633 unsigned NumEntries = 0;
634 for (unsigned i = 0, e = JT.size(); i != e; ++i)
635 NumEntries += JT[i].MBBs.size();
637 unsigned EntrySize = MJTI->getEntrySize();
639 return NumEntries * EntrySize;
642 static uintptr_t RoundUpToAlign(uintptr_t Size, unsigned Alignment) {
643 if (Alignment == 0) Alignment = 1;
644 // Since we do not know where the buffer will be allocated, be pessimistic.
645 return Size + Alignment;
648 /// addSizeOfGlobal - add the size of the global (plus any alignment padding)
649 /// into the running total Size.
651 unsigned JITEmitter::addSizeOfGlobal(const GlobalVariable *GV, unsigned Size) {
652 const Type *ElTy = GV->getType()->getElementType();
653 size_t GVSize = (size_t)TheJIT->getTargetData()->getABITypeSize(ElTy);
655 (size_t)TheJIT->getTargetData()->getPreferredAlignment(GV);
656 DOUT << "Adding in size " << GVSize << " alignment " << GVAlign;
658 // Assume code section ends with worst possible alignment, so first
659 // variable needs maximal padding.
662 Size = ((Size+GVAlign-1)/GVAlign)*GVAlign;
667 /// addSizeOfGlobalsInConstantVal - find any globals that we haven't seen yet
668 /// but are referenced from the constant; put them in GVSet and add their
669 /// size into the running total Size.
671 unsigned JITEmitter::addSizeOfGlobalsInConstantVal(const Constant *C,
673 // If its undefined, return the garbage.
674 if (isa<UndefValue>(C))
677 // If the value is a ConstantExpr
678 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
679 Constant *Op0 = CE->getOperand(0);
680 switch (CE->getOpcode()) {
681 case Instruction::GetElementPtr:
682 case Instruction::Trunc:
683 case Instruction::ZExt:
684 case Instruction::SExt:
685 case Instruction::FPTrunc:
686 case Instruction::FPExt:
687 case Instruction::UIToFP:
688 case Instruction::SIToFP:
689 case Instruction::FPToUI:
690 case Instruction::FPToSI:
691 case Instruction::PtrToInt:
692 case Instruction::IntToPtr:
693 case Instruction::BitCast: {
694 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
697 case Instruction::Add:
698 case Instruction::Sub:
699 case Instruction::Mul:
700 case Instruction::UDiv:
701 case Instruction::SDiv:
702 case Instruction::URem:
703 case Instruction::SRem:
704 case Instruction::And:
705 case Instruction::Or:
706 case Instruction::Xor: {
707 Size = addSizeOfGlobalsInConstantVal(Op0, Size);
708 Size = addSizeOfGlobalsInConstantVal(CE->getOperand(1), Size);
712 cerr << "ConstantExpr not handled: " << *CE << "\n";
718 if (C->getType()->getTypeID() == Type::PointerTyID)
719 if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(C))
720 if (GVSet.insert(GV).second)
721 Size = addSizeOfGlobal(GV, Size);
726 /// addSizeOfGLobalsInInitializer - handle any globals that we haven't seen yet
727 /// but are referenced from the given initializer.
729 unsigned JITEmitter::addSizeOfGlobalsInInitializer(const Constant *Init,
731 if (!isa<UndefValue>(Init) &&
732 !isa<ConstantVector>(Init) &&
733 !isa<ConstantAggregateZero>(Init) &&
734 !isa<ConstantArray>(Init) &&
735 !isa<ConstantStruct>(Init) &&
736 Init->getType()->isFirstClassType())
737 Size = addSizeOfGlobalsInConstantVal(Init, Size);
741 /// GetSizeOfGlobalsInBytes - walk the code for the function, looking for
742 /// globals; then walk the initializers of those globals looking for more.
743 /// If their size has not been considered yet, add it into the running total
746 unsigned JITEmitter::GetSizeOfGlobalsInBytes(MachineFunction &MF) {
750 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
752 for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
754 const TargetInstrDesc &Desc = I->getDesc();
755 const MachineInstr &MI = *I;
756 unsigned NumOps = Desc.getNumOperands();
757 for (unsigned CurOp = 0; CurOp < NumOps; CurOp++) {
758 const MachineOperand &MO = MI.getOperand(CurOp);
760 GlobalValue* V = MO.getGlobal();
761 const GlobalVariable *GV = dyn_cast<const GlobalVariable>(V);
764 // If seen in previous function, it will have an entry here.
765 if (TheJIT->getPointerToGlobalIfAvailable(GV))
767 // If seen earlier in this function, it will have an entry here.
768 // FIXME: it should be possible to combine these tables, by
769 // assuming the addresses of the new globals in this module
770 // start at 0 (or something) and adjusting them after codegen
771 // complete. Another possibility is to grab a marker bit in GV.
772 if (GVSet.insert(GV).second)
773 // A variable as yet unseen. Add in its size.
774 Size = addSizeOfGlobal(GV, Size);
779 DOUT << "About to look through initializers\n";
780 // Look for more globals that are referenced only from initializers.
781 // GVSet.end is computed each time because the set can grow as we go.
782 for (std::set<const GlobalVariable *>::iterator I = GVSet.begin();
783 I != GVSet.end(); I++) {
784 const GlobalVariable* GV = *I;
785 if (GV->hasInitializer())
786 Size = addSizeOfGlobalsInInitializer(GV->getInitializer(), Size);
792 void JITEmitter::startFunction(MachineFunction &F) {
793 uintptr_t ActualSize = 0;
794 if (MemMgr->NeedsExactSize()) {
795 DOUT << "ExactSize\n";
796 const TargetInstrInfo* TII = F.getTarget().getInstrInfo();
797 MachineJumpTableInfo *MJTI = F.getJumpTableInfo();
798 MachineConstantPool *MCP = F.getConstantPool();
800 // Ensure the constant pool/jump table info is at least 4-byte aligned.
801 ActualSize = RoundUpToAlign(ActualSize, 16);
803 // Add the alignment of the constant pool
804 ActualSize = RoundUpToAlign(ActualSize,
805 1 << MCP->getConstantPoolAlignment());
807 // Add the constant pool size
808 ActualSize += GetConstantPoolSizeInBytes(MCP);
810 // Add the aligment of the jump table info
811 ActualSize = RoundUpToAlign(ActualSize, MJTI->getAlignment());
813 // Add the jump table size
814 ActualSize += GetJumpTableSizeInBytes(MJTI);
816 // Add the alignment for the function
817 ActualSize = RoundUpToAlign(ActualSize,
818 std::max(F.getFunction()->getAlignment(), 8U));
820 // Add the function size
821 ActualSize += TII->GetFunctionSizeInBytes(F);
823 DOUT << "ActualSize before globals " << ActualSize << "\n";
824 // Add the size of the globals that will be allocated after this function.
825 // These are all the ones referenced from this function that were not
826 // previously allocated.
827 ActualSize += GetSizeOfGlobalsInBytes(F);
828 DOUT << "ActualSize after globals " << ActualSize << "\n";
831 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
833 BufferEnd = BufferBegin+ActualSize;
835 // Ensure the constant pool/jump table info is at least 4-byte aligned.
838 emitConstantPool(F.getConstantPool());
839 initJumpTableInfo(F.getJumpTableInfo());
841 // About to start emitting the machine code for the function.
842 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
843 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
845 MBBLocations.clear();
848 bool JITEmitter::finishFunction(MachineFunction &F) {
849 if (CurBufferPtr == BufferEnd) {
850 // FIXME: Allocate more space, then try again.
851 cerr << "JIT: Ran out of space for generated machine code!\n";
855 emitJumpTableInfo(F.getJumpTableInfo());
857 // FnStart is the start of the text, not the start of the constant pool and
858 // other per-function data.
859 unsigned char *FnStart =
860 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
862 if (!Relocations.empty()) {
863 NumRelos += Relocations.size();
865 // Resolve the relocations to concrete pointers.
866 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
867 MachineRelocation &MR = Relocations[i];
870 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString());
872 // If the target REALLY wants a stub for this function, emit it now.
873 if (!MR.doesntNeedStub())
874 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
875 } else if (MR.isGlobalValue()) {
876 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
877 BufferBegin+MR.getMachineCodeOffset(),
878 MR.doesntNeedStub());
879 } else if (MR.isGlobalValueLazyPtr()) {
880 ResultPtr = getPointerToGVLazyPtr(MR.getGlobalValue(),
881 BufferBegin+MR.getMachineCodeOffset(),
882 MR.doesntNeedStub());
883 } else if (MR.isBasicBlock()) {
884 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
885 } else if (MR.isConstantPoolIndex()) {
886 ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
888 assert(MR.isJumpTableIndex());
889 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
892 MR.setResultPointer(ResultPtr);
894 // if we are managing the GOT and the relocation wants an index,
896 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
897 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
899 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
900 DOUT << "GOT was out of date for " << ResultPtr
901 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
903 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
908 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
909 Relocations.size(), MemMgr->getGOTBase());
912 unsigned char *FnEnd = CurBufferPtr;
914 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd);
915 NumBytes += FnEnd-FnStart;
917 // Update the GOT entry for F to point to the new code.
918 if (MemMgr->isManagingGOT()) {
919 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
920 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
921 DOUT << "GOT was out of date for " << (void*)BufferBegin
922 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n";
923 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
927 // Invalidate the icache if necessary.
928 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
930 // Add it to the JIT symbol table if the host wants it.
931 AddFunctionToSymbolTable(F.getFunction()->getNameStart(),
932 FnStart, FnEnd-FnStart);
934 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart
935 << "] Function: " << F.getFunction()->getName()
936 << ": " << (FnEnd-FnStart) << " bytes of text, "
937 << Relocations.size() << " relocations\n";
940 // Mark code region readable and executable if it's not so already.
941 sys::Memory::SetRXPrivilege(FnStart, FnEnd-FnStart);
947 unsigned char* q = FnStart;
948 for (i=1; q!=FnEnd; q++, i++) {
950 DOUT << "0x" << (long)q << ": ";
951 DOUT<< (unsigned short)*q << " ";
956 if (sys::hasDisassembler())
957 DOUT << "Disassembled code:\n"
958 << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart);
961 if (ExceptionHandling) {
962 uintptr_t ActualSize = 0;
963 SavedBufferBegin = BufferBegin;
964 SavedBufferEnd = BufferEnd;
965 SavedCurBufferPtr = CurBufferPtr;
967 if (MemMgr->NeedsExactSize()) {
968 ActualSize = DE->GetDwarfTableSizeInBytes(F, *this, FnStart, FnEnd);
971 BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
973 BufferEnd = BufferBegin+ActualSize;
974 unsigned char* FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd);
975 MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
977 BufferBegin = SavedBufferBegin;
978 BufferEnd = SavedBufferEnd;
979 CurBufferPtr = SavedCurBufferPtr;
981 TheJIT->RegisterTable(FrameRegister);
990 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
991 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
992 if (Constants.empty()) return;
994 MachineConstantPoolEntry CPE = Constants.back();
995 unsigned Size = CPE.Offset;
996 const Type *Ty = CPE.isMachineConstantPoolEntry()
997 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType();
998 Size += TheJIT->getTargetData()->getABITypeSize(Ty);
1000 unsigned Align = 1 << MCP->getConstantPoolAlignment();
1001 ConstantPoolBase = allocateSpace(Size, Align);
1004 if (ConstantPoolBase == 0) return; // Buffer overflow.
1006 DOUT << "JIT: Emitted constant pool at [" << ConstantPoolBase
1007 << "] (size: " << Size << ", alignment: " << Align << ")\n";
1009 // Initialize the memory for all of the constant pool entries.
1010 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1011 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset;
1012 if (Constants[i].isMachineConstantPoolEntry()) {
1013 // FIXME: add support to lower machine constant pool values into bytes!
1014 cerr << "Initialize memory with machine specific constant pool entry"
1015 << " has not been implemented!\n";
1018 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr);
1019 DOUT << "JIT: CP" << i << " at [" << CAddr << "]\n";
1023 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1024 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1025 if (JT.empty()) return;
1027 unsigned NumEntries = 0;
1028 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1029 NumEntries += JT[i].MBBs.size();
1031 unsigned EntrySize = MJTI->getEntrySize();
1033 // Just allocate space for all the jump tables now. We will fix up the actual
1034 // MBB entries in the tables after we emit the code for each block, since then
1035 // we will know the final locations of the MBBs in memory.
1037 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment());
1040 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1041 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1042 if (JT.empty() || JumpTableBase == 0) return;
1044 if (TargetMachine::getRelocationModel() == Reloc::PIC_) {
1045 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?");
1046 // For each jump table, place the offset from the beginning of the table
1047 // to the target address.
1048 int *SlotPtr = (int*)JumpTableBase;
1050 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1051 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1052 // Store the offset of the basic block for this jump table slot in the
1053 // memory we allocated for the jump table in 'initJumpTableInfo'
1054 intptr_t Base = (intptr_t)SlotPtr;
1055 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1056 intptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1057 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1061 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?");
1063 // For each jump table, map each target in the jump table to the address of
1064 // an emitted MachineBasicBlock.
1065 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1067 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1068 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1069 // Store the address of the basic block for this jump table slot in the
1070 // memory we allocated for the jump table in 'initJumpTableInfo'
1071 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1072 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1077 void JITEmitter::startFunctionStub(const GlobalValue* F, unsigned StubSize,
1078 unsigned Alignment) {
1079 SavedBufferBegin = BufferBegin;
1080 SavedBufferEnd = BufferEnd;
1081 SavedCurBufferPtr = CurBufferPtr;
1083 BufferBegin = CurBufferPtr = MemMgr->allocateStub(F, StubSize, Alignment);
1084 BufferEnd = BufferBegin+StubSize+1;
1087 void *JITEmitter::finishFunctionStub(const GlobalValue* F) {
1088 NumBytes += getCurrentPCOffset();
1089 std::swap(SavedBufferBegin, BufferBegin);
1090 BufferEnd = SavedBufferEnd;
1091 CurBufferPtr = SavedCurBufferPtr;
1092 return SavedBufferBegin;
1095 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1096 // in the constant pool that was last emitted with the 'emitConstantPool'
1099 intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1100 assert(ConstantNum < ConstantPool->getConstants().size() &&
1101 "Invalid ConstantPoolIndex!");
1102 return (intptr_t)ConstantPoolBase +
1103 ConstantPool->getConstants()[ConstantNum].Offset;
1106 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1107 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1109 intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1110 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1111 assert(Index < JT.size() && "Invalid jump table index!");
1113 unsigned Offset = 0;
1114 unsigned EntrySize = JumpTable->getEntrySize();
1116 for (unsigned i = 0; i < Index; ++i)
1117 Offset += JT[i].MBBs.size();
1119 Offset *= EntrySize;
1121 return (intptr_t)((char *)JumpTableBase + Offset);
1124 //===----------------------------------------------------------------------===//
1125 // Public interface to this file
1126 //===----------------------------------------------------------------------===//
1128 MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) {
1129 return new JITEmitter(jit, JMM);
1132 // getPointerToNamedFunction - This function is used as a global wrapper to
1133 // JIT::getPointerToNamedFunction for the purpose of resolving symbols when
1134 // bugpoint is debugging the JIT. In that scenario, we are loading an .so and
1135 // need to resolve function(s) that are being mis-codegenerated, so we need to
1136 // resolve their addresses at runtime, and this is the way to do it.
1138 void *getPointerToNamedFunction(const char *Name) {
1139 if (Function *F = TheJIT->FindFunctionNamed(Name))
1140 return TheJIT->getPointerToFunction(F);
1141 return TheJIT->getPointerToNamedFunction(Name);
1145 // getPointerToFunctionOrStub - If the specified function has been
1146 // code-gen'd, return a pointer to the function. If not, compile it, or use
1147 // a stub to implement lazy compilation if available.
1149 void *JIT::getPointerToFunctionOrStub(Function *F) {
1150 // If we have already code generated the function, just return the address.
1151 if (void *Addr = getPointerToGlobalIfAvailable(F))
1154 // Get a stub if the target supports it.
1155 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1156 JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
1157 return JE->getJITResolver().getFunctionStub(F);
1160 /// freeMachineCodeForFunction - release machine code memory for given Function.
1162 void JIT::freeMachineCodeForFunction(Function *F) {
1164 // Delete translation for this from the ExecutionEngine, so it will get
1165 // retranslated next time it is used.
1166 void *OldPtr = updateGlobalMapping(F, 0);
1169 RemoveFunctionFromSymbolTable(OldPtr);
1171 // Free the actual memory for the function body and related stuff.
1172 assert(isa<JITEmitter>(MCE) && "Unexpected MCE?");
1173 cast<JITEmitter>(MCE)->deallocateMemForFunction(F);