Skip to content

Commit

Permalink
Support builtin functions (#469)
Browse files Browse the repository at this point in the history
* Support builtin functions

* Add correctness tests

The builtinin index is now created first in the lib, and not always by
visiting an ast.
Also fixed the index import to use not skip enum and hardware constants.
As a side effect of the index being imported, some index numbers changed
in some tests
  • Loading branch information
ghaith committed Apr 11, 2022
1 parent fd520d7 commit 2e3ebff
Show file tree
Hide file tree
Showing 22 changed files with 458 additions and 56 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ regex = "1"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1"
toml = "0.5"
lazy_static = "1.4.0"

[dev-dependencies]
num = "0.4"
Expand Down
1 change: 1 addition & 0 deletions src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ pub struct Implementation {
pub enum LinkageType {
Internal,
External,
BuiltIn,
}

#[derive(Debug, PartialEq)]
Expand Down
98 changes: 98 additions & 0 deletions src/builtins.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
use std::collections::HashMap;

use inkwell::values::{BasicValue, BasicValueEnum};
use lazy_static::lazy_static;

use crate::{
ast::{AstStatement, CompilationUnit, LinkageType, SourceRange},
codegen::generators::expression_generator::ExpressionCodeGenerator,
diagnostics::Diagnostic,
lexer::{self, IdProvider},
parser,
};

// Defines a set of functions that are always included in a compiled application
lazy_static! {
static ref BUILTIN: HashMap<&'static str, BuiltIn> = HashMap::from([
(
"ADR",
BuiltIn {
decl: "FUNCTION ADR<T: ANY> : LWORD
VAR_INPUT
in : T;
END_VAR
END_FUNCTION
",
code: |generator, params, location| {
if let [reference] = params {
generator
.generate_element_pointer(reference)
.map(|it| generator.ptr_as_value(it))
} else {
Err(Diagnostic::codegen_error(
"Expected exadtly one parameter for REF",
location,
))
}
}
},
),
(
"REF",
BuiltIn {
decl: "FUNCTION REF<T: ANY> : REF_TO T
VAR_INPUT
in : T;
END_VAR
END_FUNCTION
",
code: |generator, params, location| {
if let [reference] = params {
generator
.generate_element_pointer(reference)
.map(|it| it.as_basic_value_enum())
} else {
Err(Diagnostic::codegen_error(
"Expected exadtly one parameter for REF",
location,
))
}
}
},
)
]);
}

pub struct BuiltIn {
decl: &'static str,
code: for<'ink, 'b> fn(
&'b ExpressionCodeGenerator<'ink, 'b>,
&[&AstStatement],
SourceRange,
) -> Result<BasicValueEnum<'ink>, Diagnostic>,
}

impl BuiltIn {
pub fn codegen<'ink, 'b>(
&self,
generator: &'b ExpressionCodeGenerator<'ink, 'b>,
params: &[&AstStatement],
location: SourceRange,
) -> Result<BasicValueEnum<'ink>, Diagnostic> {
(self.code)(generator, params, location)
}
}

pub fn parse_built_ins(id_provider: IdProvider) -> CompilationUnit {
let src = BUILTIN
.iter()
.map(|(_, it)| it.decl)
.collect::<Vec<&str>>()
.join(" ");
parser::parse(lexer::lex_with_ids(&src, id_provider), LinkageType::BuiltIn).0
}

/// Returns the requested functio from the builtin index or None
pub fn get_builtin(name: &str) -> Option<&'static BuiltIn> {
BUILTIN.get(name.to_uppercase().as_str())
}
2 changes: 1 addition & 1 deletion src/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use super::index::*;
use inkwell::module::Module;
use inkwell::{context::Context, types::BasicType};

mod generators;
pub(crate) mod generators;
mod llvm_index;
mod llvm_typesystem;
#[cfg(test)]
Expand Down
26 changes: 26 additions & 0 deletions src/codegen/generators/expression_generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,22 @@ impl<'a, 'b> ExpressionCodeGenerator<'a, 'b> {
)
})?;

//If the function is builtin, generate a basic value enum for it
if let Some(builtin) = self
.index
.get_builtin_function(implementation.get_call_name())
{
return builtin.codegen(
self,
parameters
.as_ref()
.map(ast::flatten_expression_list)
.unwrap_or_default()
.as_slice(),
operator.get_location(),
);
}

let (class_ptr, call_ptr) = match implementation {
ImplementationIndexEntry {
implementation_type: ImplementationType::Function,
Expand Down Expand Up @@ -914,6 +930,16 @@ impl<'a, 'b> ExpressionCodeGenerator<'a, 'b> {
.into_pointer_value()
}

pub fn ptr_as_value(&self, ptr: PointerValue<'a>) -> BasicValueEnum<'a> {
let int_type = self.llvm.context.i64_type();
if ptr.is_const() {
ptr.const_to_int(int_type)
} else {
self.llvm.builder.build_ptr_to_int(ptr, int_type, "")
}
.as_basic_value_enum()
}

/// automatically derefs an inout variable pointer so it can be used like a normal variable
///
/// # Arguments
Expand Down
38 changes: 38 additions & 0 deletions src/codegen/tests/expression_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -459,3 +459,41 @@ fn nested_call_statements() {
// WE expect a flat sequence of calls, no regions and branching
insta::assert_snapshot!(result);
}

#[test]
fn builtin_function_call_adr() {
// GIVEN some nested call statements
let result = codegen(
"
PROGRAM main
VAR
a : REF_TO DINT;
b : DINT;
END_VAR
a := ADR(b);
END_PROGRAM
",
);
// WHEN compiled
// We expect a direct conversion to lword and subsequent assignment (no call)
insta::assert_snapshot!(result);
}

#[test]
fn builtin_function_call_ref() {
// GIVEN some nested call statements
let result = codegen(
"
PROGRAM main
VAR
a : REF_TO DINT;
b : DINT;
END_VAR
a := REF(b);
END_PROGRAM
",
);
// WHEN compiled
// We expect a direct conversion and subsequent assignment to pointer(no call)
insta::assert_snapshot!(result);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
source: src/codegen/tests/expression_tests.rs
assertion_line: 479
expression: result

---
; ModuleID = 'main'
source_filename = "main"

%main_interface = type { i32*, i32 }

@main_instance = global %main_interface zeroinitializer

define void @main(%main_interface* %0) {
entry:
%a = getelementptr inbounds %main_interface, %main_interface* %0, i32 0, i32 0
%b = getelementptr inbounds %main_interface, %main_interface* %0, i32 0, i32 1
%1 = ptrtoint i32* %b to i64
%2 = inttoptr i64 %1 to i32*
store i32* %2, i32** %a, align 8
ret void
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
source: src/codegen/tests/expression_tests.rs
assertion_line: 499
expression: result

---
; ModuleID = 'main'
source_filename = "main"

%main_interface = type { i32*, i32 }

@main_instance = global %main_interface zeroinitializer

define void @main(%main_interface* %0) {
entry:
%a = getelementptr inbounds %main_interface, %main_interface* %0, i32 0, i32 0
%b = getelementptr inbounds %main_interface, %main_interface* %0, i32 0, i32 1
store i32* %b, i32** %a, align 8
ret void
}

Loading

0 comments on commit 2e3ebff

Please sign in to comment.