Loading...
Searching...
No Matches
JitUtils.hpp
1#pragma once
2#undef RESET
3#include <llvm/Bitcode/BitcodeReader.h>
4#include <llvm/IR/Module.h>
5#include <llvm/Support/Error.h>
6#include <llvm/Support/FileSystem.h>
7#include <llvm/Support/MemoryBuffer.h>
8
9#include <chrono>
10#include <iostream>
11#include <list>
12#include <memory>
13#include <string>
14
15namespace Jit
16{
17struct Exception final : std::runtime_error
18{
19 using std::runtime_error::runtime_error;
20 Exception(llvm::Error E)
21 : std::runtime_error{"JIT error"}
22 {
23 llvm::handleAllErrors(
24 std::move(E), [&](const llvm::ErrorInfoBase& EI) { m_err = EI.message(); });
25 }
26
27 const char* what() const noexcept override { return m_err.c_str(); }
28
29private:
30 std::string m_err;
31};
32
42inline void parkCompiler(std::shared_ptr<void> compiler)
43{
44 static auto& parked = *new std::list<std::shared_ptr<void>>;
45 if(compiler)
46 parked.push_back(std::move(compiler));
47}
48
49struct Timer
50{
51 std::chrono::high_resolution_clock::time_point t0;
52 Timer() { t0 = decltype(t0)::clock::now(); }
53 ~Timer()
54 {
55 auto t1 = decltype(t0)::clock::now();
56 std::cerr << "Took time: "
57 << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count()
58 << "\n";
59 }
60};
61
62inline llvm::Expected<std::unique_ptr<llvm::Module>>
63readModuleFromBitcodeFile(llvm::StringRef bc, llvm::LLVMContext& context)
64{
65 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer
66 = llvm::MemoryBuffer::getFile(bc);
67 if(!buffer)
68 return llvm::errorCodeToError(buffer.getError());
69
70 return llvm::parseBitcodeFile(buffer.get()->getMemBufferRef(), context);
71}
72
73static inline std::string replaceExtension(llvm::StringRef name, llvm::StringRef ext)
74{
75 return name.substr(0, name.find_last_of('.') + 1).str() + ext.str();
76}
77
78static inline llvm::Error return_code_error(llvm::StringRef message, int returnCode)
79{
80 return llvm::make_error<llvm::StringError>(
81 message, std::error_code(returnCode, std::system_category()));
82}
83
84static inline llvm::Expected<std::string> saveSourceFile(const std::string& content)
85{
86 using llvm::sys::fs::createTemporaryFile;
87
88 int fd;
89 llvm::SmallString<128> name;
90 if(auto ec = createTemporaryFile("score-addon-cpp", "cpp", fd, name))
91 return llvm::errorCodeToError(ec);
92
93 constexpr bool shouldClose = true;
94 constexpr bool unbuffered = true;
95 llvm::raw_fd_ostream os(fd, shouldClose, unbuffered);
96 os << content;
97
98 return name.str().str();
99}
100
101}
Definition JitUtils.hpp:18
Definition JitUtils.hpp:50