#define DEBUG_TYPE "jit"
#include "JIT.h"
#include "JITDebugRegisterer.h"
#include "JITDwarfEmitter.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Constants.h"
#include "llvm/Module.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Analysis/DebugInfo.h"
#include "llvm/CodeGen/JITCodeEmitter.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineCodeInfo.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineJumpTableInfo.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineRelocation.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/ExecutionEngine/JITEventListener.h"
#include "llvm/ExecutionEngine/JITMemoryManager.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetJITInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MutexGuard.h"
#include "llvm/Support/ValueHandle.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Disassembler.h"
#include "llvm/System/Memory.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/ValueMap.h"
#include <algorithm>
#ifndef NDEBUG
#include <iomanip>
#endif
using namespace llvm;
STATISTIC(NumBytes, "Number of bytes of machine code compiled");
STATISTIC(NumRelos, "Number of relocations applied");
STATISTIC(NumRetries, "Number of retries with more memory");
static bool isNonGhostDeclaration(const Function *F) {
return F->isDeclaration() && !F->isMaterializable();
}
namespace {
class JITEmitter;
class JITResolverState;
template<typename ValueTy>
struct NoRAUWValueMapConfig : public ValueMapConfig<ValueTy> {
typedef JITResolverState *ExtraData;
static void onRAUW(JITResolverState *, Value *Old, Value *New) {
assert(false && "The JIT doesn't know how to handle a"
" RAUW on a value it has emitted.");
}
};
struct CallSiteValueMapConfig : public NoRAUWValueMapConfig<Function*> {
typedef JITResolverState *ExtraData;
static void onDelete(JITResolverState *JRS, Function *F);
};
class JITResolverState {
public:
typedef ValueMap<Function*, void*, NoRAUWValueMapConfig<Function*> >
FunctionToLazyStubMapTy;
typedef std::map<void*, AssertingVH<Function> > CallSiteToFunctionMapTy;
typedef ValueMap<Function *, SmallPtrSet<void*, 1>,
CallSiteValueMapConfig> FunctionToCallSitesMapTy;
typedef std::map<AssertingVH<GlobalValue>, void*> GlobalToIndirectSymMapTy;
private:
FunctionToLazyStubMapTy FunctionToLazyStubMap;
CallSiteToFunctionMapTy CallSiteToFunctionMap;
FunctionToCallSitesMapTy FunctionToCallSitesMap;
GlobalToIndirectSymMapTy GlobalToIndirectSymMap;
JIT *TheJIT;
public:
JITResolverState(JIT *jit) : FunctionToLazyStubMap(this),
FunctionToCallSitesMap(this),
TheJIT(jit) {}
FunctionToLazyStubMapTy& getFunctionToLazyStubMap(
const MutexGuard& locked) {
assert(locked.holds(TheJIT->lock));
return FunctionToLazyStubMap;
}
GlobalToIndirectSymMapTy& getGlobalToIndirectSymMap(const MutexGuard& locked) {
assert(locked.holds(TheJIT->lock));
return GlobalToIndirectSymMap;
}
pair<void *, Function *> LookupFunctionFromCallSite(
const MutexGuard &locked, void *CallSite) const {
assert(locked.holds(TheJIT->lock));
CallSiteToFunctionMapTy::const_iterator I =
CallSiteToFunctionMap.upper_bound(CallSite);
assert(I != CallSiteToFunctionMap.begin() &&
"This is not a known call site!");
--I;
return *I;
}
void AddCallSite(const MutexGuard &locked, void *CallSite, Function *F) {
assert(locked.holds(TheJIT->lock));
bool Inserted = CallSiteToFunctionMap.insert(
std::make_pair(CallSite, F)).second;
(void)Inserted;
assert(Inserted && "Pair was already in CallSiteToFunctionMap");
FunctionToCallSitesMap[F].insert(CallSite);
}
void EraseAllCallSitesForPrelocked(Function *F);
void EraseAllCallSitesPrelocked();
};
class JITResolver {
typedef JITResolverState::FunctionToLazyStubMapTy FunctionToLazyStubMapTy;
typedef JITResolverState::CallSiteToFunctionMapTy CallSiteToFunctionMapTy;
typedef JITResolverState::GlobalToIndirectSymMapTy GlobalToIndirectSymMapTy;
TargetJITInfo::LazyResolverFn LazyResolverFn;
JITResolverState state;
std::map<void*, void*> ExternalFnToStubMap;
std::map<void*, unsigned> revGOTMap;
unsigned nextGOTIndex;
JITEmitter &JE;
JIT *TheJIT;
public:
explicit JITResolver(JIT &jit, JITEmitter &je)
: state(&jit), nextGOTIndex(0), JE(je), TheJIT(&jit) {
LazyResolverFn = jit.getJITInfo().getLazyResolverFunction(JITCompilerFn);
}
~JITResolver();
void *getLazyFunctionStubIfAvailable(Function *F);
void *getLazyFunctionStub(Function *F);
void *getExternalFunctionStub(void *FnAddr);
void *getGlobalValueIndirectSym(GlobalValue *V, void *GVAddress);
unsigned getGOTIndexForAddr(void *addr);
static void *JITCompilerFn(void *Stub);
};
class StubToResolverMapTy {
std::map<void*, JITResolver*> Map;
mutable sys::Mutex Lock;
public:
void RegisterStubResolver(void *Stub, JITResolver *Resolver) {
MutexGuard guard(Lock);
Map.insert(std::make_pair(Stub, Resolver));
}
void UnregisterStubResolver(void *Stub) {
MutexGuard guard(Lock);
Map.erase(Stub);
}
JITResolver *getResolverFromStub(void *Stub) const {
MutexGuard guard(Lock);
std::map<void*, JITResolver*>::const_iterator I = Map.upper_bound(Stub);
assert(I != Map.begin() && "This is not a known stub!");
--I;
return I->second;
}
bool ResolverHasStubs(JITResolver* Resolver) const {
MutexGuard guard(Lock);
for (std::map<void*, JITResolver*>::const_iterator I = Map.begin(),
E = Map.end(); I != E; ++I) {
if (I->second == Resolver)
return true;
}
return false;
}
};
ManagedStatic<StubToResolverMapTy> StubToResolverMap;
class JITEmitter : public JITCodeEmitter {
JITMemoryManager *MemMgr;
uint8_t *SavedBufferBegin, *SavedBufferEnd, *SavedCurBufferPtr;
uintptr_t SizeEstimate;
std::vector<MachineRelocation> Relocations;
std::vector<uintptr_t> MBBLocations;
MachineConstantPool *ConstantPool;
void *ConstantPoolBase;
SmallVector<uintptr_t, 8> ConstPoolAddresses;
MachineJumpTableInfo *JumpTable;
void *JumpTableBase;
JITResolver Resolver;
OwningPtr<JITDwarfEmitter> DE;
OwningPtr<JITDebugRegisterer> DR;
DenseMap<MCSymbol*, uintptr_t> LabelLocations;
MachineModuleInfo* MMI;
const Function *CurFn;
JITEvent_EmittedFunctionDetails EmissionDetails;
struct EmittedCode {
void *FunctionBody; void *Code; void *ExceptionTable;
EmittedCode() : FunctionBody(0), Code(0), ExceptionTable(0) {}
};
struct EmittedFunctionConfig : public ValueMapConfig<const Function*> {
typedef JITEmitter *ExtraData;
static void onDelete(JITEmitter *, const Function*);
static void onRAUW(JITEmitter *, const Function*, const Function*);
};
ValueMap<const Function *, EmittedCode,
EmittedFunctionConfig> EmittedFunctions;
DebugLoc PrevDL;
JIT *TheJIT;
public:
JITEmitter(JIT &jit, JITMemoryManager *JMM, TargetMachine &TM)
: SizeEstimate(0), Resolver(jit, *this), MMI(0), CurFn(0),
EmittedFunctions(this), TheJIT(&jit) {
MemMgr = JMM ? JMM : JITMemoryManager::CreateDefaultMemManager();
if (jit.getJITInfo().needsGOT()) {
MemMgr->AllocateGOT();
DEBUG(dbgs() << "JIT is managing a GOT\n");
}
if (JITExceptionHandling || JITEmitDebugInfo) {
DE.reset(new JITDwarfEmitter(jit));
}
if (JITEmitDebugInfo) {
DR.reset(new JITDebugRegisterer(TM));
}
}
~JITEmitter() {
delete MemMgr;
}
static inline bool classof(const MachineCodeEmitter*) { return true; }
JITResolver &getJITResolver() { return Resolver; }
virtual void startFunction(MachineFunction &F);
virtual bool finishFunction(MachineFunction &F);
void emitConstantPool(MachineConstantPool *MCP);
void initJumpTableInfo(MachineJumpTableInfo *MJTI);
void emitJumpTableInfo(MachineJumpTableInfo *MJTI);
void startGVStub(const GlobalValue* GV,
unsigned StubSize, unsigned Alignment = 1);
void startGVStub(void *Buffer, unsigned StubSize);
void finishGVStub();
virtual void *allocIndirectGV(const GlobalValue *GV,
const uint8_t *Buffer, size_t Size,
unsigned Alignment);
virtual void *allocateSpace(uintptr_t Size, unsigned Alignment);
virtual void *allocateGlobal(uintptr_t Size, unsigned Alignment);
virtual void addRelocation(const MachineRelocation &MR) {
Relocations.push_back(MR);
}
virtual void StartMachineBasicBlock(MachineBasicBlock *MBB) {
if (MBBLocations.size() <= (unsigned)MBB->getNumber())
MBBLocations.resize((MBB->getNumber()+1)*2);
MBBLocations[MBB->getNumber()] = getCurrentPCValue();
if (MBB->hasAddressTaken())
TheJIT->addPointerToBasicBlock(MBB->getBasicBlock(),
(void*)getCurrentPCValue());
DEBUG(dbgs() << "JIT: Emitting BB" << MBB->getNumber() << " at ["
<< (void*) getCurrentPCValue() << "]\n");
}
virtual uintptr_t getConstantPoolEntryAddress(unsigned Entry) const;
virtual uintptr_t getJumpTableEntryAddress(unsigned Entry) const;
virtual uintptr_t getMachineBasicBlockAddress(MachineBasicBlock *MBB) const{
assert(MBBLocations.size() > (unsigned)MBB->getNumber() &&
MBBLocations[MBB->getNumber()] && "MBB not emitted!");
return MBBLocations[MBB->getNumber()];
}
void retryWithMoreMemory(MachineFunction &F);
void deallocateMemForFunction(const Function *F);
virtual void processDebugLoc(DebugLoc DL, bool BeforePrintingInsn);
virtual void emitLabel(MCSymbol *Label) {
LabelLocations[Label] = getCurrentPCValue();
}
virtual DenseMap<MCSymbol*, uintptr_t> *getLabelLocations() {
return &LabelLocations;
}
virtual uintptr_t getLabelAddress(MCSymbol *Label) const {
assert(LabelLocations.count(Label) && "Label not emitted!");
return LabelLocations.find(Label)->second;
}
virtual void setModuleInfo(MachineModuleInfo* Info) {
MMI = Info;
if (DE.get()) DE->setModuleInfo(Info);
}
private:
void *getPointerToGlobal(GlobalValue *GV, void *Reference,
bool MayNeedFarStub);
void *getPointerToGVIndirectSym(GlobalValue *V, void *Reference);
};
}
void CallSiteValueMapConfig::onDelete(JITResolverState *JRS, Function *F) {
JRS->EraseAllCallSitesForPrelocked(F);
}
void JITResolverState::EraseAllCallSitesForPrelocked(Function *F) {
FunctionToCallSitesMapTy::iterator F2C = FunctionToCallSitesMap.find(F);
if (F2C == FunctionToCallSitesMap.end())
return;
StubToResolverMapTy &S2RMap = *StubToResolverMap;
for (SmallPtrSet<void*, 1>::const_iterator I = F2C->second.begin(),
E = F2C->second.end(); I != E; ++I) {
S2RMap.UnregisterStubResolver(*I);
bool Erased = CallSiteToFunctionMap.erase(*I);
(void)Erased;
assert(Erased && "Missing call site->function mapping");
}
FunctionToCallSitesMap.erase(F2C);
}
void JITResolverState::EraseAllCallSitesPrelocked() {
StubToResolverMapTy &S2RMap = *StubToResolverMap;
for (CallSiteToFunctionMapTy::const_iterator
I = CallSiteToFunctionMap.begin(),
E = CallSiteToFunctionMap.end(); I != E; ++I) {
S2RMap.UnregisterStubResolver(I->first);
}
CallSiteToFunctionMap.clear();
FunctionToCallSitesMap.clear();
}
JITResolver::~JITResolver() {
state.EraseAllCallSitesPrelocked();
assert(!StubToResolverMap->ResolverHasStubs(this) &&
"Resolver destroyed with stubs still alive.");
}
void *JITResolver::getLazyFunctionStubIfAvailable(Function *F) {
MutexGuard locked(TheJIT->lock);
return state.getFunctionToLazyStubMap(locked).lookup(F);
}
void *JITResolver::getLazyFunctionStub(Function *F) {
MutexGuard locked(TheJIT->lock);
void *&Stub = state.getFunctionToLazyStubMap(locked)[F];
if (Stub) return Stub;
void *Actual = TheJIT->isCompilingLazily()
? (void *)(intptr_t)LazyResolverFn : (void *)0;
if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage()) {
Actual = TheJIT->getPointerToFunction(F);
if (!Actual) return 0;
}
TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
JE.startGVStub(F, SL.Size, SL.Alignment);
Stub = TheJIT->getJITInfo().emitFunctionStub(F, Actual, JE);
JE.finishGVStub();
if (Actual != (void*)(intptr_t)LazyResolverFn) {
TheJIT->updateGlobalMapping(F, Stub);
}
DEBUG(dbgs() << "JIT: Lazy stub emitted at [" << Stub << "] for function '"
<< F->getName() << "'\n");
if (TheJIT->isCompilingLazily()) {
StubToResolverMap->RegisterStubResolver(Stub, this);
state.AddCallSite(locked, Stub, F);
} else if (!Actual) {
assert(!isNonGhostDeclaration(F) && !F->hasAvailableExternallyLinkage() &&
"'Actual' should have been set above.");
TheJIT->addPendingFunction(F);
}
return Stub;
}
void *JITResolver::getGlobalValueIndirectSym(GlobalValue *GV, void *GVAddress) {
MutexGuard locked(TheJIT->lock);
void *&IndirectSym = state.getGlobalToIndirectSymMap(locked)[GV];
if (IndirectSym) return IndirectSym;
IndirectSym = TheJIT->getJITInfo().emitGlobalValueIndirectSym(GV, GVAddress,
JE);
DEBUG(dbgs() << "JIT: Indirect symbol emitted at [" << IndirectSym
<< "] for GV '" << GV->getName() << "'\n");
return IndirectSym;
}
void *JITResolver::getExternalFunctionStub(void *FnAddr) {
void *&Stub = ExternalFnToStubMap[FnAddr];
if (Stub) return Stub;
TargetJITInfo::StubLayout SL = TheJIT->getJITInfo().getStubLayout();
JE.startGVStub(0, SL.Size, SL.Alignment);
Stub = TheJIT->getJITInfo().emitFunctionStub(0, FnAddr, JE);
JE.finishGVStub();
DEBUG(dbgs() << "JIT: Stub emitted at [" << Stub
<< "] for external function at '" << FnAddr << "'\n");
return Stub;
}
unsigned JITResolver::getGOTIndexForAddr(void* addr) {
unsigned idx = revGOTMap[addr];
if (!idx) {
idx = ++nextGOTIndex;
revGOTMap[addr] = idx;
DEBUG(dbgs() << "JIT: Adding GOT entry " << idx << " for addr ["
<< addr << "]\n");
}
return idx;
}
void *JITResolver::JITCompilerFn(void *Stub) {
JITResolver *JR = StubToResolverMap->getResolverFromStub(Stub);
assert(JR && "Unable to find the corresponding JITResolver to the call site");
Function* F = 0;
void* ActualPtr = 0;
{
MutexGuard locked(JR->TheJIT->lock);
pair<void*, Function*> I =
JR->state.LookupFunctionFromCallSite(locked, Stub);
F = I.second;
ActualPtr = I.first;
}
void *Result = JR->TheJIT->getPointerToGlobalIfAvailable(F);
if (!Result) {
if (!JR->TheJIT->isCompilingLazily()) {
report_fatal_error("LLVM JIT requested to do lazy compilation of function '"
+ F->getName() + "' when lazy compiles are disabled!");
}
DEBUG(dbgs() << "JIT: Lazily resolving function '" << F->getName()
<< "' In stub ptr = " << Stub << " actual ptr = "
<< ActualPtr << "\n");
Result = JR->TheJIT->getPointerToFunction(F);
}
MutexGuard locked(JR->TheJIT->lock);
if(JR->revGOTMap.find(Stub) != JR->revGOTMap.end())
JR->revGOTMap[Result] = JR->revGOTMap[Stub];
return Result;
}
void *JITEmitter::getPointerToGlobal(GlobalValue *V, void *Reference,
bool MayNeedFarStub) {
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
return TheJIT->getOrEmitGlobalVariable(GV);
if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
return TheJIT->getPointerToGlobal(GA->resolveAliasedGlobal(false));
Function *F = cast<Function>(V);
void *FnStub = Resolver.getLazyFunctionStubIfAvailable(F);
if (FnStub) {
return FnStub;
}
if (!MayNeedFarStub) {
void *ResultPtr = TheJIT->getPointerToGlobalIfAvailable(F);
if (ResultPtr) return ResultPtr;
if (isNonGhostDeclaration(F) || F->hasAvailableExternallyLinkage())
return TheJIT->getPointerToFunction(F);
}
return Resolver.getLazyFunctionStub(F);
}
void *JITEmitter::getPointerToGVIndirectSym(GlobalValue *V, void *Reference) {
void *GVAddress = getPointerToGlobal(V, Reference, false);
void *StubAddr = Resolver.getGlobalValueIndirectSym(V, GVAddress);
return StubAddr;
}
void JITEmitter::processDebugLoc(DebugLoc DL, bool BeforePrintingInsn) {
if (DL.isUnknown()) return;
if (!BeforePrintingInsn) return;
const LLVMContext &Context = EmissionDetails.MF->getFunction()->getContext();
if (DL.getScope(Context) != 0 && PrevDL != DL) {
JITEvent_EmittedFunctionDetails::LineStart NextLine;
NextLine.Address = getCurrentPCValue();
NextLine.Loc = DL;
EmissionDetails.LineStarts.push_back(NextLine);
}
PrevDL = DL;
}
static unsigned GetConstantPoolSizeInBytes(MachineConstantPool *MCP,
const TargetData *TD) {
const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
if (Constants.empty()) return 0;
unsigned Size = 0;
for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
MachineConstantPoolEntry CPE = Constants[i];
unsigned AlignMask = CPE.getAlignment() - 1;
Size = (Size + AlignMask) & ~AlignMask;
const Type *Ty = CPE.getType();
Size += TD->getTypeAllocSize(Ty);
}
return Size;
}
void JITEmitter::startFunction(MachineFunction &F) {
DEBUG(dbgs() << "JIT: Starting CodeGen of Function "
<< F.getFunction()->getName() << "\n");
uintptr_t ActualSize = 0;
MemMgr->setMemoryWritable();
if (SizeEstimate > 0) {
ActualSize = SizeEstimate;
}
BufferBegin = CurBufferPtr = MemMgr->startFunctionBody(F.getFunction(),
ActualSize);
BufferEnd = BufferBegin+ActualSize;
EmittedFunctions[F.getFunction()].FunctionBody = BufferBegin;
emitAlignment(16);
emitConstantPool(F.getConstantPool());
if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
initJumpTableInfo(MJTI);
emitAlignment(std::max(F.getFunction()->getAlignment(), 8U));
TheJIT->updateGlobalMapping(F.getFunction(), CurBufferPtr);
EmittedFunctions[F.getFunction()].Code = CurBufferPtr;
MBBLocations.clear();
EmissionDetails.MF = &F;
EmissionDetails.LineStarts.clear();
}
bool JITEmitter::finishFunction(MachineFunction &F) {
if (CurBufferPtr == BufferEnd) {
MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
retryWithMoreMemory(F);
return true;
}
if (MachineJumpTableInfo *MJTI = F.getJumpTableInfo())
emitJumpTableInfo(MJTI);
uint8_t *FnStart =
(uint8_t *)TheJIT->getPointerToGlobalIfAvailable(F.getFunction());
uint8_t *FnEnd = CurBufferPtr;
if (!Relocations.empty()) {
CurFn = F.getFunction();
NumRelos += Relocations.size();
for (unsigned i = 0, e = Relocations.size(); i != e; ++i) {
MachineRelocation &MR = Relocations[i];
void *ResultPtr = 0;
if (!MR.letTargetResolve()) {
if (MR.isExternalSymbol()) {
ResultPtr = TheJIT->getPointerToNamedFunction(MR.getExternalSymbol(),
false);
DEBUG(dbgs() << "JIT: Map \'" << MR.getExternalSymbol() << "\' to ["
<< ResultPtr << "]\n");
if (MR.mayNeedFarStub()) {
ResultPtr = Resolver.getExternalFunctionStub(ResultPtr);
}
} else if (MR.isGlobalValue()) {
ResultPtr = getPointerToGlobal(MR.getGlobalValue(),
BufferBegin+MR.getMachineCodeOffset(),
MR.mayNeedFarStub());
} else if (MR.isIndirectSymbol()) {
ResultPtr = getPointerToGVIndirectSym(
MR.getGlobalValue(), BufferBegin+MR.getMachineCodeOffset());
} else if (MR.isBasicBlock()) {
ResultPtr = (void*)getMachineBasicBlockAddress(MR.getBasicBlock());
} else if (MR.isConstantPoolIndex()) {
ResultPtr = (void*)getConstantPoolEntryAddress(MR.getConstantPoolIndex());
} else {
assert(MR.isJumpTableIndex());
ResultPtr=(void*)getJumpTableEntryAddress(MR.getJumpTableIndex());
}
MR.setResultPointer(ResultPtr);
}
if (MR.isGOTRelative() && MemMgr->isManagingGOT()) {
unsigned idx = Resolver.getGOTIndexForAddr(ResultPtr);
MR.setGOTIndex(idx);
if (((void**)MemMgr->getGOTBase())[idx] != ResultPtr) {
DEBUG(dbgs() << "JIT: GOT was out of date for " << ResultPtr
<< " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
<< "\n");
((void**)MemMgr->getGOTBase())[idx] = ResultPtr;
}
}
}
CurFn = 0;
TheJIT->getJITInfo().relocate(BufferBegin, &Relocations[0],
Relocations.size(), MemMgr->getGOTBase());
}
if (MemMgr->isManagingGOT()) {
unsigned idx = Resolver.getGOTIndexForAddr((void*)BufferBegin);
if (((void**)MemMgr->getGOTBase())[idx] != (void*)BufferBegin) {
DEBUG(dbgs() << "JIT: GOT was out of date for " << (void*)BufferBegin
<< " pointing at " << ((void**)MemMgr->getGOTBase())[idx]
<< "\n");
((void**)MemMgr->getGOTBase())[idx] = (void*)BufferBegin;
}
}
MemMgr->endFunctionBody(F.getFunction(), BufferBegin, CurBufferPtr);
if (CurBufferPtr == BufferEnd) {
retryWithMoreMemory(F);
return true;
} else {
SizeEstimate = 0;
}
BufferBegin = CurBufferPtr = 0;
NumBytes += FnEnd-FnStart;
sys::Memory::InvalidateInstructionCache(FnStart, FnEnd-FnStart);
TheJIT->NotifyFunctionEmitted(*F.getFunction(), FnStart, FnEnd-FnStart,
EmissionDetails);
PrevDL = DebugLoc();
DEBUG(dbgs() << "JIT: Finished CodeGen of [" << (void*)FnStart
<< "] Function: " << F.getFunction()->getName()
<< ": " << (FnEnd-FnStart) << " bytes of text, "
<< Relocations.size() << " relocations\n");
Relocations.clear();
ConstPoolAddresses.clear();
MemMgr->setMemoryExecutable();
DEBUG({
if (sys::hasDisassembler()) {
dbgs() << "JIT: Disassembled code:\n";
dbgs() << sys::disassembleBuffer(FnStart, FnEnd-FnStart,
(uintptr_t)FnStart);
} else {
dbgs() << "JIT: Binary code:\n";
uint8_t* q = FnStart;
for (int i = 0; q < FnEnd; q += 4, ++i) {
if (i == 4)
i = 0;
if (i == 0)
dbgs() << "JIT: " << (long)(q - FnStart) << ": ";
bool Done = false;
for (int j = 3; j >= 0; --j) {
if (q + j >= FnEnd)
Done = true;
else
dbgs() << (unsigned short)q[j];
}
if (Done)
break;
dbgs() << ' ';
if (i == 3)
dbgs() << '\n';
}
dbgs()<< '\n';
}
});
if (JITExceptionHandling || JITEmitDebugInfo) {
uintptr_t ActualSize = 0;
SavedBufferBegin = BufferBegin;
SavedBufferEnd = BufferEnd;
SavedCurBufferPtr = CurBufferPtr;
BufferBegin = CurBufferPtr = MemMgr->startExceptionTable(F.getFunction(),
ActualSize);
BufferEnd = BufferBegin+ActualSize;
EmittedFunctions[F.getFunction()].ExceptionTable = BufferBegin;
uint8_t *EhStart;
uint8_t *FrameRegister = DE->EmitDwarfTable(F, *this, FnStart, FnEnd,
EhStart);
MemMgr->endExceptionTable(F.getFunction(), BufferBegin, CurBufferPtr,
FrameRegister);
uint8_t *EhEnd = CurBufferPtr;
BufferBegin = SavedBufferBegin;
BufferEnd = SavedBufferEnd;
CurBufferPtr = SavedCurBufferPtr;
if (JITExceptionHandling) {
TheJIT->RegisterTable(FrameRegister);
}
if (JITEmitDebugInfo) {
DebugInfo I;
I.FnStart = FnStart;
I.FnEnd = FnEnd;
I.EhStart = EhStart;
I.EhEnd = EhEnd;
DR->RegisterFunction(F.getFunction(), I);
}
}
if (MMI)
MMI->EndFunction();
return false;
}
void JITEmitter::retryWithMoreMemory(MachineFunction &F) {
DEBUG(dbgs() << "JIT: Ran out of space for native code. Reattempting.\n");
Relocations.clear(); ConstPoolAddresses.clear();
++NumRetries;
deallocateMemForFunction(F.getFunction());
SizeEstimate = (uintptr_t)(2 * (BufferEnd - BufferBegin));
for (MachineFunction::iterator MBB = F.begin(), E = F.end(); MBB != E; ++MBB){
if (MBB->hasAddressTaken())
TheJIT->clearPointerToBasicBlock(MBB->getBasicBlock());
}
}
void JITEmitter::deallocateMemForFunction(const Function *F) {
ValueMap<const Function *, EmittedCode, EmittedFunctionConfig>::iterator
Emitted = EmittedFunctions.find(F);
if (Emitted != EmittedFunctions.end()) {
MemMgr->deallocateFunctionBody(Emitted->second.FunctionBody);
MemMgr->deallocateExceptionTable(Emitted->second.ExceptionTable);
TheJIT->NotifyFreeingMachineCode(Emitted->second.Code);
EmittedFunctions.erase(Emitted);
}
if (JITEmitDebugInfo) {
DR->UnregisterFunction(F);
}
}
void* JITEmitter::allocateSpace(uintptr_t Size, unsigned Alignment) {
if (BufferBegin)
return JITCodeEmitter::allocateSpace(Size, Alignment);
BufferBegin = CurBufferPtr = MemMgr->allocateSpace(Size, Alignment);
BufferEnd = BufferBegin+Size;
return CurBufferPtr;
}
void* JITEmitter::allocateGlobal(uintptr_t Size, unsigned Alignment) {
return MemMgr->allocateGlobal(Size, Alignment);
}
void JITEmitter::emitConstantPool(MachineConstantPool *MCP) {
if (TheJIT->getJITInfo().hasCustomConstantPool())
return;
const std::vector<MachineConstantPoolEntry> &Constants = MCP->getConstants();
if (Constants.empty()) return;
unsigned Size = GetConstantPoolSizeInBytes(MCP, TheJIT->getTargetData());
unsigned Align = MCP->getConstantPoolAlignment();
ConstantPoolBase = allocateSpace(Size, Align);
ConstantPool = MCP;
if (ConstantPoolBase == 0) return;
DEBUG(dbgs() << "JIT: Emitted constant pool at [" << ConstantPoolBase
<< "] (size: " << Size << ", alignment: " << Align << ")\n");
unsigned Offset = 0;
for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
MachineConstantPoolEntry CPE = Constants[i];
unsigned AlignMask = CPE.getAlignment() - 1;
Offset = (Offset + AlignMask) & ~AlignMask;
uintptr_t CAddr = (uintptr_t)ConstantPoolBase + Offset;
ConstPoolAddresses.push_back(CAddr);
if (CPE.isMachineConstantPoolEntry()) {
report_fatal_error("Initialize memory with machine specific constant pool"
"entry has not been implemented!");
}
TheJIT->InitializeMemory(CPE.Val.ConstVal, (void*)CAddr);
DEBUG(dbgs() << "JIT: CP" << i << " at [0x";
dbgs().write_hex(CAddr) << "]\n");
const Type *Ty = CPE.Val.ConstVal->getType();
Offset += TheJIT->getTargetData()->getTypeAllocSize(Ty);
}
}
void JITEmitter::initJumpTableInfo(MachineJumpTableInfo *MJTI) {
if (TheJIT->getJITInfo().hasCustomJumpTables())
return;
if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline)
return;
const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
if (JT.empty()) return;
unsigned NumEntries = 0;
for (unsigned i = 0, e = JT.size(); i != e; ++i)
NumEntries += JT[i].MBBs.size();
unsigned EntrySize = MJTI->getEntrySize(*TheJIT->getTargetData());
JumpTable = MJTI;
JumpTableBase = allocateSpace(NumEntries * EntrySize,
MJTI->getEntryAlignment(*TheJIT->getTargetData()));
}
void JITEmitter::emitJumpTableInfo(MachineJumpTableInfo *MJTI) {
if (TheJIT->getJITInfo().hasCustomJumpTables())
return;
const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
if (JT.empty() || JumpTableBase == 0) return;
switch (MJTI->getEntryKind()) {
case MachineJumpTableInfo::EK_Inline:
return;
case MachineJumpTableInfo::EK_BlockAddress: {
assert(MJTI->getEntrySize(*TheJIT->getTargetData()) == sizeof(void*) &&
"Cross JIT'ing?");
intptr_t *SlotPtr = (intptr_t*)JumpTableBase;
for (unsigned i = 0, e = JT.size(); i != e; ++i) {
const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi)
*SlotPtr++ = getMachineBasicBlockAddress(MBBs[mi]);
}
break;
}
case MachineJumpTableInfo::EK_Custom32:
case MachineJumpTableInfo::EK_GPRel32BlockAddress:
case MachineJumpTableInfo::EK_LabelDifference32: {
assert(MJTI->getEntrySize(*TheJIT->getTargetData()) == 4&&"Cross JIT'ing?");
int *SlotPtr = (int*)JumpTableBase;
for (unsigned i = 0, e = JT.size(); i != e; ++i) {
const std::vector<MachineBasicBlock*> &MBBs = JT[i].MBBs;
uintptr_t Base = (uintptr_t)SlotPtr;
for (unsigned mi = 0, me = MBBs.size(); mi != me; ++mi) {
uintptr_t MBBAddr = getMachineBasicBlockAddress(MBBs[mi]);
*SlotPtr++ = TheJIT->getJITInfo().getPICJumpTableEntry(MBBAddr, Base);
}
}
break;
}
}
}
void JITEmitter::startGVStub(const GlobalValue* GV,
unsigned StubSize, unsigned Alignment) {
SavedBufferBegin = BufferBegin;
SavedBufferEnd = BufferEnd;
SavedCurBufferPtr = CurBufferPtr;
BufferBegin = CurBufferPtr = MemMgr->allocateStub(GV, StubSize, Alignment);
BufferEnd = BufferBegin+StubSize+1;
}
void JITEmitter::startGVStub(void *Buffer, unsigned StubSize) {
SavedBufferBegin = BufferBegin;
SavedBufferEnd = BufferEnd;
SavedCurBufferPtr = CurBufferPtr;
BufferBegin = CurBufferPtr = (uint8_t *)Buffer;
BufferEnd = BufferBegin+StubSize+1;
}
void JITEmitter::finishGVStub() {
assert(CurBufferPtr != BufferEnd && "Stub overflowed allocated space.");
NumBytes += getCurrentPCOffset();
BufferBegin = SavedBufferBegin;
BufferEnd = SavedBufferEnd;
CurBufferPtr = SavedCurBufferPtr;
}
void *JITEmitter::allocIndirectGV(const GlobalValue *GV,
const uint8_t *Buffer, size_t Size,
unsigned Alignment) {
uint8_t *IndGV = MemMgr->allocateStub(GV, Size, Alignment);
memcpy(IndGV, Buffer, Size);
return IndGV;
}
uintptr_t JITEmitter::getConstantPoolEntryAddress(unsigned ConstantNum) const {
assert(ConstantNum < ConstantPool->getConstants().size() &&
"Invalid ConstantPoolIndex!");
return ConstPoolAddresses[ConstantNum];
}
uintptr_t JITEmitter::getJumpTableEntryAddress(unsigned Index) const {
const std::vector<MachineJumpTableEntry> &JT = JumpTable->getJumpTables();
assert(Index < JT.size() && "Invalid jump table index!");
unsigned EntrySize = JumpTable->getEntrySize(*TheJIT->getTargetData());
unsigned Offset = 0;
for (unsigned i = 0; i < Index; ++i)
Offset += JT[i].MBBs.size();
Offset *= EntrySize;
return (uintptr_t)((char *)JumpTableBase + Offset);
}
void JITEmitter::EmittedFunctionConfig::onDelete(
JITEmitter *Emitter, const Function *F) {
Emitter->deallocateMemForFunction(F);
}
void JITEmitter::EmittedFunctionConfig::onRAUW(
JITEmitter *, const Function*, const Function*) {
llvm_unreachable("The JIT doesn't know how to handle a"
" RAUW on a value it has emitted.");
}
JITCodeEmitter *JIT::createEmitter(JIT &jit, JITMemoryManager *JMM,
TargetMachine &tm) {
return new JITEmitter(jit, JMM, tm);
}
void *JIT::getPointerToFunctionOrStub(Function *F) {
if (void *Addr = getPointerToGlobalIfAvailable(F))
return Addr;
assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
return JE->getJITResolver().getLazyFunctionStub(F);
}
void JIT::updateFunctionStub(Function *F) {
assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
JITEmitter *JE = cast<JITEmitter>(getCodeEmitter());
void *Stub = JE->getJITResolver().getLazyFunctionStub(F);
void *Addr = getPointerToGlobalIfAvailable(F);
assert(Addr != Stub && "Function must have non-stub address to be updated.");
TargetJITInfo::StubLayout layout = getJITInfo().getStubLayout();
JE->startGVStub(Stub, layout.Size);
getJITInfo().emitFunctionStub(F, Addr, *getCodeEmitter());
JE->finishGVStub();
}
void JIT::freeMachineCodeForFunction(Function *F) {
updateGlobalMapping(F, 0);
assert(isa<JITEmitter>(JCE) && "Unexpected MCE?");
cast<JITEmitter>(JCE)->deallocateMemForFunction(F);
}