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 <string>
12
13namespace Jit
14{
15struct Exception final : std::runtime_error
16{
17 using std::runtime_error::runtime_error;
18 Exception(llvm::Error E)
19 : std::runtime_error{"JIT error"}
20 {
21 llvm::handleAllErrors(
22 std::move(E), [&](const llvm::ErrorInfoBase& EI) { m_err = EI.message(); });
23 }
24
25 const char* what() const noexcept override { return m_err.c_str(); }
26
27private:
28 std::string m_err;
29};
30
31struct Timer
32{
33 std::chrono::high_resolution_clock::time_point t0;
34 Timer() { t0 = decltype(t0)::clock::now(); }
35 ~Timer()
36 {
37 auto t1 = decltype(t0)::clock::now();
38 std::cerr << "Took time: "
39 << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count()
40 << "\n";
41 }
42};
43
44inline llvm::Expected<std::unique_ptr<llvm::Module>>
45readModuleFromBitcodeFile(llvm::StringRef bc, llvm::LLVMContext& context)
46{
47 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer
48 = llvm::MemoryBuffer::getFile(bc);
49 if(!buffer)
50 return llvm::errorCodeToError(buffer.getError());
51
52 return llvm::parseBitcodeFile(buffer.get()->getMemBufferRef(), context);
53}
54
55static inline std::string replaceExtension(llvm::StringRef name, llvm::StringRef ext)
56{
57 return name.substr(0, name.find_last_of('.') + 1).str() + ext.str();
58}
59
60static inline llvm::Error return_code_error(llvm::StringRef message, int returnCode)
61{
62 return llvm::make_error<llvm::StringError>(
63 message, std::error_code(returnCode, std::system_category()));
64}
65
66static inline llvm::Expected<std::string> saveSourceFile(const std::string& content)
67{
68 using llvm::sys::fs::createTemporaryFile;
69
70 int fd;
71 llvm::SmallString<128> name;
72 if(auto ec = createTemporaryFile("score-addon-cpp", "cpp", fd, name))
73 return llvm::errorCodeToError(ec);
74
75 constexpr bool shouldClose = true;
76 constexpr bool unbuffered = true;
77 llvm::raw_fd_ostream os(fd, shouldClose, unbuffered);
78 os << content;
79
80 return name.str().str();
81}
82
83}
Definition JitUtils.hpp:16
Definition JitUtils.hpp:32