Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support builtin functions #469

Merged
merged 7 commits into from
Apr 11, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so far we avoided &'static str
is there a benefit over String?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Honestly, I don't remember, it feels like less code (not having .to_string() in each entry)
I think initially this came when I was using a static array of declarations instead of the lazy_static map

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, Vec<Diagnostic>) {
let src = BUILTIN
.iter()
.map(|(_, it)| it.decl)
.collect::<Vec<&str>>()
.join(" ");
parser::parse(lexer::lex_with_ids(&src, id_provider), LinkageType::BuiltIn)
}

/// 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(|it| ast::flatten_expression_list(it))
.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