rpcs3/Utilities/JIT.cpp

533 lines
13 KiB
C++
Raw Normal View History

#ifdef LLVM_AVAILABLE
#include <unordered_map>
#include <map>
#include <unordered_set>
#include <set>
#include <array>
#include <deque>
#include "types.h"
#include "StrFmt.h"
#include "File.h"
#include "Log.h"
2017-06-24 15:36:49 +00:00
#include "mutex.h"
#include "sysinfo.h"
#include "VirtualMemory.h"
#ifdef _MSC_VER
#pragma warning(push, 0)
#endif
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
#include "llvm/ExecutionEngine/JITEventListener.h"
#include "llvm/ExecutionEngine/ObjectCache.h"
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#ifdef _WIN32
#include <Windows.h>
Fixes from FreeBSD package (#3765) * Thread: unbreak on BSDs after dbc9bdfe02ae Utilities/Thread.cpp:1920:2: error: unknown type name 'cpu_set_t'; did you mean 'cpusetid_t'? cpu_set_t cs; ^~~~~~~~~ cpusetid_t /usr/include/sys/types.h:84:22: note: 'cpusetid_t' declared here typedef __cpusetid_t cpusetid_t; ^ Utilities/Thread.cpp:1921:2: error: use of undeclared identifier 'CPU_ZERO' CPU_ZERO(&cs); ^ Utilities/Thread.cpp:1922:2: error: use of undeclared identifier 'CPU_SET' CPU_SET(core, &cs); ^ Utilities/Thread.cpp:1923:48: error: unknown type name 'cpu_set_t'; did you mean 'cpusetid_t'? pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cs); ^~~~~~~~~ cpusetid_t * JIT: use MAP_32BIT on Linux and FreeBSD Unless RLIMIT_DATA is low enough FreeBSD by default reserves lower 2Gb for brk(2) style heap, ignoring mmap(2) address hint requested by RPCS3. Passing MAP_32BIT fixes the following crash Assertion failed: ((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) || (Type == ELF::R_X86_64_32S && ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN))), function resolveX86_64Relocation, file /usr/ports/devel/llvm40/work/llvm-4.0.1.src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp, line 287. * build: unbreak -DVULKAN_PREBUILT with system glslang on Unix rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:4:10: fatal error: '../../../../Vulkan/glslang/SPIRV/GlslangToSpv.h' file not found #include "../../../../Vulkan/glslang/SPIRV/GlslangToSpv.h" ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ rpcs3/CMakeFiles/rpcs3.dir/Emu/RSX/VK/VKCommonDecompiler.cpp.o: In function `vk::compile_glsl_to_spv(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&, glsl::program_domain, std::__1::vector<unsigned int, std::__1::allocator<unsigned int> >&)': rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x50e): undefined reference to `glslang::TProgram::TProgram()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x51d): undefined reference to `glslang::TShader::TShader(EShLanguage)' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x542): undefined reference to `glslang::TShader::setStrings(char const* const*, int)' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x581): undefined reference to `glslang::TShader::parse(TBuiltInResource const*, int, EProfile, bool, bool, EShMessages, glslang::TShader::Includer&)' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x5d6): undefined reference to `glslang::TProgram::link(EShMessages)' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x5f1): undefined reference to `glslang::GlslangToSpv(glslang::TIntermediate const&, std::__1::vector<unsigned int, std::__1::allocator<unsigned int> >&, glslang::SpvOptions*)' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x5ff): undefined reference to `glslang::TShader::getInfoLog()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x61a): undefined reference to `glslang::TShader::getInfoDebugLog()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x630): undefined reference to `glslang::TShader::~TShader()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x63c): undefined reference to `glslang::TProgram::~TProgram()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x6d2): undefined reference to `glslang::TShader::~TShader()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x6de): undefined reference to `glslang::TProgram::~TProgram()' rpcs3/CMakeFiles/rpcs3.dir/Emu/RSX/VK/VKCommonDecompiler.cpp.o: In function `vk::initialize_compiler_context()': rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x6f5): undefined reference to `glslang::InitializeProcess()' rpcs3/CMakeFiles/rpcs3.dir/Emu/RSX/VK/VKCommonDecompiler.cpp.o: In function `vk::finalize_compiler_context()': rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x856): undefined reference to `glslang::FinalizeProcess()' * build/msvc: add missing glslang include directory after 6bb3f1b4d75c "c:\projects\rpcs3\rpcs3\VKGSRender.vcxproj" (default target) (15) -> (ClCompile target) -> Emu\RSX\VK\VKCommonDecompiler.cpp(4): fatal error C1083: Cannot open include file: 'SPIRV/GlslangToSpv.h': No such file or directory [c:\projects\rpcs3\rpcs3\VKGSRender.vcxproj]
2017-11-20 21:56:25 +00:00
#else
#include <sys/mman.h>
#endif
#include "JIT.h"
2017-06-24 15:36:49 +00:00
// Memory manager mutex
shared_mutex s_mutex;
// Size of virtual memory area reserved: 512 MB
static const u64 s_memory_size = 0x20000000;
// Try to reserve a portion of virtual memory in the first 2 GB address space beforehand, if possible.
static void* const s_memory = []() -> void*
{
2017-06-24 15:36:49 +00:00
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
LLVMLinkInMCJIT();
Fixes from FreeBSD package (#3765) * Thread: unbreak on BSDs after dbc9bdfe02ae Utilities/Thread.cpp:1920:2: error: unknown type name 'cpu_set_t'; did you mean 'cpusetid_t'? cpu_set_t cs; ^~~~~~~~~ cpusetid_t /usr/include/sys/types.h:84:22: note: 'cpusetid_t' declared here typedef __cpusetid_t cpusetid_t; ^ Utilities/Thread.cpp:1921:2: error: use of undeclared identifier 'CPU_ZERO' CPU_ZERO(&cs); ^ Utilities/Thread.cpp:1922:2: error: use of undeclared identifier 'CPU_SET' CPU_SET(core, &cs); ^ Utilities/Thread.cpp:1923:48: error: unknown type name 'cpu_set_t'; did you mean 'cpusetid_t'? pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cs); ^~~~~~~~~ cpusetid_t * JIT: use MAP_32BIT on Linux and FreeBSD Unless RLIMIT_DATA is low enough FreeBSD by default reserves lower 2Gb for brk(2) style heap, ignoring mmap(2) address hint requested by RPCS3. Passing MAP_32BIT fixes the following crash Assertion failed: ((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) || (Type == ELF::R_X86_64_32S && ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN))), function resolveX86_64Relocation, file /usr/ports/devel/llvm40/work/llvm-4.0.1.src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp, line 287. * build: unbreak -DVULKAN_PREBUILT with system glslang on Unix rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:4:10: fatal error: '../../../../Vulkan/glslang/SPIRV/GlslangToSpv.h' file not found #include "../../../../Vulkan/glslang/SPIRV/GlslangToSpv.h" ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ rpcs3/CMakeFiles/rpcs3.dir/Emu/RSX/VK/VKCommonDecompiler.cpp.o: In function `vk::compile_glsl_to_spv(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&, glsl::program_domain, std::__1::vector<unsigned int, std::__1::allocator<unsigned int> >&)': rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x50e): undefined reference to `glslang::TProgram::TProgram()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x51d): undefined reference to `glslang::TShader::TShader(EShLanguage)' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x542): undefined reference to `glslang::TShader::setStrings(char const* const*, int)' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x581): undefined reference to `glslang::TShader::parse(TBuiltInResource const*, int, EProfile, bool, bool, EShMessages, glslang::TShader::Includer&)' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x5d6): undefined reference to `glslang::TProgram::link(EShMessages)' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x5f1): undefined reference to `glslang::GlslangToSpv(glslang::TIntermediate const&, std::__1::vector<unsigned int, std::__1::allocator<unsigned int> >&, glslang::SpvOptions*)' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x5ff): undefined reference to `glslang::TShader::getInfoLog()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x61a): undefined reference to `glslang::TShader::getInfoDebugLog()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x630): undefined reference to `glslang::TShader::~TShader()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x63c): undefined reference to `glslang::TProgram::~TProgram()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x6d2): undefined reference to `glslang::TShader::~TShader()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x6de): undefined reference to `glslang::TProgram::~TProgram()' rpcs3/CMakeFiles/rpcs3.dir/Emu/RSX/VK/VKCommonDecompiler.cpp.o: In function `vk::initialize_compiler_context()': rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x6f5): undefined reference to `glslang::InitializeProcess()' rpcs3/CMakeFiles/rpcs3.dir/Emu/RSX/VK/VKCommonDecompiler.cpp.o: In function `vk::finalize_compiler_context()': rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x856): undefined reference to `glslang::FinalizeProcess()' * build/msvc: add missing glslang include directory after 6bb3f1b4d75c "c:\projects\rpcs3\rpcs3\VKGSRender.vcxproj" (default target) (15) -> (ClCompile target) -> Emu\RSX\VK\VKCommonDecompiler.cpp(4): fatal error C1083: Cannot open include file: 'SPIRV/GlslangToSpv.h': No such file or directory [c:\projects\rpcs3\rpcs3\VKGSRender.vcxproj]
2017-11-20 21:56:25 +00:00
#ifdef MAP_32BIT
auto ptr = ::mmap(nullptr, s_memory_size, PROT_NONE, MAP_ANON | MAP_PRIVATE | MAP_32BIT, -1, 0);
if (ptr != MAP_FAILED)
return ptr;
#else
for (u64 addr = 0x10000000; addr <= 0x80000000 - s_memory_size; addr += 0x1000000)
{
if (auto ptr = utils::memory_reserve(s_memory_size, (void*)addr))
{
return ptr;
}
}
Fixes from FreeBSD package (#3765) * Thread: unbreak on BSDs after dbc9bdfe02ae Utilities/Thread.cpp:1920:2: error: unknown type name 'cpu_set_t'; did you mean 'cpusetid_t'? cpu_set_t cs; ^~~~~~~~~ cpusetid_t /usr/include/sys/types.h:84:22: note: 'cpusetid_t' declared here typedef __cpusetid_t cpusetid_t; ^ Utilities/Thread.cpp:1921:2: error: use of undeclared identifier 'CPU_ZERO' CPU_ZERO(&cs); ^ Utilities/Thread.cpp:1922:2: error: use of undeclared identifier 'CPU_SET' CPU_SET(core, &cs); ^ Utilities/Thread.cpp:1923:48: error: unknown type name 'cpu_set_t'; did you mean 'cpusetid_t'? pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cs); ^~~~~~~~~ cpusetid_t * JIT: use MAP_32BIT on Linux and FreeBSD Unless RLIMIT_DATA is low enough FreeBSD by default reserves lower 2Gb for brk(2) style heap, ignoring mmap(2) address hint requested by RPCS3. Passing MAP_32BIT fixes the following crash Assertion failed: ((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) || (Type == ELF::R_X86_64_32S && ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN))), function resolveX86_64Relocation, file /usr/ports/devel/llvm40/work/llvm-4.0.1.src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldELF.cpp, line 287. * build: unbreak -DVULKAN_PREBUILT with system glslang on Unix rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:4:10: fatal error: '../../../../Vulkan/glslang/SPIRV/GlslangToSpv.h' file not found #include "../../../../Vulkan/glslang/SPIRV/GlslangToSpv.h" ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ rpcs3/CMakeFiles/rpcs3.dir/Emu/RSX/VK/VKCommonDecompiler.cpp.o: In function `vk::compile_glsl_to_spv(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&, glsl::program_domain, std::__1::vector<unsigned int, std::__1::allocator<unsigned int> >&)': rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x50e): undefined reference to `glslang::TProgram::TProgram()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x51d): undefined reference to `glslang::TShader::TShader(EShLanguage)' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x542): undefined reference to `glslang::TShader::setStrings(char const* const*, int)' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x581): undefined reference to `glslang::TShader::parse(TBuiltInResource const*, int, EProfile, bool, bool, EShMessages, glslang::TShader::Includer&)' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x5d6): undefined reference to `glslang::TProgram::link(EShMessages)' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x5f1): undefined reference to `glslang::GlslangToSpv(glslang::TIntermediate const&, std::__1::vector<unsigned int, std::__1::allocator<unsigned int> >&, glslang::SpvOptions*)' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x5ff): undefined reference to `glslang::TShader::getInfoLog()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x61a): undefined reference to `glslang::TShader::getInfoDebugLog()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x630): undefined reference to `glslang::TShader::~TShader()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x63c): undefined reference to `glslang::TProgram::~TProgram()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x6d2): undefined reference to `glslang::TShader::~TShader()' rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x6de): undefined reference to `glslang::TProgram::~TProgram()' rpcs3/CMakeFiles/rpcs3.dir/Emu/RSX/VK/VKCommonDecompiler.cpp.o: In function `vk::initialize_compiler_context()': rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x6f5): undefined reference to `glslang::InitializeProcess()' rpcs3/CMakeFiles/rpcs3.dir/Emu/RSX/VK/VKCommonDecompiler.cpp.o: In function `vk::finalize_compiler_context()': rpcs3/Emu/RSX/VK/VKCommonDecompiler.cpp:(.text+0x856): undefined reference to `glslang::FinalizeProcess()' * build/msvc: add missing glslang include directory after 6bb3f1b4d75c "c:\projects\rpcs3\rpcs3\VKGSRender.vcxproj" (default target) (15) -> (ClCompile target) -> Emu\RSX\VK\VKCommonDecompiler.cpp(4): fatal error C1083: Cannot open include file: 'SPIRV/GlslangToSpv.h': No such file or directory [c:\projects\rpcs3\rpcs3\VKGSRender.vcxproj]
2017-11-20 21:56:25 +00:00
#endif
return utils::memory_reserve(s_memory_size);
}();
2017-06-24 15:36:49 +00:00
static void* s_next = s_memory;
2016-08-10 10:09:11 +00:00
#ifdef _WIN32
static std::deque<std::vector<RUNTIME_FUNCTION>> s_unwater;
2017-02-26 15:56:31 +00:00
static std::vector<std::vector<RUNTIME_FUNCTION>> s_unwind; // .pdata
#else
static std::deque<std::tuple<u8*, u64, std::size_t>> s_unfire;
#endif
2017-06-24 15:36:49 +00:00
// Reset memory manager
extern void jit_finalize()
{
#ifdef _WIN32
for (auto&& unwind : s_unwind)
{
if (!RtlDeleteFunctionTable(unwind.data()))
{
LOG_FATAL(GENERAL, "RtlDeleteFunctionTable() failed! Error %u", GetLastError());
}
}
s_unwind.clear();
#else
struct MemoryManager : llvm::RTDyldMemoryManager
{
u8* allocateCodeSection(std::uintptr_t size, uint align, uint sec_id, llvm::StringRef sec_name) override
{
return nullptr;
}
u8* allocateDataSection(std::uintptr_t size, uint align, uint sec_id, llvm::StringRef sec_name, bool is_ro) override
{
return nullptr;
}
bool finalizeMemory(std::string* = nullptr) override
{
return false;
}
} mem;
for (auto&& t : s_unfire)
{
mem.deregisterEHFrames(std::get<0>(t), std::get<1>(t), std::get<2>(t));
}
s_unfire.clear();
2017-06-24 15:36:49 +00:00
#endif
utils::memory_decommit(s_memory, s_memory_size);
s_next = s_memory;
}
// Helper class
2017-06-24 15:36:49 +00:00
struct MemoryManager : llvm::RTDyldMemoryManager
{
2017-08-07 22:05:59 +00:00
std::unordered_map<std::string, u64>& m_link;
2017-06-24 15:36:49 +00:00
std::array<u8, 16>* m_tramps{};
u8* m_code_addr{}; // TODO
2017-08-07 22:05:59 +00:00
MemoryManager(std::unordered_map<std::string, u64>& table)
2017-02-26 15:56:31 +00:00
: m_link(table)
{
}
[[noreturn]] static void null()
{
fmt::throw_exception("Null function" HERE);
}
llvm::JITSymbol findSymbol(const std::string& name) override
{
auto& addr = m_link[name];
// Find function address
if (!addr)
{
addr = RTDyldMemoryManager::getSymbolAddress(name);
if (addr)
{
LOG_WARNING(GENERAL, "LLVM: Symbol requested: %s -> 0x%016llx", name, addr);
}
else
{
LOG_ERROR(GENERAL, "LLVM: Linkage failed: %s", name);
addr = (u64)null;
}
}
// Verify address for small code model
if ((u64)s_memory > 0x80000000 - s_memory_size ? (u64)addr - (u64)s_memory >= s_memory_size : addr >= 0x80000000)
2017-03-11 16:49:32 +00:00
{
2017-06-24 15:36:49 +00:00
// Lock memory manager
writer_lock lock(s_mutex);
// Allocate memory for trampolines
if (!m_tramps)
{
m_tramps = reinterpret_cast<decltype(m_tramps)>(s_next);
utils::memory_commit(s_next, 4096, utils::protection::wx);
s_next = (u8*)((u64)s_next + 4096);
}
// Create a trampoline
auto& data = *m_tramps++;
data[0x0] = 0xff; // JMP [rip+2]
data[0x1] = 0x25;
data[0x2] = 0x02;
data[0x3] = 0x00;
data[0x4] = 0x00;
data[0x5] = 0x00;
data[0x6] = 0x48; // MOV rax, imm64 (not executed)
data[0x7] = 0xb8;
std::memcpy(data.data() + 8, &addr, 8);
addr = (u64)&data;
// Reset pointer (memory page exhausted)
if (((u64)m_tramps % 4096) == 0)
{
m_tramps = nullptr;
}
2017-03-11 16:49:32 +00:00
}
return {addr, llvm::JITSymbolFlags::Exported};
}
u8* allocateCodeSection(std::uintptr_t size, uint align, uint sec_id, llvm::StringRef sec_name) override
{
2017-06-24 15:36:49 +00:00
// Lock memory manager
writer_lock lock(s_mutex);
// Simple allocation
const u64 next = ::align((u64)s_next + size, 4096);
if (next > (u64)s_memory + s_memory_size)
{
LOG_FATAL(GENERAL, "LLVM: Out of memory (size=0x%llx, aligned 0x%x)", size, align);
return nullptr;
}
utils::memory_commit(s_next, size, utils::protection::wx);
2017-06-24 15:36:49 +00:00
m_code_addr = (u8*)s_next;
2016-08-10 10:09:11 +00:00
LOG_NOTICE(GENERAL, "LLVM: Code section %u '%s' allocated -> %p (size=0x%llx, aligned 0x%x)", sec_id, sec_name.data(), s_next, size, align);
return (u8*)std::exchange(s_next, (void*)next);
}
u8* allocateDataSection(std::uintptr_t size, uint align, uint sec_id, llvm::StringRef sec_name, bool is_ro) override
{
2017-06-24 15:36:49 +00:00
// Lock memory manager
writer_lock lock(s_mutex);
// Simple allocation
const u64 next = ::align((u64)s_next + size, 4096);
if (next > (u64)s_memory + s_memory_size)
{
LOG_FATAL(GENERAL, "LLVM: Out of memory (size=0x%llx, aligned 0x%x)", size, align);
return nullptr;
}
2016-08-10 10:09:11 +00:00
if (!is_ro)
{
LOG_ERROR(GENERAL, "LLVM: Writeable data section not supported!");
}
utils::memory_commit(s_next, size);
LOG_NOTICE(GENERAL, "LLVM: Data section %u '%s' allocated -> %p (size=0x%llx, aligned 0x%x, %s)", sec_id, sec_name.data(), s_next, size, align, is_ro ? "ro" : "rw");
return (u8*)std::exchange(s_next, (void*)next);
}
bool finalizeMemory(std::string* = nullptr) override
{
2017-06-24 15:36:49 +00:00
// Lock memory manager
writer_lock lock(s_mutex);
2016-08-10 10:09:11 +00:00
// TODO: make only read-only sections read-only
2017-02-26 15:56:31 +00:00
//#ifdef _WIN32
// DWORD op;
// VirtualProtect(s_memory, (u64)m_next - (u64)s_memory, PAGE_READONLY, &op);
// VirtualProtect(s_code_addr, s_code_size, PAGE_EXECUTE_READ, &op);
//#else
// ::mprotect(s_memory, (u64)m_next - (u64)s_memory, PROT_READ);
// ::mprotect(s_code_addr, s_code_size, PROT_READ | PROT_EXEC);
//#endif
return false;
}
void registerEHFrames(u8* addr, u64 load_addr, std::size_t size) override
{
2017-03-20 13:23:50 +00:00
#ifdef _WIN32
2017-06-24 15:36:49 +00:00
// Lock memory manager
writer_lock lock(s_mutex);
2017-03-20 13:23:50 +00:00
// Use s_memory as a BASE, compute the difference
const u64 unwind_diff = (u64)addr - (u64)s_memory;
// Fix RUNTIME_FUNCTION records (.pdata section)
auto pdata = std::move(s_unwater.front());
s_unwater.pop_front();
2017-03-20 13:23:50 +00:00
for (auto& rf : pdata)
{
rf.UnwindData += static_cast<DWORD>(unwind_diff);
2017-03-20 13:23:50 +00:00
}
// Register .xdata UNWIND_INFO structs
if (!RtlAddFunctionTable(pdata.data(), (DWORD)pdata.size(), (u64)s_memory))
{
LOG_ERROR(GENERAL, "RtlAddFunctionTable() failed! Error %u", GetLastError());
}
else
{
s_unwind.emplace_back(std::move(pdata));
}
#else
s_unfire.push_front(std::make_tuple(addr, load_addr, size));
2017-03-20 13:23:50 +00:00
#endif
return RTDyldMemoryManager::registerEHFrames(addr, load_addr, size);
}
void deregisterEHFrames(u8* addr, u64 load_addr, std::size_t size) override
{
}
};
// Helper class
2017-06-24 15:36:49 +00:00
struct EventListener : llvm::JITEventListener
{
2017-06-24 15:36:49 +00:00
MemoryManager& m_mem;
EventListener(MemoryManager& mem)
: m_mem(mem)
{
}
void NotifyObjectEmitted(const llvm::object::ObjectFile& obj, const llvm::RuntimeDyld::LoadedObjectInfo& inf) override
{
2017-03-20 13:23:50 +00:00
#ifdef _WIN32
for (auto it = obj.section_begin(), end = obj.section_end(); it != end; ++it)
{
llvm::StringRef name;
it->getName(name);
if (name == ".pdata")
{
llvm::StringRef data;
it->getContents(data);
std::vector<RUNTIME_FUNCTION> rfs(data.size() / sizeof(RUNTIME_FUNCTION));
auto offsets = reinterpret_cast<DWORD*>(rfs.data());
// Initialize .pdata section using relocation info
for (auto ri = it->relocation_begin(), end = it->relocation_end(); ri != end; ++ri)
{
if (ri->getType() == 3 /*R_X86_64_GOT32*/)
{
const u64 value = *reinterpret_cast<const DWORD*>(data.data() + ri->getOffset());
offsets[ri->getOffset() / sizeof(DWORD)] = static_cast<DWORD>(value + ri->getSymbol()->getAddress().get());
}
}
2017-06-24 15:36:49 +00:00
// Lock memory manager
writer_lock lock(s_mutex);
// Use s_memory as a BASE, compute the difference
2017-06-24 15:36:49 +00:00
const u64 code_diff = (u64)m_mem.m_code_addr - (u64)s_memory;
// Fix RUNTIME_FUNCTION records (.pdata section)
for (auto& rf : rfs)
{
rf.BeginAddress += static_cast<DWORD>(code_diff);
rf.EndAddress += static_cast<DWORD>(code_diff);
}
s_unwater.emplace_back(std::move(rfs));
2017-03-20 13:23:50 +00:00
}
}
#endif
}
};
// Helper class
class ObjectCache final : public llvm::ObjectCache
{
const std::string& m_path;
public:
ObjectCache(const std::string& path)
: m_path(path)
{
}
~ObjectCache() override = default;
void notifyObjectCompiled(const llvm::Module* module, llvm::MemoryBufferRef obj) override
{
std::string name = m_path;
name.append(module->getName());
fs::file(name, fs::rewrite).write(obj.getBufferStart(), obj.getBufferSize());
LOG_SUCCESS(GENERAL, "LLVM: Created module: %s", module->getName().data());
}
2017-07-15 09:20:40 +00:00
static std::unique_ptr<llvm::MemoryBuffer> load(const std::string& path)
{
2017-07-15 09:20:40 +00:00
if (fs::file cached{path, fs::read})
{
auto buf = llvm::MemoryBuffer::getNewUninitMemBuffer(cached.size());
cached.read(const_cast<char*>(buf->getBufferStart()), buf->getBufferSize());
return buf;
}
2017-07-15 09:20:40 +00:00
return nullptr;
}
std::unique_ptr<llvm::MemoryBuffer> getObject(const llvm::Module* module) override
{
std::string path = m_path;
path.append(module->getName());
if (auto buf = load(path))
{
2017-07-15 09:20:40 +00:00
LOG_SUCCESS(GENERAL, "LLVM: Loaded module: %s", module->getName().data());
return buf;
}
2017-07-15 09:20:40 +00:00
return nullptr;
}
};
2017-08-07 22:05:59 +00:00
jit_compiler::jit_compiler(const std::unordered_map<std::string, u64>& _link, std::string _cpu)
2017-12-01 22:47:05 +00:00
: m_link(_link)
2017-03-14 12:23:07 +00:00
, m_cpu(std::move(_cpu))
{
2017-03-14 12:23:07 +00:00
if (m_cpu.empty())
{
m_cpu = llvm::sys::getHostCPUName();
if (m_cpu == "sandybridge" ||
m_cpu == "ivybridge" ||
m_cpu == "haswell" ||
m_cpu == "broadwell" ||
m_cpu == "skylake" ||
m_cpu == "skylake-avx512" ||
m_cpu == "cannonlake")
{
if (!utils::has_avx())
{
m_cpu = "nehalem";
}
}
2017-03-14 12:23:07 +00:00
}
2017-02-26 15:56:31 +00:00
std::string result;
2017-06-24 15:36:49 +00:00
if (m_link.empty())
{
2017-06-29 14:25:39 +00:00
// Auxiliary JIT (does not use custom memory manager, only writes the objects)
2017-06-24 15:36:49 +00:00
m_engine.reset(llvm::EngineBuilder(std::make_unique<llvm::Module>("null_", m_context))
.setErrorStr(&result)
.setOptLevel(llvm::CodeGenOpt::Aggressive)
.setCodeModel(llvm::CodeModel::Small)
.setMCPU(m_cpu)
.create());
}
else
{
2017-06-29 14:25:39 +00:00
// Primary JIT
2017-06-24 15:36:49 +00:00
auto mem = std::make_unique<MemoryManager>(m_link);
m_jit_el = std::make_unique<EventListener>(*mem);
m_engine.reset(llvm::EngineBuilder(std::make_unique<llvm::Module>("null", m_context))
.setErrorStr(&result)
.setMCJITMemoryManager(std::move(mem))
.setOptLevel(llvm::CodeGenOpt::Aggressive)
.setCodeModel(llvm::CodeModel::Small)
.setMCPU(m_cpu)
.create());
if (m_engine)
{
m_engine->RegisterJITEventListener(m_jit_el.get());
}
}
if (!m_engine)
{
fmt::throw_exception("LLVM: Failed to create ExecutionEngine: %s", result);
}
2017-06-24 15:36:49 +00:00
}
2017-06-24 15:36:49 +00:00
jit_compiler::~jit_compiler()
{
2017-02-26 15:56:31 +00:00
}
void jit_compiler::add(std::unique_ptr<llvm::Module> module, const std::string& path)
2017-02-26 15:56:31 +00:00
{
ObjectCache cache{path};
m_engine->setObjectCache(&cache);
2017-02-26 15:56:31 +00:00
const auto ptr = module.get();
2017-02-26 15:56:31 +00:00
m_engine->addModule(std::move(module));
m_engine->generateCodeForModule(ptr);
m_engine->setObjectCache(nullptr);
2017-02-26 15:56:31 +00:00
for (auto& func : ptr->functions())
2017-02-26 15:56:31 +00:00
{
// Delete IR to lower memory consumption
func.deleteBody();
2017-02-26 15:56:31 +00:00
}
}
2017-07-15 09:20:40 +00:00
void jit_compiler::add(const std::string& path)
{
m_engine->addObjectFile(std::move(llvm::object::ObjectFile::createObjectFile(*ObjectCache::load(path)).get()));
}
2017-06-24 15:36:49 +00:00
void jit_compiler::fin()
2017-02-26 15:56:31 +00:00
{
m_engine->finalizeObject();
}
2017-06-29 14:25:39 +00:00
u64 jit_compiler::get(const std::string& name)
{
2017-06-29 14:25:39 +00:00
return m_engine->getGlobalValueAddress(name);
2017-06-24 15:36:49 +00:00
}
std::unordered_map<std::string, u64> jit_compiler::add(std::unordered_map<std::string, std::string> data)
{
// Lock memory manager
writer_lock lock(s_mutex);
std::unordered_map<std::string, u64> result;
std::size_t size = 0;
2017-02-26 15:56:31 +00:00
for (auto&& pair : data)
{
size += ::align(pair.second.size(), 16);
}
utils::memory_commit(s_next, size, utils::protection::wx);
std::memset(s_next, 0xc3, ::align(size, 4096));
for (auto&& pair : data)
{
std::memcpy(s_next, pair.second.data(), pair.second.size());
2017-06-24 15:36:49 +00:00
result.emplace(pair.first, (u64)s_next);
s_next = (void*)::align((u64)s_next + pair.second.size(), 16);
}
s_next = (void*)::align((u64)s_next, 4096);
2017-06-24 15:36:49 +00:00
return result;
}
#endif