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 "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/CodeGen/JITCodeEmitter.h"
22 #include "llvm/CodeGen/MachineCodeInfo.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineJumpTableInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/MachineRelocation.h"
28 #include "llvm/ExecutionEngine/GenericValue.h"
29 #include "llvm/ExecutionEngine/JITEventListener.h"
30 #include "llvm/ExecutionEngine/JITMemoryManager.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/ValueHandle.h"
37 #include "llvm/IR/ValueMap.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Disassembler.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/Memory.h"
43 #include "llvm/Support/MutexGuard.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetJITInfo.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
55 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
56 STATISTIC(NumRelos, "Number of relocations applied");
57 STATISTIC(NumRetries, "Number of retries with more memory");
60 // A declaration may stop being a declaration once it's fully read from bitcode.
61 // This function returns true if F is fully read and is still a declaration.
62 static bool isNonGhostDeclaration(const Function *F) {
63 return F->isDeclaration() && !F->isMaterializable();
66 //===----------------------------------------------------------------------===//
67 // JIT lazy compilation code.
71 class JITResolverState;
73 template<typename ValueTy>
74 struct NoRAUWValueMapConfig : public ValueMapConfig<ValueTy> {
75 typedef JITResolverState *ExtraData;
76 static void onRAUW(JITResolverState *, Value *Old, Value *New) {
77 llvm_unreachable("The JIT doesn't know how to handle a"
78 " RAUW on a value it has emitted.");
82 struct CallSiteValueMapConfig : public NoRAUWValueMapConfig<Function*> {
83 typedef JITResolverState *ExtraData;
84 static void onDelete(JITResolverState *JRS, Function *F);
87 class JITResolverState {
89 typedef ValueMap<Function*, void*, NoRAUWValueMapConfig<Function*> >
90 FunctionToLazyStubMapTy;
91 typedef std::map<void*, AssertingVH<Function> > CallSiteToFunctionMapTy;
92 typedef ValueMap<Function *, SmallPtrSet<void*, 1>,
93 CallSiteValueMapConfig> FunctionToCallSitesMapTy;
94 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
96 /// FunctionToLazyStubMap - Keep track of the lazy stub created for a
97 /// particular function so that we can reuse them if necessary.
98 FunctionToLazyStubMapTy FunctionToLazyStubMap;
100 /// CallSiteToFunctionMap - Keep track of the function that each lazy call
101 /// site corresponds to, and vice versa.
102 CallSiteToFunctionMapTy CallSiteToFunctionMap;
103 FunctionToCallSitesMapTy FunctionToCallSitesMap;
105 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
106 /// particular GlobalVariable so that we can reuse them if necessary.
107 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
110 /// Instance of the JIT this ResolverState serves.
115 JITResolverState(JIT *jit) : FunctionToLazyStubMap(this),
116 FunctionToCallSitesMap(this) {
122 FunctionToLazyStubMapTy& getFunctionToLazyStubMap(
123 const MutexGuard& locked) {
124 assert(locked.holds(TheJIT->lock));
125 return FunctionToLazyStubMap;
128 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& lck) {
129 assert(lck.holds(TheJIT->lock));
130 return GlobalToIndirectSymMap;
133 std::pair<void *, Function *> LookupFunctionFromCallSite(
134 const MutexGuard &locked, void *CallSite) const {
135 assert(locked.holds(TheJIT->lock));
137 // The address given to us for the stub may not be exactly right, it
138 // might be a little bit after the stub. As such, use upper_bound to
140 CallSiteToFunctionMapTy::const_iterator I =
141 CallSiteToFunctionMap.upper_bound(CallSite);
142 assert(I != CallSiteToFunctionMap.begin() &&
143 "This is not a known call site!");
148 void AddCallSite(const MutexGuard &locked, void *CallSite, Function *F) {
149 assert(locked.holds(TheJIT->lock));
151 bool Inserted = CallSiteToFunctionMap.insert(
152 std::make_pair(CallSite, F)).second;
154 assert(Inserted && "Pair was already in CallSiteToFunctionMap");
155 FunctionToCallSitesMap[F].insert(CallSite);
158 void EraseAllCallSitesForPrelocked(Function *F);
160 // Erases _all_ call sites regardless of their function. This is used to
161 // unregister the stub addresses from the StubToResolverMap in
163 void EraseAllCallSitesPrelocked();
166 /// JITResolver - Keep track of, and resolve, call sites for functions that
167 /// have not yet been compiled.
169 typedef JITResolverState::FunctionToLazyStubMapTy FunctionToLazyStubMapTy;
170 typedef JITResolverState::CallSiteToFunctionMapTy CallSiteToFunctionMapTy;
171 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
173 /// LazyResolverFn - The target lazy resolver function that we actually
174 /// rewrite instructions to use.
175 TargetJITInfo::LazyResolverFn LazyResolverFn;
177 JITResolverState state;
179 /// ExternalFnToStubMap - This is the equivalent of FunctionToLazyStubMap
180 /// for external functions. TODO: Of course, external functions don't need
181 /// a lazy stub. It's actually here to make it more likely that far calls
182 /// succeed, but no single stub can guarantee that. I'll remove this in a
183 /// subsequent checkin when I actually fix far calls.
184 std::map<void*, void*> ExternalFnToStubMap;
186 /// revGOTMap - map addresses to indexes in the GOT
187 std::map<void*, unsigned> revGOTMap;
188 unsigned nextGOTIndex;
192 /// Instance of JIT corresponding to this Resolver.
196 explicit JITResolver(JIT &jit, JITEmitter &je)
197 : state(&jit), nextGOTIndex(0), JE(je), TheJIT(&jit) {
198 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
203 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function's
204 /// lazy-compilation stub if it has already been created.
205 void *getLazyFunctionStubIfAvailable(Function *F);
207 /// getLazyFunctionStub - This returns a pointer to a function's
208 /// lazy-compilation stub, creating one on demand as needed.
209 void *getLazyFunctionStub(Function *F);
211 /// getExternalFunctionStub - Return a stub for the function at the
212 /// specified address, created lazily on demand.
213 void *getExternalFunctionStub(void *FnAddr);
215 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
216 /// specified GV address.
217 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
219 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
220 /// an address. This function only manages slots, it does not manage the
221 /// contents of the slots or the memory associated with the GOT.
222 unsigned getGOTIndexForAddr(void *addr);
224 /// JITCompilerFn - This function is called to resolve a stub to a compiled
225 /// address. If the LLVM Function corresponding to the stub has not yet
226 /// been compiled, this function compiles it first.
227 static void *JITCompilerFn(void *Stub);
230 class StubToResolverMapTy {
231 /// Map a stub address to a specific instance of a JITResolver so that
232 /// lazily-compiled functions can find the right resolver to use.
235 std::map<void*, JITResolver*> Map;
237 /// Guards Map from concurrent accesses.
238 mutable sys::Mutex Lock;
241 /// Registers a Stub to be resolved by Resolver.
242 void RegisterStubResolver(void *Stub, JITResolver *Resolver) {
243 MutexGuard guard(Lock);
244 Map.insert(std::make_pair(Stub, Resolver));
246 /// Unregisters the Stub when it's invalidated.
247 void UnregisterStubResolver(void *Stub) {
248 MutexGuard guard(Lock);
251 /// Returns the JITResolver instance that owns the Stub.
252 JITResolver *getResolverFromStub(void *Stub) const {
253 MutexGuard guard(Lock);
254 // The address given to us for the stub may not be exactly right, it might
255 // be a little bit after the stub. As such, use upper_bound to find it.
256 // This is the same trick as in LookupFunctionFromCallSite from
258 std::map<void*, JITResolver*>::const_iterator I = Map.upper_bound(Stub);
259 assert(I != Map.begin() && "This is not a known stub!");
263 /// True if any stubs refer to the given resolver. Only used in an assert().
265 bool ResolverHasStubs(JITResolver* Resolver) const {
266 MutexGuard guard(Lock);
267 for (std::map<void*, JITResolver*>::const_iterator I = Map.begin(),
268 E = Map.end(); I != E; ++I) {
269 if (I->second == Resolver)
275 /// This needs to be static so that a lazy call stub can access it with no
276 /// context except the address of the stub.
277 ManagedStatic<StubToResolverMapTy> StubToResolverMap;
279 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
280 /// used to output functions to memory for execution.
281 class JITEmitter : public JITCodeEmitter {
282 JITMemoryManager *MemMgr;
284 // When outputting a function stub in the context of some other function, we
285 // save BufferBegin/BufferEnd/CurBufferPtr here.
286 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
288 // When reattempting to JIT a function after running out of space, we store
289 // the estimated size of the function we're trying to JIT here, so we can
290 // ask the memory manager for at least this much space. When we
291 // successfully emit the function, we reset this back to zero.
292 uintptr_t SizeEstimate;
294 /// Relocations - These are the relocations that the function needs, as
296 std::vector<MachineRelocation> Relocations;
298 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
299 /// It is filled in by the StartMachineBasicBlock callback and queried by
300 /// the getMachineBasicBlockAddress callback.
301 std::vector<uintptr_t> MBBLocations;
303 /// ConstantPool - The constant pool for the current function.
305 MachineConstantPool *ConstantPool;
307 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
309 void *ConstantPoolBase;
311 /// ConstPoolAddresses - Addresses of individual constant pool entries.
313 SmallVector<uintptr_t, 8> ConstPoolAddresses;
315 /// JumpTable - The jump tables for the current function.
317 MachineJumpTableInfo *JumpTable;
319 /// JumpTableBase - A pointer to the first entry in the jump table.
323 /// Resolver - This contains info about the currently resolved functions.
324 JITResolver Resolver;
326 /// LabelLocations - This vector is a mapping from Label ID's to their
328 DenseMap<MCSymbol*, uintptr_t> LabelLocations;
330 /// MMI - Machine module info for exception informations
331 MachineModuleInfo* MMI;
333 // CurFn - The llvm function being emitted. Only valid during
335 const Function *CurFn;
337 /// Information about emitted code, which is passed to the
338 /// JITEventListeners. This is reset in startFunction and used in
340 JITEvent_EmittedFunctionDetails EmissionDetails;
343 void *FunctionBody; // Beginning of the function's allocation.
344 void *Code; // The address the function's code actually starts at.
345 void *ExceptionTable;
346 EmittedCode() : FunctionBody(0), Code(0), ExceptionTable(0) {}
348 struct EmittedFunctionConfig : public ValueMapConfig<const Function*> {
349 typedef JITEmitter *ExtraData;
350 static void onDelete(JITEmitter *, const Function*);
351 static void onRAUW(JITEmitter *, const Function*, const Function*);
353 ValueMap<const Function *, EmittedCode,
354 EmittedFunctionConfig> EmittedFunctions;
358 /// Instance of the JIT
362 JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
363 : SizeEstimate(0), Resolver(jit, *this), MMI(0), CurFn(0),
364 EmittedFunctions(this), TheJIT(&jit) {
365 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
366 if (jit.getJITInfo().needsGOT()) {
367 MemMgr->AllocateGOT();
368 DEBUG(dbgs() << "JIT is managing a GOT\n");
376 JITResolver &getJITResolver() { return Resolver; }
378 void startFunction(MachineFunction &F) override;
379 bool finishFunction(MachineFunction &F) override;
381 void emitConstantPool(MachineConstantPool *MCP);
382 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
383 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
385 void startGVStub(const GlobalValue* GV,
386 unsigned StubSize, unsigned Alignment = 1);
387 void startGVStub(void *Buffer, unsigned StubSize);
389 void *allocIndirectGV(const GlobalValue *GV, const uint8_t *Buffer,
390 size_t Size, unsigned Alignment) override;
392 /// allocateSpace - Reserves space in the current block if any, or
393 /// allocate a new one of the given size.
394 void *allocateSpace(uintptr_t Size, unsigned Alignment) override;
396 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
397 /// this method does not allocate memory in the current output buffer,
398 /// because a global may live longer than the current function.
399 void *allocateGlobal(uintptr_t Size, unsigned Alignment) override;
401 void addRelocation(const MachineRelocation &MR) override {
402 Relocations.push_back(MR);
405 void StartMachineBasicBlock(MachineBasicBlock *MBB) override {
406 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
407 MBBLocations.resize((MBB->getNumber()+1)*2);
408 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
409 if (MBB->hasAddressTaken())
410 TheJIT->addPointerToBasicBlock(MBB->getBasicBlock(),
411 (void*)getCurrentPCValue());
412 DEBUG(dbgs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
413 << (void*) getCurrentPCValue() << "]\n");
416 uintptr_t getConstantPoolEntryAddress(unsigned Entry) const override;
417 uintptr_t getJumpTableEntryAddress(unsigned Entry) const override;
420 getMachineBasicBlockAddress(MachineBasicBlock *MBB) const override {
421 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
422 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
423 return MBBLocations[MBB->getNumber()];
426 /// retryWithMoreMemory - Log a retry and deallocate all memory for the
427 /// given function. Increase the minimum allocation size so that we get
428 /// more memory next time.
429 void retryWithMoreMemory(MachineFunction &F);
431 /// deallocateMemForFunction - Deallocate all memory for the specified
433 void deallocateMemForFunction(const Function *F);
435 void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) override;
437 void emitLabel(MCSymbol *Label) override {
438 LabelLocations[Label] = getCurrentPCValue();
441 DenseMap<MCSymbol*, uintptr_t> *getLabelLocations() override {
442 return &LabelLocations;
445 uintptr_t getLabelAddress(MCSymbol *Label) const override {
446 assert(LabelLocations.count(Label) && "Label not emitted!");
447 return LabelLocations.find(Label)->second;
450 void setModuleInfo(MachineModuleInfo* Info) override {
455 void *getPointerToGlobal(GlobalValue *GV, void *Reference,
456 bool MayNeedFarStub);
457 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference);
461 void CallSiteValueMapConfig::onDelete(JITResolverState *JRS, Function *F) {
462 JRS->EraseAllCallSitesForPrelocked(F);
465 void JITResolverState::EraseAllCallSitesForPrelocked(Function *F) {
466 FunctionToCallSitesMapTy::iterator F2C = FunctionToCallSitesMap.find(F);
467 if (F2C == FunctionToCallSitesMap.end())
469 StubToResolverMapTy &S2RMap = *StubToResolverMap;
470 for (SmallPtrSet<void*, 1>::const_iterator I = F2C->second.begin(),
471 E = F2C->second.end(); I != E; ++I) {
472 S2RMap.UnregisterStubResolver(*I);
473 bool Erased = CallSiteToFunctionMap.erase(*I);
475 assert(Erased && "Missing call site->function mapping");
477 FunctionToCallSitesMap.erase(F2C);
480 void JITResolverState::EraseAllCallSitesPrelocked() {
481 StubToResolverMapTy &S2RMap = *StubToResolverMap;
482 for (CallSiteToFunctionMapTy::const_iterator
483 I = CallSiteToFunctionMap.begin(),
484 E = CallSiteToFunctionMap.end(); I != E; ++I) {
485 S2RMap.UnregisterStubResolver(I->first);
487 CallSiteToFunctionMap.clear();
488 FunctionToCallSitesMap.clear();
491 JITResolver::~JITResolver() {
492 // No need to lock because we're in the destructor, and state isn't shared.
493 state.EraseAllCallSitesPrelocked();
494 assert(!StubToResolverMap->ResolverHasStubs(this) &&
495 "Resolver destroyed with stubs still alive.");
498 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function stub
499 /// if it has already been created.
500 void *JITResolver::getLazyFunctionStubIfAvailable(Function *F) {
501 MutexGuard locked(TheJIT->lock);
503 // If we already have a stub for this function, recycle it.
504 return state.getFunctionToLazyStubMap(locked).lookup(F);
507 /// getFunctionStub - This returns a pointer to a function stub, creating
508 /// one on demand as needed.
509 void *JITResolver::getLazyFunctionStub(Function *F) {
510 MutexGuard locked(TheJIT->lock);
512 // If we already have a lazy stub for this function, recycle it.
513 void *&Stub = state.getFunctionToLazyStubMap(locked)[F];
514 if (Stub) return Stub;
516 // Call the lazy resolver function if we are JIT'ing lazily. Otherwise we
517 // must resolve the symbol now.
518 void *Actual = TheJIT->isCompilingLazily()
519 ? (void *)(intptr_t)LazyResolverFn : (void *)0;
521 // If this is an external declaration, attempt to resolve the address now
522 // to place in the stub.
523 if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage()) {
524 Actual = TheJIT->getPointerToFunction(F);
526 // If we resolved the symbol to a null address (eg. a weak external)
527 // don't emit a stub. Return a null pointer to the application.
528 if (!Actual) return 0;
531 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
532 JE.startGVStub(F, SL.Size, SL.Alignment);
533 // Codegen a new stub, calling the lazy resolver or the actual address of the
534 // external function, if it was resolved.
535 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual, JE);
538 if (Actual != (void*)(intptr_t)LazyResolverFn) {
539 // If we are getting the stub for an external function, we really want the
540 // address of the stub in the GlobalAddressMap for the JIT, not the address
541 // of the external function.
542 TheJIT->updateGlobalMapping(F, Stub);
545 DEBUG(dbgs() << "JIT: Lazy stub emitted at [" << Stub << "] for function '"
546 << F->getName() << "'\n");
548 if (TheJIT->isCompilingLazily()) {
549 // Register this JITResolver as the one corresponding to this call site so
550 // JITCompilerFn will be able to find it.
551 StubToResolverMap->RegisterStubResolver(Stub, this);
553 // Finally, keep track of the stub-to-Function mapping so that the
554 // JITCompilerFn knows which function to compile!
555 state.AddCallSite(locked, Stub, F);
556 } else if (!Actual) {
557 // If we are JIT'ing non-lazily but need to call a function that does not
558 // exist yet, add it to the JIT's work list so that we can fill in the
559 // stub address later.
560 assert(!isNonGhostDeclaration(F) && !F->hasAvailableExternallyLinkage() &&
561 "'Actual' should have been set above.");
562 TheJIT->addPendingFunction(F);
568 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
570 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
571 MutexGuard locked(TheJIT->lock);
573 // If we already have a stub for this global variable, recycle it.
574 void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
575 if (IndirectSym) return IndirectSym;
577 // Otherwise, codegen a new indirect symbol.
578 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
581 DEBUG(dbgs() << "JIT: Indirect symbol emitted at [" << IndirectSym
582 << "] for GV '" << GV->getName() << "'\n");
587 /// getExternalFunctionStub - Return a stub for the function at the
588 /// specified address, created lazily on demand.
589 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
590 // If we already have a stub for this function, recycle it.
591 void *&Stub = ExternalFnToStubMap[FnAddr];
592 if (Stub) return Stub;
594 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
595 JE.startGVStub(0, SL.Size, SL.Alignment);
596 Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr, JE);
599 DEBUG(dbgs() << "JIT: Stub emitted at [" << Stub
600 << "] for external function at '" << FnAddr << "'\n");
604 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
605 unsigned idx = revGOTMap[addr];
607 idx = ++nextGOTIndex;
608 revGOTMap[addr] = idx;
609 DEBUG(dbgs() << "JIT: Adding GOT entry " << idx << " for addr ["
615 /// JITCompilerFn - This function is called when a lazy compilation stub has
616 /// been entered. It looks up which function this stub corresponds to, compiles
617 /// it if necessary, then returns the resultant function pointer.
618 void *JITResolver::JITCompilerFn(void *Stub) {
619 JITResolver *JR = StubToResolverMap->getResolverFromStub(Stub);
620 assert(JR && "Unable to find the corresponding JITResolver to the call site");
626 // Only lock for getting the Function. The call getPointerToFunction made
627 // in this function might trigger function materializing, which requires
628 // JIT lock to be unlocked.
629 MutexGuard locked(JR->TheJIT->lock);
631 // The address given to us for the stub may not be exactly right, it might
632 // be a little bit after the stub. As such, use upper_bound to find it.
633 std::pair<void*, Function*> I =
634 JR->state.LookupFunctionFromCallSite(locked, Stub);
639 // If we have already code generated the function, just return the address.
640 void *Result = JR->TheJIT->getPointerToGlobalIfAvailable(F);
643 // Otherwise we don't have it, do lazy compilation now.
645 // If lazy compilation is disabled, emit a useful error message and abort.
646 if (!JR->TheJIT->isCompilingLazily()) {
647 report_fatal_error("LLVM JIT requested to do lazy compilation of"
649 + F->getName() + "' when lazy compiles are disabled!");
652 DEBUG(dbgs() << "JIT: Lazily resolving function '" << F->getName()
653 << "' In stub ptr = " << Stub << " actual ptr = "
654 << ActualPtr << "\n");
657 Result = JR->TheJIT->getPointerToFunction(F);
660 // Reacquire the lock to update the GOT map.
661 MutexGuard locked(JR->TheJIT->lock);
663 // We might like to remove the call site from the CallSiteToFunction map, but
664 // we can't do that! Multiple threads could be stuck, waiting to acquire the
665 // lock above. As soon as the 1st function finishes compiling the function,
666 // the next one will be released, and needs to be able to find the function it
669 // FIXME: We could rewrite all references to this stub if we knew them.
671 // What we will do is set the compiled function address to map to the
672 // same GOT entry as the stub so that later clients may update the GOT
673 // if they see it still using the stub address.
674 // Note: this is done so the Resolver doesn't have to manage GOT memory
675 // Do this without allocating map space if the target isn't using a GOT
676 if(JR->revGOTMap.find(Stub) != JR->revGOTMap.end())
677 JR->revGOTMap[Result] = JR->revGOTMap[Stub];
682 //===----------------------------------------------------------------------===//
685 void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
686 bool MayNeedFarStub) {
687 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
688 return TheJIT->getOrEmitGlobalVariable(GV);
690 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
691 return TheJIT->getPointerToGlobal(GA->getAliasedGlobal());
693 // If we have already compiled the function, return a pointer to its body.
694 Function *F = cast<Function>(V);
696 void *FnStub = Resolver.getLazyFunctionStubIfAvailable(F);
698 // Return the function stub if it's already created. We do this first so
699 // that we're returning the same address for the function as any previous
700 // call. TODO: Yes, this is wrong. The lazy stub isn't guaranteed to be
701 // close enough to call.
705 // If we know the target can handle arbitrary-distance calls, try to
706 // return a direct pointer.
707 if (!MayNeedFarStub) {
708 // If we have code, go ahead and return that.
709 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
710 if (ResultPtr) return ResultPtr;
712 // If this is an external function pointer, we can force the JIT to
713 // 'compile' it, which really just adds it to the map.
714 if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage())
715 return TheJIT->getPointerToFunction(F);
718 // Otherwise, we may need a to emit a stub, and, conservatively, we always do
719 // so. Note that it's possible to return null from getLazyFunctionStub in the
720 // case of a weak extern that fails to resolve.
721 return Resolver.getLazyFunctionStub(F);
724 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference) {
725 // Make sure GV is emitted first, and create a stub containing the fully
727 void *GVAddress = getPointerToGlobal(V, Reference, false);
728 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
732 void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
733 if (DL.isUnknown()) return;
734 if (!BeforePrintingInsn) return;
736 const LLVMContext &Context = EmissionDetails.MF->getFunction()->getContext();
738 if (DL.getScope(Context) != 0 && PrevDL != DL) {
739 JITEvent_EmittedFunctionDetails::LineStart NextLine;
740 NextLine.Address = getCurrentPCValue();
742 EmissionDetails.LineStarts.push_back(NextLine);
748 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
749 const DataLayout *TD) {
750 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
751 if (Constants.empty()) return 0;
754 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
755 MachineConstantPoolEntry CPE = Constants[i];
756 unsigned AlignMask = CPE.getAlignment() - 1;
757 Size = (Size + AlignMask) & ~AlignMask;
758 Type *Ty = CPE.getType();
759 Size += TD->getTypeAllocSize(Ty);
764 void JITEmitter::startFunction(MachineFunction &F) {
765 DEBUG(dbgs() << "JIT: Starting CodeGen of Function "
766 << F.getName() << "\n");
768 uintptr_t ActualSize = 0;
769 // Set the memory writable, if it's not already
770 MemMgr->setMemoryWritable();
772 if (SizeEstimate > 0) {
773 // SizeEstimate will be non-zero on reallocation attempts.
774 ActualSize = SizeEstimate;
777 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
779 BufferEnd = BufferBegin+ActualSize;
780 EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
782 // Ensure the constant pool/jump table info is at least 4-byte aligned.
785 emitConstantPool(F.getConstantPool());
786 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
787 initJumpTableInfo(MJTI);
789 // About to start emitting the machine code for the function.
790 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
791 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
792 EmittedFunctions[F.getFunction()].Code = CurBufferPtr;
794 MBBLocations.clear();
796 EmissionDetails.MF = &F;
797 EmissionDetails.LineStarts.clear();
800 bool JITEmitter::finishFunction(MachineFunction &F) {
801 if (CurBufferPtr == BufferEnd) {
802 // We must call endFunctionBody before retrying, because
803 // deallocateMemForFunction requires it.
804 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
805 retryWithMoreMemory(F);
809 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
810 emitJumpTableInfo(MJTI);
812 // FnStart is the start of the text, not the start of the constant pool and
813 // other per-function data.
815 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
817 // FnEnd is the end of the function's machine code.
818 uint8_t *FnEnd = CurBufferPtr;
820 if (!Relocations.empty()) {
821 CurFn = F.getFunction();
822 NumRelos += Relocations.size();
824 // Resolve the relocations to concrete pointers.
825 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
826 MachineRelocation &MR = Relocations[i];
828 if (!MR.letTargetResolve()) {
829 if (MR.isExternalSymbol()) {
830 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
832 DEBUG(dbgs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
833 << ResultPtr << "]\n");
835 // If the target REALLY wants a stub for this function, emit it now.
836 if (MR.mayNeedFarStub()) {
837 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
839 } else if (MR.isGlobalValue()) {
840 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
841 BufferBegin+MR.getMachineCodeOffset(),
842 MR.mayNeedFarStub());
843 } else if (MR.isIndirectSymbol()) {
844 ResultPtr = getPointerToGVIndirectSym(
845 MR.getGlobalValue(), BufferBegin+MR.getMachineCodeOffset());
846 } else if (MR.isBasicBlock()) {
847 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
848 } else if (MR.isConstantPoolIndex()) {
850 (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
852 assert(MR.isJumpTableIndex());
853 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
856 MR.setResultPointer(ResultPtr);
859 // if we are managing the GOT and the relocation wants an index,
861 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
862 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
864 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
865 DEBUG(dbgs() << "JIT: GOT was out of date for " << ResultPtr
866 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
868 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
874 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
875 Relocations.size(), MemMgr->getGOTBase());
878 // Update the GOT entry for F to point to the new code.
879 if (MemMgr->isManagingGOT()) {
880 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
881 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
882 DEBUG(dbgs() << "JIT: GOT was out of date for " << (void*)BufferBegin
883 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
885 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
889 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
890 // global variables that were referenced in the relocations.
891 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
893 if (CurBufferPtr == BufferEnd) {
894 retryWithMoreMemory(F);
897 // Now that we've succeeded in emitting the function, reset the
898 // SizeEstimate back down to zero.
902 BufferBegin = CurBufferPtr = 0;
903 NumBytes += FnEnd-FnStart;
905 // Invalidate the icache if necessary.
906 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
908 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
911 // Reset the previous debug location.
914 DEBUG(dbgs() << "JIT: Finished CodeGen of [" << (void*)FnStart
915 << "] Function: " << F.getName()
916 << ": " << (FnEnd-FnStart) << " bytes of text, "
917 << Relocations.size() << " relocations\n");
920 ConstPoolAddresses.clear();
922 // Mark code region readable and executable if it's not so already.
923 MemMgr->setMemoryExecutable();
926 if (sys::hasDisassembler()) {
927 dbgs() << "JIT: Disassembled code:\n";
928 dbgs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
931 dbgs() << "JIT: Binary code:\n";
932 uint8_t* q = FnStart;
933 for (int i = 0; q < FnEnd; q += 4, ++i) {
937 dbgs() << "JIT: " << (long)(q - FnStart) << ": ";
939 for (int j = 3; j >= 0; --j) {
943 dbgs() << (unsigned short)q[j];
961 void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
962 DEBUG(dbgs() << "JIT: Ran out of space for native code. Reattempting.\n");
963 Relocations.clear(); // Clear the old relocations or we'll reapply them.
964 ConstPoolAddresses.clear();
966 deallocateMemForFunction(F.getFunction());
967 // Try again with at least twice as much free space.
968 SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
970 for (MachineFunction::iterator MBB = F.begin(), E = F.end(); MBB != E; ++MBB){
971 if (MBB->hasAddressTaken())
972 TheJIT->clearPointerToBasicBlock(MBB->getBasicBlock());
976 /// deallocateMemForFunction - Deallocate all memory for the specified
977 /// function body. Also drop any references the function has to stubs.
978 /// May be called while the Function is being destroyed inside ~Value().
979 void JITEmitter::deallocateMemForFunction(const Function *F) {
980 ValueMap<const Function *, EmittedCode, EmittedFunctionConfig>::iterator
981 Emitted = EmittedFunctions.find(F);
982 if (Emitted != EmittedFunctions.end()) {
983 MemMgr->deallocateFunctionBody(Emitted->second.FunctionBody);
984 TheJIT->NotifyFreeingMachineCode(Emitted->second.Code);
986 EmittedFunctions.erase(Emitted);
991 void *JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
993 return JITCodeEmitter::allocateSpace(Size, Alignment);
995 // create a new memory block if there is no active one.
996 // care must be taken so that BufferBegin is invalidated when a
998 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
999 BufferEnd = BufferBegin+Size;
1000 return CurBufferPtr;
1003 void *JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1004 // Delegate this call through the memory manager.
1005 return MemMgr->allocateGlobal(Size, Alignment);
1008 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1009 if (TheJIT->getJITInfo().hasCustomConstantPool())
1012 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1013 if (Constants.empty()) return;
1015 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getDataLayout());
1016 unsigned Align = MCP->getConstantPoolAlignment();
1017 ConstantPoolBase = allocateSpace(Size, Align);
1020 if (ConstantPoolBase == 0) return; // Buffer overflow.
1022 DEBUG(dbgs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1023 << "] (size: " << Size << ", alignment: " << Align << ")\n");
1025 // Initialize the memory for all of the constant pool entries.
1026 unsigned Offset = 0;
1027 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1028 MachineConstantPoolEntry CPE = Constants[i];
1029 unsigned AlignMask = CPE.getAlignment() - 1;
1030 Offset = (Offset + AlignMask) & ~AlignMask;
1032 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1033 ConstPoolAddresses.push_back(CAddr);
1034 if (CPE.isMachineConstantPoolEntry()) {
1035 // FIXME: add support to lower machine constant pool values into bytes!
1036 report_fatal_error("Initialize memory with machine specific constant pool"
1037 "entry has not been implemented!");
1039 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1040 DEBUG(dbgs() << "JIT: CP" << i << " at [0x";
1041 dbgs().write_hex(CAddr) << "]\n");
1043 Type *Ty = CPE.Val.ConstVal->getType();
1044 Offset += TheJIT->getDataLayout()->getTypeAllocSize(Ty);
1048 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1049 if (TheJIT->getJITInfo().hasCustomJumpTables())
1051 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline)
1054 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1055 if (JT.empty()) return;
1057 unsigned NumEntries = 0;
1058 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1059 NumEntries += JT[i].MBBs.size();
1061 unsigned EntrySize = MJTI->getEntrySize(*TheJIT->getDataLayout());
1063 // Just allocate space for all the jump tables now. We will fix up the actual
1064 // MBB entries in the tables after we emit the code for each block, since then
1065 // we will know the final locations of the MBBs in memory.
1067 JumpTableBase = allocateSpace(NumEntries * EntrySize,
1068 MJTI->getEntryAlignment(*TheJIT->getDataLayout()));
1071 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1072 if (TheJIT->getJITInfo().hasCustomJumpTables())
1075 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1076 if (JT.empty() || JumpTableBase == 0) return;
1079 switch (MJTI->getEntryKind()) {
1080 case MachineJumpTableInfo::EK_Inline:
1082 case MachineJumpTableInfo::EK_BlockAddress: {
1083 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1085 assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == sizeof(void*) &&
1088 // For each jump table, map each target in the jump table to the address of
1089 // an emitted MachineBasicBlock.
1090 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1092 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1093 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1094 // Store the address of the basic block for this jump table slot in the
1095 // memory we allocated for the jump table in 'initJumpTableInfo'
1096 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1097 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1102 case MachineJumpTableInfo::EK_Custom32:
1103 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1104 case MachineJumpTableInfo::EK_LabelDifference32: {
1105 assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == 4&&"Cross JIT'ing?");
1106 // For each jump table, place the offset from the beginning of the table
1107 // to the target address.
1108 int *SlotPtr = (int*)JumpTableBase;
1110 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1111 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1112 // Store the offset of the basic block for this jump table slot in the
1113 // memory we allocated for the jump table in 'initJumpTableInfo'
1114 uintptr_t Base = (uintptr_t)SlotPtr;
1115 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1116 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1117 /// FIXME: USe EntryKind instead of magic "getPICJumpTableEntry" hook.
1118 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1123 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1125 "JT Info emission not implemented for GPRel64BlockAddress yet.");
1129 void JITEmitter::startGVStub(const GlobalValue* GV,
1130 unsigned StubSize, unsigned Alignment) {
1131 SavedBufferBegin = BufferBegin;
1132 SavedBufferEnd = BufferEnd;
1133 SavedCurBufferPtr = CurBufferPtr;
1135 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1136 BufferEnd = BufferBegin+StubSize+1;
1139 void JITEmitter::startGVStub(void *Buffer, unsigned StubSize) {
1140 SavedBufferBegin = BufferBegin;
1141 SavedBufferEnd = BufferEnd;
1142 SavedCurBufferPtr = CurBufferPtr;
1144 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
1145 BufferEnd = BufferBegin+StubSize+1;
1148 void JITEmitter::finishGVStub() {
1149 assert(CurBufferPtr != BufferEnd && "Stub overflowed allocated space.");
1150 NumBytes += getCurrentPCOffset();
1151 BufferBegin = SavedBufferBegin;
1152 BufferEnd = SavedBufferEnd;
1153 CurBufferPtr = SavedCurBufferPtr;
1156 void *JITEmitter::allocIndirectGV(const GlobalValue *GV,
1157 const uint8_t *Buffer, size_t Size,
1158 unsigned Alignment) {
1159 uint8_t *IndGV = MemMgr->allocateStub(GV, Size, Alignment);
1160 memcpy(IndGV, Buffer, Size);
1164 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1165 // in the constant pool that was last emitted with the 'emitConstantPool'
1168 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1169 assert(ConstantNum < ConstantPool->getConstants().size() &&
1170 "Invalid ConstantPoolIndex!");
1171 return ConstPoolAddresses[ConstantNum];
1174 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1175 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1177 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1178 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1179 assert(Index < JT.size() && "Invalid jump table index!");
1181 unsigned EntrySize = JumpTable->getEntrySize(*TheJIT->getDataLayout());
1183 unsigned Offset = 0;
1184 for (unsigned i = 0; i < Index; ++i)
1185 Offset += JT[i].MBBs.size();
1187 Offset *= EntrySize;
1189 return (uintptr_t)((char *)JumpTableBase + Offset);
1192 void JITEmitter::EmittedFunctionConfig::onDelete(
1193 JITEmitter *Emitter, const Function *F) {
1194 Emitter->deallocateMemForFunction(F);
1196 void JITEmitter::EmittedFunctionConfig::onRAUW(
1197 JITEmitter *, const Function*, const Function*) {
1198 llvm_unreachable("The JIT doesn't know how to handle a"
1199 " RAUW on a value it has emitted.");
1203 //===----------------------------------------------------------------------===//
1204 // Public interface to this file
1205 //===----------------------------------------------------------------------===//
1207 JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1208 TargetMachine &tm) {
1209 return new JITEmitter(jit, JMM, tm);
1212 // getPointerToFunctionOrStub - If the specified function has been
1213 // code-gen'd, return a pointer to the function. If not, compile it, or use
1214 // a stub to implement lazy compilation if available.
1216 void *JIT::getPointerToFunctionOrStub(Function *F) {
1217 // If we have already code generated the function, just return the address.
1218 if (void *Addr = getPointerToGlobalIfAvailable(F))
1221 // Get a stub if the target supports it.
1222 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
1223 return JE->getJITResolver().getLazyFunctionStub(F);
1226 void JIT::updateFunctionStub(Function *F) {
1227 // Get the empty stub we generated earlier.
1228 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
1229 void *Stub = JE->getJITResolver().getLazyFunctionStub(F);
1230 void *Addr = getPointerToGlobalIfAvailable(F);
1231 assert(Addr != Stub && "Function must have non-stub address to be updated.");
1233 // Tell the target jit info to rewrite the stub at the specified address,
1234 // rather than creating a new one.
1235 TargetJITInfo::StubLayout layout = getJITInfo().getStubLayout();
1236 JE->startGVStub(Stub, layout.Size);
1237 getJITInfo().emitFunctionStub(F, Addr, *getCodeEmitter());
1241 /// freeMachineCodeForFunction - release machine code memory for given Function.
1243 void JIT::freeMachineCodeForFunction(Function *F) {
1244 // Delete translation for this from the ExecutionEngine, so it will get
1245 // retranslated next time it is used.
1246 updateGlobalMapping(F, 0);
1248 // Free the actual memory for the function body and related stuff.
1249 static_cast<JITEmitter*>(JCE)->deallocateMemForFunction(F);