chigraph  master
Systems programming language written for beginners in LLVM
BitcodeParser.cpp
Go to the documentation of this file.
1 
3 #include "chi/BitcodeParser.hpp"
4 #include "chi/LLVMVersion.hpp"
5 #include "chi/Support/Result.hpp"
6 
7 #if LLVM_VERSION_LESS_EQUAL(3, 9)
8 #include <llvm/Bitcode/ReaderWriter.h>
9 #else
10 #include <llvm/Bitcode/BitcodeReader.h>
11 #endif
12 
13 #include <llvm/IR/Module.h>
14 #include <llvm/Support/MemoryBuffer.h>
15 
16 namespace chi {
17 
18 namespace {
19 
20 template <typename MemBuffType>
21 Result parseBitcodeMemBuff(MemBuffType buff, llvm::LLVMContext& ctx,
22  std::unique_ptr<llvm::Module>* toFill) {
23  assert(toFill != nullptr && "Cannot pass a null toFill pointer to parseBitcodeMemBuff");
24 
25  Result res;
26 
27  auto errorOrMod = llvm::parseBitcodeFile(buff, ctx);
28  if (!errorOrMod) {
29  std::vector<std::string> errorMsgs;
30 
31 #if LLVM_VERSION_AT_LEAST(4, 0)
32  auto E = errorOrMod.takeError();
33 
34  llvm::handleAllErrors(std::move(E), [&errorMsgs](llvm::ErrorInfoBase& err) {
35  errorMsgs.push_back(err.message());
36  });
37 #endif
38 
39  res.addEntry("EUKN", "Failed to parse generated bitcode.", {{"Error Messages", errorMsgs}});
40 
41  return res;
42  }
43  *toFill =
44 #if LLVM_VERSION_LESS_EQUAL(3, 6)
45  std::unique_ptr<llvm::Module>
46 #else
47  std::move
48 #endif
49  (errorOrMod.get());
50 
51  return res;
52 }
53 
54 } // namespace
55 
56 Result parseBitcodeFile(const boost::filesystem::path& file, llvm::LLVMContext& ctx,
57  std::unique_ptr<llvm::Module>* toFill) {
58  Result res;
59 
60  // if all of this is true, then we can read the cache
61  auto bcFileBufferOrError = llvm::MemoryBuffer::getFile(file.string());
62  if (!bcFileBufferOrError) {
63  res.addEntry("EUKN", "Failed to load LLVM module from disk", {{"File", file.string()}});
64  return res;
65  }
66 
67  return parseBitcodeMemBuff(bcFileBufferOrError
68  .get()
69 #if LLVM_VERSION_AT_LEAST(3, 6)
70  ->getMemBufferRef()
71 #else
72  .get()
73 #endif
74  ,
75  ctx, toFill);
76 }
77 Result parseBitcodeString(const std::string& bitcode, llvm::LLVMContext& ctx,
78  std::unique_ptr<llvm::Module>* toFill) {
79  return parseBitcodeMemBuff(
80 #if LLVM_VERSION_LESS_EQUAL(3, 5)
81  llvm::MemoryBuffer::getMemBufferCopy
82 #else
83  llvm::MemoryBufferRef
84 #endif
85  (bitcode, "generated.bc"),
86  ctx, toFill);
87 }
88 
89 } // namespace chi
Result parseBitcodeFile(const boost::filesystem::path &file, llvm::LLVMContext &ctx, std::unique_ptr< llvm::Module > *toFill)
Parse a bitcode file.
void addEntry(const char *ec, const char *overview, nlohmann::json data)
Add a entry to the result, either a warning or an error.
Definition: Result.cpp:52
Defines the Result class and related functions.
The namespace where chigraph lives.
The result object, used for identifiying errors with good diagnostics.
Definition: Result.hpp:72