-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllvmcodegen.cpp
More file actions
33 lines (28 loc) · 1.15 KB
/
Copy pathllvmcodegen.cpp
File metadata and controls
33 lines (28 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include "llvmcodegen.hpp"
#include "ast.hpp"
#include <llvm/IR/Verifier.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/FileSystem.h>
void CodeGenContext::generateCode(ASTNode* root) {
// Create main function
llvm::FunctionType *ftype = llvm::FunctionType::get(builder.getInt32Ty(), false);
llvm::Function *mainFunc = llvm::Function::Create(ftype, llvm::GlobalValue::ExternalLinkage, "main", module.get());
llvm::BasicBlock *bblock = llvm::BasicBlock::Create(context, "entry", mainFunc);
builder.SetInsertPoint(bblock);
// Generate code from AST
root->codegen(*this);
// Ensure main returns 0
builder.CreateRet(llvm::ConstantInt::get(builder.getInt32Ty(), 0));
// Validate generated code
llvm::verifyFunction(*mainFunc);
llvm::verifyModule(*module, &llvm::errs());
}
void CodeGenContext::writeIR(const std::string &filename) {
std::error_code EC;
llvm::raw_fd_ostream out(filename, EC, llvm::sys::fs::OpenFlags::OF_Text);
if (EC) {
fprintf(stderr, "Could not open file: %s\n", EC.message().c_str());
return;
}
module->print(out, nullptr);
}