Compare commits
4 Commits
20dfdfec9f
...
48ae533f33
Author | SHA1 | Date | |
---|---|---|---|
48ae533f33 | |||
35efa78a56 | |||
58117d86e4 | |||
454cefafc9 |
@ -1,105 +1,60 @@
|
|||||||
use reid_lib::{
|
use reid_lib::{ConstValue, Context, InstructionKind, IntPredicate, TerminatorKind, Type};
|
||||||
Context, IntPredicate,
|
|
||||||
types::{BasicType, IntegerValue, Value},
|
|
||||||
};
|
|
||||||
|
|
||||||
pub fn main() {
|
fn main() {
|
||||||
// Notes from inkwell:
|
use ConstValue::*;
|
||||||
// - Creating new values should probably just be functions in the context
|
use InstructionKind::*;
|
||||||
// - Creating functions should probably be functions from module
|
|
||||||
// - Builder could well be it's own struct
|
|
||||||
// - Although, I do like the fact where blocks move the builder by itself..
|
|
||||||
|
|
||||||
let context = Context::new();
|
let context = Context::new();
|
||||||
|
|
||||||
let module = context.module("testmodule");
|
let mut module = context.module("test");
|
||||||
|
|
||||||
let int_32 = context.type_i32();
|
let main = module.function("main", Type::I32, Vec::new());
|
||||||
|
let mut m_entry = main.block("entry");
|
||||||
|
|
||||||
let fibonacci = module.add_function(int_32.function_type(vec![int_32.into()]), "fibonacci");
|
let fibonacci = module.function("fibonacci", Type::I32, vec![Type::I32]);
|
||||||
let mut f_main = fibonacci.block("main");
|
|
||||||
|
|
||||||
let param = fibonacci
|
let arg = m_entry.build(Constant(I32(5))).unwrap();
|
||||||
.get_param::<IntegerValue>(0, int_32.into())
|
let fibonacci_call = m_entry
|
||||||
|
.build(FunctionCall(fibonacci.value(), vec![arg]))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let mut cmp = f_main
|
m_entry
|
||||||
.integer_compare(¶m, &int_32.from_unsigned(3), &IntPredicate::ULT, "cmp")
|
.terminate(TerminatorKind::Ret(fibonacci_call))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let mut done = fibonacci.block("done");
|
let mut f_entry = fibonacci.block("entry");
|
||||||
let mut recurse = fibonacci.block("recurse");
|
|
||||||
f_main.conditional_br(&cmp, &done, &recurse).unwrap();
|
|
||||||
|
|
||||||
done.ret(&int_32.from_unsigned(1)).unwrap();
|
let num_3 = f_entry.build(Constant(I32(3))).unwrap();
|
||||||
|
let param_n = f_entry.build(Param(0)).unwrap();
|
||||||
let minus_one = recurse
|
let cond = f_entry
|
||||||
.sub(¶m, &int_32.from_unsigned(1), "minus_one")
|
.build(ICmp(IntPredicate::LessThan, param_n, num_3))
|
||||||
.unwrap();
|
|
||||||
let minus_two = recurse
|
|
||||||
.sub(¶m, &int_32.from_unsigned(2), "minus_two")
|
|
||||||
.unwrap();
|
|
||||||
let one: IntegerValue = recurse
|
|
||||||
.call(&fibonacci, vec![Value::Integer(minus_one)], "call_one")
|
|
||||||
.unwrap();
|
|
||||||
let two = recurse
|
|
||||||
.call(&fibonacci, vec![Value::Integer(minus_two)], "call_two")
|
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let add = recurse.add(&one, &two, "add").unwrap();
|
let mut then_b = fibonacci.block("then");
|
||||||
|
let mut else_b = fibonacci.block("else");
|
||||||
|
|
||||||
recurse.ret(&add).unwrap();
|
f_entry
|
||||||
|
.terminate(TerminatorKind::CondBr(cond, then_b.value(), else_b.value()))
|
||||||
let main_f = module.add_function(int_32.function_type(Vec::new()), "main");
|
|
||||||
|
|
||||||
let mut main_b = main_f.block("main");
|
|
||||||
let call: IntegerValue = main_b
|
|
||||||
.call(
|
|
||||||
&fibonacci,
|
|
||||||
vec![Value::Integer(int_32.from_unsigned(8))],
|
|
||||||
"fib_call",
|
|
||||||
)
|
|
||||||
.unwrap();
|
.unwrap();
|
||||||
main_b.ret(&call).unwrap();
|
|
||||||
|
|
||||||
// let secondary = module.add_function(int_32.function_type(&[]), "secondary");
|
let ret_const = then_b.build(Constant(I32(1))).unwrap();
|
||||||
// let s_entry = secondary.block("entry");
|
then_b.terminate(TerminatorKind::Ret(ret_const)).unwrap();
|
||||||
// s_entry.ret(&int_32.from_signed(54)).unwrap();
|
|
||||||
|
|
||||||
// let function = module.add_function(int_32.function_type(&[]), "main");
|
let const_1 = else_b.build(Constant(I32(1))).unwrap();
|
||||||
|
let const_2 = else_b.build(Constant(I32(2))).unwrap();
|
||||||
|
let param_1 = else_b.build(Sub(param_n, const_1)).unwrap();
|
||||||
|
let param_2 = else_b.build(Sub(param_n, const_2)).unwrap();
|
||||||
|
let call_1 = else_b
|
||||||
|
.build(FunctionCall(fibonacci.value(), vec![param_1]))
|
||||||
|
.unwrap();
|
||||||
|
let call_2 = else_b
|
||||||
|
.build(FunctionCall(fibonacci.value(), vec![param_2]))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
// let entry = function.block("entry");
|
let add = else_b.build(Add(call_1, call_2)).unwrap();
|
||||||
|
|
||||||
// let call = entry.call(&secondary, vec![], "call").unwrap();
|
else_b.terminate(TerminatorKind::Ret(add)).unwrap();
|
||||||
// let add = entry.add(&int_32.from_signed(100), &call, "add").unwrap();
|
|
||||||
// let rhs_cmp = int_32.from_signed(200);
|
|
||||||
|
|
||||||
// let cond_res = entry
|
dbg!(&context);
|
||||||
// .integer_compare(&add, &rhs_cmp, &IntPredicate::SLT, "cmp")
|
|
||||||
// .unwrap();
|
|
||||||
|
|
||||||
// let (lhs, rhs) = entry.conditional_br(&cond_res, "lhs", "rhs").unwrap();
|
context.compile();
|
||||||
|
|
||||||
// let left = lhs.add(&call, &int_32.from_signed(20), "add").unwrap();
|
|
||||||
// let right = rhs.add(&call, &int_32.from_signed(30), "add").unwrap();
|
|
||||||
|
|
||||||
// let final_block = function.block("final");
|
|
||||||
// let phi = final_block
|
|
||||||
// .phi::<IntegerValue>(&int_32, "phi")
|
|
||||||
// .unwrap()
|
|
||||||
// .add_incoming(&left, &lhs)
|
|
||||||
// .add_incoming(&right, &rhs)
|
|
||||||
// .build();
|
|
||||||
|
|
||||||
// lhs.br(&final_block).unwrap();
|
|
||||||
// rhs.br(&final_block).unwrap();
|
|
||||||
|
|
||||||
// let val = final_block
|
|
||||||
// .add(&phi, &int_32.from_signed(11), "add")
|
|
||||||
// .unwrap();
|
|
||||||
// final_block.ret(&val).unwrap();
|
|
||||||
|
|
||||||
match module.print_to_string() {
|
|
||||||
Ok(v) => println!("{}", v),
|
|
||||||
Err(e) => println!("Err: {:?}", e),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
348
reid-llvm-lib/src/builder.rs
Normal file
348
reid-llvm-lib/src/builder.rs
Normal file
@ -0,0 +1,348 @@
|
|||||||
|
use std::{cell::RefCell, marker::PhantomData, rc::Rc};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
BlockData, ConstValue, FunctionData, InstructionData, InstructionKind, ModuleData,
|
||||||
|
TerminatorKind, Type, util::match_types,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Hash, Copy, PartialEq, Eq)]
|
||||||
|
pub struct ModuleValue(usize);
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Hash, Copy, PartialEq, Eq)]
|
||||||
|
pub struct FunctionValue(ModuleValue, usize);
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Hash, Copy, PartialEq, Eq)]
|
||||||
|
pub struct BlockValue(FunctionValue, usize);
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Hash, Copy, PartialEq, Eq)]
|
||||||
|
pub struct InstructionValue(pub(crate) BlockValue, usize);
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ModuleHolder {
|
||||||
|
pub(crate) value: ModuleValue,
|
||||||
|
pub(crate) data: ModuleData,
|
||||||
|
pub(crate) functions: Vec<FunctionHolder>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct FunctionHolder {
|
||||||
|
pub(crate) value: FunctionValue,
|
||||||
|
pub(crate) data: FunctionData,
|
||||||
|
pub(crate) blocks: Vec<BlockHolder>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct BlockHolder {
|
||||||
|
pub(crate) value: BlockValue,
|
||||||
|
pub(crate) data: BlockData,
|
||||||
|
pub(crate) instructions: Vec<InstructionHolder>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct InstructionHolder {
|
||||||
|
pub(crate) value: InstructionValue,
|
||||||
|
pub(crate) data: InstructionData,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Builder {
|
||||||
|
modules: Rc<RefCell<Vec<ModuleHolder>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Builder {
|
||||||
|
pub fn new() -> Builder {
|
||||||
|
Builder {
|
||||||
|
modules: Rc::new(RefCell::new(Vec::new())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn add_module(&self, data: ModuleData) -> ModuleValue {
|
||||||
|
let value = ModuleValue(self.modules.borrow().len());
|
||||||
|
self.modules.borrow_mut().push(ModuleHolder {
|
||||||
|
value,
|
||||||
|
data,
|
||||||
|
functions: Vec::new(),
|
||||||
|
});
|
||||||
|
value
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) unsafe fn add_function(
|
||||||
|
&self,
|
||||||
|
mod_val: &ModuleValue,
|
||||||
|
data: FunctionData,
|
||||||
|
) -> FunctionValue {
|
||||||
|
unsafe {
|
||||||
|
let mut modules = self.modules.borrow_mut();
|
||||||
|
let module = modules.get_unchecked_mut(mod_val.0);
|
||||||
|
let value = FunctionValue(module.value, module.functions.len());
|
||||||
|
module.functions.push(FunctionHolder {
|
||||||
|
value,
|
||||||
|
data,
|
||||||
|
blocks: Vec::new(),
|
||||||
|
});
|
||||||
|
value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) unsafe fn add_block(&self, fun_val: &FunctionValue, data: BlockData) -> BlockValue {
|
||||||
|
unsafe {
|
||||||
|
let mut modules = self.modules.borrow_mut();
|
||||||
|
let module = modules.get_unchecked_mut(fun_val.0.0);
|
||||||
|
let function = module.functions.get_unchecked_mut(fun_val.1);
|
||||||
|
let value = BlockValue(function.value, function.blocks.len());
|
||||||
|
function.blocks.push(BlockHolder {
|
||||||
|
value,
|
||||||
|
data,
|
||||||
|
instructions: Vec::new(),
|
||||||
|
});
|
||||||
|
value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) unsafe fn add_instruction(
|
||||||
|
&self,
|
||||||
|
block_val: &BlockValue,
|
||||||
|
data: InstructionData,
|
||||||
|
) -> Result<InstructionValue, ()> {
|
||||||
|
unsafe {
|
||||||
|
let mut modules = self.modules.borrow_mut();
|
||||||
|
let module = modules.get_unchecked_mut(block_val.0.0.0);
|
||||||
|
let function = module.functions.get_unchecked_mut(block_val.0.1);
|
||||||
|
let block = function.blocks.get_unchecked_mut(block_val.1);
|
||||||
|
let value = InstructionValue(block.value, block.instructions.len());
|
||||||
|
block.instructions.push(InstructionHolder { value, data });
|
||||||
|
|
||||||
|
// Drop modules so that it is no longer mutable borrowed
|
||||||
|
// (check_instruction requires an immutable borrow).
|
||||||
|
drop(modules);
|
||||||
|
|
||||||
|
self.check_instruction(&value)?;
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) unsafe fn terminate(
|
||||||
|
&self,
|
||||||
|
block: &BlockValue,
|
||||||
|
value: TerminatorKind,
|
||||||
|
) -> Result<(), ()> {
|
||||||
|
unsafe {
|
||||||
|
let mut modules = self.modules.borrow_mut();
|
||||||
|
let module = modules.get_unchecked_mut(block.0.0.0);
|
||||||
|
let function = module.functions.get_unchecked_mut(block.0.1);
|
||||||
|
let block = function.blocks.get_unchecked_mut(block.1);
|
||||||
|
if let Some(_) = &block.data.terminator {
|
||||||
|
Err(())
|
||||||
|
} else {
|
||||||
|
block.data.terminator = Some(value);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) unsafe fn module_data(&self, value: &ModuleValue) -> ModuleData {
|
||||||
|
unsafe { self.modules.borrow().get_unchecked(value.0).data.clone() }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) unsafe fn function_data(&self, value: &FunctionValue) -> FunctionData {
|
||||||
|
unsafe {
|
||||||
|
self.modules
|
||||||
|
.borrow()
|
||||||
|
.get_unchecked(value.0.0)
|
||||||
|
.functions
|
||||||
|
.get_unchecked(value.1)
|
||||||
|
.data
|
||||||
|
.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) unsafe fn block_data(&self, value: &BlockValue) -> BlockData {
|
||||||
|
unsafe {
|
||||||
|
self.modules
|
||||||
|
.borrow()
|
||||||
|
.get_unchecked(value.0.0.0)
|
||||||
|
.functions
|
||||||
|
.get_unchecked(value.0.1)
|
||||||
|
.blocks
|
||||||
|
.get_unchecked(value.1)
|
||||||
|
.data
|
||||||
|
.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) unsafe fn instr_data(&self, value: &InstructionValue) -> InstructionData {
|
||||||
|
unsafe {
|
||||||
|
self.modules
|
||||||
|
.borrow()
|
||||||
|
.get_unchecked(value.0.0.0.0)
|
||||||
|
.functions
|
||||||
|
.get_unchecked(value.0.0.1)
|
||||||
|
.blocks
|
||||||
|
.get_unchecked(value.0.1)
|
||||||
|
.instructions
|
||||||
|
.get_unchecked(value.1)
|
||||||
|
.data
|
||||||
|
.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn get_modules(&self) -> Rc<RefCell<Vec<ModuleHolder>>> {
|
||||||
|
self.modules.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
// pub(crate) fn get_functions(&self, module: ModuleValue) -> Vec<(FunctionValue, FunctionData)> {
|
||||||
|
// unsafe {
|
||||||
|
// self.modules
|
||||||
|
// .borrow()
|
||||||
|
// .get_unchecked(module.0)
|
||||||
|
// .2
|
||||||
|
// .iter()
|
||||||
|
// .map(|h| (h.0, h.1.clone()))
|
||||||
|
// .collect()
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// pub(crate) fn get_blocks(&self, function: FunctionValue) -> Vec<(BlockValue, BlockData)> {
|
||||||
|
// unsafe {
|
||||||
|
// self.modules
|
||||||
|
// .borrow()
|
||||||
|
// .get_unchecked(function.0.0)
|
||||||
|
// .2
|
||||||
|
// .get_unchecked(function.1)
|
||||||
|
// .2
|
||||||
|
// .iter()
|
||||||
|
// .map(|h| (h.0, h.1.clone()))
|
||||||
|
// .collect()
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// pub(crate) fn get_instructions(
|
||||||
|
// &self,
|
||||||
|
// block: BlockValue,
|
||||||
|
// ) -> (
|
||||||
|
// Vec<(InstructionValue, InstructionData)>,
|
||||||
|
// Option<TerminatorKind>,
|
||||||
|
// ) {
|
||||||
|
// unsafe {
|
||||||
|
// let modules = self.modules.borrow();
|
||||||
|
// let block = modules
|
||||||
|
// .get_unchecked(block.0.0.0)
|
||||||
|
// .2
|
||||||
|
// .get_unchecked(block.0.1)
|
||||||
|
// .2
|
||||||
|
// .get_unchecked(block.1);
|
||||||
|
// (
|
||||||
|
// block.2.iter().map(|h| (h.0, h.1.clone())).collect(),
|
||||||
|
// block.1.terminator.clone(),
|
||||||
|
// )
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
pub fn check_instruction(&self, instruction: &InstructionValue) -> Result<(), ()> {
|
||||||
|
use super::InstructionKind::*;
|
||||||
|
unsafe {
|
||||||
|
match self.instr_data(&instruction).kind {
|
||||||
|
Param(_) => Ok(()),
|
||||||
|
Constant(_) => Ok(()),
|
||||||
|
Add(lhs, rhs) => match_types(&lhs, &rhs, &self).map(|_| ()),
|
||||||
|
Sub(lhs, rhs) => match_types(&lhs, &rhs, &self).map(|_| ()),
|
||||||
|
ICmp(_, lhs, rhs) => {
|
||||||
|
let t = match_types(&lhs, &rhs, self)?;
|
||||||
|
if t.comparable() {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(()) // TODO error: Types not comparable
|
||||||
|
}
|
||||||
|
}
|
||||||
|
FunctionCall(fun, params) => {
|
||||||
|
let param_types = self.function_data(&fun).params;
|
||||||
|
if param_types.len() != params.len() {
|
||||||
|
return Err(()); // TODO error: invalid amount of params
|
||||||
|
}
|
||||||
|
for (a, b) in param_types.iter().zip(params) {
|
||||||
|
if *a != b.get_type(&self)? {
|
||||||
|
return Err(()); // TODO error: params do not match
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Phi(vals) => {
|
||||||
|
let mut iter = vals.iter();
|
||||||
|
// TODO error: Phi must contain at least one item
|
||||||
|
let first = iter.next().ok_or(())?;
|
||||||
|
for item in iter {
|
||||||
|
match_types(first, item, &self)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InstructionValue {
|
||||||
|
pub fn get_type(&self, builder: &Builder) -> Result<Type, ()> {
|
||||||
|
use InstructionKind::*;
|
||||||
|
use Type::*;
|
||||||
|
unsafe {
|
||||||
|
match &builder.instr_data(self).kind {
|
||||||
|
Param(nth) => builder
|
||||||
|
.function_data(&self.0.0)
|
||||||
|
.params
|
||||||
|
.get(*nth)
|
||||||
|
.copied()
|
||||||
|
.ok_or(()),
|
||||||
|
Constant(c) => Ok(c.get_type()),
|
||||||
|
Add(lhs, rhs) => match_types(lhs, rhs, &builder),
|
||||||
|
Sub(lhs, rhs) => match_types(lhs, rhs, &builder),
|
||||||
|
ICmp(pred, lhs, rhs) => Ok(Type::Bool),
|
||||||
|
FunctionCall(function_value, _) => Ok(builder.function_data(function_value).ret),
|
||||||
|
Phi(values) => values.first().ok_or(()).and_then(|v| v.get_type(&builder)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConstValue {
|
||||||
|
pub fn get_type(&self) -> Type {
|
||||||
|
use Type::*;
|
||||||
|
match self {
|
||||||
|
ConstValue::I32(_) => I32,
|
||||||
|
ConstValue::I16(_) => I16,
|
||||||
|
ConstValue::U32(_) => U32,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Type {
|
||||||
|
pub fn comparable(&self) -> bool {
|
||||||
|
match self {
|
||||||
|
Type::I32 => true,
|
||||||
|
Type::I16 => true,
|
||||||
|
Type::U32 => true,
|
||||||
|
Type::Bool => true,
|
||||||
|
Type::Void => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn signed(&self) -> bool {
|
||||||
|
match self {
|
||||||
|
Type::I32 => true,
|
||||||
|
Type::I16 => true,
|
||||||
|
Type::U32 => false,
|
||||||
|
Type::Bool => false,
|
||||||
|
Type::Void => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TerminatorKind {
|
||||||
|
pub fn get_type(&self, builder: &Builder) -> Result<Type, ()> {
|
||||||
|
use TerminatorKind::*;
|
||||||
|
match self {
|
||||||
|
Ret(instr_val) => instr_val.get_type(builder),
|
||||||
|
Branch(_) => Ok(Type::Void),
|
||||||
|
CondBr(_, _, _) => Ok(Type::Void),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
386
reid-llvm-lib/src/compile.rs
Normal file
386
reid-llvm-lib/src/compile.rs
Normal file
@ -0,0 +1,386 @@
|
|||||||
|
use std::{collections::HashMap, ffi::CString, hash::Hash, process::Termination, ptr::null_mut};
|
||||||
|
|
||||||
|
use llvm_sys::{
|
||||||
|
LLVMIntPredicate,
|
||||||
|
analysis::LLVMVerifyModule,
|
||||||
|
core::*,
|
||||||
|
prelude::*,
|
||||||
|
target::{
|
||||||
|
LLVM_InitializeAllAsmParsers, LLVM_InitializeAllAsmPrinters, LLVM_InitializeAllTargetInfos,
|
||||||
|
LLVM_InitializeAllTargetMCs, LLVM_InitializeAllTargets, LLVMSetModuleDataLayout,
|
||||||
|
},
|
||||||
|
target_machine::{
|
||||||
|
LLVMCodeGenFileType, LLVMCreateTargetDataLayout, LLVMCreateTargetMachine,
|
||||||
|
LLVMGetDefaultTargetTriple, LLVMGetTargetFromTriple, LLVMTargetMachineEmitToFile,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::util::{ErrorMessageHolder, from_cstring, into_cstring};
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
ConstValue, Context, Function, IntPredicate, Module, TerminatorKind, Type,
|
||||||
|
builder::{
|
||||||
|
BlockHolder, BlockValue, Builder, FunctionHolder, FunctionValue, InstructionHolder,
|
||||||
|
InstructionValue, ModuleHolder,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub struct LLVMContext {
|
||||||
|
context_ref: LLVMContextRef,
|
||||||
|
builder_ref: LLVMBuilderRef,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Context {
|
||||||
|
pub fn compile(&self) {
|
||||||
|
unsafe {
|
||||||
|
let context_ref = LLVMContextCreate();
|
||||||
|
|
||||||
|
let context = LLVMContext {
|
||||||
|
context_ref,
|
||||||
|
builder_ref: LLVMCreateBuilderInContext(context_ref),
|
||||||
|
};
|
||||||
|
|
||||||
|
for holder in self.builder.get_modules().borrow().iter() {
|
||||||
|
holder.compile(&context, &self.builder);
|
||||||
|
}
|
||||||
|
|
||||||
|
LLVMDisposeBuilder(context.builder_ref);
|
||||||
|
LLVMContextDispose(context.context_ref);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct LLVMModule<'a> {
|
||||||
|
builder: &'a Builder,
|
||||||
|
context_ref: LLVMContextRef,
|
||||||
|
builder_ref: LLVMBuilderRef,
|
||||||
|
module_ref: LLVMModuleRef,
|
||||||
|
functions: HashMap<FunctionValue, LLVMFunction>,
|
||||||
|
blocks: HashMap<BlockValue, LLVMBasicBlockRef>,
|
||||||
|
values: HashMap<InstructionValue, LLVMValue>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub struct LLVMFunction {
|
||||||
|
type_ref: LLVMTypeRef,
|
||||||
|
value_ref: LLVMValueRef,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct LLVMValue {
|
||||||
|
ty: Type,
|
||||||
|
value_ref: LLVMValueRef,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ModuleHolder {
|
||||||
|
fn compile(&self, context: &LLVMContext, builder: &Builder) {
|
||||||
|
unsafe {
|
||||||
|
let module_ref = LLVMModuleCreateWithNameInContext(
|
||||||
|
into_cstring(&self.data.name).as_ptr(),
|
||||||
|
context.context_ref,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Compile the contents
|
||||||
|
|
||||||
|
let mut functions = HashMap::new();
|
||||||
|
|
||||||
|
for function in &self.functions {
|
||||||
|
functions.insert(
|
||||||
|
function.value,
|
||||||
|
function.compile_signature(context, module_ref),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut module = LLVMModule {
|
||||||
|
builder,
|
||||||
|
context_ref: context.context_ref,
|
||||||
|
builder_ref: context.builder_ref,
|
||||||
|
module_ref,
|
||||||
|
functions,
|
||||||
|
blocks: HashMap::new(),
|
||||||
|
values: HashMap::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
for function in &self.functions {
|
||||||
|
function.compile(&mut module);
|
||||||
|
}
|
||||||
|
|
||||||
|
LLVM_InitializeAllTargets();
|
||||||
|
LLVM_InitializeAllTargetInfos();
|
||||||
|
LLVM_InitializeAllTargetMCs();
|
||||||
|
LLVM_InitializeAllAsmParsers();
|
||||||
|
LLVM_InitializeAllAsmPrinters();
|
||||||
|
|
||||||
|
let triple = LLVMGetDefaultTargetTriple();
|
||||||
|
|
||||||
|
let mut target: _ = null_mut();
|
||||||
|
let mut err = ErrorMessageHolder::null();
|
||||||
|
LLVMGetTargetFromTriple(triple, &mut target, err.borrow_mut());
|
||||||
|
println!("{:?}, {:?}", from_cstring(triple), target);
|
||||||
|
err.into_result().unwrap();
|
||||||
|
|
||||||
|
let target_machine = LLVMCreateTargetMachine(
|
||||||
|
target,
|
||||||
|
triple,
|
||||||
|
c"generic".as_ptr(),
|
||||||
|
c"".as_ptr(),
|
||||||
|
llvm_sys::target_machine::LLVMCodeGenOptLevel::LLVMCodeGenLevelNone,
|
||||||
|
llvm_sys::target_machine::LLVMRelocMode::LLVMRelocDefault,
|
||||||
|
llvm_sys::target_machine::LLVMCodeModel::LLVMCodeModelDefault,
|
||||||
|
);
|
||||||
|
|
||||||
|
let data_layout = LLVMCreateTargetDataLayout(target_machine);
|
||||||
|
LLVMSetTarget(module_ref, triple);
|
||||||
|
LLVMSetModuleDataLayout(module_ref, data_layout);
|
||||||
|
|
||||||
|
let mut err = ErrorMessageHolder::null();
|
||||||
|
LLVMVerifyModule(
|
||||||
|
module_ref,
|
||||||
|
llvm_sys::analysis::LLVMVerifierFailureAction::LLVMPrintMessageAction,
|
||||||
|
err.borrow_mut(),
|
||||||
|
);
|
||||||
|
err.into_result().unwrap();
|
||||||
|
|
||||||
|
let mut err = ErrorMessageHolder::null();
|
||||||
|
LLVMTargetMachineEmitToFile(
|
||||||
|
target_machine,
|
||||||
|
module_ref,
|
||||||
|
CString::new("hello.asm").unwrap().into_raw(),
|
||||||
|
LLVMCodeGenFileType::LLVMAssemblyFile,
|
||||||
|
err.borrow_mut(),
|
||||||
|
);
|
||||||
|
err.into_result().unwrap();
|
||||||
|
|
||||||
|
let mut err = ErrorMessageHolder::null();
|
||||||
|
LLVMTargetMachineEmitToFile(
|
||||||
|
target_machine,
|
||||||
|
module_ref,
|
||||||
|
CString::new("hello.o").unwrap().into_raw(),
|
||||||
|
LLVMCodeGenFileType::LLVMObjectFile,
|
||||||
|
err.borrow_mut(),
|
||||||
|
);
|
||||||
|
err.into_result().unwrap();
|
||||||
|
|
||||||
|
let module_str = from_cstring(LLVMPrintModuleToString(module_ref));
|
||||||
|
println!("{}", module_str.unwrap());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FunctionHolder {
|
||||||
|
unsafe fn compile_signature(
|
||||||
|
&self,
|
||||||
|
context: &LLVMContext,
|
||||||
|
module_ref: LLVMModuleRef,
|
||||||
|
) -> LLVMFunction {
|
||||||
|
unsafe {
|
||||||
|
let ret_type = self.data.ret.as_llvm(context.context_ref);
|
||||||
|
let mut param_types: Vec<LLVMTypeRef> = self
|
||||||
|
.data
|
||||||
|
.params
|
||||||
|
.iter()
|
||||||
|
.map(|t| t.as_llvm(context.context_ref))
|
||||||
|
.collect();
|
||||||
|
let param_ptr = param_types.as_mut_ptr();
|
||||||
|
let param_len = param_types.len();
|
||||||
|
|
||||||
|
let fn_type = LLVMFunctionType(ret_type, param_ptr, param_len as u32, 0);
|
||||||
|
|
||||||
|
let function_ref =
|
||||||
|
LLVMAddFunction(module_ref, into_cstring(&self.data.name).as_ptr(), fn_type);
|
||||||
|
|
||||||
|
LLVMFunction {
|
||||||
|
type_ref: fn_type,
|
||||||
|
value_ref: function_ref,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn compile(&self, module: &mut LLVMModule) {
|
||||||
|
unsafe {
|
||||||
|
let own_function = *module.functions.get(&self.value).unwrap();
|
||||||
|
|
||||||
|
for block in &self.blocks {
|
||||||
|
let block_ref = LLVMCreateBasicBlockInContext(
|
||||||
|
module.context_ref,
|
||||||
|
into_cstring(&self.data.name).as_ptr(),
|
||||||
|
);
|
||||||
|
LLVMAppendExistingBasicBlock(own_function.value_ref, block_ref);
|
||||||
|
module.blocks.insert(block.value, block_ref);
|
||||||
|
}
|
||||||
|
|
||||||
|
for block in &self.blocks {
|
||||||
|
block.compile(module, &own_function);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BlockHolder {
|
||||||
|
unsafe fn compile(&self, module: &mut LLVMModule, function: &LLVMFunction) {
|
||||||
|
unsafe {
|
||||||
|
let block_ref = *module.blocks.get(&self.value).unwrap();
|
||||||
|
LLVMPositionBuilderAtEnd(module.builder_ref, block_ref);
|
||||||
|
|
||||||
|
for instruction in &self.instructions {
|
||||||
|
let key = instruction.value;
|
||||||
|
let ret = instruction.compile(module, function, block_ref);
|
||||||
|
module.values.insert(key, ret);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.data
|
||||||
|
.terminator
|
||||||
|
.clone()
|
||||||
|
.expect(&format!(
|
||||||
|
"Block {} does not have a terminator!",
|
||||||
|
self.data.name
|
||||||
|
))
|
||||||
|
.compile(module, function, block_ref);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InstructionHolder {
|
||||||
|
unsafe fn compile(
|
||||||
|
&self,
|
||||||
|
module: &LLVMModule,
|
||||||
|
function: &LLVMFunction,
|
||||||
|
block: LLVMBasicBlockRef,
|
||||||
|
) -> LLVMValue {
|
||||||
|
let ty = self.value.get_type(module.builder).unwrap();
|
||||||
|
let val = unsafe {
|
||||||
|
use super::InstructionKind::*;
|
||||||
|
match &self.data.kind {
|
||||||
|
Param(nth) => LLVMGetParam(function.value_ref, *nth as u32),
|
||||||
|
Constant(val) => val.as_llvm(module.context_ref),
|
||||||
|
Add(lhs, rhs) => {
|
||||||
|
let lhs_val = module.values.get(&lhs).unwrap().value_ref;
|
||||||
|
let rhs_val = module.values.get(&rhs).unwrap().value_ref;
|
||||||
|
LLVMBuildAdd(module.builder_ref, lhs_val, rhs_val, c"add".as_ptr())
|
||||||
|
}
|
||||||
|
Sub(lhs, rhs) => {
|
||||||
|
let lhs_val = module.values.get(&lhs).unwrap().value_ref;
|
||||||
|
let rhs_val = module.values.get(&rhs).unwrap().value_ref;
|
||||||
|
LLVMBuildSub(module.builder_ref, lhs_val, rhs_val, c"sub".as_ptr())
|
||||||
|
}
|
||||||
|
ICmp(pred, lhs, rhs) => {
|
||||||
|
let lhs_val = module.values.get(&lhs).unwrap().value_ref;
|
||||||
|
let rhs_val = module.values.get(&rhs).unwrap().value_ref;
|
||||||
|
LLVMBuildICmp(
|
||||||
|
module.builder_ref,
|
||||||
|
pred.as_llvm(ty.signed()),
|
||||||
|
lhs_val,
|
||||||
|
rhs_val,
|
||||||
|
c"icmp".as_ptr(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
FunctionCall(function_value, instruction_values) => {
|
||||||
|
let fun = module.functions.get(&function_value).unwrap();
|
||||||
|
let mut param_list: Vec<LLVMValueRef> = instruction_values
|
||||||
|
.iter()
|
||||||
|
.map(|i| module.values.get(i).unwrap().value_ref)
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
LLVMBuildCall2(
|
||||||
|
module.builder_ref,
|
||||||
|
fun.type_ref,
|
||||||
|
fun.value_ref,
|
||||||
|
param_list.as_mut_ptr(),
|
||||||
|
param_list.len() as u32,
|
||||||
|
c"call".as_ptr(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
Phi(values) => {
|
||||||
|
let mut inc_values = Vec::new();
|
||||||
|
let mut inc_blocks = Vec::new();
|
||||||
|
for item in values {
|
||||||
|
inc_values.push(module.values.get(&item).unwrap().value_ref);
|
||||||
|
inc_blocks.push(*module.blocks.get(&item.0).unwrap());
|
||||||
|
}
|
||||||
|
let phi = LLVMBuildPhi(
|
||||||
|
module.builder_ref,
|
||||||
|
ty.as_llvm(module.context_ref),
|
||||||
|
c"phi".as_ptr(),
|
||||||
|
);
|
||||||
|
LLVMAddIncoming(
|
||||||
|
phi,
|
||||||
|
inc_values.as_mut_ptr(),
|
||||||
|
inc_blocks.as_mut_ptr(),
|
||||||
|
values.len() as u32,
|
||||||
|
);
|
||||||
|
phi
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
LLVMValue { ty, value_ref: val }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TerminatorKind {
|
||||||
|
fn compile(
|
||||||
|
&self,
|
||||||
|
module: &LLVMModule,
|
||||||
|
function: &LLVMFunction,
|
||||||
|
block: LLVMBasicBlockRef,
|
||||||
|
) -> LLVMValue {
|
||||||
|
let ty = self.get_type(module.builder).unwrap();
|
||||||
|
let val = unsafe {
|
||||||
|
match self {
|
||||||
|
TerminatorKind::Ret(val) => {
|
||||||
|
let value = module.values.get(val).unwrap();
|
||||||
|
LLVMBuildRet(module.builder_ref, value.value_ref)
|
||||||
|
}
|
||||||
|
TerminatorKind::Branch(block_value) => {
|
||||||
|
let dest = *module.blocks.get(block_value).unwrap();
|
||||||
|
LLVMBuildBr(module.builder_ref, dest)
|
||||||
|
}
|
||||||
|
TerminatorKind::CondBr(cond, then_b, else_b) => {
|
||||||
|
let cond_val = module.values.get(cond).unwrap().value_ref;
|
||||||
|
let then_bb = *module.blocks.get(then_b).unwrap();
|
||||||
|
let else_bb = *module.blocks.get(else_b).unwrap();
|
||||||
|
LLVMBuildCondBr(module.builder_ref, cond_val, then_bb, else_bb)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
LLVMValue { ty, value_ref: val }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntPredicate {
|
||||||
|
fn as_llvm(&self, signed: bool) -> LLVMIntPredicate {
|
||||||
|
use IntPredicate::*;
|
||||||
|
use LLVMIntPredicate::*;
|
||||||
|
match (self, signed) {
|
||||||
|
(LessThan, true) => LLVMIntSLT,
|
||||||
|
(GreaterThan, true) => LLVMIntSGT,
|
||||||
|
(LessThan, false) => LLVMIntULT,
|
||||||
|
(GreaterThan, false) => LLVMIntUGT,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConstValue {
|
||||||
|
fn as_llvm(&self, context: LLVMContextRef) -> LLVMValueRef {
|
||||||
|
unsafe {
|
||||||
|
let t = self.get_type().as_llvm(context);
|
||||||
|
match *self {
|
||||||
|
ConstValue::I32(val) => LLVMConstInt(t, val as u64, 1),
|
||||||
|
ConstValue::I16(val) => LLVMConstInt(t, val as u64, 1),
|
||||||
|
ConstValue::U32(val) => LLVMConstInt(t, val as u64, 0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Type {
|
||||||
|
fn as_llvm(&self, context: LLVMContextRef) -> LLVMTypeRef {
|
||||||
|
unsafe {
|
||||||
|
match self {
|
||||||
|
Type::I32 => LLVMInt32TypeInContext(context),
|
||||||
|
Type::I16 => LLVMInt16TypeInContext(context),
|
||||||
|
Type::U32 => LLVMInt32TypeInContext(context),
|
||||||
|
Type::Bool => LLVMInt1TypeInContext(context),
|
||||||
|
Type::Void => LLVMVoidType(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,454 +1,233 @@
|
|||||||
use std::ffi::CString;
|
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::net::Incoming;
|
|
||||||
use std::ptr::null_mut;
|
|
||||||
|
|
||||||
use llvm_sys::analysis::LLVMVerifyModule;
|
use builder::{BlockValue, Builder, FunctionValue, InstructionValue, ModuleValue};
|
||||||
use llvm_sys::target::{
|
|
||||||
LLVM_InitializeAllAsmParsers, LLVM_InitializeAllAsmPrinters, LLVM_InitializeAllTargetInfos,
|
|
||||||
LLVM_InitializeAllTargetMCs, LLVM_InitializeAllTargets, LLVMSetModuleDataLayout,
|
|
||||||
};
|
|
||||||
use llvm_sys::target_machine::{
|
|
||||||
LLVMCodeGenFileType, LLVMCreateTargetDataLayout, LLVMCreateTargetMachine,
|
|
||||||
LLVMGetDefaultTargetTriple, LLVMGetTargetFromTriple, LLVMTargetMachineEmitToFile,
|
|
||||||
};
|
|
||||||
use llvm_sys::{LLVMBuilder, LLVMContext, LLVMIntPredicate, core::*, prelude::*};
|
|
||||||
use types::{BasicType, BasicValue, FunctionType, IntegerType, Value};
|
|
||||||
use util::{ErrorMessageHolder, from_cstring, into_cstring};
|
|
||||||
|
|
||||||
pub mod types;
|
pub mod builder;
|
||||||
|
pub mod compile;
|
||||||
mod util;
|
mod util;
|
||||||
|
|
||||||
pub enum IntPredicate {
|
// pub struct InstructionValue(BlockValue, usize);
|
||||||
SLT,
|
|
||||||
SGT,
|
|
||||||
|
|
||||||
ULT,
|
|
||||||
UGT,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl IntPredicate {
|
|
||||||
pub fn as_llvm(&self) -> LLVMIntPredicate {
|
|
||||||
match *self {
|
|
||||||
Self::SLT => LLVMIntPredicate::LLVMIntSLT,
|
|
||||||
Self::SGT => LLVMIntPredicate::LLVMIntSGT,
|
|
||||||
Self::ULT => LLVMIntPredicate::LLVMIntULT,
|
|
||||||
Self::UGT => LLVMIntPredicate::LLVMIntUGT,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
pub struct Context {
|
pub struct Context {
|
||||||
pub(crate) context_ref: *mut LLVMContext,
|
builder: Builder,
|
||||||
pub(crate) builder_ref: *mut LLVMBuilder,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Context {
|
impl Context {
|
||||||
pub fn new() -> Context {
|
pub fn new() -> Context {
|
||||||
unsafe {
|
Context {
|
||||||
// Set up a context, module and builder in that context.
|
builder: Builder::new(),
|
||||||
let context = LLVMContextCreate();
|
|
||||||
let builder = LLVMCreateBuilderInContext(context);
|
|
||||||
|
|
||||||
Context {
|
|
||||||
context_ref: context,
|
|
||||||
builder_ref: builder,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn type_i1<'a>(&'a self) -> IntegerType<'a> {
|
pub fn module<'ctx>(&'ctx self, name: &str) -> Module<'ctx> {
|
||||||
IntegerType::in_context(&self, 1)
|
let value = self.builder.add_module(ModuleData {
|
||||||
}
|
name: name.to_owned(),
|
||||||
|
});
|
||||||
pub fn type_i8<'a>(&'a self) -> IntegerType<'a> {
|
Module {
|
||||||
IntegerType::in_context(&self, 8)
|
phantom: PhantomData,
|
||||||
}
|
builder: self.builder.clone(),
|
||||||
|
value,
|
||||||
pub fn type_i16<'a>(&'a self) -> IntegerType<'a> {
|
}
|
||||||
IntegerType::in_context(&self, 16)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn type_i32<'a>(&'a self) -> IntegerType<'a> {
|
|
||||||
IntegerType::in_context(&self, 32)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn module(&self, name: &str) -> Module {
|
|
||||||
Module::with_name(self, name)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for Context {
|
#[derive(Debug, Clone, Hash)]
|
||||||
fn drop(&mut self) {
|
pub struct ModuleData {
|
||||||
// Clean up. Values created in the context mostly get cleaned up there.
|
name: String,
|
||||||
unsafe {
|
|
||||||
LLVMDisposeBuilder(self.builder_ref);
|
|
||||||
LLVMContextDispose(self.context_ref);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Module<'ctx> {
|
pub struct Module<'ctx> {
|
||||||
context: &'ctx Context,
|
phantom: PhantomData<&'ctx ()>,
|
||||||
module_ref: LLVMModuleRef,
|
builder: Builder,
|
||||||
name: CString,
|
value: ModuleValue,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'ctx> Module<'ctx> {
|
impl<'ctx> Module<'ctx> {
|
||||||
fn with_name(context: &'ctx Context, name: &str) -> Module<'ctx> {
|
pub fn function(&mut self, name: &str, ret: Type, params: Vec<Type>) -> Function<'ctx> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let cstring_name = into_cstring(name);
|
|
||||||
let module_ref =
|
|
||||||
LLVMModuleCreateWithNameInContext(cstring_name.as_ptr(), context.context_ref);
|
|
||||||
Module {
|
|
||||||
context,
|
|
||||||
module_ref,
|
|
||||||
name: cstring_name,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn add_function(&'ctx self, fn_type: FunctionType<'ctx>, name: &str) -> Function<'ctx> {
|
|
||||||
unsafe {
|
|
||||||
let name_cstring = into_cstring(name);
|
|
||||||
let function_ref =
|
|
||||||
LLVMAddFunction(self.module_ref, name_cstring.as_ptr(), fn_type.llvm_type());
|
|
||||||
Function {
|
Function {
|
||||||
module: self,
|
phantom: PhantomData,
|
||||||
fn_type,
|
builder: self.builder.clone(),
|
||||||
name: name_cstring,
|
value: self.builder.add_function(
|
||||||
fn_ref: function_ref,
|
&self.value,
|
||||||
|
FunctionData {
|
||||||
|
name: name.to_owned(),
|
||||||
|
ret,
|
||||||
|
params,
|
||||||
|
},
|
||||||
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn print_to_string(&self) -> Result<String, String> {
|
pub fn value(&self) -> ModuleValue {
|
||||||
unsafe {
|
self.value
|
||||||
LLVM_InitializeAllTargets();
|
|
||||||
LLVM_InitializeAllTargetInfos();
|
|
||||||
LLVM_InitializeAllTargetMCs();
|
|
||||||
LLVM_InitializeAllAsmParsers();
|
|
||||||
LLVM_InitializeAllAsmPrinters();
|
|
||||||
|
|
||||||
let triple = LLVMGetDefaultTargetTriple();
|
|
||||||
|
|
||||||
let mut target: _ = null_mut();
|
|
||||||
let mut err = ErrorMessageHolder::null();
|
|
||||||
LLVMGetTargetFromTriple(triple, &mut target, err.borrow_mut());
|
|
||||||
println!("{:?}, {:?}", from_cstring(triple), target);
|
|
||||||
err.into_result().unwrap();
|
|
||||||
|
|
||||||
let target_machine = LLVMCreateTargetMachine(
|
|
||||||
target,
|
|
||||||
triple,
|
|
||||||
c"generic".as_ptr(),
|
|
||||||
c"".as_ptr(),
|
|
||||||
llvm_sys::target_machine::LLVMCodeGenOptLevel::LLVMCodeGenLevelNone,
|
|
||||||
llvm_sys::target_machine::LLVMRelocMode::LLVMRelocDefault,
|
|
||||||
llvm_sys::target_machine::LLVMCodeModel::LLVMCodeModelDefault,
|
|
||||||
);
|
|
||||||
|
|
||||||
let data_layout = LLVMCreateTargetDataLayout(target_machine);
|
|
||||||
LLVMSetTarget(self.module_ref, triple);
|
|
||||||
LLVMSetModuleDataLayout(self.module_ref, data_layout);
|
|
||||||
|
|
||||||
let mut err = ErrorMessageHolder::null();
|
|
||||||
LLVMVerifyModule(
|
|
||||||
self.module_ref,
|
|
||||||
llvm_sys::analysis::LLVMVerifierFailureAction::LLVMPrintMessageAction,
|
|
||||||
err.borrow_mut(),
|
|
||||||
);
|
|
||||||
err.into_result().unwrap();
|
|
||||||
|
|
||||||
let mut err = ErrorMessageHolder::null();
|
|
||||||
LLVMTargetMachineEmitToFile(
|
|
||||||
target_machine,
|
|
||||||
self.module_ref,
|
|
||||||
CString::new("hello.asm").unwrap().into_raw(),
|
|
||||||
LLVMCodeGenFileType::LLVMAssemblyFile,
|
|
||||||
err.borrow_mut(),
|
|
||||||
);
|
|
||||||
err.into_result().unwrap();
|
|
||||||
|
|
||||||
let mut err = ErrorMessageHolder::null();
|
|
||||||
LLVMTargetMachineEmitToFile(
|
|
||||||
target_machine,
|
|
||||||
self.module_ref,
|
|
||||||
CString::new("hello.o").unwrap().into_raw(),
|
|
||||||
LLVMCodeGenFileType::LLVMObjectFile,
|
|
||||||
err.borrow_mut(),
|
|
||||||
);
|
|
||||||
err.into_result().unwrap();
|
|
||||||
|
|
||||||
from_cstring(LLVMPrintModuleToString(self.module_ref)).ok_or("UTF-8 error".to_owned())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> Drop for Module<'a> {
|
#[derive(Debug, Clone, Hash)]
|
||||||
fn drop(&mut self) {
|
pub struct FunctionData {
|
||||||
// Clean up. Values created in the context mostly get cleaned up there.
|
name: String,
|
||||||
unsafe {
|
ret: Type,
|
||||||
LLVMDisposeModule(self.module_ref);
|
params: Vec<Type>,
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct Function<'ctx> {
|
pub struct Function<'ctx> {
|
||||||
module: &'ctx Module<'ctx>,
|
phantom: PhantomData<&'ctx ()>,
|
||||||
name: CString,
|
builder: Builder,
|
||||||
fn_type: FunctionType<'ctx>,
|
value: FunctionValue,
|
||||||
fn_ref: LLVMValueRef,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'ctx> Function<'ctx> {
|
impl<'ctx> Function<'ctx> {
|
||||||
pub fn block<T: Into<String>>(&'ctx self, name: T) -> BasicBlock<'ctx> {
|
pub fn block(&self, name: &str) -> Block<'ctx> {
|
||||||
BasicBlock::in_function(&self, name.into())
|
unsafe {
|
||||||
|
Block {
|
||||||
|
phantom: PhantomData,
|
||||||
|
builder: self.builder.clone(),
|
||||||
|
value: self.builder.add_block(
|
||||||
|
&self.value,
|
||||||
|
BlockData {
|
||||||
|
name: name.to_owned(),
|
||||||
|
terminator: None,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_param<T: BasicValue<'ctx>>(
|
pub fn value(&self) -> FunctionValue {
|
||||||
&'ctx self,
|
self.value
|
||||||
nth: usize,
|
|
||||||
param_type: T::BaseType,
|
|
||||||
) -> Result<T, String> {
|
|
||||||
if let Some(actual_type) = self.fn_type.param_types.iter().nth(nth) {
|
|
||||||
if param_type.llvm_type() != *actual_type {
|
|
||||||
return Err(String::from("Wrong type"));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return Err(String::from("nth too large"));
|
|
||||||
}
|
|
||||||
unsafe { Ok(T::from_llvm(LLVMGetParam(self.fn_ref, nth as u32))) }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct BasicBlock<'ctx> {
|
#[derive(Debug, Clone, Hash)]
|
||||||
function: &'ctx Function<'ctx>,
|
pub struct BlockData {
|
||||||
builder_ref: LLVMBuilderRef,
|
|
||||||
name: String,
|
name: String,
|
||||||
blockref: LLVMBasicBlockRef,
|
terminator: Option<TerminatorKind>,
|
||||||
inserted: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'ctx> BasicBlock<'ctx> {
|
pub struct Block<'builder> {
|
||||||
fn in_function(function: &'ctx Function<'ctx>, name: String) -> BasicBlock<'ctx> {
|
phantom: PhantomData<&'builder ()>,
|
||||||
|
builder: Builder,
|
||||||
|
value: BlockValue,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'builder> Block<'builder> {
|
||||||
|
pub fn build(&mut self, instruction: InstructionKind) -> Result<InstructionValue, ()> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let block_name = into_cstring(name.clone());
|
self.builder
|
||||||
let block_ref = LLVMCreateBasicBlockInContext(
|
.add_instruction(&self.value, InstructionData { kind: instruction })
|
||||||
function.module.context.context_ref,
|
|
||||||
block_name.as_ptr(),
|
|
||||||
);
|
|
||||||
LLVMAppendExistingBasicBlock(function.fn_ref, block_ref);
|
|
||||||
BasicBlock {
|
|
||||||
function: function,
|
|
||||||
builder_ref: function.module.context.builder_ref,
|
|
||||||
name,
|
|
||||||
blockref: block_ref,
|
|
||||||
inserted: false,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
pub fn terminate(&mut self, instruction: TerminatorKind) -> Result<(), ()> {
|
||||||
pub fn integer_compare<T: BasicValue<'ctx>>(
|
unsafe { self.builder.terminate(&self.value, instruction) }
|
||||||
&self,
|
|
||||||
lhs: &T,
|
|
||||||
rhs: &T,
|
|
||||||
comparison: &IntPredicate,
|
|
||||||
name: &str,
|
|
||||||
) -> Result<T, ()> {
|
|
||||||
unsafe {
|
|
||||||
LLVMPositionBuilderAtEnd(self.builder_ref, self.blockref);
|
|
||||||
let value = LLVMBuildICmp(
|
|
||||||
self.builder_ref,
|
|
||||||
comparison.as_llvm(),
|
|
||||||
lhs.llvm_value(),
|
|
||||||
rhs.llvm_value(),
|
|
||||||
into_cstring(name).as_ptr(),
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(T::from_llvm(value))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[must_use]
|
pub fn value(&self) -> BlockValue {
|
||||||
pub fn call<T: BasicValue<'ctx>>(
|
self.value
|
||||||
&self,
|
|
||||||
callee: &Function<'ctx>,
|
|
||||||
params: Vec<Value<'ctx>>,
|
|
||||||
name: &str,
|
|
||||||
) -> Result<T, ()> {
|
|
||||||
if params.len() != callee.fn_type.param_types.len() {
|
|
||||||
return Err(()); // TODO invalid amount of parameters
|
|
||||||
}
|
|
||||||
for (t1, t2) in callee.fn_type.param_types.iter().zip(¶ms) {
|
|
||||||
if t1 != &t2.llvm_type() {
|
|
||||||
return Err(()); // TODO wrong types in parameters
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !T::BaseType::is_type(callee.fn_type.return_type) {
|
|
||||||
return Err(()); // TODO wrong return type
|
|
||||||
}
|
|
||||||
unsafe {
|
|
||||||
let mut param_list: Vec<LLVMValueRef> = params.iter().map(|p| p.llvm_value()).collect();
|
|
||||||
LLVMPositionBuilderAtEnd(self.builder_ref, self.blockref);
|
|
||||||
let ret_val = LLVMBuildCall2(
|
|
||||||
self.builder_ref,
|
|
||||||
callee.fn_type.llvm_type(),
|
|
||||||
callee.fn_ref,
|
|
||||||
param_list.as_mut_ptr(),
|
|
||||||
param_list.len() as u32,
|
|
||||||
into_cstring(name).as_ptr(),
|
|
||||||
);
|
|
||||||
Ok(T::from_llvm(ret_val))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn add<T: BasicValue<'ctx>>(&self, lhs: &T, rhs: &T, name: &str) -> Result<T, ()> {
|
|
||||||
if lhs.llvm_type() != rhs.llvm_type() {
|
|
||||||
return Err(()); // TODO error
|
|
||||||
}
|
|
||||||
unsafe {
|
|
||||||
LLVMPositionBuilderAtEnd(self.builder_ref, self.blockref);
|
|
||||||
let add_value_ref = LLVMBuildAdd(
|
|
||||||
self.builder_ref,
|
|
||||||
lhs.llvm_value(),
|
|
||||||
rhs.llvm_value(),
|
|
||||||
into_cstring(name).as_ptr(),
|
|
||||||
);
|
|
||||||
Ok(T::from_llvm(add_value_ref))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn sub<T: BasicValue<'ctx>>(&self, lhs: &T, rhs: &T, name: &str) -> Result<T, ()> {
|
|
||||||
dbg!(lhs, rhs);
|
|
||||||
dbg!(lhs.llvm_type(), rhs.llvm_type());
|
|
||||||
if lhs.llvm_type() != rhs.llvm_type() {
|
|
||||||
return Err(()); // TODO error
|
|
||||||
}
|
|
||||||
unsafe {
|
|
||||||
LLVMPositionBuilderAtEnd(self.builder_ref, self.blockref);
|
|
||||||
let add_value_ref = LLVMBuildSub(
|
|
||||||
self.builder_ref,
|
|
||||||
lhs.llvm_value(),
|
|
||||||
rhs.llvm_value(),
|
|
||||||
into_cstring(name).as_ptr(),
|
|
||||||
);
|
|
||||||
Ok(T::from_llvm(add_value_ref))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn phi<PhiValue: BasicValue<'ctx>>(
|
|
||||||
&self,
|
|
||||||
phi_type: &PhiValue::BaseType,
|
|
||||||
name: &str,
|
|
||||||
) -> Result<PhiBuilder<'ctx, PhiValue>, ()> {
|
|
||||||
unsafe {
|
|
||||||
LLVMPositionBuilderAtEnd(self.builder_ref, self.blockref);
|
|
||||||
let phi_node = LLVMBuildPhi(
|
|
||||||
self.builder_ref,
|
|
||||||
phi_type.llvm_type(),
|
|
||||||
into_cstring(name).as_ptr(),
|
|
||||||
);
|
|
||||||
Ok(PhiBuilder::new(phi_node))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn br(&mut self, into: &BasicBlock<'ctx>) -> Result<(), ()> {
|
|
||||||
self.try_insert()?;
|
|
||||||
unsafe {
|
|
||||||
LLVMPositionBuilderAtEnd(self.builder_ref, self.blockref);
|
|
||||||
LLVMBuildBr(self.builder_ref, into.blockref);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn conditional_br<T: BasicValue<'ctx>>(
|
|
||||||
&mut self,
|
|
||||||
condition: &T,
|
|
||||||
lhs: &BasicBlock<'ctx>,
|
|
||||||
rhs: &BasicBlock<'ctx>,
|
|
||||||
) -> Result<(), ()> {
|
|
||||||
self.try_insert()?;
|
|
||||||
unsafe {
|
|
||||||
LLVMPositionBuilderAtEnd(self.builder_ref, self.blockref);
|
|
||||||
LLVMBuildCondBr(
|
|
||||||
self.builder_ref,
|
|
||||||
condition.llvm_value(),
|
|
||||||
lhs.blockref,
|
|
||||||
rhs.blockref,
|
|
||||||
);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub fn ret<T: BasicValue<'ctx>>(&mut self, return_value: &T) -> Result<(), ()> {
|
|
||||||
if self.function.fn_type.return_type != return_value.llvm_type() {
|
|
||||||
return Err(());
|
|
||||||
}
|
|
||||||
self.try_insert()?;
|
|
||||||
|
|
||||||
unsafe {
|
|
||||||
LLVMPositionBuilderAtEnd(self.builder_ref, self.blockref);
|
|
||||||
LLVMBuildRet(self.builder_ref, return_value.llvm_value());
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn try_insert(&mut self) -> Result<(), ()> {
|
|
||||||
if self.inserted {
|
|
||||||
return Err(());
|
|
||||||
}
|
|
||||||
self.inserted = true;
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'ctx> Drop for BasicBlock<'ctx> {
|
#[derive(Debug, Clone, Hash)]
|
||||||
fn drop(&mut self) {
|
pub struct InstructionData {
|
||||||
if !self.inserted {
|
kind: InstructionKind,
|
||||||
unsafe {
|
|
||||||
LLVMDeleteBasicBlock(self.blockref);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct PhiBuilder<'ctx, PhiValue: BasicValue<'ctx>> {
|
#[derive(Debug, Clone, Copy, Hash)]
|
||||||
phi_node: LLVMValueRef,
|
pub enum IntPredicate {
|
||||||
phantom: PhantomData<&'ctx PhiValue>,
|
LessThan,
|
||||||
|
GreaterThan,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'ctx, PhiValue: BasicValue<'ctx>> PhiBuilder<'ctx, PhiValue> {
|
#[derive(Debug, Clone, Hash)]
|
||||||
fn new(phi_node: LLVMValueRef) -> PhiBuilder<'ctx, PhiValue> {
|
pub enum InstructionKind {
|
||||||
PhiBuilder {
|
Param(usize),
|
||||||
phi_node,
|
Constant(ConstValue),
|
||||||
phantom: PhantomData,
|
Add(InstructionValue, InstructionValue),
|
||||||
}
|
Sub(InstructionValue, InstructionValue),
|
||||||
}
|
Phi(Vec<InstructionValue>),
|
||||||
|
|
||||||
pub fn add_incoming(&self, value: &PhiValue, block: &BasicBlock<'ctx>) -> &Self {
|
/// Integer Comparison
|
||||||
let mut values = vec![value.llvm_value()];
|
ICmp(IntPredicate, InstructionValue, InstructionValue),
|
||||||
let mut blocks = vec![block.blockref];
|
|
||||||
unsafe {
|
|
||||||
LLVMAddIncoming(
|
|
||||||
self.phi_node,
|
|
||||||
values.as_mut_ptr(),
|
|
||||||
blocks.as_mut_ptr(),
|
|
||||||
values.len() as u32,
|
|
||||||
);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn build(&self) -> PhiValue {
|
FunctionCall(FunctionValue, Vec<InstructionValue>),
|
||||||
unsafe { PhiValue::from_llvm(self.phi_node) }
|
}
|
||||||
}
|
|
||||||
|
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
|
||||||
|
pub enum Type {
|
||||||
|
I32,
|
||||||
|
I16,
|
||||||
|
U32,
|
||||||
|
Bool,
|
||||||
|
Void,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Hash)]
|
||||||
|
pub enum ConstValue {
|
||||||
|
I32(i32),
|
||||||
|
I16(i16),
|
||||||
|
U32(u32),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Hash)]
|
||||||
|
pub enum TerminatorKind {
|
||||||
|
Ret(InstructionValue),
|
||||||
|
Branch(BlockValue),
|
||||||
|
CondBr(InstructionValue, BlockValue, BlockValue),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test() {
|
||||||
|
use ConstValue::*;
|
||||||
|
use InstructionKind::*;
|
||||||
|
|
||||||
|
let context = Context::new();
|
||||||
|
|
||||||
|
let mut module = context.module("test");
|
||||||
|
|
||||||
|
let mut main = module.function("main", Type::I32, Vec::new());
|
||||||
|
let mut m_entry = main.block("entry");
|
||||||
|
|
||||||
|
let mut fibonacci = module.function("fibonacci", Type::I32, vec![Type::I32]);
|
||||||
|
|
||||||
|
let arg = m_entry.build(Constant(I32(5))).unwrap();
|
||||||
|
m_entry
|
||||||
|
.build(FunctionCall(fibonacci.value, vec![arg]))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let mut f_entry = fibonacci.block("entry");
|
||||||
|
|
||||||
|
let num_3 = f_entry.build(Constant(I32(3))).unwrap();
|
||||||
|
let param_n = f_entry.build(Param(0)).unwrap();
|
||||||
|
let cond = f_entry
|
||||||
|
.build(ICmp(IntPredicate::LessThan, param_n, num_3))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let mut then_b = fibonacci.block("then");
|
||||||
|
let mut else_b = fibonacci.block("else");
|
||||||
|
|
||||||
|
f_entry
|
||||||
|
.terminate(TerminatorKind::CondBr(cond, then_b.value, else_b.value))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let ret_const = then_b.build(Constant(I32(1))).unwrap();
|
||||||
|
then_b.terminate(TerminatorKind::Ret(ret_const)).unwrap();
|
||||||
|
|
||||||
|
let const_1 = else_b.build(Constant(I32(1))).unwrap();
|
||||||
|
let const_2 = else_b.build(Constant(I32(2))).unwrap();
|
||||||
|
let param_1 = else_b.build(Sub(param_n, const_1)).unwrap();
|
||||||
|
let param_2 = else_b.build(Sub(param_n, const_2)).unwrap();
|
||||||
|
let call_1 = else_b
|
||||||
|
.build(FunctionCall(fibonacci.value, vec![param_1]))
|
||||||
|
.unwrap();
|
||||||
|
let call_2 = else_b
|
||||||
|
.build(FunctionCall(fibonacci.value, vec![param_2]))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let add = else_b.build(Add(call_1, call_2)).unwrap();
|
||||||
|
|
||||||
|
else_b.terminate(TerminatorKind::Ret(add)).unwrap();
|
||||||
|
|
||||||
|
dbg!(context);
|
||||||
}
|
}
|
||||||
|
@ -1,336 +0,0 @@
|
|||||||
use std::{any::Any, marker::PhantomData, ptr::null_mut};
|
|
||||||
|
|
||||||
use llvm_sys::{
|
|
||||||
LLVMTypeKind,
|
|
||||||
core::*,
|
|
||||||
prelude::{LLVMTypeRef, LLVMValueRef},
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::{BasicBlock, Context, PhiBuilder};
|
|
||||||
|
|
||||||
pub trait BasicType<'ctx> {
|
|
||||||
fn llvm_type(&self) -> LLVMTypeRef;
|
|
||||||
|
|
||||||
fn is_type(llvm_type: LLVMTypeRef) -> bool
|
|
||||||
where
|
|
||||||
Self: Sized;
|
|
||||||
|
|
||||||
unsafe fn from_llvm(context: &'ctx Context, llvm_type: LLVMTypeRef) -> Self
|
|
||||||
where
|
|
||||||
Self: Sized;
|
|
||||||
|
|
||||||
fn function_type(&self, params: Vec<TypeEnum>) -> FunctionType<'ctx> {
|
|
||||||
unsafe {
|
|
||||||
let mut typerefs: Vec<LLVMTypeRef> = params.iter().map(|b| b.llvm_type()).collect();
|
|
||||||
let param_ptr = typerefs.as_mut_ptr();
|
|
||||||
let param_len = typerefs.len();
|
|
||||||
FunctionType {
|
|
||||||
phantom: PhantomData,
|
|
||||||
return_type: self.llvm_type(),
|
|
||||||
param_types: typerefs,
|
|
||||||
type_ref: LLVMFunctionType(self.llvm_type(), param_ptr, param_len as u32, 0),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn array_type(&'ctx self, length: u32) -> ArrayType<'ctx>
|
|
||||||
where
|
|
||||||
Self: Sized,
|
|
||||||
{
|
|
||||||
ArrayType {
|
|
||||||
phantom: PhantomData,
|
|
||||||
element_type: self.llvm_type(),
|
|
||||||
length,
|
|
||||||
type_ref: unsafe { LLVMArrayType(self.llvm_type(), length) },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'ctx> PartialEq for &dyn BasicType<'ctx> {
|
|
||||||
fn eq(&self, other: &Self) -> bool {
|
|
||||||
self.llvm_type() == other.llvm_type()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'ctx> PartialEq<LLVMTypeRef> for &dyn BasicType<'ctx> {
|
|
||||||
fn eq(&self, other: &LLVMTypeRef) -> bool {
|
|
||||||
self.llvm_type() == *other
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
|
||||||
pub struct IntegerType<'ctx> {
|
|
||||||
context: &'ctx Context,
|
|
||||||
type_ref: LLVMTypeRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'ctx> BasicType<'ctx> for IntegerType<'ctx> {
|
|
||||||
fn llvm_type(&self) -> LLVMTypeRef {
|
|
||||||
self.type_ref
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn from_llvm(context: &'ctx Context, llvm_type: LLVMTypeRef) -> Self
|
|
||||||
where
|
|
||||||
Self: Sized,
|
|
||||||
{
|
|
||||||
IntegerType {
|
|
||||||
context,
|
|
||||||
type_ref: llvm_type,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_type(llvm_type: LLVMTypeRef) -> bool {
|
|
||||||
unsafe { LLVMGetTypeKind(llvm_type) == LLVMTypeKind::LLVMIntegerTypeKind }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'ctx> IntegerType<'ctx> {
|
|
||||||
pub(crate) fn in_context(context: &Context, width: u32) -> IntegerType {
|
|
||||||
let type_ref = unsafe {
|
|
||||||
match width {
|
|
||||||
128 => LLVMInt128TypeInContext(context.context_ref),
|
|
||||||
64 => LLVMInt64TypeInContext(context.context_ref),
|
|
||||||
32 => LLVMInt32TypeInContext(context.context_ref),
|
|
||||||
16 => LLVMInt16TypeInContext(context.context_ref),
|
|
||||||
8 => LLVMInt8TypeInContext(context.context_ref),
|
|
||||||
1 => LLVMInt1TypeInContext(context.context_ref),
|
|
||||||
_ => LLVMIntTypeInContext(context.context_ref, width),
|
|
||||||
}
|
|
||||||
};
|
|
||||||
IntegerType { context, type_ref }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn from_signed(&self, value: i64) -> IntegerValue<'ctx> {
|
|
||||||
self.from_const(value as u64, true)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn from_unsigned(&self, value: i64) -> IntegerValue<'ctx> {
|
|
||||||
self.from_const(value as u64, false)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn from_const(&self, value: u64, sign: bool) -> IntegerValue<'ctx> {
|
|
||||||
unsafe {
|
|
||||||
IntegerValue::from_llvm(LLVMConstInt(
|
|
||||||
self.type_ref,
|
|
||||||
value,
|
|
||||||
match sign {
|
|
||||||
true => 1,
|
|
||||||
false => 0,
|
|
||||||
},
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct FunctionType<'ctx> {
|
|
||||||
phantom: PhantomData<&'ctx ()>,
|
|
||||||
pub(crate) return_type: LLVMTypeRef,
|
|
||||||
pub(crate) param_types: Vec<LLVMTypeRef>,
|
|
||||||
type_ref: LLVMTypeRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'ctx> BasicType<'ctx> for FunctionType<'ctx> {
|
|
||||||
fn llvm_type(&self) -> LLVMTypeRef {
|
|
||||||
self.type_ref
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn from_llvm(_context: &'ctx Context, fn_type: LLVMTypeRef) -> Self
|
|
||||||
where
|
|
||||||
Self: Sized,
|
|
||||||
{
|
|
||||||
unsafe {
|
|
||||||
let param_count = LLVMCountParamTypes(fn_type);
|
|
||||||
let param_types_ptr: *mut LLVMTypeRef = null_mut();
|
|
||||||
LLVMGetParamTypes(fn_type, param_types_ptr);
|
|
||||||
let param_types: Vec<LLVMTypeRef> =
|
|
||||||
std::slice::from_raw_parts(param_types_ptr, param_count as usize)
|
|
||||||
.iter()
|
|
||||||
.map(|t| *t)
|
|
||||||
.collect();
|
|
||||||
FunctionType {
|
|
||||||
phantom: PhantomData,
|
|
||||||
return_type: LLVMGetReturnType(fn_type),
|
|
||||||
param_types,
|
|
||||||
type_ref: fn_type,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_type(llvm_type: LLVMTypeRef) -> bool {
|
|
||||||
unsafe { LLVMGetTypeKind(llvm_type) == LLVMTypeKind::LLVMFunctionTypeKind }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
|
||||||
pub struct ArrayType<'ctx> {
|
|
||||||
phantom: PhantomData<&'ctx ()>,
|
|
||||||
element_type: LLVMTypeRef,
|
|
||||||
length: u32,
|
|
||||||
type_ref: LLVMTypeRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'ctx> BasicType<'ctx> for ArrayType<'ctx> {
|
|
||||||
fn llvm_type(&self) -> LLVMTypeRef {
|
|
||||||
self.type_ref
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn from_llvm(context: &'ctx Context, llvm_type: LLVMTypeRef) -> Self
|
|
||||||
where
|
|
||||||
Self: Sized,
|
|
||||||
{
|
|
||||||
unsafe {
|
|
||||||
let length = LLVMGetArrayLength(llvm_type);
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_type(llvm_type: LLVMTypeRef) -> bool {
|
|
||||||
unsafe { LLVMGetTypeKind(llvm_type) == LLVMTypeKind::LLVMArrayTypeKind }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub enum TypeEnum<'ctx> {
|
|
||||||
Integer(IntegerType<'ctx>),
|
|
||||||
Array(ArrayType<'ctx>),
|
|
||||||
Function(FunctionType<'ctx>),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'ctx> From<IntegerType<'ctx>> for TypeEnum<'ctx> {
|
|
||||||
fn from(int: IntegerType<'ctx>) -> Self {
|
|
||||||
TypeEnum::Integer(int)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'ctx> From<ArrayType<'ctx>> for TypeEnum<'ctx> {
|
|
||||||
fn from(arr: ArrayType<'ctx>) -> Self {
|
|
||||||
TypeEnum::Array(arr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'ctx> From<FunctionType<'ctx>> for TypeEnum<'ctx> {
|
|
||||||
fn from(func: FunctionType<'ctx>) -> Self {
|
|
||||||
TypeEnum::Function(func)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'ctx> TypeEnum<'ctx> {
|
|
||||||
fn inner_basic(&'ctx self) -> &'ctx dyn BasicType<'ctx> {
|
|
||||||
match self {
|
|
||||||
TypeEnum::Integer(integer_type) => integer_type,
|
|
||||||
TypeEnum::Array(array_type) => array_type,
|
|
||||||
TypeEnum::Function(function_type) => function_type,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'ctx> BasicType<'ctx> for TypeEnum<'ctx> {
|
|
||||||
fn llvm_type(&self) -> LLVMTypeRef {
|
|
||||||
self.inner_basic().llvm_type()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_type(llvm_type: LLVMTypeRef) -> bool
|
|
||||||
where
|
|
||||||
Self: Sized,
|
|
||||||
{
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
unsafe fn from_llvm(context: &'ctx Context, llvm_type: LLVMTypeRef) -> Self
|
|
||||||
where
|
|
||||||
Self: Sized,
|
|
||||||
{
|
|
||||||
unsafe {
|
|
||||||
match LLVMGetTypeKind(llvm_type) {
|
|
||||||
LLVMTypeKind::LLVMIntegerTypeKind => {
|
|
||||||
TypeEnum::Integer(IntegerType::from_llvm(context, llvm_type))
|
|
||||||
}
|
|
||||||
LLVMTypeKind::LLVMArrayTypeKind => {
|
|
||||||
TypeEnum::Array(ArrayType::from_llvm(context, llvm_type))
|
|
||||||
}
|
|
||||||
LLVMTypeKind::LLVMFunctionTypeKind => {
|
|
||||||
TypeEnum::Function(FunctionType::from_llvm(context, llvm_type))
|
|
||||||
}
|
|
||||||
_ => todo!(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait BasicValue<'ctx>: std::fmt::Debug {
|
|
||||||
type BaseType: BasicType<'ctx>;
|
|
||||||
unsafe fn from_llvm(value: LLVMValueRef) -> Self
|
|
||||||
where
|
|
||||||
Self: Sized;
|
|
||||||
fn llvm_value(&self) -> LLVMValueRef;
|
|
||||||
fn llvm_type(&self) -> LLVMTypeRef;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct IntegerValue<'ctx> {
|
|
||||||
phantom: PhantomData<&'ctx ()>,
|
|
||||||
pub(crate) value_ref: LLVMValueRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'ctx> BasicValue<'ctx> for IntegerValue<'ctx> {
|
|
||||||
type BaseType = IntegerType<'ctx>;
|
|
||||||
|
|
||||||
unsafe fn from_llvm(value: LLVMValueRef) -> Self {
|
|
||||||
IntegerValue {
|
|
||||||
phantom: PhantomData,
|
|
||||||
value_ref: value,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn llvm_value(&self) -> LLVMValueRef {
|
|
||||||
self.value_ref
|
|
||||||
}
|
|
||||||
|
|
||||||
fn llvm_type(&self) -> LLVMTypeRef {
|
|
||||||
unsafe { LLVMTypeOf(self.value_ref) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub enum Value<'ctx> {
|
|
||||||
Integer(IntegerValue<'ctx>),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'ctx> BasicValue<'ctx> for Value<'ctx> {
|
|
||||||
type BaseType = TypeEnum<'ctx>;
|
|
||||||
|
|
||||||
unsafe fn from_llvm(value: LLVMValueRef) -> Self
|
|
||||||
where
|
|
||||||
Self: Sized,
|
|
||||||
{
|
|
||||||
unsafe {
|
|
||||||
use LLVMTypeKind::*;
|
|
||||||
|
|
||||||
let llvm_type = LLVMTypeOf(value);
|
|
||||||
let type_kind = LLVMGetTypeKind(llvm_type);
|
|
||||||
match type_kind {
|
|
||||||
LLVMIntegerTypeKind => Value::Integer(IntegerValue::from_llvm(value)),
|
|
||||||
_ => panic!("asd"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn llvm_value(&self) -> LLVMValueRef {
|
|
||||||
match self {
|
|
||||||
Self::Integer(i) => i.llvm_value(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn llvm_type(&self) -> LLVMTypeRef {
|
|
||||||
match self {
|
|
||||||
Self::Integer(i) => i.llvm_type(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'ctx> From<IntegerValue<'ctx>> for Value<'ctx> {
|
|
||||||
fn from(value: IntegerValue<'ctx>) -> Self {
|
|
||||||
Value::Integer(value)
|
|
||||||
}
|
|
||||||
}
|
|
@ -5,6 +5,11 @@ use std::{
|
|||||||
|
|
||||||
use llvm_sys::error::LLVMDisposeErrorMessage;
|
use llvm_sys::error::LLVMDisposeErrorMessage;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
Type,
|
||||||
|
builder::{Builder, InstructionValue},
|
||||||
|
};
|
||||||
|
|
||||||
pub fn into_cstring<T: Into<String>>(value: T) -> CString {
|
pub fn into_cstring<T: Into<String>>(value: T) -> CString {
|
||||||
let string = value.into();
|
let string = value.into();
|
||||||
unsafe { CString::from_vec_with_nul_unchecked((string + "\0").into_bytes()) }
|
unsafe { CString::from_vec_with_nul_unchecked((string + "\0").into_bytes()) }
|
||||||
@ -49,3 +54,17 @@ impl Drop for ErrorMessageHolder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn match_types(
|
||||||
|
lhs: &InstructionValue,
|
||||||
|
rhs: &InstructionValue,
|
||||||
|
builder: &Builder,
|
||||||
|
) -> Result<Type, ()> {
|
||||||
|
let lhs_type = lhs.get_type(&builder);
|
||||||
|
let rhs_type = rhs.get_type(&builder);
|
||||||
|
if let (Ok(lhs_t), Ok(rhs_t)) = (lhs_type, rhs_type) {
|
||||||
|
if lhs_t == rhs_t { Ok(lhs_t) } else { Err(()) }
|
||||||
|
} else {
|
||||||
|
Err(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
// Main
|
// Main
|
||||||
fn main() {
|
fn main() {
|
||||||
return fibonacci(10);
|
return fibonacci(3);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fibonacci
|
// Fibonacci
|
||||||
|
@ -164,8 +164,9 @@ fn main() {
|
|||||||
|
|
||||||
println!("test3");
|
println!("test3");
|
||||||
|
|
||||||
match codegen_module.module.print_to_string() {
|
codegen_module.context.compile();
|
||||||
Ok(v) => println!("{}", v),
|
// match codegen_module.module.print_to_string() {
|
||||||
Err(e) => println!("Err: {:?}", e),
|
// Ok(v) => println!("{}", v),
|
||||||
}
|
// Err(e) => println!("Err: {:?}", e),
|
||||||
|
// }
|
||||||
}
|
}
|
||||||
|
@ -28,47 +28,50 @@ impl Parse for Type {
|
|||||||
|
|
||||||
impl Parse for Expression {
|
impl Parse for Expression {
|
||||||
fn parse(mut stream: TokenStream) -> Result<Expression, Error> {
|
fn parse(mut stream: TokenStream) -> Result<Expression, Error> {
|
||||||
let lhs = parse_primary_expression(&mut stream)?;
|
let lhs = stream.parse::<PrimaryExpression>()?.0;
|
||||||
parse_binop_rhs(&mut stream, lhs, None)
|
parse_binop_rhs(&mut stream, lhs, None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_primary_expression(stream: &mut TokenStream) -> Result<Expression, Error> {
|
#[derive(Debug)]
|
||||||
use ExpressionKind as Kind;
|
pub struct PrimaryExpression(Expression);
|
||||||
|
|
||||||
if let Ok(exp) = stream.parse() {
|
impl Parse for PrimaryExpression {
|
||||||
Ok(Expression(
|
fn parse(mut stream: TokenStream) -> Result<Self, Error> {
|
||||||
Kind::FunctionCall(Box::new(exp)),
|
use ExpressionKind as Kind;
|
||||||
stream.get_range().unwrap(),
|
|
||||||
))
|
let expr = if let Ok(exp) = stream.parse() {
|
||||||
} else if let Ok(block) = stream.parse() {
|
Expression(
|
||||||
Ok(Expression(
|
Kind::FunctionCall(Box::new(exp)),
|
||||||
Kind::BlockExpr(Box::new(block)),
|
|
||||||
stream.get_range().unwrap(),
|
|
||||||
))
|
|
||||||
} else if let Ok(ifexpr) = stream.parse() {
|
|
||||||
Ok(Expression(
|
|
||||||
Kind::IfExpr(Box::new(ifexpr)),
|
|
||||||
stream.get_range().unwrap(),
|
|
||||||
))
|
|
||||||
} else if let Some(token) = stream.next() {
|
|
||||||
Ok(match &token {
|
|
||||||
Token::Identifier(v) => {
|
|
||||||
Expression(Kind::VariableName(v.clone()), stream.get_range().unwrap())
|
|
||||||
}
|
|
||||||
Token::DecimalValue(v) => Expression(
|
|
||||||
Kind::Literal(Literal::I32(v.parse().unwrap())),
|
|
||||||
stream.get_range().unwrap(),
|
stream.get_range().unwrap(),
|
||||||
),
|
)
|
||||||
Token::ParenOpen => {
|
} else if let Ok(block) = stream.parse() {
|
||||||
let exp = stream.parse()?;
|
Expression(
|
||||||
stream.expect(Token::ParenClose)?;
|
Kind::BlockExpr(Box::new(block)),
|
||||||
exp
|
stream.get_range().unwrap(),
|
||||||
|
)
|
||||||
|
} else if let Ok(ifexpr) = stream.parse() {
|
||||||
|
Expression(Kind::IfExpr(Box::new(ifexpr)), stream.get_range().unwrap())
|
||||||
|
} else if let Some(token) = stream.next() {
|
||||||
|
match &token {
|
||||||
|
Token::Identifier(v) => {
|
||||||
|
Expression(Kind::VariableName(v.clone()), stream.get_range().unwrap())
|
||||||
|
}
|
||||||
|
Token::DecimalValue(v) => Expression(
|
||||||
|
Kind::Literal(Literal::I32(v.parse().unwrap())),
|
||||||
|
stream.get_range().unwrap(),
|
||||||
|
),
|
||||||
|
Token::ParenOpen => {
|
||||||
|
let exp = stream.parse()?;
|
||||||
|
stream.expect(Token::ParenClose)?;
|
||||||
|
exp
|
||||||
|
}
|
||||||
|
_ => Err(stream.expected_err("identifier, constant or parentheses")?)?,
|
||||||
}
|
}
|
||||||
_ => Err(stream.expected_err("identifier, constant or parentheses")?)?,
|
} else {
|
||||||
})
|
Err(stream.expected_err("expression")?)?
|
||||||
} else {
|
};
|
||||||
Err(stream.expected_err("expression")?)?
|
Ok(PrimaryExpression(expr))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -95,7 +98,7 @@ fn parse_binop_rhs(
|
|||||||
stream.parse_if::<BinaryOperator, _>(|b| b.get_precedence() >= expr_precedence)
|
stream.parse_if::<BinaryOperator, _>(|b| b.get_precedence() >= expr_precedence)
|
||||||
{
|
{
|
||||||
let curr_token_prec = op.get_precedence();
|
let curr_token_prec = op.get_precedence();
|
||||||
let mut rhs = parse_primary_expression(stream)?;
|
let mut rhs = stream.parse::<PrimaryExpression>()?.0;
|
||||||
|
|
||||||
if let Ok(next_op) = stream.parse_peek::<BinaryOperator>() {
|
if let Ok(next_op) = stream.parse_peek::<BinaryOperator>() {
|
||||||
let next_prec = next_op.get_precedence();
|
let next_prec = next_op.get_precedence();
|
||||||
|
@ -1,35 +1,35 @@
|
|||||||
use std::{collections::HashMap, mem, ops::Deref};
|
use std::{collections::HashMap, mem, ops::Deref};
|
||||||
|
|
||||||
use crate::mir::{self, types::ReturnType, TypeKind, VariableReference};
|
|
||||||
use reid_lib::{
|
use reid_lib::{
|
||||||
types::{BasicType, BasicValue, IntegerValue, TypeEnum, Value},
|
builder::{FunctionValue, InstructionValue},
|
||||||
BasicBlock, Context, Function, IntPredicate, Module,
|
Block, ConstValue, Context, Function, InstructionKind, IntPredicate, Module, TerminatorKind,
|
||||||
|
Type,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use crate::mir::{self, types::ReturnType, TypeKind, VariableReference};
|
||||||
|
|
||||||
pub struct ModuleCodegen<'ctx> {
|
pub struct ModuleCodegen<'ctx> {
|
||||||
context: &'ctx Context,
|
pub context: &'ctx Context,
|
||||||
pub module: Module<'ctx>,
|
pub module: Module<'ctx>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl mir::Module {
|
impl mir::Module {
|
||||||
pub fn codegen<'ctx>(&self, context: &'ctx Context) -> ModuleCodegen<'ctx> {
|
pub fn codegen<'ctx>(&self, context: &'ctx Context) -> ModuleCodegen<'ctx> {
|
||||||
let module = context.module(&self.name);
|
let mut module = context.module(&self.name);
|
||||||
|
|
||||||
let mut functions = HashMap::new();
|
let mut functions = HashMap::new();
|
||||||
|
|
||||||
for function in &self.functions {
|
for function in &self.functions {
|
||||||
let ret_type = function.return_type().unwrap().get_type(&context);
|
let ret_type = function.return_type().unwrap().get_type();
|
||||||
let fn_type = ret_type.function_type(
|
let param_types: Vec<Type> = function
|
||||||
function
|
.parameters
|
||||||
.parameters
|
.iter()
|
||||||
.iter()
|
.map(|(_, p)| p.get_type())
|
||||||
.map(|(_, p)| p.get_type(&context))
|
.collect();
|
||||||
.collect(),
|
|
||||||
);
|
|
||||||
|
|
||||||
let func = match &function.kind {
|
let func = match &function.kind {
|
||||||
mir::FunctionDefinitionKind::Local(_, _) => {
|
mir::FunctionDefinitionKind::Local(_, _) => {
|
||||||
module.add_function(fn_type, &function.name)
|
module.function(&function.name, ret_type, param_types)
|
||||||
}
|
}
|
||||||
mir::FunctionDefinitionKind::Extern(_) => todo!(),
|
mir::FunctionDefinitionKind::Extern(_) => todo!(),
|
||||||
};
|
};
|
||||||
@ -38,12 +38,13 @@ impl mir::Module {
|
|||||||
|
|
||||||
for mir_function in &self.functions {
|
for mir_function in &self.functions {
|
||||||
let function = functions.get(&mir_function.name).unwrap();
|
let function = functions.get(&mir_function.name).unwrap();
|
||||||
|
let mut entry = function.block("entry");
|
||||||
|
|
||||||
let mut stack_values = HashMap::new();
|
let mut stack_values = HashMap::new();
|
||||||
for (i, (p_name, p_type)) in mir_function.parameters.iter().enumerate() {
|
for (i, (p_name, p_type)) in mir_function.parameters.iter().enumerate() {
|
||||||
stack_values.insert(
|
stack_values.insert(
|
||||||
p_name.clone(),
|
p_name.clone(),
|
||||||
function.get_param(i, p_type.get_type(&context)).unwrap(),
|
entry.build(InstructionKind::Param(i)).unwrap(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -51,14 +52,14 @@ impl mir::Module {
|
|||||||
context,
|
context,
|
||||||
module: &module,
|
module: &module,
|
||||||
function,
|
function,
|
||||||
block: function.block("entry"),
|
block: entry,
|
||||||
functions: functions.clone(),
|
functions: &functions,
|
||||||
stack_values,
|
stack_values,
|
||||||
};
|
};
|
||||||
match &mir_function.kind {
|
match &mir_function.kind {
|
||||||
mir::FunctionDefinitionKind::Local(block, _) => {
|
mir::FunctionDefinitionKind::Local(block, _) => {
|
||||||
if let Some(ret) = block.codegen(&mut scope) {
|
if let Some(ret) = block.codegen(&mut scope) {
|
||||||
scope.block.ret(&ret).unwrap();
|
scope.block.terminate(TerminatorKind::Ret(ret)).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
mir::FunctionDefinitionKind::Extern(_) => {}
|
mir::FunctionDefinitionKind::Extern(_) => {}
|
||||||
@ -69,21 +70,21 @@ impl mir::Module {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Scope<'ctx> {
|
pub struct Scope<'ctx, 'a> {
|
||||||
context: &'ctx Context,
|
context: &'ctx Context,
|
||||||
module: &'ctx Module<'ctx>,
|
module: &'ctx Module<'ctx>,
|
||||||
function: &'ctx Function<'ctx>,
|
function: &'ctx Function<'ctx>,
|
||||||
block: BasicBlock<'ctx>,
|
block: Block<'ctx>,
|
||||||
functions: HashMap<String, Function<'ctx>>,
|
functions: &'a HashMap<String, Function<'ctx>>,
|
||||||
stack_values: HashMap<String, Value<'ctx>>,
|
stack_values: HashMap<String, InstructionValue>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'ctx> Scope<'ctx> {
|
impl<'ctx, 'a> Scope<'ctx, 'a> {
|
||||||
pub fn with_block(&self, block: BasicBlock<'ctx>) -> Scope<'ctx> {
|
pub fn with_block(&self, block: Block<'ctx>) -> Scope<'ctx, 'a> {
|
||||||
Scope {
|
Scope {
|
||||||
block,
|
block,
|
||||||
context: self.context,
|
|
||||||
function: self.function,
|
function: self.function,
|
||||||
|
context: self.context,
|
||||||
module: self.module,
|
module: self.module,
|
||||||
functions: self.functions.clone(),
|
functions: self.functions.clone(),
|
||||||
stack_values: self.stack_values.clone(),
|
stack_values: self.stack_values.clone(),
|
||||||
@ -92,7 +93,7 @@ impl<'ctx> Scope<'ctx> {
|
|||||||
|
|
||||||
/// Takes the block out from this scope, swaps the given block in it's place
|
/// Takes the block out from this scope, swaps the given block in it's place
|
||||||
/// and returns the old block.
|
/// and returns the old block.
|
||||||
pub fn swap_block(&mut self, block: BasicBlock<'ctx>) -> BasicBlock<'ctx> {
|
pub fn swap_block(&mut self, block: Block<'ctx>) -> Block<'ctx> {
|
||||||
let mut old_block = block;
|
let mut old_block = block;
|
||||||
mem::swap(&mut self.block, &mut old_block);
|
mem::swap(&mut self.block, &mut old_block);
|
||||||
old_block
|
old_block
|
||||||
@ -100,7 +101,7 @@ impl<'ctx> Scope<'ctx> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl mir::Statement {
|
impl mir::Statement {
|
||||||
pub fn codegen<'ctx>(&self, scope: &mut Scope<'ctx>) -> Option<Value<'ctx>> {
|
pub fn codegen<'ctx, 'a>(&self, scope: &mut Scope<'ctx, 'a>) -> Option<InstructionValue> {
|
||||||
match &self.0 {
|
match &self.0 {
|
||||||
mir::StmtKind::Let(VariableReference(_, name, _), expression) => {
|
mir::StmtKind::Let(VariableReference(_, name, _), expression) => {
|
||||||
let value = expression.codegen(scope).unwrap();
|
let value = expression.codegen(scope).unwrap();
|
||||||
@ -115,7 +116,7 @@ impl mir::Statement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl mir::IfExpression {
|
impl mir::IfExpression {
|
||||||
pub fn codegen<'ctx>(&self, scope: &mut Scope<'ctx>) -> Option<Value<'ctx>> {
|
pub fn codegen<'ctx, 'a>(&self, scope: &mut Scope<'ctx, 'a>) -> Option<InstructionValue> {
|
||||||
let condition = self.0.codegen(scope).unwrap();
|
let condition = self.0.codegen(scope).unwrap();
|
||||||
|
|
||||||
// Create blocks
|
// Create blocks
|
||||||
@ -125,55 +126,62 @@ impl mir::IfExpression {
|
|||||||
|
|
||||||
let mut then_scope = scope.with_block(then_bb);
|
let mut then_scope = scope.with_block(then_bb);
|
||||||
let then_res = self.1.codegen(&mut then_scope);
|
let then_res = self.1.codegen(&mut then_scope);
|
||||||
then_scope.block.br(&scope.block).ok();
|
then_scope
|
||||||
|
.block
|
||||||
|
.terminate(TerminatorKind::Branch(scope.block.value()))
|
||||||
|
.ok();
|
||||||
|
|
||||||
let else_bb = scope.function.block("else");
|
let else_bb = scope.function.block("else");
|
||||||
let mut else_scope = scope.with_block(else_bb);
|
let mut else_scope = scope.with_block(else_bb);
|
||||||
|
|
||||||
let else_opt = if let Some(else_block) = &self.2 {
|
let else_res = if let Some(else_block) = &self.2 {
|
||||||
before_bb
|
before_bb
|
||||||
.conditional_br(&condition, &then_scope.block, &else_scope.block)
|
.terminate(TerminatorKind::CondBr(
|
||||||
|
condition,
|
||||||
|
then_scope.block.value(),
|
||||||
|
else_scope.block.value(),
|
||||||
|
))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let opt = else_block.codegen(&mut else_scope);
|
let opt = else_block.codegen(&mut else_scope);
|
||||||
|
|
||||||
if let Some(ret) = opt {
|
if let Some(ret) = opt {
|
||||||
else_scope.block.br(&scope.block).ok();
|
else_scope
|
||||||
Some((else_scope.block, ret))
|
.block
|
||||||
|
.terminate(TerminatorKind::Branch(scope.block.value()))
|
||||||
|
.ok();
|
||||||
|
Some(ret)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
else_scope.block.br(&scope.block).unwrap();
|
else_scope
|
||||||
|
.block
|
||||||
|
.terminate(TerminatorKind::Branch(scope.block.value()))
|
||||||
|
.unwrap();
|
||||||
before_bb
|
before_bb
|
||||||
.conditional_br(&condition, &then_scope.block, &scope.block)
|
.terminate(TerminatorKind::CondBr(
|
||||||
|
condition,
|
||||||
|
then_scope.block.value(),
|
||||||
|
scope.block.value(),
|
||||||
|
))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
if then_res.is_none() && else_opt.is_none() {
|
if then_res.is_none() && else_res.is_none() {
|
||||||
None
|
None
|
||||||
} else if let Ok(ret_type) = self.1.return_type() {
|
|
||||||
let phi = scope
|
|
||||||
.block
|
|
||||||
.phi(&ret_type.get_type(scope.context), "phi")
|
|
||||||
.unwrap();
|
|
||||||
if let Some(then_ret) = then_res {
|
|
||||||
phi.add_incoming(&then_ret, &then_scope.block);
|
|
||||||
}
|
|
||||||
if let Some((else_bb, else_ret)) = else_opt {
|
|
||||||
phi.add_incoming(&else_ret, &else_bb);
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(phi.build())
|
|
||||||
} else {
|
} else {
|
||||||
None
|
let mut inc = Vec::from(then_res.as_slice());
|
||||||
|
inc.extend(else_res);
|
||||||
|
|
||||||
|
Some(scope.block.build(InstructionKind::Phi(vec![])).unwrap())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl mir::Expression {
|
impl mir::Expression {
|
||||||
pub fn codegen<'ctx>(&self, scope: &mut Scope<'ctx>) -> Option<Value<'ctx>> {
|
pub fn codegen<'ctx, 'a>(&self, scope: &mut Scope<'ctx, 'a>) -> Option<InstructionValue> {
|
||||||
match &self.0 {
|
match &self.0 {
|
||||||
mir::ExprKind::Variable(varref) => {
|
mir::ExprKind::Variable(varref) => {
|
||||||
let v = scope
|
let v = scope
|
||||||
@ -182,20 +190,24 @@ impl mir::Expression {
|
|||||||
.expect("Variable reference not found?!");
|
.expect("Variable reference not found?!");
|
||||||
Some(v.clone())
|
Some(v.clone())
|
||||||
}
|
}
|
||||||
mir::ExprKind::Literal(lit) => Some(lit.codegen(scope.context)),
|
mir::ExprKind::Literal(lit) => Some(lit.as_const(&mut scope.block)),
|
||||||
mir::ExprKind::BinOp(binop, lhs_exp, rhs_exp) => {
|
mir::ExprKind::BinOp(binop, lhs_exp, rhs_exp) => {
|
||||||
let lhs = lhs_exp.codegen(scope).expect("lhs has no return value");
|
let lhs = lhs_exp.codegen(scope).expect("lhs has no return value");
|
||||||
let rhs = rhs_exp.codegen(scope).expect("rhs has no return value");
|
let rhs = rhs_exp.codegen(scope).expect("rhs has no return value");
|
||||||
Some(match binop {
|
Some(match binop {
|
||||||
mir::BinaryOperator::Add => scope.block.add(&lhs, &rhs, "add").unwrap(),
|
mir::BinaryOperator::Add => {
|
||||||
mir::BinaryOperator::Minus => scope.block.sub(&lhs, &rhs, "sub").unwrap(),
|
scope.block.build(InstructionKind::Add(lhs, rhs)).unwrap()
|
||||||
|
}
|
||||||
|
mir::BinaryOperator::Minus => {
|
||||||
|
scope.block.build(InstructionKind::Sub(lhs, rhs)).unwrap()
|
||||||
|
}
|
||||||
mir::BinaryOperator::Mult => todo!(),
|
mir::BinaryOperator::Mult => todo!(),
|
||||||
mir::BinaryOperator::And => todo!(),
|
mir::BinaryOperator::And => todo!(),
|
||||||
mir::BinaryOperator::Logic(l) => {
|
mir::BinaryOperator::Logic(l) => {
|
||||||
let ret_type = lhs_exp.return_type().expect("No ret type in lhs?");
|
let ret_type = lhs_exp.return_type().expect("No ret type in lhs?");
|
||||||
scope
|
scope
|
||||||
.block
|
.block
|
||||||
.integer_compare(&lhs, &rhs, &l.int_predicate(ret_type.signed()), "cmp")
|
.build(InstructionKind::ICmp(l.int_predicate(), lhs, rhs))
|
||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@ -210,13 +222,21 @@ impl mir::Expression {
|
|||||||
.functions
|
.functions
|
||||||
.get(&call.name)
|
.get(&call.name)
|
||||||
.expect("function not found!");
|
.expect("function not found!");
|
||||||
Some(scope.block.call(callee, params, "call").unwrap())
|
Some(
|
||||||
|
scope
|
||||||
|
.block
|
||||||
|
.build(InstructionKind::FunctionCall(callee.value(), params))
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
mir::ExprKind::If(if_expression) => if_expression.codegen(scope),
|
mir::ExprKind::If(if_expression) => if_expression.codegen(scope),
|
||||||
mir::ExprKind::Block(block) => {
|
mir::ExprKind::Block(block) => {
|
||||||
let mut inner_scope = scope.with_block(scope.function.block("inner"));
|
let mut inner_scope = scope.with_block(scope.function.block("inner"));
|
||||||
if let Some(ret) = block.codegen(&mut inner_scope) {
|
if let Some(ret) = block.codegen(&mut inner_scope) {
|
||||||
inner_scope.block.br(&scope.block);
|
inner_scope
|
||||||
|
.block
|
||||||
|
.terminate(TerminatorKind::Branch(scope.block.value()))
|
||||||
|
.unwrap();
|
||||||
Some(ret)
|
Some(ret)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
@ -227,18 +247,16 @@ impl mir::Expression {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl mir::LogicOperator {
|
impl mir::LogicOperator {
|
||||||
fn int_predicate(&self, signed: bool) -> IntPredicate {
|
fn int_predicate(&self) -> IntPredicate {
|
||||||
match (self, signed) {
|
match self {
|
||||||
(mir::LogicOperator::LessThan, true) => IntPredicate::SLT,
|
mir::LogicOperator::LessThan => IntPredicate::LessThan,
|
||||||
(mir::LogicOperator::GreaterThan, true) => IntPredicate::SGT,
|
mir::LogicOperator::GreaterThan => IntPredicate::GreaterThan,
|
||||||
(mir::LogicOperator::LessThan, false) => IntPredicate::ULT,
|
|
||||||
(mir::LogicOperator::GreaterThan, false) => IntPredicate::UGT,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl mir::Block {
|
impl mir::Block {
|
||||||
pub fn codegen<'ctx>(&self, mut scope: &mut Scope<'ctx>) -> Option<Value<'ctx>> {
|
pub fn codegen<'ctx, 'a>(&self, mut scope: &mut Scope<'ctx, 'a>) -> Option<InstructionValue> {
|
||||||
for stmt in &self.statements {
|
for stmt in &self.statements {
|
||||||
stmt.codegen(&mut scope);
|
stmt.codegen(&mut scope);
|
||||||
}
|
}
|
||||||
@ -247,7 +265,7 @@ impl mir::Block {
|
|||||||
let ret = expr.codegen(&mut scope).unwrap();
|
let ret = expr.codegen(&mut scope).unwrap();
|
||||||
match kind {
|
match kind {
|
||||||
mir::ReturnKind::Hard => {
|
mir::ReturnKind::Hard => {
|
||||||
scope.block.ret(&ret).unwrap();
|
scope.block.terminate(TerminatorKind::Ret(ret)).unwrap();
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
mir::ReturnKind::Soft => Some(ret),
|
mir::ReturnKind::Soft => Some(ret),
|
||||||
@ -259,20 +277,23 @@ impl mir::Block {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl mir::Literal {
|
impl mir::Literal {
|
||||||
pub fn codegen<'ctx>(&self, context: &'ctx Context) -> Value<'ctx> {
|
pub fn as_const(&self, block: &mut Block) -> InstructionValue {
|
||||||
let val: IntegerValue<'ctx> = match *self {
|
block.build(self.as_const_kind()).unwrap()
|
||||||
mir::Literal::I32(val) => context.type_i32().from_signed(val as i64),
|
}
|
||||||
mir::Literal::I16(val) => context.type_i16().from_signed(val as i64),
|
|
||||||
};
|
pub fn as_const_kind(&self) -> InstructionKind {
|
||||||
Value::Integer(val)
|
InstructionKind::Constant(match *self {
|
||||||
|
mir::Literal::I32(val) => ConstValue::I32(val),
|
||||||
|
mir::Literal::I16(val) => ConstValue::I16(val),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TypeKind {
|
impl TypeKind {
|
||||||
fn get_type<'ctx>(&self, context: &'ctx Context) -> TypeEnum<'ctx> {
|
fn get_type(&self) -> Type {
|
||||||
match &self {
|
match &self {
|
||||||
TypeKind::I32 => TypeEnum::Integer(context.type_i32()),
|
TypeKind::I32 => Type::I32,
|
||||||
TypeKind::I16 => TypeEnum::Integer(context.type_i16()),
|
TypeKind::I16 => Type::I16,
|
||||||
TypeKind::Void => panic!("Void not a supported type"),
|
TypeKind::Void => panic!("Void not a supported type"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -50,10 +50,15 @@ pub fn compile(source: &str) -> Result<String, ReidError> {
|
|||||||
dbg!(&mir_module);
|
dbg!(&mir_module);
|
||||||
|
|
||||||
let mut context = Context::new();
|
let mut context = Context::new();
|
||||||
let cogegen_module = mir_module.codegen(&mut context);
|
let codegen_module = mir_module.codegen(&mut context);
|
||||||
|
|
||||||
Ok(match cogegen_module.module.print_to_string() {
|
dbg!(&codegen_module.context);
|
||||||
Ok(v) => v,
|
codegen_module.context.compile();
|
||||||
Err(e) => panic!("Err: {:?}", e),
|
|
||||||
})
|
Ok(String::new())
|
||||||
|
|
||||||
|
// Ok(match cogegen_module.module.print_to_string() {
|
||||||
|
// Ok(v) => v,
|
||||||
|
// Err(e) => panic!("Err: {:?}", e),
|
||||||
|
// })
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user