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 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/JITCodeEmitter.h"
21 #include "llvm/CodeGen/MachineCodeInfo.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRelocation.h"
27 #include "llvm/ExecutionEngine/GenericValue.h"
28 #include "llvm/ExecutionEngine/JITEventListener.h"
29 #include "llvm/ExecutionEngine/JITMemoryManager.h"
30 #include "llvm/IR/Constants.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/IR/ValueHandle.h"
37 #include "llvm/IR/ValueMap.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/ManagedStatic.h"
41 #include "llvm/Support/Memory.h"
42 #include "llvm/Support/MutexGuard.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetJITInfo.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
54 #define DEBUG_TYPE "jit"
56 STATISTIC(NumBytes, "Number of bytes of machine code compiled");
57 STATISTIC(NumRelos, "Number of relocations applied");
58 STATISTIC(NumRetries, "Number of retries with more memory");
61 // A declaration may stop being a declaration once it's fully read from bitcode.
62 // This function returns true if F is fully read and is still a declaration.
63 static bool isNonGhostDeclaration(const Function *F) {
64 return F->isDeclaration() && !F->isMaterializable();
67 //===----------------------------------------------------------------------===//
68 // JIT lazy compilation code.
72 class JITResolverState;
74 template<typename ValueTy>
75 struct NoRAUWValueMapConfig : public ValueMapConfig<ValueTy> {
76 typedef JITResolverState *ExtraData;
77 static void onRAUW(JITResolverState *, Value *Old, Value *New) {
78 llvm_unreachable("The JIT doesn't know how to handle a"
79 " RAUW on a value it has emitted.");
83 struct CallSiteValueMapConfig : public NoRAUWValueMapConfig<Function*> {
84 typedef JITResolverState *ExtraData;
85 static void onDelete(JITResolverState *JRS, Function *F);
88 class JITResolverState {
90 typedef ValueMap<Function*, void*, NoRAUWValueMapConfig<Function*> >
91 FunctionToLazyStubMapTy;
92 typedef std::map<void*, AssertingVH<Function> > CallSiteToFunctionMapTy;
93 typedef ValueMap<Function *, SmallPtrSet<void*, 1>,
94 CallSiteValueMapConfig> FunctionToCallSitesMapTy;
95 typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
97 /// FunctionToLazyStubMap - Keep track of the lazy stub created for a
98 /// particular function so that we can reuse them if necessary.
99 FunctionToLazyStubMapTy FunctionToLazyStubMap;
101 /// CallSiteToFunctionMap - Keep track of the function that each lazy call
102 /// site corresponds to, and vice versa.
103 CallSiteToFunctionMapTy CallSiteToFunctionMap;
104 FunctionToCallSitesMapTy FunctionToCallSitesMap;
106 /// GlobalToIndirectSymMap - Keep track of the indirect symbol created for a
107 /// particular GlobalVariable so that we can reuse them if necessary.
108 GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
111 /// Instance of the JIT this ResolverState serves.
116 JITResolverState(JIT *jit) : FunctionToLazyStubMap(this),
117 FunctionToCallSitesMap(this) {
123 FunctionToLazyStubMapTy& getFunctionToLazyStubMap() {
124 return FunctionToLazyStubMap;
127 GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap() {
128 return GlobalToIndirectSymMap;
131 std::pair<void *, Function *> LookupFunctionFromCallSite(
132 void *CallSite) const {
133 // The address given to us for the stub may not be exactly right, it
134 // might be a little bit after the stub. As such, use upper_bound to
136 CallSiteToFunctionMapTy::const_iterator I =
137 CallSiteToFunctionMap.upper_bound(CallSite);
138 assert(I != CallSiteToFunctionMap.begin() &&
139 "This is not a known call site!");
144 void AddCallSite(void *CallSite, Function *F) {
145 bool Inserted = CallSiteToFunctionMap.insert(
146 std::make_pair(CallSite, F)).second;
148 assert(Inserted && "Pair was already in CallSiteToFunctionMap");
149 FunctionToCallSitesMap[F].insert(CallSite);
152 void EraseAllCallSitesForPrelocked(Function *F);
154 // Erases _all_ call sites regardless of their function. This is used to
155 // unregister the stub addresses from the StubToResolverMap in
157 void EraseAllCallSitesPrelocked();
160 /// JITResolver - Keep track of, and resolve, call sites for functions that
161 /// have not yet been compiled.
163 typedef JITResolverState::FunctionToLazyStubMapTy FunctionToLazyStubMapTy;
164 typedef JITResolverState::CallSiteToFunctionMapTy CallSiteToFunctionMapTy;
165 typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
167 /// LazyResolverFn - The target lazy resolver function that we actually
168 /// rewrite instructions to use.
169 TargetJITInfo::LazyResolverFn LazyResolverFn;
171 JITResolverState state;
173 /// ExternalFnToStubMap - This is the equivalent of FunctionToLazyStubMap
174 /// for external functions. TODO: Of course, external functions don't need
175 /// a lazy stub. It's actually here to make it more likely that far calls
176 /// succeed, but no single stub can guarantee that. I'll remove this in a
177 /// subsequent checkin when I actually fix far calls.
178 std::map<void*, void*> ExternalFnToStubMap;
180 /// revGOTMap - map addresses to indexes in the GOT
181 std::map<void*, unsigned> revGOTMap;
182 unsigned nextGOTIndex;
186 /// Instance of JIT corresponding to this Resolver.
190 explicit JITResolver(JIT &jit, JITEmitter &je)
191 : state(&jit), nextGOTIndex(0), JE(je), TheJIT(&jit) {
192 LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
197 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function's
198 /// lazy-compilation stub if it has already been created.
199 void *getLazyFunctionStubIfAvailable(Function *F);
201 /// getLazyFunctionStub - This returns a pointer to a function's
202 /// lazy-compilation stub, creating one on demand as needed.
203 void *getLazyFunctionStub(Function *F);
205 /// getExternalFunctionStub - Return a stub for the function at the
206 /// specified address, created lazily on demand.
207 void *getExternalFunctionStub(void *FnAddr);
209 /// getGlobalValueIndirectSym - Return an indirect symbol containing the
210 /// specified GV address.
211 void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
213 /// getGOTIndexForAddress - Return a new or existing index in the GOT for
214 /// an address. This function only manages slots, it does not manage the
215 /// contents of the slots or the memory associated with the GOT.
216 unsigned getGOTIndexForAddr(void *addr);
218 /// JITCompilerFn - This function is called to resolve a stub to a compiled
219 /// address. If the LLVM Function corresponding to the stub has not yet
220 /// been compiled, this function compiles it first.
221 static void *JITCompilerFn(void *Stub);
224 class StubToResolverMapTy {
225 /// Map a stub address to a specific instance of a JITResolver so that
226 /// lazily-compiled functions can find the right resolver to use.
229 std::map<void*, JITResolver*> Map;
231 /// Guards Map from concurrent accesses.
232 mutable sys::Mutex Lock;
235 /// Registers a Stub to be resolved by Resolver.
236 void RegisterStubResolver(void *Stub, JITResolver *Resolver) {
237 MutexGuard guard(Lock);
238 Map.insert(std::make_pair(Stub, Resolver));
240 /// Unregisters the Stub when it's invalidated.
241 void UnregisterStubResolver(void *Stub) {
242 MutexGuard guard(Lock);
245 /// Returns the JITResolver instance that owns the Stub.
246 JITResolver *getResolverFromStub(void *Stub) const {
247 MutexGuard guard(Lock);
248 // The address given to us for the stub may not be exactly right, it might
249 // be a little bit after the stub. As such, use upper_bound to find it.
250 // This is the same trick as in LookupFunctionFromCallSite from
252 std::map<void*, JITResolver*>::const_iterator I = Map.upper_bound(Stub);
253 assert(I != Map.begin() && "This is not a known stub!");
257 /// True if any stubs refer to the given resolver. Only used in an assert().
259 bool ResolverHasStubs(JITResolver* Resolver) const {
260 MutexGuard guard(Lock);
261 for (std::map<void*, JITResolver*>::const_iterator I = Map.begin(),
262 E = Map.end(); I != E; ++I) {
263 if (I->second == Resolver)
269 /// This needs to be static so that a lazy call stub can access it with no
270 /// context except the address of the stub.
271 ManagedStatic<StubToResolverMapTy> StubToResolverMap;
273 /// JITEmitter - The JIT implementation of the MachineCodeEmitter, which is
274 /// used to output functions to memory for execution.
275 class JITEmitter : public JITCodeEmitter {
276 JITMemoryManager *MemMgr;
278 // When outputting a function stub in the context of some other function, we
279 // save BufferBegin/BufferEnd/CurBufferPtr here.
280 uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
282 // When reattempting to JIT a function after running out of space, we store
283 // the estimated size of the function we're trying to JIT here, so we can
284 // ask the memory manager for at least this much space. When we
285 // successfully emit the function, we reset this back to zero.
286 uintptr_t SizeEstimate;
288 /// Relocations - These are the relocations that the function needs, as
290 std::vector<MachineRelocation> Relocations;
292 /// MBBLocations - This vector is a mapping from MBB ID's to their address.
293 /// It is filled in by the StartMachineBasicBlock callback and queried by
294 /// the getMachineBasicBlockAddress callback.
295 std::vector<uintptr_t> MBBLocations;
297 /// ConstantPool - The constant pool for the current function.
299 MachineConstantPool *ConstantPool;
301 /// ConstantPoolBase - A pointer to the first entry in the constant pool.
303 void *ConstantPoolBase;
305 /// ConstPoolAddresses - Addresses of individual constant pool entries.
307 SmallVector<uintptr_t, 8> ConstPoolAddresses;
309 /// JumpTable - The jump tables for the current function.
311 MachineJumpTableInfo *JumpTable;
313 /// JumpTableBase - A pointer to the first entry in the jump table.
317 /// Resolver - This contains info about the currently resolved functions.
318 JITResolver Resolver;
320 /// LabelLocations - This vector is a mapping from Label ID's to their
322 DenseMap<MCSymbol*, uintptr_t> LabelLocations;
324 /// MMI - Machine module info for exception informations
325 MachineModuleInfo* MMI;
327 // CurFn - The llvm function being emitted. Only valid during
329 const Function *CurFn;
331 /// Information about emitted code, which is passed to the
332 /// JITEventListeners. This is reset in startFunction and used in
334 JITEvent_EmittedFunctionDetails EmissionDetails;
337 void *FunctionBody; // Beginning of the function's allocation.
338 void *Code; // The address the function's code actually starts at.
339 void *ExceptionTable;
340 EmittedCode() : FunctionBody(nullptr), Code(nullptr),
341 ExceptionTable(nullptr) {}
343 struct EmittedFunctionConfig : public ValueMapConfig<const Function*> {
344 typedef JITEmitter *ExtraData;
345 static void onDelete(JITEmitter *, const Function*);
346 static void onRAUW(JITEmitter *, const Function*, const Function*);
348 ValueMap<const Function *, EmittedCode,
349 EmittedFunctionConfig> EmittedFunctions;
353 /// Instance of the JIT
357 JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
358 : SizeEstimate(0), Resolver(jit, *this), MMI(nullptr), CurFn(nullptr),
359 EmittedFunctions(this), TheJIT(&jit) {
360 MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
361 if (jit.getJITInfo().needsGOT()) {
362 MemMgr->AllocateGOT();
363 DEBUG(dbgs() << "JIT is managing a GOT\n");
371 JITResolver &getJITResolver() { return Resolver; }
373 void startFunction(MachineFunction &F) override;
374 bool finishFunction(MachineFunction &F) override;
376 void emitConstantPool(MachineConstantPool *MCP);
377 void initJumpTableInfo(MachineJumpTableInfo *MJTI);
378 void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
380 void startGVStub(const GlobalValue* GV,
381 unsigned StubSize, unsigned Alignment = 1);
382 void startGVStub(void *Buffer, unsigned StubSize);
384 void *allocIndirectGV(const GlobalValue *GV, const uint8_t *Buffer,
385 size_t Size, unsigned Alignment) override;
387 /// allocateSpace - Reserves space in the current block if any, or
388 /// allocate a new one of the given size.
389 void *allocateSpace(uintptr_t Size, unsigned Alignment) override;
391 /// allocateGlobal - Allocate memory for a global. Unlike allocateSpace,
392 /// this method does not allocate memory in the current output buffer,
393 /// because a global may live longer than the current function.
394 void *allocateGlobal(uintptr_t Size, unsigned Alignment) override;
396 void addRelocation(const MachineRelocation &MR) override {
397 Relocations.push_back(MR);
400 void StartMachineBasicBlock(MachineBasicBlock *MBB) override {
401 if (MBBLocations.size() <= (unsigned)MBB->getNumber())
402 MBBLocations.resize((MBB->getNumber()+1)*2);
403 MBBLocations[MBB->getNumber()] = getCurrentPCValue();
404 if (MBB->hasAddressTaken())
405 TheJIT->addPointerToBasicBlock(MBB->getBasicBlock(),
406 (void*)getCurrentPCValue());
407 DEBUG(dbgs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
408 << (void*) getCurrentPCValue() << "]\n");
411 uintptr_t getConstantPoolEntryAddress(unsigned Entry) const override;
412 uintptr_t getJumpTableEntryAddress(unsigned Entry) const override;
415 getMachineBasicBlockAddress(MachineBasicBlock *MBB) const override {
416 assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
417 MBBLocations[MBB->getNumber()] && "MBB not emitted!");
418 return MBBLocations[MBB->getNumber()];
421 /// retryWithMoreMemory - Log a retry and deallocate all memory for the
422 /// given function. Increase the minimum allocation size so that we get
423 /// more memory next time.
424 void retryWithMoreMemory(MachineFunction &F);
426 /// deallocateMemForFunction - Deallocate all memory for the specified
428 void deallocateMemForFunction(const Function *F);
430 void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) override;
432 void emitLabel(MCSymbol *Label) override {
433 LabelLocations[Label] = getCurrentPCValue();
436 DenseMap<MCSymbol*, uintptr_t> *getLabelLocations() override {
437 return &LabelLocations;
440 uintptr_t getLabelAddress(MCSymbol *Label) const override {
441 assert(LabelLocations.count(Label) && "Label not emitted!");
442 return LabelLocations.find(Label)->second;
445 void setModuleInfo(MachineModuleInfo* Info) override {
450 void *getPointerToGlobal(GlobalValue *GV, void *Reference,
451 bool MayNeedFarStub);
452 void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference);
456 void CallSiteValueMapConfig::onDelete(JITResolverState *JRS, Function *F) {
457 JRS->EraseAllCallSitesForPrelocked(F);
460 void JITResolverState::EraseAllCallSitesForPrelocked(Function *F) {
461 FunctionToCallSitesMapTy::iterator F2C = FunctionToCallSitesMap.find(F);
462 if (F2C == FunctionToCallSitesMap.end())
464 StubToResolverMapTy &S2RMap = *StubToResolverMap;
465 for (void *C : F2C->second) {
466 S2RMap.UnregisterStubResolver(C);
467 bool Erased = CallSiteToFunctionMap.erase(C);
469 assert(Erased && "Missing call site->function mapping");
471 FunctionToCallSitesMap.erase(F2C);
474 void JITResolverState::EraseAllCallSitesPrelocked() {
475 StubToResolverMapTy &S2RMap = *StubToResolverMap;
476 for (CallSiteToFunctionMapTy::const_iterator
477 I = CallSiteToFunctionMap.begin(),
478 E = CallSiteToFunctionMap.end(); I != E; ++I) {
479 S2RMap.UnregisterStubResolver(I->first);
481 CallSiteToFunctionMap.clear();
482 FunctionToCallSitesMap.clear();
485 JITResolver::~JITResolver() {
486 // No need to lock because we're in the destructor, and state isn't shared.
487 state.EraseAllCallSitesPrelocked();
488 assert(!StubToResolverMap->ResolverHasStubs(this) &&
489 "Resolver destroyed with stubs still alive.");
492 /// getLazyFunctionStubIfAvailable - This returns a pointer to a function stub
493 /// if it has already been created.
494 void *JITResolver::getLazyFunctionStubIfAvailable(Function *F) {
495 MutexGuard locked(TheJIT->lock);
497 // If we already have a stub for this function, recycle it.
498 return state.getFunctionToLazyStubMap().lookup(F);
501 /// getFunctionStub - This returns a pointer to a function stub, creating
502 /// one on demand as needed.
503 void *JITResolver::getLazyFunctionStub(Function *F) {
504 MutexGuard locked(TheJIT->lock);
506 // If we already have a lazy stub for this function, recycle it.
507 void *&Stub = state.getFunctionToLazyStubMap()[F];
508 if (Stub) return Stub;
510 // Call the lazy resolver function if we are JIT'ing lazily. Otherwise we
511 // must resolve the symbol now.
512 void *Actual = TheJIT->isCompilingLazily()
513 ? (void *)(intptr_t)LazyResolverFn : (void *)nullptr;
515 // If this is an external declaration, attempt to resolve the address now
516 // to place in the stub.
517 if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage()) {
518 Actual = TheJIT->getPointerToFunction(F);
520 // If we resolved the symbol to a null address (eg. a weak external)
521 // don't emit a stub. Return a null pointer to the application.
522 if (!Actual) return nullptr;
525 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
526 JE.startGVStub(F, SL.Size, SL.Alignment);
527 // Codegen a new stub, calling the lazy resolver or the actual address of the
528 // external function, if it was resolved.
529 Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual, JE);
532 if (Actual != (void*)(intptr_t)LazyResolverFn) {
533 // If we are getting the stub for an external function, we really want the
534 // address of the stub in the GlobalAddressMap for the JIT, not the address
535 // of the external function.
536 TheJIT->updateGlobalMapping(F, Stub);
539 DEBUG(dbgs() << "JIT: Lazy stub emitted at [" << Stub << "] for function '"
540 << F->getName() << "'\n");
542 if (TheJIT->isCompilingLazily()) {
543 // Register this JITResolver as the one corresponding to this call site so
544 // JITCompilerFn will be able to find it.
545 StubToResolverMap->RegisterStubResolver(Stub, this);
547 // Finally, keep track of the stub-to-Function mapping so that the
548 // JITCompilerFn knows which function to compile!
549 state.AddCallSite(Stub, F);
550 } else if (!Actual) {
551 // If we are JIT'ing non-lazily but need to call a function that does not
552 // exist yet, add it to the JIT's work list so that we can fill in the
553 // stub address later.
554 assert(!isNonGhostDeclaration(F) && !F->hasAvailableExternallyLinkage() &&
555 "'Actual' should have been set above.");
556 TheJIT->addPendingFunction(F);
562 /// getGlobalValueIndirectSym - Return a lazy pointer containing the specified
564 void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
565 MutexGuard locked(TheJIT->lock);
567 // If we already have a stub for this global variable, recycle it.
568 void *&IndirectSym = state.getGlobalToIndirectSymMap()[GV];
569 if (IndirectSym) return IndirectSym;
571 // Otherwise, codegen a new indirect symbol.
572 IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
575 DEBUG(dbgs() << "JIT: Indirect symbol emitted at [" << IndirectSym
576 << "] for GV '" << GV->getName() << "'\n");
581 /// getExternalFunctionStub - Return a stub for the function at the
582 /// specified address, created lazily on demand.
583 void *JITResolver::getExternalFunctionStub(void *FnAddr) {
584 // If we already have a stub for this function, recycle it.
585 void *&Stub = ExternalFnToStubMap[FnAddr];
586 if (Stub) return Stub;
588 TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
589 JE.startGVStub(nullptr, SL.Size, SL.Alignment);
590 Stub = TheJIT->getJITInfo().emitFunctionStub(nullptr, FnAddr, JE);
593 DEBUG(dbgs() << "JIT: Stub emitted at [" << Stub
594 << "] for external function at '" << FnAddr << "'\n");
598 unsigned JITResolver::getGOTIndexForAddr(void* addr) {
599 unsigned idx = revGOTMap[addr];
601 idx = ++nextGOTIndex;
602 revGOTMap[addr] = idx;
603 DEBUG(dbgs() << "JIT: Adding GOT entry " << idx << " for addr ["
609 /// JITCompilerFn - This function is called when a lazy compilation stub has
610 /// been entered. It looks up which function this stub corresponds to, compiles
611 /// it if necessary, then returns the resultant function pointer.
612 void *JITResolver::JITCompilerFn(void *Stub) {
613 JITResolver *JR = StubToResolverMap->getResolverFromStub(Stub);
614 assert(JR && "Unable to find the corresponding JITResolver to the call site");
616 Function* F = nullptr;
617 void* ActualPtr = nullptr;
620 // Only lock for getting the Function. The call getPointerToFunction made
621 // in this function might trigger function materializing, which requires
622 // JIT lock to be unlocked.
623 MutexGuard locked(JR->TheJIT->lock);
625 // The address given to us for the stub may not be exactly right, it might
626 // be a little bit after the stub. As such, use upper_bound to find it.
627 std::pair<void*, Function*> I =
628 JR->state.LookupFunctionFromCallSite(Stub);
633 // If we have already code generated the function, just return the address.
634 void *Result = JR->TheJIT->getPointerToGlobalIfAvailable(F);
637 // Otherwise we don't have it, do lazy compilation now.
639 // If lazy compilation is disabled, emit a useful error message and abort.
640 if (!JR->TheJIT->isCompilingLazily()) {
641 report_fatal_error("LLVM JIT requested to do lazy compilation of"
643 + F->getName() + "' when lazy compiles are disabled!");
646 DEBUG(dbgs() << "JIT: Lazily resolving function '" << F->getName()
647 << "' In stub ptr = " << Stub << " actual ptr = "
648 << ActualPtr << "\n");
651 Result = JR->TheJIT->getPointerToFunction(F);
654 // Reacquire the lock to update the GOT map.
655 MutexGuard locked(JR->TheJIT->lock);
657 // We might like to remove the call site from the CallSiteToFunction map, but
658 // we can't do that! Multiple threads could be stuck, waiting to acquire the
659 // lock above. As soon as the 1st function finishes compiling the function,
660 // the next one will be released, and needs to be able to find the function it
663 // FIXME: We could rewrite all references to this stub if we knew them.
665 // What we will do is set the compiled function address to map to the
666 // same GOT entry as the stub so that later clients may update the GOT
667 // if they see it still using the stub address.
668 // Note: this is done so the Resolver doesn't have to manage GOT memory
669 // Do this without allocating map space if the target isn't using a GOT
670 if(JR->revGOTMap.find(Stub) != JR->revGOTMap.end())
671 JR->revGOTMap[Result] = JR->revGOTMap[Stub];
676 //===----------------------------------------------------------------------===//
680 static GlobalObject *getSimpleAliasee(Constant *C) {
681 C = C->stripPointerCasts();
682 return dyn_cast<GlobalObject>(C);
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 // We can only handle simple cases.
692 if (GlobalValue *GV = getSimpleAliasee(GA->getAliasee()))
693 return TheJIT->getPointerToGlobal(GV);
697 // If we have already compiled the function, return a pointer to its body.
698 Function *F = cast<Function>(V);
700 void *FnStub = Resolver.getLazyFunctionStubIfAvailable(F);
702 // Return the function stub if it's already created. We do this first so
703 // that we're returning the same address for the function as any previous
704 // call. TODO: Yes, this is wrong. The lazy stub isn't guaranteed to be
705 // close enough to call.
709 // If we know the target can handle arbitrary-distance calls, try to
710 // return a direct pointer.
711 if (!MayNeedFarStub) {
712 // If we have code, go ahead and return that.
713 void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
714 if (ResultPtr) return ResultPtr;
716 // If this is an external function pointer, we can force the JIT to
717 // 'compile' it, which really just adds it to the map.
718 if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage())
719 return TheJIT->getPointerToFunction(F);
722 // Otherwise, we may need a to emit a stub, and, conservatively, we always do
723 // so. Note that it's possible to return null from getLazyFunctionStub in the
724 // case of a weak extern that fails to resolve.
725 return Resolver.getLazyFunctionStub(F);
728 void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference) {
729 // Make sure GV is emitted first, and create a stub containing the fully
731 void *GVAddress = getPointerToGlobal(V, Reference, false);
732 void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
736 void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
737 if (DL.isUnknown()) return;
738 if (!BeforePrintingInsn) return;
740 const LLVMContext &Context = EmissionDetails.MF->getFunction()->getContext();
742 if (DL.getScope(Context) != nullptr && PrevDL != DL) {
743 JITEvent_EmittedFunctionDetails::LineStart NextLine;
744 NextLine.Address = getCurrentPCValue();
746 EmissionDetails.LineStarts.push_back(NextLine);
752 static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
753 const DataLayout *TD) {
754 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
755 if (Constants.empty()) return 0;
758 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
759 MachineConstantPoolEntry CPE = Constants[i];
760 unsigned AlignMask = CPE.getAlignment() - 1;
761 Size = (Size + AlignMask) & ~AlignMask;
762 Type *Ty = CPE.getType();
763 Size += TD->getTypeAllocSize(Ty);
768 void JITEmitter::startFunction(MachineFunction &F) {
769 DEBUG(dbgs() << "JIT: Starting CodeGen of Function "
770 << F.getName() << "\n");
772 uintptr_t ActualSize = 0;
773 // Set the memory writable, if it's not already
774 MemMgr->setMemoryWritable();
776 if (SizeEstimate > 0) {
777 // SizeEstimate will be non-zero on reallocation attempts.
778 ActualSize = SizeEstimate;
781 BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
783 BufferEnd = BufferBegin+ActualSize;
784 EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
786 // Ensure the constant pool/jump table info is at least 4-byte aligned.
789 emitConstantPool(F.getConstantPool());
790 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
791 initJumpTableInfo(MJTI);
793 // About to start emitting the machine code for the function.
794 emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
795 TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
796 EmittedFunctions[F.getFunction()].Code = CurBufferPtr;
798 MBBLocations.clear();
800 EmissionDetails.MF = &F;
801 EmissionDetails.LineStarts.clear();
804 bool JITEmitter::finishFunction(MachineFunction &F) {
805 if (CurBufferPtr == BufferEnd) {
806 // We must call endFunctionBody before retrying, because
807 // deallocateMemForFunction requires it.
808 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
809 retryWithMoreMemory(F);
813 if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
814 emitJumpTableInfo(MJTI);
816 // FnStart is the start of the text, not the start of the constant pool and
817 // other per-function data.
819 (uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
821 // FnEnd is the end of the function's machine code.
822 uint8_t *FnEnd = CurBufferPtr;
824 if (!Relocations.empty()) {
825 CurFn = F.getFunction();
826 NumRelos += Relocations.size();
828 // Resolve the relocations to concrete pointers.
829 for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
830 MachineRelocation &MR = Relocations[i];
831 void *ResultPtr = nullptr;
832 if (!MR.letTargetResolve()) {
833 if (MR.isExternalSymbol()) {
834 ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
836 DEBUG(dbgs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
837 << ResultPtr << "]\n");
839 // If the target REALLY wants a stub for this function, emit it now.
840 if (MR.mayNeedFarStub()) {
841 ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
843 } else if (MR.isGlobalValue()) {
844 ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
845 BufferBegin+MR.getMachineCodeOffset(),
846 MR.mayNeedFarStub());
847 } else if (MR.isIndirectSymbol()) {
848 ResultPtr = getPointerToGVIndirectSym(
849 MR.getGlobalValue(), BufferBegin+MR.getMachineCodeOffset());
850 } else if (MR.isBasicBlock()) {
851 ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
852 } else if (MR.isConstantPoolIndex()) {
854 (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
856 assert(MR.isJumpTableIndex());
857 ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
860 MR.setResultPointer(ResultPtr);
863 // if we are managing the GOT and the relocation wants an index,
865 if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
866 unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
868 if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
869 DEBUG(dbgs() << "JIT: GOT was out of date for " << ResultPtr
870 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
872 ((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
878 TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
879 Relocations.size(), MemMgr->getGOTBase());
882 // Update the GOT entry for F to point to the new code.
883 if (MemMgr->isManagingGOT()) {
884 unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
885 if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
886 DEBUG(dbgs() << "JIT: GOT was out of date for " << (void*)BufferBegin
887 << " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
889 ((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
893 // CurBufferPtr may have moved beyond FnEnd, due to memory allocation for
894 // global variables that were referenced in the relocations.
895 MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
897 if (CurBufferPtr == BufferEnd) {
898 retryWithMoreMemory(F);
901 // Now that we've succeeded in emitting the function, reset the
902 // SizeEstimate back down to zero.
906 BufferBegin = CurBufferPtr = nullptr;
907 NumBytes += FnEnd-FnStart;
909 // Invalidate the icache if necessary.
910 sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
912 TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
915 // Reset the previous debug location.
918 DEBUG(dbgs() << "JIT: Finished CodeGen of [" << (void*)FnStart
919 << "] Function: " << F.getName()
920 << ": " << (FnEnd-FnStart) << " bytes of text, "
921 << Relocations.size() << " relocations\n");
924 ConstPoolAddresses.clear();
926 // Mark code region readable and executable if it's not so already.
927 MemMgr->setMemoryExecutable();
930 dbgs() << "JIT: Binary code:\n";
931 uint8_t* q = FnStart;
932 for (int i = 0; q < FnEnd; q += 4, ++i) {
936 dbgs() << "JIT: " << (long)(q - FnStart) << ": ";
938 for (int j = 3; j >= 0; --j) {
942 dbgs() << (unsigned short)q[j];
959 void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
960 DEBUG(dbgs() << "JIT: Ran out of space for native code. Reattempting.\n");
961 Relocations.clear(); // Clear the old relocations or we'll reapply them.
962 ConstPoolAddresses.clear();
964 deallocateMemForFunction(F.getFunction());
965 // Try again with at least twice as much free space.
966 SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
968 for (MachineFunction::iterator MBB = F.begin(), E = F.end(); MBB != E; ++MBB){
969 if (MBB->hasAddressTaken())
970 TheJIT->clearPointerToBasicBlock(MBB->getBasicBlock());
974 /// deallocateMemForFunction - Deallocate all memory for the specified
975 /// function body. Also drop any references the function has to stubs.
976 /// May be called while the Function is being destroyed inside ~Value().
977 void JITEmitter::deallocateMemForFunction(const Function *F) {
978 ValueMap<const Function *, EmittedCode, EmittedFunctionConfig>::iterator
979 Emitted = EmittedFunctions.find(F);
980 if (Emitted != EmittedFunctions.end()) {
981 MemMgr->deallocateFunctionBody(Emitted->second.FunctionBody);
982 TheJIT->NotifyFreeingMachineCode(Emitted->second.Code);
984 EmittedFunctions.erase(Emitted);
989 void *JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
991 return JITCodeEmitter::allocateSpace(Size, Alignment);
993 // create a new memory block if there is no active one.
994 // care must be taken so that BufferBegin is invalidated when a
996 BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
997 BufferEnd = BufferBegin+Size;
1001 void *JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
1002 // Delegate this call through the memory manager.
1003 return MemMgr->allocateGlobal(Size, Alignment);
1006 void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
1007 if (TheJIT->getJITInfo().hasCustomConstantPool())
1010 const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
1011 if (Constants.empty()) return;
1013 unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getDataLayout());
1014 unsigned Align = MCP->getConstantPoolAlignment();
1015 ConstantPoolBase = allocateSpace(Size, Align);
1018 if (!ConstantPoolBase) return; // Buffer overflow.
1020 DEBUG(dbgs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
1021 << "] (size: " << Size << ", alignment: " << Align << ")\n");
1023 // Initialize the memory for all of the constant pool entries.
1024 unsigned Offset = 0;
1025 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1026 MachineConstantPoolEntry CPE = Constants[i];
1027 unsigned AlignMask = CPE.getAlignment() - 1;
1028 Offset = (Offset + AlignMask) & ~AlignMask;
1030 uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
1031 ConstPoolAddresses.push_back(CAddr);
1032 if (CPE.isMachineConstantPoolEntry()) {
1033 // FIXME: add support to lower machine constant pool values into bytes!
1034 report_fatal_error("Initialize memory with machine specific constant pool"
1035 "entry has not been implemented!");
1037 TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
1038 DEBUG(dbgs() << "JIT: CP" << i << " at [0x";
1039 dbgs().write_hex(CAddr) << "]\n");
1041 Type *Ty = CPE.Val.ConstVal->getType();
1042 Offset += TheJIT->getDataLayout()->getTypeAllocSize(Ty);
1046 void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
1047 if (TheJIT->getJITInfo().hasCustomJumpTables())
1049 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline)
1052 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1053 if (JT.empty()) return;
1055 unsigned NumEntries = 0;
1056 for (unsigned i = 0, e = JT.size(); i != e; ++i)
1057 NumEntries += JT[i].MBBs.size();
1059 unsigned EntrySize = MJTI->getEntrySize(*TheJIT->getDataLayout());
1061 // Just allocate space for all the jump tables now. We will fix up the actual
1062 // MBB entries in the tables after we emit the code for each block, since then
1063 // we will know the final locations of the MBBs in memory.
1065 JumpTableBase = allocateSpace(NumEntries * EntrySize,
1066 MJTI->getEntryAlignment(*TheJIT->getDataLayout()));
1069 void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
1070 if (TheJIT->getJITInfo().hasCustomJumpTables())
1073 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1074 if (JT.empty() || !JumpTableBase) return;
1077 switch (MJTI->getEntryKind()) {
1078 case MachineJumpTableInfo::EK_Inline:
1080 case MachineJumpTableInfo::EK_BlockAddress: {
1081 // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1083 assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == sizeof(void*) &&
1086 // For each jump table, map each target in the jump table to the address of
1087 // an emitted MachineBasicBlock.
1088 intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
1090 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1091 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1092 // Store the address of the basic block for this jump table slot in the
1093 // memory we allocated for the jump table in 'initJumpTableInfo'
1094 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
1095 *SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
1100 case MachineJumpTableInfo::EK_Custom32:
1101 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1102 case MachineJumpTableInfo::EK_LabelDifference32: {
1103 assert(MJTI->getEntrySize(*TheJIT->getDataLayout()) == 4&&"Cross JIT'ing?");
1104 // For each jump table, place the offset from the beginning of the table
1105 // to the target address.
1106 int *SlotPtr = (int*)JumpTableBase;
1108 for (unsigned i = 0, e = JT.size(); i != e; ++i) {
1109 const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
1110 // Store the offset of the basic block for this jump table slot in the
1111 // memory we allocated for the jump table in 'initJumpTableInfo'
1112 uintptr_t Base = (uintptr_t)SlotPtr;
1113 for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
1114 uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
1115 /// FIXME: USe EntryKind instead of magic "getPICJumpTableEntry" hook.
1116 *SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
1121 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1123 "JT Info emission not implemented for GPRel64BlockAddress yet.");
1127 void JITEmitter::startGVStub(const GlobalValue* GV,
1128 unsigned StubSize, unsigned Alignment) {
1129 SavedBufferBegin = BufferBegin;
1130 SavedBufferEnd = BufferEnd;
1131 SavedCurBufferPtr = CurBufferPtr;
1133 BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
1134 BufferEnd = BufferBegin+StubSize+1;
1137 void JITEmitter::startGVStub(void *Buffer, unsigned StubSize) {
1138 SavedBufferBegin = BufferBegin;
1139 SavedBufferEnd = BufferEnd;
1140 SavedCurBufferPtr = CurBufferPtr;
1142 BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
1143 BufferEnd = BufferBegin+StubSize+1;
1146 void JITEmitter::finishGVStub() {
1147 assert(CurBufferPtr != BufferEnd && "Stub overflowed allocated space.");
1148 NumBytes += getCurrentPCOffset();
1149 BufferBegin = SavedBufferBegin;
1150 BufferEnd = SavedBufferEnd;
1151 CurBufferPtr = SavedCurBufferPtr;
1154 void *JITEmitter::allocIndirectGV(const GlobalValue *GV,
1155 const uint8_t *Buffer, size_t Size,
1156 unsigned Alignment) {
1157 uint8_t *IndGV = MemMgr->allocateStub(GV, Size, Alignment);
1158 memcpy(IndGV, Buffer, Size);
1162 // getConstantPoolEntryAddress - Return the address of the 'ConstantNum' entry
1163 // in the constant pool that was last emitted with the 'emitConstantPool'
1166 uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
1167 assert(ConstantNum < ConstantPool->getConstants().size() &&
1168 "Invalid ConstantPoolIndex!");
1169 return ConstPoolAddresses[ConstantNum];
1172 // getJumpTableEntryAddress - Return the address of the JumpTable with index
1173 // 'Index' in the jumpp table that was last initialized with 'initJumpTableInfo'
1175 uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
1176 const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
1177 assert(Index < JT.size() && "Invalid jump table index!");
1179 unsigned EntrySize = JumpTable->getEntrySize(*TheJIT->getDataLayout());
1181 unsigned Offset = 0;
1182 for (unsigned i = 0; i < Index; ++i)
1183 Offset += JT[i].MBBs.size();
1185 Offset *= EntrySize;
1187 return (uintptr_t)((char *)JumpTableBase + Offset);
1190 void JITEmitter::EmittedFunctionConfig::onDelete(
1191 JITEmitter *Emitter, const Function *F) {
1192 Emitter->deallocateMemForFunction(F);
1194 void JITEmitter::EmittedFunctionConfig::onRAUW(
1195 JITEmitter *, const Function*, const Function*) {
1196 llvm_unreachable("The JIT doesn't know how to handle a"
1197 " RAUW on a value it has emitted.");
1201 //===----------------------------------------------------------------------===//
1202 // Public interface to this file
1203 //===----------------------------------------------------------------------===//
1205 JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
1206 TargetMachine &tm) {
1207 return new JITEmitter(jit, JMM, tm);
1210 // getPointerToFunctionOrStub - If the specified function has been
1211 // code-gen'd, return a pointer to the function. If not, compile it, or use
1212 // a stub to implement lazy compilation if available.
1214 void *JIT::getPointerToFunctionOrStub(Function *F) {
1215 // If we have already code generated the function, just return the address.
1216 if (void *Addr = getPointerToGlobalIfAvailable(F))
1219 // Get a stub if the target supports it.
1220 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
1221 return JE->getJITResolver().getLazyFunctionStub(F);
1224 void JIT::updateFunctionStubUnlocked(Function *F) {
1225 // Get the empty stub we generated earlier.
1226 JITEmitter *JE = static_cast<JITEmitter*>(getCodeEmitter());
1227 void *Stub = JE->getJITResolver().getLazyFunctionStub(F);
1228 void *Addr = getPointerToGlobalIfAvailable(F);
1229 assert(Addr != Stub && "Function must have non-stub address to be updated.");
1231 // Tell the target jit info to rewrite the stub at the specified address,
1232 // rather than creating a new one.
1233 TargetJITInfo::StubLayout layout = getJITInfo().getStubLayout();
1234 JE->startGVStub(Stub, layout.Size);
1235 getJITInfo().emitFunctionStub(F, Addr, *getCodeEmitter());
1239 /// freeMachineCodeForFunction - release machine code memory for given Function.
1241 void JIT::freeMachineCodeForFunction(Function *F) {
1242 // Delete translation for this from the ExecutionEngine, so it will get
1243 // retranslated next time it is used.
1244 updateGlobalMapping(F, nullptr);
1246 // Free the actual memory for the function body and related stuff.
1247 static_cast<JITEmitter*>(JCE)->deallocateMemForFunction(F);