JITEmitter.cpp revision be8c03fc66b75fa775e1f47d62a1b0d803fced1c
1//===-- JITEmitter.cpp - Write machine code to executable memory ----------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 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. 12// 13//===----------------------------------------------------------------------===// 14 15#define DEBUG_TYPE "jit" 16#include "JIT.h" 17#include "llvm/Constant.h" 18#include "llvm/Module.h" 19#include "llvm/Type.h" 20#include "llvm/CodeGen/MachineCodeEmitter.h" 21#include "llvm/CodeGen/MachineFunction.h" 22#include "llvm/CodeGen/MachineConstantPool.h" 23#include "llvm/CodeGen/MachineJumpTableInfo.h" 24#include "llvm/CodeGen/MachineRelocation.h" 25#include "llvm/ExecutionEngine/JITMemoryManager.h" 26#include "llvm/Target/TargetData.h" 27#include "llvm/Target/TargetJITInfo.h" 28#include "llvm/Target/TargetMachine.h" 29#include "llvm/Support/Debug.h" 30#include "llvm/Support/MutexGuard.h" 31#include "llvm/System/Disassembler.h" 32#include "llvm/ADT/Statistic.h" 33#include <algorithm> 34using namespace llvm; 35 36STATISTIC(NumBytes, "Number of bytes of machine code compiled"); 37STATISTIC(NumRelos, "Number of relocations applied"); 38static JIT *TheJIT = 0; 39 40 41//===----------------------------------------------------------------------===// 42// JIT lazy compilation code. 43// 44namespace { 45 class JITResolverState { 46 private: 47 /// FunctionToStubMap - Keep track of the stub created for a particular 48 /// function so that we can reuse them if necessary. 49 std::map<Function*, void*> FunctionToStubMap; 50 51 /// StubToFunctionMap - Keep track of the function that each stub 52 /// corresponds to. 53 std::map<void*, Function*> StubToFunctionMap; 54 55 /// GlobalToLazyPtrMap - Keep track of the lazy pointer created for a 56 /// particular GlobalVariable so that we can reuse them if necessary. 57 std::map<GlobalValue*, void*> GlobalToLazyPtrMap; 58 59 public: 60 std::map<Function*, void*>& getFunctionToStubMap(const MutexGuard& locked) { 61 assert(locked.holds(TheJIT->lock)); 62 return FunctionToStubMap; 63 } 64 65 std::map<void*, Function*>& getStubToFunctionMap(const MutexGuard& locked) { 66 assert(locked.holds(TheJIT->lock)); 67 return StubToFunctionMap; 68 } 69 70 std::map<GlobalValue*, void*>& 71 getGlobalToLazyPtrMap(const MutexGuard& locked) { 72 assert(locked.holds(TheJIT->lock)); 73 return GlobalToLazyPtrMap; 74 } 75 }; 76 77 /// JITResolver - Keep track of, and resolve, call sites for functions that 78 /// have not yet been compiled. 79 class JITResolver { 80 /// LazyResolverFn - The target lazy resolver function that we actually 81 /// rewrite instructions to use. 82 TargetJITInfo::LazyResolverFn LazyResolverFn; 83 84 JITResolverState state; 85 86 /// ExternalFnToStubMap - This is the equivalent of FunctionToStubMap for 87 /// external functions. 88 std::map<void*, void*> ExternalFnToStubMap; 89 90 //map addresses to indexes in the GOT 91 std::map<void*, unsigned> revGOTMap; 92 unsigned nextGOTIndex; 93 94 static JITResolver *TheJITResolver; 95 public: 96 JITResolver(JIT &jit) : nextGOTIndex(0) { 97 TheJIT = &jit; 98 99 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn); 100 assert(TheJITResolver == 0 && "Multiple JIT resolvers?"); 101 TheJITResolver = this; 102 } 103 104 ~JITResolver() { 105 TheJITResolver = 0; 106 } 107 108 /// getFunctionStub - This returns a pointer to a function stub, creating 109 /// one on demand as needed. 110 void *getFunctionStub(Function *F); 111 112 /// getExternalFunctionStub - Return a stub for the function at the 113 /// specified address, created lazily on demand. 114 void *getExternalFunctionStub(void *FnAddr); 115 116 /// getGlobalValueLazyPtr - Return a lazy pointer containing the specified 117 /// GV address. 118 void *getGlobalValueLazyPtr(GlobalValue *V, void *GVAddress); 119 120 /// AddCallbackAtLocation - If the target is capable of rewriting an 121 /// instruction without the use of a stub, record the location of the use so 122 /// we know which function is being used at the location. 123 void *AddCallbackAtLocation(Function *F, void *Location) { 124 MutexGuard locked(TheJIT->lock); 125 /// Get the target-specific JIT resolver function. 126 state.getStubToFunctionMap(locked)[Location] = F; 127 return (void*)(intptr_t)LazyResolverFn; 128 } 129 130 /// getGOTIndexForAddress - Return a new or existing index in the GOT for 131 /// an address. This function only manages slots, it does not manage the 132 /// contents of the slots or the memory associated with the GOT. 133 unsigned getGOTIndexForAddr(void *addr); 134 135 /// JITCompilerFn - This function is called to resolve a stub to a compiled 136 /// address. If the LLVM Function corresponding to the stub has not yet 137 /// been compiled, this function compiles it first. 138 static void *JITCompilerFn(void *Stub); 139 }; 140} 141 142JITResolver *JITResolver::TheJITResolver = 0; 143 144#if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \ 145 defined(__APPLE__) 146extern "C" void sys_icache_invalidate(const void *Addr, size_t len); 147#endif 148 149/// synchronizeICache - On some targets, the JIT emitted code must be 150/// explicitly refetched to ensure correct execution. 151static void synchronizeICache(const void *Addr, size_t len) { 152#if (defined(__POWERPC__) || defined (__ppc__) || defined(_POWER)) && \ 153 defined(__APPLE__) 154 sys_icache_invalidate(Addr, len); 155#endif 156} 157 158/// getFunctionStub - This returns a pointer to a function stub, creating 159/// one on demand as needed. 160void *JITResolver::getFunctionStub(Function *F) { 161 MutexGuard locked(TheJIT->lock); 162 163 // If we already have a stub for this function, recycle it. 164 void *&Stub = state.getFunctionToStubMap(locked)[F]; 165 if (Stub) return Stub; 166 167 // Call the lazy resolver function unless we already KNOW it is an external 168 // function, in which case we just skip the lazy resolution step. 169 void *Actual = (void*)(intptr_t)LazyResolverFn; 170 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) 171 Actual = TheJIT->getPointerToFunction(F); 172 173 // Otherwise, codegen a new stub. For now, the stub will call the lazy 174 // resolver function. 175 Stub = TheJIT->getJITInfo().emitFunctionStub(Actual, 176 *TheJIT->getCodeEmitter()); 177 178 if (Actual != (void*)(intptr_t)LazyResolverFn) { 179 // If we are getting the stub for an external function, we really want the 180 // address of the stub in the GlobalAddressMap for the JIT, not the address 181 // of the external function. 182 TheJIT->updateGlobalMapping(F, Stub); 183 } 184 185 // Invalidate the icache if necessary. 186 synchronizeICache(Stub, TheJIT->getCodeEmitter()->getCurrentPCValue() - 187 (intptr_t)Stub); 188 189 DOUT << "JIT: Stub emitted at [" << Stub << "] for function '" 190 << F->getName() << "'\n"; 191 192 // Finally, keep track of the stub-to-Function mapping so that the 193 // JITCompilerFn knows which function to compile! 194 state.getStubToFunctionMap(locked)[Stub] = F; 195 return Stub; 196} 197 198/// getGlobalValueLazyPtr - Return a lazy pointer containing the specified 199/// GV address. 200void *JITResolver::getGlobalValueLazyPtr(GlobalValue *GV, void *GVAddress) { 201 MutexGuard locked(TheJIT->lock); 202 203 // If we already have a stub for this global variable, recycle it. 204 void *&LazyPtr = state.getGlobalToLazyPtrMap(locked)[GV]; 205 if (LazyPtr) return LazyPtr; 206 207 // Otherwise, codegen a new lazy pointer. 208 LazyPtr = TheJIT->getJITInfo().emitGlobalValueLazyPtr(GVAddress, 209 *TheJIT->getCodeEmitter()); 210 211 DOUT << "JIT: Stub emitted at [" << LazyPtr << "] for GV '" 212 << GV->getName() << "'\n"; 213 214 return LazyPtr; 215} 216 217/// getExternalFunctionStub - Return a stub for the function at the 218/// specified address, created lazily on demand. 219void *JITResolver::getExternalFunctionStub(void *FnAddr) { 220 // If we already have a stub for this function, recycle it. 221 void *&Stub = ExternalFnToStubMap[FnAddr]; 222 if (Stub) return Stub; 223 224 Stub = TheJIT->getJITInfo().emitFunctionStub(FnAddr, 225 *TheJIT->getCodeEmitter()); 226 227 // Invalidate the icache if necessary. 228 synchronizeICache(Stub, TheJIT->getCodeEmitter()->getCurrentPCValue() - 229 (intptr_t)Stub); 230 231 DOUT << "JIT: Stub emitted at [" << Stub 232 << "] for external function at '" << FnAddr << "'\n"; 233 return Stub; 234} 235 236unsigned JITResolver::getGOTIndexForAddr(void* addr) { 237 unsigned idx = revGOTMap[addr]; 238 if (!idx) { 239 idx = ++nextGOTIndex; 240 revGOTMap[addr] = idx; 241 DOUT << "Adding GOT entry " << idx 242 << " for addr " << addr << "\n"; 243 } 244 return idx; 245} 246 247/// JITCompilerFn - This function is called when a lazy compilation stub has 248/// been entered. It looks up which function this stub corresponds to, compiles 249/// it if necessary, then returns the resultant function pointer. 250void *JITResolver::JITCompilerFn(void *Stub) { 251 JITResolver &JR = *TheJITResolver; 252 253 MutexGuard locked(TheJIT->lock); 254 255 // The address given to us for the stub may not be exactly right, it might be 256 // a little bit after the stub. As such, use upper_bound to find it. 257 std::map<void*, Function*>::iterator I = 258 JR.state.getStubToFunctionMap(locked).upper_bound(Stub); 259 assert(I != JR.state.getStubToFunctionMap(locked).begin() && 260 "This is not a known stub!"); 261 Function *F = (--I)->second; 262 263 // If we have already code generated the function, just return the address. 264 void *Result = TheJIT->getPointerToGlobalIfAvailable(F); 265 266 if (!Result) { 267 // Otherwise we don't have it, do lazy compilation now. 268 269 // If lazy compilation is disabled, emit a useful error message and abort. 270 if (TheJIT->isLazyCompilationDisabled()) { 271 cerr << "LLVM JIT requested to do lazy compilation of function '" 272 << F->getName() << "' when lazy compiles are disabled!\n"; 273 abort(); 274 } 275 276 // We might like to remove the stub from the StubToFunction map. 277 // We can't do that! Multiple threads could be stuck, waiting to acquire the 278 // lock above. As soon as the 1st function finishes compiling the function, 279 // the next one will be released, and needs to be able to find the function 280 // it needs to call. 281 //JR.state.getStubToFunctionMap(locked).erase(I); 282 283 DOUT << "JIT: Lazily resolving function '" << F->getName() 284 << "' In stub ptr = " << Stub << " actual ptr = " 285 << I->first << "\n"; 286 287 Result = TheJIT->getPointerToFunction(F); 288 } 289 290 // We don't need to reuse this stub in the future, as F is now compiled. 291 JR.state.getFunctionToStubMap(locked).erase(F); 292 293 // FIXME: We could rewrite all references to this stub if we knew them. 294 295 // What we will do is set the compiled function address to map to the 296 // same GOT entry as the stub so that later clients may update the GOT 297 // if they see it still using the stub address. 298 // Note: this is done so the Resolver doesn't have to manage GOT memory 299 // Do this without allocating map space if the target isn't using a GOT 300 if(JR.revGOTMap.find(Stub) != JR.revGOTMap.end()) 301 JR.revGOTMap[Result] = JR.revGOTMap[Stub]; 302 303 return Result; 304} 305 306 307//===----------------------------------------------------------------------===// 308// JITEmitter code. 309// 310namespace { 311 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is 312 /// used to output functions to memory for execution. 313 class JITEmitter : public MachineCodeEmitter { 314 JITMemoryManager *MemMgr; 315 316 // When outputting a function stub in the context of some other function, we 317 // save BufferBegin/BufferEnd/CurBufferPtr here. 318 unsigned char *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr; 319 320 /// Relocations - These are the relocations that the function needs, as 321 /// emitted. 322 std::vector<MachineRelocation> Relocations; 323 324 /// MBBLocations - This vector is a mapping from MBB ID's to their address. 325 /// It is filled in by the StartMachineBasicBlock callback and queried by 326 /// the getMachineBasicBlockAddress callback. 327 std::vector<intptr_t> MBBLocations; 328 329 /// ConstantPool - The constant pool for the current function. 330 /// 331 MachineConstantPool *ConstantPool; 332 333 /// ConstantPoolBase - A pointer to the first entry in the constant pool. 334 /// 335 void *ConstantPoolBase; 336 337 /// JumpTable - The jump tables for the current function. 338 /// 339 MachineJumpTableInfo *JumpTable; 340 341 /// JumpTableBase - A pointer to the first entry in the jump table. 342 /// 343 void *JumpTableBase; 344 345 /// Resolver - This contains info about the currently resolved functions. 346 JITResolver Resolver; 347 public: 348 JITEmitter(JIT &jit, JITMemoryManager *JMM) : Resolver(jit) { 349 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager(); 350 if (jit.getJITInfo().needsGOT()) { 351 MemMgr->AllocateGOT(); 352 DOUT << "JIT is managing a GOT\n"; 353 } 354 } 355 ~JITEmitter() { 356 delete MemMgr; 357 } 358 359 JITResolver &getJITResolver() { return Resolver; } 360 361 virtual void startFunction(MachineFunction &F); 362 virtual bool finishFunction(MachineFunction &F); 363 364 void emitConstantPool(MachineConstantPool *MCP); 365 void initJumpTableInfo(MachineJumpTableInfo *MJTI); 366 void emitJumpTableInfo(MachineJumpTableInfo *MJTI); 367 368 virtual void startFunctionStub(unsigned StubSize, unsigned Alignment = 1); 369 virtual void* finishFunctionStub(const Function *F); 370 371 virtual void addRelocation(const MachineRelocation &MR) { 372 Relocations.push_back(MR); 373 } 374 375 virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) { 376 if (MBBLocations.size() <= (unsigned)MBB->getNumber()) 377 MBBLocations.resize((MBB->getNumber()+1)*2); 378 MBBLocations[MBB->getNumber()] = getCurrentPCValue(); 379 } 380 381 virtual intptr_t getConstantPoolEntryAddress(unsigned Entry) const; 382 virtual intptr_t getJumpTableEntryAddress(unsigned Entry) const; 383 384 virtual intptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const { 385 assert(MBBLocations.size() > (unsigned)MBB->getNumber() && 386 MBBLocations[MBB->getNumber()] && "MBB not emitted!"); 387 return MBBLocations[MBB->getNumber()]; 388 } 389 390 /// deallocateMemForFunction - Deallocate all memory for the specified 391 /// function body. 392 void deallocateMemForFunction(Function *F) { 393 MemMgr->deallocateMemForFunction(F); 394 } 395 private: 396 void *getPointerToGlobal(GlobalValue *GV, void *Reference, bool NoNeedStub); 397 void *getPointerToGVLazyPtr(GlobalValue *V, void *Reference, 398 bool NoNeedStub); 399 }; 400} 401 402void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference, 403 bool DoesntNeedStub) { 404 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) { 405 /// FIXME: If we straightened things out, this could actually emit the 406 /// global immediately instead of queuing it for codegen later! 407 return TheJIT->getOrEmitGlobalVariable(GV); 408 } 409 410 // If we have already compiled the function, return a pointer to its body. 411 Function *F = cast<Function>(V); 412 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F); 413 if (ResultPtr) return ResultPtr; 414 415 if (F->isDeclaration() && !F->hasNotBeenReadFromBitcode()) { 416 // If this is an external function pointer, we can force the JIT to 417 // 'compile' it, which really just adds it to the map. 418 if (DoesntNeedStub) 419 return TheJIT->getPointerToFunction(F); 420 421 return Resolver.getFunctionStub(F); 422 } 423 424 // Okay, the function has not been compiled yet, if the target callback 425 // mechanism is capable of rewriting the instruction directly, prefer to do 426 // that instead of emitting a stub. 427 if (DoesntNeedStub) 428 return Resolver.AddCallbackAtLocation(F, Reference); 429 430 // Otherwise, we have to emit a lazy resolving stub. 431 return Resolver.getFunctionStub(F); 432} 433 434void *JITEmitter::getPointerToGVLazyPtr(GlobalValue *V, void *Reference, 435 bool DoesntNeedStub) { 436 // Make sure GV is emitted first. 437 // FIXME: For now, if the GV is an external function we force the JIT to 438 // compile it so the lazy pointer will contain the fully resolved address. 439 void *GVAddress = getPointerToGlobal(V, Reference, true); 440 return Resolver.getGlobalValueLazyPtr(V, GVAddress); 441} 442 443 444void JITEmitter::startFunction(MachineFunction &F) { 445 uintptr_t ActualSize; 446 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(), 447 ActualSize); 448 BufferEnd = BufferBegin+ActualSize; 449 450 // Ensure the constant pool/jump table info is at least 4-byte aligned. 451 emitAlignment(16); 452 453 emitConstantPool(F.getConstantPool()); 454 initJumpTableInfo(F.getJumpTableInfo()); 455 456 // About to start emitting the machine code for the function. 457 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U)); 458 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr); 459 460 MBBLocations.clear(); 461} 462 463bool JITEmitter::finishFunction(MachineFunction &F) { 464 if (CurBufferPtr == BufferEnd) { 465 // FIXME: Allocate more space, then try again. 466 cerr << "JIT: Ran out of space for generated machine code!\n"; 467 abort(); 468 } 469 470 emitJumpTableInfo(F.getJumpTableInfo()); 471 472 // FnStart is the start of the text, not the start of the constant pool and 473 // other per-function data. 474 unsigned char *FnStart = 475 (unsigned char *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction()); 476 unsigned char *FnEnd = CurBufferPtr; 477 478 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, FnEnd); 479 NumBytes += FnEnd-FnStart; 480 481 if (!Relocations.empty()) { 482 NumRelos += Relocations.size(); 483 484 // Resolve the relocations to concrete pointers. 485 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) { 486 MachineRelocation &MR = Relocations[i]; 487 void *ResultPtr; 488 if (MR.isString()) { 489 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getString()); 490 491 // If the target REALLY wants a stub for this function, emit it now. 492 if (!MR.doesntNeedStub()) 493 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr); 494 } else if (MR.isGlobalValue()) { 495 ResultPtr = getPointerToGlobal(MR.getGlobalValue(), 496 BufferBegin+MR.getMachineCodeOffset(), 497 MR.doesntNeedStub()); 498 } else if (MR.isGlobalValueLazyPtr()) { 499 ResultPtr = getPointerToGVLazyPtr(MR.getGlobalValue(), 500 BufferBegin+MR.getMachineCodeOffset(), 501 MR.doesntNeedStub()); 502 } else if (MR.isBasicBlock()) { 503 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock()); 504 } else if (MR.isConstantPoolIndex()) { 505 ResultPtr=(void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex()); 506 } else { 507 assert(MR.isJumpTableIndex()); 508 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex()); 509 } 510 511 MR.setResultPointer(ResultPtr); 512 513 // if we are managing the GOT and the relocation wants an index, 514 // give it one 515 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) { 516 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr); 517 MR.setGOTIndex(idx); 518 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) { 519 DOUT << "GOT was out of date for " << ResultPtr 520 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] 521 << "\n"; 522 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr; 523 } 524 } 525 } 526 527 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0], 528 Relocations.size(), MemMgr->getGOTBase()); 529 } 530 531 // Update the GOT entry for F to point to the new code. 532 if (MemMgr->isManagingGOT()) { 533 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin); 534 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) { 535 DOUT << "GOT was out of date for " << (void*)BufferBegin 536 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx] << "\n"; 537 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin; 538 } 539 } 540 541 // Invalidate the icache if necessary. 542 synchronizeICache(FnStart, FnEnd-FnStart); 543 544 DOUT << "JIT: Finished CodeGen of [" << (void*)FnStart 545 << "] Function: " << F.getFunction()->getName() 546 << ": " << (FnEnd-FnStart) << " bytes of text, " 547 << Relocations.size() << " relocations\n"; 548 Relocations.clear(); 549 550#ifndef NDEBUG 551 if (sys::hasDisassembler()) 552 DOUT << "Disassembled code:\n" 553 << sys::disassembleBuffer(FnStart, FnEnd-FnStart, (uintptr_t)FnStart); 554#endif 555 556 return false; 557} 558 559void JITEmitter::emitConstantPool(MachineConstantPool *MCP) { 560 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants(); 561 if (Constants.empty()) return; 562 563 MachineConstantPoolEntry CPE = Constants.back(); 564 unsigned Size = CPE.Offset; 565 const Type *Ty = CPE.isMachineConstantPoolEntry() 566 ? CPE.Val.MachineCPVal->getType() : CPE.Val.ConstVal->getType(); 567 Size += TheJIT->getTargetData()->getABITypeSize(Ty); 568 569 ConstantPoolBase = allocateSpace(Size, 1 << MCP->getConstantPoolAlignment()); 570 ConstantPool = MCP; 571 572 if (ConstantPoolBase == 0) return; // Buffer overflow. 573 574 // Initialize the memory for all of the constant pool entries. 575 for (unsigned i = 0, e = Constants.size(); i != e; ++i) { 576 void *CAddr = (char*)ConstantPoolBase+Constants[i].Offset; 577 if (Constants[i].isMachineConstantPoolEntry()) { 578 // FIXME: add support to lower machine constant pool values into bytes! 579 cerr << "Initialize memory with machine specific constant pool entry" 580 << " has not been implemented!\n"; 581 abort(); 582 } 583 TheJIT->InitializeMemory(Constants[i].Val.ConstVal, CAddr); 584 } 585} 586 587void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) { 588 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 589 if (JT.empty()) return; 590 591 unsigned NumEntries = 0; 592 for (unsigned i = 0, e = JT.size(); i != e; ++i) 593 NumEntries += JT[i].MBBs.size(); 594 595 unsigned EntrySize = MJTI->getEntrySize(); 596 597 // Just allocate space for all the jump tables now. We will fix up the actual 598 // MBB entries in the tables after we emit the code for each block, since then 599 // we will know the final locations of the MBBs in memory. 600 JumpTable = MJTI; 601 JumpTableBase = allocateSpace(NumEntries * EntrySize, MJTI->getAlignment()); 602} 603 604void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) { 605 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 606 if (JT.empty() || JumpTableBase == 0) return; 607 608 if (TargetMachine::getRelocationModel() == Reloc::PIC_) { 609 assert(MJTI->getEntrySize() == 4 && "Cross JIT'ing?"); 610 // For each jump table, place the offset from the beginning of the table 611 // to the target address. 612 int *SlotPtr = (int*)JumpTableBase; 613 614 for (unsigned i = 0, e = JT.size(); i != e; ++i) { 615 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs; 616 // Store the offset of the basic block for this jump table slot in the 617 // memory we allocated for the jump table in 'initJumpTableInfo' 618 intptr_t Base = (intptr_t)SlotPtr; 619 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) 620 *SlotPtr++ = (intptr_t)getMachineBasicBlockAddress(MBBs[mi]) - Base; 621 } 622 } else { 623 assert(MJTI->getEntrySize() == sizeof(void*) && "Cross JIT'ing?"); 624 625 // For each jump table, map each target in the jump table to the address of 626 // an emitted MachineBasicBlock. 627 intptr_t *SlotPtr = (intptr_t*)JumpTableBase; 628 629 for (unsigned i = 0, e = JT.size(); i != e; ++i) { 630 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs; 631 // Store the address of the basic block for this jump table slot in the 632 // memory we allocated for the jump table in 'initJumpTableInfo' 633 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) 634 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]); 635 } 636 } 637} 638 639void JITEmitter::startFunctionStub(unsigned StubSize, unsigned Alignment) { 640 SavedBufferBegin = BufferBegin; 641 SavedBufferEnd = BufferEnd; 642 SavedCurBufferPtr = CurBufferPtr; 643 644 BufferBegin = CurBufferPtr = MemMgr->allocateStub(StubSize, Alignment); 645 BufferEnd = BufferBegin+StubSize+1; 646} 647 648void *JITEmitter::finishFunctionStub(const Function *F) { 649 NumBytes += getCurrentPCOffset(); 650 std::swap(SavedBufferBegin, BufferBegin); 651 BufferEnd = SavedBufferEnd; 652 CurBufferPtr = SavedCurBufferPtr; 653 return SavedBufferBegin; 654} 655 656// getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry 657// in the constant pool that was last emitted with the 'emitConstantPool' 658// method. 659// 660intptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const { 661 assert(ConstantNum < ConstantPool->getConstants().size() && 662 "Invalid ConstantPoolIndex!"); 663 return (intptr_t)ConstantPoolBase + 664 ConstantPool->getConstants()[ConstantNum].Offset; 665} 666 667// getJumpTableEntryAddress - Return the address of the JumpTable with index 668// 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo' 669// 670intptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const { 671 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables(); 672 assert(Index < JT.size() && "Invalid jump table index!"); 673 674 unsigned Offset = 0; 675 unsigned EntrySize = JumpTable->getEntrySize(); 676 677 for (unsigned i = 0; i < Index; ++i) 678 Offset += JT[i].MBBs.size(); 679 680 Offset *= EntrySize; 681 682 return (intptr_t)((char *)JumpTableBase + Offset); 683} 684 685//===----------------------------------------------------------------------===// 686// Public interface to this file 687//===----------------------------------------------------------------------===// 688 689MachineCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM) { 690 return new JITEmitter(jit, JMM); 691} 692 693// getPointerToNamedFunction - This function is used as a global wrapper to 694// JIT::getPointerToNamedFunction for the purpose of resolving symbols when 695// bugpoint is debugging the JIT. In that scenario, we are loading an .so and 696// need to resolve function(s) that are being mis-codegenerated, so we need to 697// resolve their addresses at runtime, and this is the way to do it. 698extern "C" { 699 void *getPointerToNamedFunction(const char *Name) { 700 if (Function *F = TheJIT->FindFunctionNamed(Name)) 701 return TheJIT->getPointerToFunction(F); 702 return TheJIT->getPointerToNamedFunction(Name); 703 } 704} 705 706// getPointerToFunctionOrStub - If the specified function has been 707// code-gen'd, return a pointer to the function. If not, compile it, or use 708// a stub to implement lazy compilation if available. 709// 710void *JIT::getPointerToFunctionOrStub(Function *F) { 711 // If we have already code generated the function, just return the address. 712 if (void *Addr = getPointerToGlobalIfAvailable(F)) 713 return Addr; 714 715 // Get a stub if the target supports it. 716 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?"); 717 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter()); 718 return JE->getJITResolver().getFunctionStub(F); 719} 720 721/// freeMachineCodeForFunction - release machine code memory for given Function. 722/// 723void JIT::freeMachineCodeForFunction(Function *F) { 724 // Delete translation for this from the ExecutionEngine, so it will get 725 // retranslated next time it is used. 726 updateGlobalMapping(F, 0); 727 728 // Free the actual memory for the function body and related stuff. 729 assert(dynamic_cast<JITEmitter*>(MCE) && "Unexpected MCE?"); 730 static_cast<JITEmitter*>(MCE)->deallocateMemForFunction(F); 731} 732 733