holey-bytes/lang/src/son.rs

3712 lines
130 KiB
Rust
Raw Normal View History

2024-09-02 17:07:20 -05:00
use {
2024-10-27 08:29:14 -05:00
self::{hbvm::Comptime, strong_ref::StrongRef},
2024-09-02 17:07:20 -05:00
crate::{
2024-10-01 14:33:30 -05:00
ctx_map::CtxEntry,
2024-10-27 08:29:14 -05:00
debug,
2024-09-03 10:51:28 -05:00
lexer::{self, TokenKind},
2024-09-04 09:54:34 -05:00
parser::{
self,
2024-09-04 10:56:59 -05:00
idfl::{self},
2024-10-25 07:51:33 -05:00
CtorField, Expr, FileId, Pos,
2024-09-04 09:54:34 -05:00
},
2024-10-27 08:29:14 -05:00
task,
2024-10-24 02:43:07 -05:00
ty::{self, Arg, ArrayLen, Loc, Tuple},
vc::{BitSet, Vc},
2024-10-27 08:29:14 -05:00
FTask, Func, Global, Ident, Offset, OffsetIter, Reloc, Sig, StringRef, SymKey, TypeParser,
TypedReloc, Types,
2024-09-02 17:07:20 -05:00
},
2024-10-27 08:29:14 -05:00
alloc::{string::String, vec::Vec},
2024-09-30 12:09:17 -05:00
core::{
assert_matches::debug_assert_matches,
2024-09-06 11:50:28 -05:00
cell::RefCell,
2024-09-30 12:09:17 -05:00
fmt::{self, Debug, Display, Write},
2024-10-04 14:44:29 -05:00
format_args as fa, mem,
2024-10-26 05:09:53 -05:00
ops::{self, Deref},
2024-09-02 17:07:20 -05:00
},
2024-09-30 12:09:17 -05:00
hashbrown::hash_map,
2024-10-26 05:09:53 -05:00
hbbytecode::DisasmError,
2024-09-02 17:07:20 -05:00
};
const VOID: Nid = 0;
const NEVER: Nid = 1;
2024-09-27 09:53:28 -05:00
const ENTRY: Nid = 2;
const MEM: Nid = 3;
2024-10-27 05:32:34 -05:00
const LOOPS: Nid = 4;
const ARG_START: usize = 3;
2024-09-12 11:42:21 -05:00
2024-10-27 08:29:14 -05:00
pub mod hbvm;
type Nid = u16;
2024-09-02 17:07:20 -05:00
2024-10-01 14:33:30 -05:00
type Lookup = crate::ctx_map::CtxMap<Nid>;
impl crate::ctx_map::CtxEntry for Nid {
2024-10-24 06:25:30 -05:00
type Ctx = [Result<Node, (Nid, debug::Trace)>];
2024-10-01 14:33:30 -05:00
type Key<'a> = (Kind, &'a [Nid], ty::Id);
2024-09-08 05:00:07 -05:00
2024-10-01 14:33:30 -05:00
fn key<'a>(&self, ctx: &'a Self::Ctx) -> Self::Key<'a> {
ctx[*self as usize].as_ref().unwrap().key()
2024-09-08 05:00:07 -05:00
}
}
2024-10-21 11:57:23 -05:00
#[derive(Clone)]
2024-09-04 09:54:34 -05:00
struct Nodes {
2024-10-24 06:25:30 -05:00
values: Vec<Result<Node, (Nid, debug::Trace)>>,
visited: BitSet,
free: Nid,
lookup: Lookup,
2024-09-04 09:54:34 -05:00
}
impl Default for Nodes {
fn default() -> Self {
Self {
values: Default::default(),
free: Nid::MAX,
lookup: Default::default(),
visited: Default::default(),
}
2024-09-04 09:54:34 -05:00
}
}
impl Nodes {
2024-10-26 05:09:53 -05:00
fn merge_scopes(
&mut self,
loops: &mut [Loop],
ctrl: &StrongRef,
to: &mut Scope,
from: &mut Scope,
) {
for (i, (to_value, from_value)) in to.iter_mut().zip(from.iter_mut()).enumerate() {
debug_assert_eq!(to_value.ty, from_value.ty);
if to_value.value() != from_value.value() {
self.load_loop_var(i, from_value, loops);
self.load_loop_var(i, to_value, loops);
if to_value.value() != from_value.value() {
let inps = [ctrl.get(), from_value.value(), to_value.value()];
to_value.set_value_remove(self.new_node(from_value.ty, Kind::Phi, inps), self);
}
}
}
to.loads.drain(..).for_each(|l| _ = l.remove(self));
from.loads.drain(..).for_each(|l| _ = l.remove(self));
}
2024-10-20 03:37:48 -05:00
fn graphviz_low(
&self,
tys: &Types,
files: &[parser::Ast],
out: &mut String,
) -> core::fmt::Result {
use core::fmt::Write;
2024-10-22 15:57:40 -05:00
writeln!(out)?;
writeln!(out, "digraph G {{")?;
writeln!(out, "rankdir=BT;")?;
writeln!(out, "concentrate=true;")?;
writeln!(out, "compound=true;")?;
2024-10-20 03:37:48 -05:00
for (i, node) in self.iter() {
2024-10-22 15:57:40 -05:00
let color = match () {
2024-10-23 05:26:07 -05:00
_ if node.lock_rc == Nid::MAX => "orange",
_ if node.lock_rc == Nid::MAX - 1 => "blue",
_ if node.lock_rc != 0 => "red",
_ if node.outputs.is_empty() => "purple",
_ if node.is_mem() => "green",
2024-10-22 15:57:40 -05:00
_ if self.is_cfg(i) => "yellow",
_ => "white",
2024-10-22 09:03:23 -05:00
};
2024-10-22 15:57:40 -05:00
2024-10-23 05:26:07 -05:00
if node.ty != ty::Id::VOID {
writeln!(
out,
" node{i}[label=\"{i} {} {}\" color={color}]",
node.kind,
ty::Display::new(tys, files, node.ty)
)?;
2024-10-22 15:57:40 -05:00
} else {
2024-10-23 05:26:07 -05:00
writeln!(out, " node{i}[label=\"{i} {}\" color={color}]", node.kind,)?;
2024-10-22 15:57:40 -05:00
}
2024-10-20 03:37:48 -05:00
for (j, &o) in node.outputs.iter().enumerate() {
let color = if self.is_cfg(i) && self.is_cfg(o) { "red" } else { "lightgray" };
let index = self[o].inputs.iter().position(|&inp| i == inp).unwrap();
let style = if index == 0 && !self.is_cfg(o) { "style=dotted" } else { "" };
writeln!(
out,
2024-10-26 03:25:42 -05:00
" node{o} -> node{i}[color={color} taillabel={index} headlabel={j} {style}]",
2024-10-20 03:37:48 -05:00
)?;
}
}
2024-10-22 15:57:40 -05:00
writeln!(out, "}}")?;
2024-10-20 03:37:48 -05:00
Ok(())
}
fn graphviz(&self, tys: &Types, files: &[parser::Ast]) {
let out = &mut String::new();
_ = self.graphviz_low(tys, files, out);
log::info!("{out}");
}
2024-10-27 07:57:00 -05:00
fn graphviz_in_browser(&self, _tys: &Types, _files: &[parser::Ast]) {
2024-10-24 06:25:30 -05:00
#[cfg(all(debug_assertions, feature = "std"))]
2024-10-22 15:57:40 -05:00
{
2024-10-27 07:57:00 -05:00
let out = &mut String::new();
_ = self.graphviz_low(_tys, _files, out);
if !std::process::Command::new("brave")
.arg(format!("https://dreampuf.github.io/GraphvizOnline/#{out}"))
.status()
.unwrap()
.success()
{
log::error!("{out}");
}
2024-10-22 15:57:40 -05:00
}
}
2024-10-19 12:37:02 -05:00
fn gcm(&mut self) {
2024-10-27 05:32:34 -05:00
fix_loops(self);
2024-10-19 12:37:02 -05:00
self.visited.clear(self.values.len());
push_up(self);
self.visited.clear(self.values.len());
push_down(self, VOID);
}
2024-09-04 09:54:34 -05:00
fn clear(&mut self) {
self.values.clear();
2024-09-04 16:46:32 -05:00
self.lookup.clear();
self.free = Nid::MAX;
2024-09-04 09:54:34 -05:00
}
2024-10-17 12:32:10 -05:00
fn new_node_nop(&mut self, ty: ty::Id, kind: Kind, inps: impl Into<Vc>) -> Nid {
2024-09-19 06:40:03 -05:00
let node =
Node { ralloc_backref: u16::MAX, inputs: inps.into(), kind, ty, ..Default::default() };
2024-10-23 05:26:07 -05:00
if node.kind == Kind::Phi && node.ty != ty::Id::VOID {
debug_assert_ne!(
self[node.inputs[1]].ty,
ty::Id::VOID,
"{:?} {:?}",
self[node.inputs[1]],
node.ty.expand(),
);
if self[node.inputs[0]].kind != Kind::Loop {
debug_assert_ne!(
self[node.inputs[2]].ty,
ty::Id::VOID,
"{:?} {:?}",
self[node.inputs[2]],
node.ty.expand(),
);
}
}
2024-09-08 05:00:07 -05:00
let mut lookup_meta = None;
if !node.is_not_gvnd() {
2024-10-01 14:33:30 -05:00
let (raw_entry, hash) = self.lookup.entry(node.key(), &self.values);
2024-09-04 09:54:34 -05:00
2024-09-08 05:00:07 -05:00
let entry = match raw_entry {
2024-10-01 14:33:30 -05:00
hash_map::RawEntryMut::Occupied(o) => return o.get_key_value().0.value,
2024-09-08 05:00:07 -05:00
hash_map::RawEntryMut::Vacant(v) => v,
};
2024-09-04 09:54:34 -05:00
2024-09-08 05:00:07 -05:00
lookup_meta = Some((entry, hash));
}
if self.free == Nid::MAX {
self.free = self.values.len() as _;
2024-10-24 06:25:30 -05:00
self.values.push(Err((Nid::MAX, debug::trace())));
}
let free = self.free;
for &d in node.inputs.as_slice() {
debug_assert_ne!(d, free);
2024-09-15 13:14:56 -05:00
self.values[d as usize].as_mut().unwrap_or_else(|_| panic!("{d}")).outputs.push(free);
}
2024-10-22 09:53:48 -05:00
self.free = mem::replace(&mut self.values[free as usize], Ok(node)).unwrap_err().0;
2024-09-08 05:00:07 -05:00
if let Some((entry, hash)) = lookup_meta {
2024-10-01 14:33:30 -05:00
entry.insert(crate::ctx_map::Key { value: free, hash }, ());
2024-09-08 05:00:07 -05:00
}
free
}
fn remove_node_lookup(&mut self, target: Nid) {
if !self[target].is_not_gvnd() {
2024-10-26 08:18:00 -05:00
self.lookup
.remove(&target, &self.values)
.unwrap_or_else(|| panic!("{:?}", self[target]));
2024-09-08 05:00:07 -05:00
}
}
2024-10-27 07:57:00 -05:00
fn new_node(&mut self, ty: ty::Id, kind: Kind, inps: impl Into<Vc>) -> Nid {
2024-09-06 11:50:28 -05:00
let id = self.new_node_nop(ty, kind, inps);
2024-09-04 09:54:34 -05:00
if let Some(opt) = self.peephole(id) {
debug_assert_ne!(opt, id);
self.lock(opt);
self.remove(id);
self.unlock(opt);
2024-10-27 07:57:00 -05:00
opt
2024-09-04 09:54:34 -05:00
} else {
2024-10-27 07:57:00 -05:00
id
2024-09-04 09:54:34 -05:00
}
}
2024-10-17 12:32:10 -05:00
fn new_node_lit(&mut self, ty: ty::Id, kind: Kind, inps: impl Into<Vc>) -> Value {
2024-10-27 07:57:00 -05:00
Value::new(self.new_node(ty, kind, inps)).ty(ty)
2024-10-17 12:32:10 -05:00
}
2024-09-04 09:54:34 -05:00
fn lock(&mut self, target: Nid) {
self[target].lock_rc += 1;
}
2024-09-05 18:17:54 -05:00
#[track_caller]
2024-09-04 09:54:34 -05:00
fn unlock(&mut self, target: Nid) {
self[target].lock_rc -= 1;
}
2024-09-05 18:17:54 -05:00
fn remove(&mut self, target: Nid) -> bool {
2024-09-04 09:54:34 -05:00
if !self[target].is_dangling() {
2024-09-05 18:17:54 -05:00
return false;
2024-09-04 09:54:34 -05:00
}
2024-09-05 18:17:54 -05:00
for i in 0..self[target].inputs.len() {
2024-09-04 09:54:34 -05:00
let inp = self[target].inputs[i];
let index = self[inp].outputs.iter().position(|&p| p == target).unwrap();
self[inp].outputs.swap_remove(index);
self.remove(inp);
}
2024-09-06 11:50:28 -05:00
self.remove_node_lookup(target);
2024-10-27 07:57:00 -05:00
if cfg!(debug_assertions) {
mem::replace(&mut self.values[target as usize], Err((Nid::MAX, debug::trace())))
.unwrap();
} else {
mem::replace(&mut self.values[target as usize], Err((self.free, debug::trace())))
.unwrap();
self.free = target;
}
2024-09-05 18:17:54 -05:00
true
2024-09-04 09:54:34 -05:00
}
2024-10-26 03:45:50 -05:00
fn late_peephole(&mut self, target: Nid) -> Option<Nid> {
if let Some(id) = self.peephole(target) {
self.replace(target, id);
return Some(id);
}
None
}
2024-10-27 05:32:34 -05:00
fn iter_peeps(&mut self, mut fuel: usize, stack: &mut Vec<Nid>) {
stack.clear();
2024-10-26 08:18:00 -05:00
2024-10-27 05:32:34 -05:00
self.iter()
2024-10-26 13:29:31 -05:00
.filter_map(|(id, node)| node.kind.is_peeped().then_some(id))
2024-10-27 05:32:34 -05:00
.collect_into(stack);
2024-10-26 08:18:00 -05:00
stack.iter().for_each(|&s| self.lock(s));
2024-10-26 03:45:50 -05:00
while fuel != 0
&& let Some(node) = stack.pop()
{
fuel -= 1;
2024-10-26 08:18:00 -05:00
if self.unlock_remove(node) {
continue;
}
2024-10-26 03:45:50 -05:00
let new = self.late_peephole(node);
if let Some(new) = new {
2024-10-26 08:18:00 -05:00
let prev_len = stack.len();
2024-10-26 03:45:50 -05:00
for &i in self[new].outputs.iter().chain(self[new].inputs.iter()) {
2024-10-26 13:29:31 -05:00
if self[i].kind.is_peeped() && self[i].lock_rc == 0 {
stack.push(i);
2024-10-26 03:45:50 -05:00
}
}
2024-10-26 08:18:00 -05:00
stack.iter().skip(prev_len).for_each(|&n| self.lock(n));
2024-10-26 03:45:50 -05:00
}
}
}
2024-09-04 09:54:34 -05:00
fn peephole(&mut self, target: Nid) -> Option<Nid> {
2024-09-28 08:13:32 -05:00
use {Kind as K, TokenKind as T};
2024-09-04 09:54:34 -05:00
match self[target].kind {
2024-09-28 08:13:32 -05:00
K::BinOp { op } => {
let &[ctrl, mut lhs, mut rhs] = self[target].inputs.as_slice() else {
unreachable!()
};
let ty = self[target].ty;
2024-09-04 09:54:34 -05:00
2024-09-28 08:13:32 -05:00
if let (&K::CInt { value: a }, &K::CInt { value: b }) =
(&self[lhs].kind, &self[rhs].kind)
{
return Some(
self.new_node(ty, K::CInt { value: op.apply_binop(a, b) }, [ctrl]),
);
}
2024-09-08 05:00:07 -05:00
2024-09-28 08:13:32 -05:00
if lhs == rhs {
match op {
T::Sub => return Some(self.new_node(ty, K::CInt { value: 0 }, [ctrl])),
T::Add => {
let rhs = self.new_node_nop(ty, K::CInt { value: 2 }, [ctrl]);
return Some(
self.new_node(ty, K::BinOp { op: T::Mul }, [ctrl, lhs, rhs]),
);
}
_ => {}
}
}
2024-09-08 05:00:07 -05:00
2024-09-28 08:13:32 -05:00
// this is more general the pushing constants to left to help deduplicate expressions more
let mut changed = false;
if op.is_comutative() && self[lhs].key() < self[rhs].key() {
2024-10-26 05:09:53 -05:00
mem::swap(&mut lhs, &mut rhs);
2024-09-28 08:13:32 -05:00
changed = true;
}
2024-09-06 11:50:28 -05:00
2024-09-28 08:13:32 -05:00
if let K::CInt { value } = self[rhs].kind {
match (op, value) {
(T::Add | T::Sub | T::Shl, 0) | (T::Mul | T::Div, 1) => return Some(lhs),
(T::Mul, 0) => return Some(rhs),
_ => {}
}
}
2024-09-15 13:14:56 -05:00
2024-09-28 08:13:32 -05:00
if op.is_comutative() && self[lhs].kind == (K::BinOp { op }) {
let &[_, a, b] = self[lhs].inputs.as_slice() else { unreachable!() };
if let K::CInt { value: av } = self[b].kind
&& let K::CInt { value: bv } = self[rhs].kind
{
// (a op #b) op #c => a op (#b op #c)
let new_rhs =
self.new_node_nop(ty, K::CInt { value: op.apply_binop(av, bv) }, [
ctrl,
]);
return Some(self.new_node(ty, K::BinOp { op }, [ctrl, a, new_rhs]));
}
2024-09-15 13:14:56 -05:00
2024-09-28 08:13:32 -05:00
if self.is_const(b) {
// (a op #b) op c => (a op c) op #b
let new_lhs = self.new_node(ty, K::BinOp { op }, [ctrl, a, rhs]);
return Some(self.new_node(ty, K::BinOp { op }, [ctrl, new_lhs, b]));
}
}
2024-09-15 13:14:56 -05:00
2024-09-28 08:13:32 -05:00
if op == T::Add
&& self[lhs].kind == (K::BinOp { op: T::Mul })
&& self[lhs].inputs[1] == rhs
&& let K::CInt { value } = self[self[lhs].inputs[2]].kind
{
// a * #n + a => a * (#n + 1)
let new_rhs = self.new_node_nop(ty, K::CInt { value: value + 1 }, [ctrl]);
return Some(self.new_node(ty, K::BinOp { op: T::Mul }, [ctrl, rhs, new_rhs]));
}
2024-09-08 10:11:33 -05:00
2024-10-21 10:29:11 -05:00
if op == T::Sub
&& self[lhs].kind == (K::BinOp { op: T::Add })
&& let K::CInt { value: a } = self[rhs].kind
&& let K::CInt { value: b } = self[self[lhs].inputs[2]].kind
{
let new_rhs = self.new_node_nop(ty, K::CInt { value: b - a }, [ctrl]);
return Some(self.new_node(ty, K::BinOp { op: T::Add }, [
ctrl,
self[lhs].inputs[1],
new_rhs,
]));
}
2024-09-28 08:13:32 -05:00
if op == T::Sub && self[lhs].kind == (K::BinOp { op }) {
// (a - b) - c => a - (b + c)
let &[_, a, b] = self[lhs].inputs.as_slice() else { unreachable!() };
let c = rhs;
let new_rhs = self.new_node(ty, K::BinOp { op: T::Add }, [ctrl, b, c]);
return Some(self.new_node(ty, K::BinOp { op }, [ctrl, a, new_rhs]));
}
2024-09-04 09:54:34 -05:00
2024-09-28 08:13:32 -05:00
if changed {
return Some(self.new_node(ty, self[target].kind, [ctrl, lhs, rhs]));
2024-09-04 09:54:34 -05:00
}
}
2024-09-28 08:13:32 -05:00
K::UnOp { op } => {
let &[ctrl, oper] = self[target].inputs.as_slice() else { unreachable!() };
let ty = self[target].ty;
2024-09-04 09:54:34 -05:00
2024-09-28 08:13:32 -05:00
if let K::CInt { value } = self[oper].kind {
return Some(
self.new_node(ty, K::CInt { value: op.apply_unop(value) }, [ctrl]),
);
}
2024-09-04 09:54:34 -05:00
}
2024-09-28 08:13:32 -05:00
K::If => {
2024-10-26 13:29:31 -05:00
if self[target].ty == ty::Id::VOID {
let &[ctrl, cond] = self[target].inputs.as_slice() else { unreachable!() };
if let K::CInt { value } = self[cond].kind {
let ty = if value == 0 {
ty::Id::LEFT_UNREACHABLE
} else {
ty::Id::RIGHT_UNREACHABLE
};
return Some(self.new_node_nop(ty, K::If, [ctrl, cond]));
}
'b: {
let mut cursor = ctrl;
let ty = loop {
if cursor == ENTRY {
break 'b;
}
// TODO: do more inteligent checks on the condition
if self[cursor].kind == Kind::Then
&& self[self[cursor].inputs[0]].inputs[1] == cond
{
break ty::Id::RIGHT_UNREACHABLE;
}
if self[cursor].kind == Kind::Else
&& self[self[cursor].inputs[0]].inputs[1] == cond
{
break ty::Id::LEFT_UNREACHABLE;
}
cursor = idom(self, cursor);
};
return Some(self.new_node_nop(ty, K::If, [ctrl, cond]));
}
}
}
K::Then => {
if self[self[target].inputs[0]].ty == ty::Id::LEFT_UNREACHABLE {
return Some(NEVER);
} else if self[self[target].inputs[0]].ty == ty::Id::RIGHT_UNREACHABLE {
return Some(self[self[target].inputs[0]].inputs[0]);
2024-09-28 08:13:32 -05:00
}
2024-09-04 09:54:34 -05:00
}
2024-10-26 13:29:31 -05:00
K::Else => {
if self[self[target].inputs[0]].ty == ty::Id::RIGHT_UNREACHABLE {
return Some(NEVER);
} else if self[self[target].inputs[0]].ty == ty::Id::LEFT_UNREACHABLE {
return Some(self[self[target].inputs[0]].inputs[0]);
}
}
K::Region => {
let (ctrl, side) = match self[target].inputs.as_slice() {
[NEVER, NEVER] => return Some(NEVER),
&[NEVER, ctrl] => (ctrl, 2),
&[ctrl, NEVER] => (ctrl, 1),
_ => return None,
};
self.lock(target);
for i in self[target].outputs.clone() {
if self[i].kind == Kind::Phi {
self.replace(i, self[i].inputs[side]);
}
}
self.unlock(target);
return Some(ctrl);
}
2024-10-27 05:32:34 -05:00
K::Call { .. } | K::Return => {
if self[target].inputs[0] == NEVER {
return Some(NEVER);
}
}
2024-09-28 08:13:32 -05:00
K::Phi => {
2024-10-18 06:11:11 -05:00
let &[ctrl, lhs, rhs] = self[target].inputs.as_slice() else { unreachable!() };
if lhs == rhs {
return Some(lhs);
}
if self[lhs].kind == Kind::Stre
&& self[rhs].kind == Kind::Stre
&& self[lhs].ty == self[rhs].ty
&& self[lhs].inputs[2] == self[rhs].inputs[2]
&& self[lhs].inputs.get(3) == self[rhs].inputs.get(3)
{
let pick_value = self.new_node(self[lhs].ty, Kind::Phi, [
ctrl,
self[lhs].inputs[1],
self[rhs].inputs[1],
]);
let mut vc = Vc::from([VOID, pick_value, self[lhs].inputs[2]]);
for &rest in &self[lhs].inputs[3..] {
vc.push(rest);
}
for &rest in &self[rhs].inputs[4..] {
vc.push(rest);
}
return Some(self.new_node(self[lhs].ty, Kind::Stre, vc));
}
}
K::Stre => {
if self[target].inputs[2] != VOID
&& self[target].inputs.len() == 4
&& self[self[target].inputs[1]].kind != Kind::Load
2024-10-18 06:11:11 -05:00
&& self[self[target].inputs[3]].kind == Kind::Stre
&& self[self[target].inputs[3]].lock_rc == 0
2024-10-18 06:11:11 -05:00
&& self[self[target].inputs[3]].inputs[2] == self[target].inputs[2]
{
return Some(self.modify_input(
self[target].inputs[3],
1,
self[target].inputs[1],
));
}
}
K::Load => {
if self[target].inputs.len() == 3
&& self[self[target].inputs[2]].kind == Kind::Stre
&& self[self[target].inputs[2]].inputs[2] == self[target].inputs[1]
&& self[self[target].inputs[2]].ty == self[target].ty
{
return Some(self[self[target].inputs[2]].inputs[1]);
2024-09-28 08:13:32 -05:00
}
2024-09-04 09:54:34 -05:00
}
K::Extend => {
if self[target].ty.simple_size() == self[self[target].inputs[1]].ty.simple_size() {
return Some(self[target].inputs[1]);
}
}
K::Loop => {
2024-10-26 13:29:31 -05:00
if self[target].inputs[0] == NEVER {
return Some(NEVER);
}
if self[target].inputs[1] == NEVER {
2024-10-22 15:57:40 -05:00
self.lock(target);
for o in self[target].outputs.clone() {
if self[o].kind == Kind::Phi {
self.replace(o, self[o].inputs[1]);
}
}
2024-10-22 15:57:40 -05:00
self.unlock(target);
return Some(self[target].inputs[0]);
}
}
2024-09-28 08:13:32 -05:00
_ => {}
2024-09-04 09:54:34 -05:00
}
2024-09-28 08:13:32 -05:00
None
2024-09-04 09:54:34 -05:00
}
fn is_const(&self, id: Nid) -> bool {
2024-09-08 10:11:33 -05:00
matches!(self[id].kind, Kind::CInt { .. })
2024-09-04 09:54:34 -05:00
}
fn replace(&mut self, target: Nid, with: Nid) {
2024-10-26 13:29:31 -05:00
debug_assert_ne!(target, with, "{:?}", self[target]);
2024-09-08 05:00:07 -05:00
let mut back_press = 0;
2024-09-04 09:54:34 -05:00
for i in 0..self[target].outputs.len() {
2024-09-08 05:00:07 -05:00
let out = self[target].outputs[i - back_press];
let index = self[out].inputs.iter().position(|&p| p == target).unwrap();
2024-09-28 08:13:32 -05:00
self.lock(target);
2024-09-08 05:00:07 -05:00
let prev_len = self[target].outputs.len();
self.modify_input(out, index, with);
back_press += (self[target].outputs.len() != prev_len) as usize;
2024-09-28 08:13:32 -05:00
self.unlock(target);
2024-09-04 09:54:34 -05:00
}
2024-09-05 18:17:54 -05:00
self.remove(target);
2024-09-04 09:54:34 -05:00
}
fn modify_input(&mut self, target: Nid, inp_index: usize, with: Nid) -> Nid {
self.remove_node_lookup(target);
2024-10-26 13:29:31 -05:00
debug_assert_ne!(self[target].inputs[inp_index], with, "{:?}", self[target]);
2024-09-04 09:54:34 -05:00
2024-09-05 18:17:54 -05:00
let prev = self[target].inputs[inp_index];
2024-09-04 09:54:34 -05:00
self[target].inputs[inp_index] = with;
2024-10-01 14:33:30 -05:00
let (entry, hash) = self.lookup.entry(target.key(&self.values), &self.values);
match entry {
2024-09-30 12:09:17 -05:00
hash_map::RawEntryMut::Occupied(other) => {
2024-10-01 14:33:30 -05:00
let rpl = other.get_key_value().0.value;
self[target].inputs[inp_index] = prev;
self.lookup.insert(target.key(&self.values), target, &self.values);
self.replace(target, rpl);
rpl
}
hash_map::RawEntryMut::Vacant(slot) => {
2024-10-01 14:33:30 -05:00
slot.insert(crate::ctx_map::Key { value: target, hash }, ());
let index = self[prev].outputs.iter().position(|&o| o == target).unwrap();
self[prev].outputs.swap_remove(index);
self[with].outputs.push(target);
2024-09-28 08:13:32 -05:00
self.remove(prev);
2024-09-05 18:17:54 -05:00
target
}
}
2024-09-04 09:54:34 -05:00
}
2024-09-05 18:17:54 -05:00
#[track_caller]
fn unlock_remove(&mut self, id: Nid) -> bool {
self[id].lock_rc -= 1;
self.remove(id)
2024-09-04 09:54:34 -05:00
}
fn iter(&self) -> impl DoubleEndedIterator<Item = (Nid, &Node)> {
self.values.iter().enumerate().filter_map(|(i, s)| Some((i as _, s.as_ref().ok()?)))
}
2024-10-27 07:57:00 -05:00
#[expect(clippy::format_in_format_args)]
2024-09-30 12:09:17 -05:00
fn basic_blocks_instr(&mut self, out: &mut String, node: Nid) -> core::fmt::Result {
2024-09-12 11:42:21 -05:00
if self[node].kind != Kind::Loop && self[node].kind != Kind::Region {
2024-09-19 06:40:03 -05:00
write!(out, " {node:>2}-c{:>2}: ", self[node].ralloc_backref)?;
}
match self[node].kind {
Kind::Start => unreachable!(),
2024-10-27 05:32:34 -05:00
Kind::End => return Ok(()),
Kind::If => write!(out, " if: "),
2024-09-12 11:42:21 -05:00
Kind::Region | Kind::Loop => writeln!(out, " goto: {node}"),
Kind::Return => write!(out, " ret: "),
Kind::CInt { value } => write!(out, "cint: #{value:<4}"),
Kind::Phi => write!(out, " phi: "),
2024-10-19 12:37:02 -05:00
Kind::Arg => write!(
out,
" arg: {:<5}",
self[VOID].outputs.iter().position(|&n| n == node).unwrap() - 2
),
2024-09-15 13:14:56 -05:00
Kind::BinOp { op } | Kind::UnOp { op } => {
write!(out, "{:>4}: ", op.name())
}
2024-10-24 02:43:07 -05:00
Kind::Call { func, args: _ } => {
2024-09-12 11:42:21 -05:00
write!(out, "call: {func} {} ", self[node].depth)
}
2024-10-20 03:37:48 -05:00
Kind::Global { global } => write!(out, "glob: {global:<5}"),
2024-09-27 09:53:28 -05:00
Kind::Entry => write!(out, "ctrl: {:<5}", "entry"),
Kind::Then => write!(out, "ctrl: {:<5}", "then"),
Kind::Else => write!(out, "ctrl: {:<5}", "else"),
Kind::Stck => write!(out, "stck: "),
2024-10-19 03:17:36 -05:00
Kind::Load => write!(out, "load: "),
2024-10-18 02:52:50 -05:00
Kind::Stre => write!(out, "stre: "),
2024-10-19 03:17:36 -05:00
Kind::Mem => write!(out, " mem: "),
2024-10-27 05:32:34 -05:00
Kind::Loops => write!(out, " loops: "),
Kind::Extend => write!(out, " ext: "),
}?;
2024-09-12 11:42:21 -05:00
if self[node].kind != Kind::Loop && self[node].kind != Kind::Region {
writeln!(
out,
" {:<14} {}",
format!("{:?}", self[node].inputs),
format!("{:?}", self[node].outputs)
)?;
}
Ok(())
}
2024-09-30 12:09:17 -05:00
fn basic_blocks_low(&mut self, out: &mut String, mut node: Nid) -> core::fmt::Result {
2024-09-12 11:42:21 -05:00
let iter = |nodes: &Nodes, node| nodes[node].outputs.clone().into_iter().rev();
while self.visited.set(node) {
2024-09-12 11:42:21 -05:00
match self[node].kind {
Kind::Start => {
writeln!(out, "start: {}", self[node].depth)?;
let mut cfg_index = Nid::MAX;
2024-09-12 11:42:21 -05:00
for o in iter(self, node) {
self.basic_blocks_instr(out, o)?;
if self[o].kind.is_cfg() {
cfg_index = o;
}
}
node = cfg_index;
}
Kind::End => break,
Kind::If => {
self.basic_blocks_low(out, self[node].outputs[0])?;
node = self[node].outputs[1];
}
Kind::Region => {
2024-09-15 13:14:56 -05:00
writeln!(
out,
"region{node}: {} {} {:?}",
self[node].depth, self[node].loop_depth, self[node].inputs
)?;
let mut cfg_index = Nid::MAX;
2024-09-12 11:42:21 -05:00
for o in iter(self, node) {
self.basic_blocks_instr(out, o)?;
if self.is_cfg(o) {
cfg_index = o;
}
}
node = cfg_index;
}
Kind::Loop => {
2024-09-15 13:14:56 -05:00
writeln!(
out,
"loop{node}: {} {} {:?}",
self[node].depth, self[node].loop_depth, self[node].outputs
)?;
let mut cfg_index = Nid::MAX;
2024-09-12 11:42:21 -05:00
for o in iter(self, node) {
self.basic_blocks_instr(out, o)?;
if self.is_cfg(o) {
cfg_index = o;
}
}
node = cfg_index;
}
Kind::Return => {
node = self[node].outputs[0];
}
2024-09-27 09:53:28 -05:00
Kind::Then | Kind::Else | Kind::Entry => {
2024-09-15 13:14:56 -05:00
writeln!(
out,
"b{node}: {} {} {:?}",
self[node].depth, self[node].loop_depth, self[node].outputs
)?;
let mut cfg_index = Nid::MAX;
2024-09-12 11:42:21 -05:00
for o in iter(self, node) {
self.basic_blocks_instr(out, o)?;
if self.is_cfg(o) {
cfg_index = o;
}
}
node = cfg_index;
}
Kind::Call { .. } => {
let mut cfg_index = Nid::MAX;
let mut print_ret = true;
2024-09-12 11:42:21 -05:00
for o in iter(self, node) {
if self[o].inputs[0] == node
2024-10-26 05:09:53 -05:00
&& (self[node].outputs[0] != o || mem::take(&mut print_ret))
{
self.basic_blocks_instr(out, o)?;
}
2024-09-12 11:42:21 -05:00
if self.is_cfg(o) {
cfg_index = o;
}
}
node = cfg_index;
}
2024-09-27 09:53:28 -05:00
_ => unreachable!(),
}
}
Ok(())
}
fn basic_blocks(&mut self) {
let mut out = String::new();
self.visited.clear(self.values.len());
self.basic_blocks_low(&mut out, VOID).unwrap();
2024-09-30 12:27:00 -05:00
log::info!("{out}");
}
2024-09-04 09:54:34 -05:00
fn is_cfg(&self, o: Nid) -> bool {
self[o].kind.is_cfg()
2024-09-04 16:46:32 -05:00
}
2024-10-22 15:57:40 -05:00
fn check_final_integrity(&self, tys: &Types, files: &[parser::Ast]) {
2024-10-22 09:54:32 -05:00
if !cfg!(debug_assertions) {
return;
}
2024-10-19 12:37:02 -05:00
2024-10-22 15:57:40 -05:00
let mut failed = false;
for (id, node) in self.iter() {
if node.lock_rc != 0 {
log::error!("{} {} {:?}", node.lock_rc, 0, node.kind);
failed = true;
}
2024-10-27 05:32:34 -05:00
if !matches!(node.kind, Kind::End | Kind::Mem | Kind::Arg | Kind::Loops)
&& node.outputs.is_empty()
{
2024-10-22 15:57:40 -05:00
log::error!("outputs are empry {id} {:?}", node.kind);
failed = true;
}
2024-10-27 05:32:34 -05:00
if node.inputs.first() == Some(&NEVER) && id != NEVER {
log::error!("is unreachable but still present {id} {:?}", node.kind);
failed = true;
}
2024-10-22 09:54:32 -05:00
}
2024-10-26 03:25:42 -05:00
2024-10-22 15:57:40 -05:00
if failed {
self.graphviz_in_browser(tys, files);
panic!()
}
2024-09-04 09:54:34 -05:00
}
2024-10-22 15:57:40 -05:00
fn load_loop_var(&mut self, index: usize, value: &mut Variable, loops: &mut [Loop]) {
self.load_loop_value(&mut |l| l.scope.iter_mut().nth(index).unwrap(), value, loops);
2024-10-19 03:17:36 -05:00
}
2024-10-22 15:57:40 -05:00
fn load_loop_store(&mut self, value: &mut Variable, loops: &mut [Loop]) {
self.load_loop_value(&mut |l| &mut l.scope.store, value, loops);
2024-10-19 03:17:36 -05:00
}
fn load_loop_value(
&mut self,
2024-10-22 15:57:40 -05:00
get_lvalue: &mut impl FnMut(&mut Loop) -> &mut Variable,
var: &mut Variable,
2024-10-19 03:17:36 -05:00
loops: &mut [Loop],
) {
2024-10-22 15:57:40 -05:00
if var.value() != VOID {
2024-09-08 10:11:33 -05:00
return;
}
let [loops @ .., loob] = loops else { unreachable!() };
2024-10-19 03:17:36 -05:00
let node = loob.node;
2024-10-22 15:57:40 -05:00
let lvar = get_lvalue(loob);
2024-09-08 10:11:33 -05:00
2024-10-22 15:57:40 -05:00
self.load_loop_value(get_lvalue, lvar, loops);
2024-09-08 10:11:33 -05:00
2024-10-22 15:57:40 -05:00
if !self[lvar.value()].is_lazy_phi(node) {
let inps = [node, lvar.value(), VOID];
lvar.set_value(self.new_node_nop(lvar.ty, Kind::Phi, inps), self);
2024-09-15 13:14:56 -05:00
}
2024-10-22 15:57:40 -05:00
var.set_value(lvar.value(), self);
2024-09-15 13:14:56 -05:00
}
fn check_dominance(&mut self, nd: Nid, min: Nid, check_outputs: bool) {
2024-10-19 12:37:02 -05:00
if !cfg!(debug_assertions) {
return;
}
2024-09-15 13:14:56 -05:00
let node = self[nd].clone();
for &i in node.inputs.iter() {
let dom = idom(self, i);
debug_assert!(
self.dominates(dom, min),
"{dom} {min} {node:?} {:?}",
self.basic_blocks()
);
}
if check_outputs {
for &o in node.outputs.iter() {
let dom = use_block(nd, o, self);
debug_assert!(
self.dominates(min, dom),
"{min} {dom} {node:?} {:?}",
self.basic_blocks()
);
}
}
}
fn dominates(&mut self, dominator: Nid, mut dominated: Nid) -> bool {
loop {
if dominator == dominated {
break true;
}
if idepth(self, dominator) > idepth(self, dominated) {
break false;
}
dominated = idom(self, dominated);
2024-09-08 10:11:33 -05:00
}
}
2024-09-19 06:40:03 -05:00
2024-10-22 09:03:23 -05:00
fn eliminate_stack_temporaries(&mut self) {
'o: for stack in self[MEM].outputs.clone() {
if self.values[stack as usize].is_err() || self[stack].kind != Kind::Stck {
2024-10-22 09:03:23 -05:00
continue;
}
let mut full_read_into = None;
let mut unidentifed = Vc::default();
for &o in self[stack].outputs.iter() {
match self[o].kind {
Kind::Load
if self[o].ty == self[stack].ty
2024-10-24 03:21:10 -05:00
&& self[o].outputs.iter().all(|&n| self[n].kind == Kind::Stre)
2024-10-22 09:03:23 -05:00
&& let mut full_stores = self[o].outputs.iter().filter(|&&n| {
self[n].kind == Kind::Stre && self[n].inputs[1] == o
})
&& let Some(&n) = full_stores.next()
&& full_stores.next().is_none() =>
{
if full_read_into.replace(n).is_some() {
continue 'o;
}
}
_ => unidentifed.push(o),
}
}
let Some(dst) = full_read_into else { continue };
let mut saved = Vc::default();
let mut cursor = dst;
cursor = *self[cursor].inputs.get(3).unwrap_or(&MEM);
while cursor != MEM && self[cursor].kind == Kind::Stre {
let mut contact_point = cursor;
let mut region = self[cursor].inputs[2];
if let Kind::BinOp { op } = self[region].kind {
debug_assert_matches!(op, TokenKind::Add | TokenKind::Sub);
contact_point = region;
region = self[region].inputs[1]
}
if region != stack {
2024-10-24 12:57:36 -05:00
break;
2024-10-22 09:03:23 -05:00
}
let Some(index) = unidentifed.iter().position(|&n| n == contact_point) else {
continue 'o;
};
unidentifed.remove(index);
saved.push(contact_point);
cursor = *self[cursor].inputs.get(3).unwrap_or(&MEM);
if unidentifed.is_empty() {
break;
}
}
let region = self[dst].inputs[2];
// TODO: this can be an offset already due to previous peeps so handle that
if let &[mcall] = unidentifed.as_slice()
&& matches!(self[mcall].kind, Kind::Call { .. })
&& self[mcall].inputs.last() == Some(&stack)
{
self.modify_input(mcall, self[mcall].inputs.len() - 1, region);
} else {
if !unidentifed.is_empty() {
continue;
2024-10-22 09:03:23 -05:00
}
// FIXME: when the loads and stores become parallel we will need to get saved
// differently
for mut oper in saved.into_iter().rev() {
let mut region = region;
if let Kind::BinOp { op } = self[oper].kind {
debug_assert_eq!(self[oper].outputs.len(), 1);
debug_assert_eq!(self[self[oper].outputs[0]].kind, Kind::Stre);
region = self.new_node(self[oper].ty, Kind::BinOp { op }, [
VOID,
region,
self[oper].inputs[2],
]);
oper = self[oper].outputs[0];
}
self.modify_input(oper, 2, region);
}
2024-10-22 09:03:23 -05:00
}
self.replace(dst, *self[dst].inputs.get(3).unwrap_or(&MEM));
if self.values[stack as usize].is_ok() {
self.lock(stack);
}
if self.values[dst as usize].is_ok() {
self.lock(dst);
}
}
}
2024-09-04 09:54:34 -05:00
}
impl ops::Index<Nid> for Nodes {
2024-09-04 09:54:34 -05:00
type Output = Node;
fn index(&self, index: Nid) -> &Self::Output {
2024-10-22 09:53:48 -05:00
self.values[index as usize].as_ref().unwrap_or_else(|(_, bt)| panic!("{index} {bt:#?}"))
2024-09-02 17:07:20 -05:00
}
2024-09-04 09:54:34 -05:00
}
2024-09-02 17:07:20 -05:00
impl ops::IndexMut<Nid> for Nodes {
fn index_mut(&mut self, index: Nid) -> &mut Self::Output {
2024-10-22 09:53:48 -05:00
self.values[index as usize].as_mut().unwrap_or_else(|(_, bt)| panic!("{index} {bt:#?}"))
2024-09-02 17:07:20 -05:00
}
2024-09-04 09:54:34 -05:00
}
2024-09-02 17:07:20 -05:00
2024-09-12 11:42:21 -05:00
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
2024-09-04 09:54:34 -05:00
#[repr(u8)]
pub enum Kind {
2024-09-12 11:42:21 -05:00
#[default]
2024-09-04 09:54:34 -05:00
Start,
2024-09-30 12:09:17 -05:00
// [ctrl]
Entry,
2024-10-27 05:32:34 -05:00
// [VOID]
2024-09-30 12:09:17 -05:00
Mem,
2024-10-27 05:32:34 -05:00
// [VOID]
Loops,
// [terms...]
2024-09-04 09:54:34 -05:00
End,
// [ctrl, cond]
If,
2024-09-30 12:09:17 -05:00
Then,
Else,
// [lhs, rhs]
Region,
// [entry, back]
2024-09-05 18:17:54 -05:00
Loop,
// [ctrl, ?value]
2024-09-04 09:54:34 -05:00
Return,
// [ctrl]
2024-09-12 11:42:21 -05:00
CInt {
value: i64,
},
// [ctrl, lhs, rhs]
Phi,
2024-10-19 12:37:02 -05:00
Arg,
// [ctrl, oper]
Extend,
// [ctrl, oper]
2024-09-15 13:14:56 -05:00
UnOp {
op: lexer::TokenKind,
},
// [ctrl, lhs, rhs]
2024-09-12 11:42:21 -05:00
BinOp {
op: lexer::TokenKind,
},
2024-10-20 03:37:48 -05:00
// [ctrl]
Global {
global: ty::Global,
},
// [ctrl, ...args]
2024-09-12 11:42:21 -05:00
Call {
func: ty::Func,
2024-10-24 02:43:07 -05:00
args: ty::Tuple,
2024-09-12 11:42:21 -05:00
},
// [ctrl]
2024-09-27 09:53:28 -05:00
Stck,
// [ctrl, memory]
2024-10-18 02:52:50 -05:00
Load,
2024-09-30 12:09:17 -05:00
// [ctrl, value, memory]
2024-10-18 02:52:50 -05:00
Stre,
2024-09-04 09:54:34 -05:00
}
impl Kind {
fn is_pinned(&self) -> bool {
2024-10-27 05:32:34 -05:00
self.is_cfg() || matches!(self, Self::Phi | Self::Arg | Self::Mem | Self::Loops)
}
fn is_cfg(&self) -> bool {
matches!(
self,
2024-09-19 06:40:03 -05:00
Self::Start
| Self::End
| Self::Return
2024-09-27 09:53:28 -05:00
| Self::Entry
| Self::Then
| Self::Else
2024-09-19 06:40:03 -05:00
| Self::Call { .. }
| Self::If
| Self::Region
| Self::Loop
)
}
fn ends_basic_block(&self) -> bool {
2024-09-19 06:40:03 -05:00
matches!(self, Self::Return | Self::If | Self::End)
}
2024-10-26 13:29:31 -05:00
fn is_peeped(&self) -> bool {
!matches!(self, Self::End | Self::Arg)
}
2024-09-04 09:54:34 -05:00
}
2024-09-02 17:07:20 -05:00
impl fmt::Display for Kind {
2024-09-30 12:09:17 -05:00
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
2024-09-08 10:11:33 -05:00
Kind::CInt { value } => write!(f, "#{value}"),
2024-09-27 09:53:28 -05:00
Kind::Entry => write!(f, "ctrl[entry]"),
Kind::Then => write!(f, "ctrl[then]"),
Kind::Else => write!(f, "ctrl[else]"),
Kind::BinOp { op } => write!(f, "{op}"),
Kind::Call { func, .. } => write!(f, "call {func}"),
slf => write!(f, "{slf:?}"),
}
}
}
2024-09-14 04:26:54 -05:00
#[derive(Debug, Default, Clone)]
2024-10-01 14:33:30 -05:00
pub struct Node {
2024-09-27 09:53:28 -05:00
kind: Kind,
inputs: Vc,
outputs: Vc,
2024-09-27 09:53:28 -05:00
ty: ty::Id,
offset: Offset,
2024-09-19 06:40:03 -05:00
ralloc_backref: RallocBRef,
depth: IDomDepth,
lock_rc: LockRc,
loop_depth: LoopDepth,
2024-09-04 09:54:34 -05:00
}
impl Node {
fn is_dangling(&self) -> bool {
self.outputs.len() + self.lock_rc as usize == 0
2024-09-02 17:07:20 -05:00
}
2024-09-08 10:11:33 -05:00
fn key(&self) -> (Kind, &[Nid], ty::Id) {
(self.kind, &self.inputs, self.ty)
}
fn is_lazy_phi(&self, loob: Nid) -> bool {
self.kind == Kind::Phi && self.inputs[2] == 0 && self.inputs[0] == loob
2024-09-02 17:07:20 -05:00
}
2024-10-19 12:37:02 -05:00
fn is_not_gvnd(&self) -> bool {
(self.kind == Kind::Phi && self.inputs[2] == 0)
2024-10-27 05:32:34 -05:00
|| matches!(self.kind, Kind::Arg | Kind::Stck | Kind::End)
2024-10-19 12:37:02 -05:00
}
2024-10-22 15:57:40 -05:00
fn is_mem(&self) -> bool {
matches!(self.kind, Kind::Stre | Kind::Load | Kind::Stck)
}
2024-09-02 17:07:20 -05:00
}
2024-09-19 06:40:03 -05:00
type RallocBRef = u16;
type LoopDepth = u16;
type LockRc = u16;
type IDomDepth = u16;
2024-09-04 09:54:34 -05:00
2024-10-21 11:57:23 -05:00
#[derive(Clone)]
2024-09-02 17:07:20 -05:00
struct Loop {
2024-09-05 18:17:54 -05:00
node: Nid,
2024-10-26 05:09:53 -05:00
ctrl: [StrongRef; 2],
2024-10-18 06:11:11 -05:00
ctrl_scope: [Scope; 2],
scope: Scope,
2024-09-02 17:07:20 -05:00
}
2024-10-26 05:09:53 -05:00
mod strong_ref {
2024-10-22 15:57:40 -05:00
use {
super::{Kind, Nid, Nodes},
2024-10-26 05:09:53 -05:00
crate::debug,
core::ops::Not,
2024-10-22 15:57:40 -05:00
};
2024-09-02 17:07:20 -05:00
2024-10-26 05:09:53 -05:00
#[derive(Clone)]
pub struct StrongRef(Nid);
2024-10-22 15:57:40 -05:00
2024-10-26 05:09:53 -05:00
impl StrongRef {
pub const DEFAULT: Self = Self(Nid::MAX);
pub fn new(value: Nid, nodes: &mut Nodes) -> Self {
2024-10-22 15:57:40 -05:00
nodes.lock(value);
2024-10-26 05:09:53 -05:00
Self(value)
}
pub fn get(&self) -> Nid {
debug_assert!(self.0 != Nid::MAX);
self.0
2024-10-22 15:57:40 -05:00
}
2024-10-19 03:17:36 -05:00
2024-10-26 05:09:53 -05:00
pub fn unwrap(self, nodes: &mut Nodes) -> Option<Nid> {
let nid = self.0;
if nid != Nid::MAX {
nodes.unlock(nid);
core::mem::forget(self);
Some(nid)
} else {
None
}
2024-10-22 15:57:40 -05:00
}
2024-10-26 05:09:53 -05:00
pub fn set(&mut self, mut new_value: Nid, nodes: &mut Nodes) -> Nid {
nodes.unlock(self.0);
core::mem::swap(&mut self.0, &mut new_value);
nodes.lock(self.0);
2024-10-22 15:57:40 -05:00
new_value
}
pub fn dup(&self, nodes: &mut Nodes) -> Self {
2024-10-26 05:09:53 -05:00
nodes.lock(self.0);
Self(self.0)
2024-10-22 15:57:40 -05:00
}
2024-10-26 05:09:53 -05:00
pub fn remove(self, nodes: &mut Nodes) -> Option<Nid> {
let ret = nodes.unlock_remove(self.0).not().then_some(self.0);
2024-10-24 05:28:18 -05:00
core::mem::forget(self);
2024-10-26 05:09:53 -05:00
ret
2024-10-22 15:57:40 -05:00
}
2024-10-26 05:09:53 -05:00
pub fn set_remove(&mut self, new_value: Nid, nodes: &mut Nodes) {
let old = self.set(new_value, nodes);
2024-10-22 15:57:40 -05:00
nodes.remove(old);
}
pub fn remove_ignore_arg(self, nodes: &mut Nodes) {
2024-10-26 05:09:53 -05:00
if nodes[self.0].kind == Kind::Arg {
nodes.unlock(self.0);
2024-10-22 15:57:40 -05:00
} else {
2024-10-26 05:09:53 -05:00
nodes.unlock_remove(self.0);
2024-10-22 15:57:40 -05:00
}
2024-10-24 05:28:18 -05:00
core::mem::forget(self);
2024-10-22 15:57:40 -05:00
}
2024-10-26 05:09:53 -05:00
pub fn soft_remove(self, nodes: &mut Nodes) -> Nid {
let nid = self.0;
nodes.unlock(self.0);
core::mem::forget(self);
nid
}
pub fn is_live(&self) -> bool {
self.0 != Nid::MAX
}
2024-10-22 15:57:40 -05:00
}
2024-10-26 05:09:53 -05:00
impl Default for StrongRef {
fn default() -> Self {
Self::DEFAULT
}
}
impl Drop for StrongRef {
2024-10-22 15:57:40 -05:00
fn drop(&mut self) {
2024-10-26 05:09:53 -05:00
if self.0 != Nid::MAX && !debug::panicking() {
2024-10-22 15:57:40 -05:00
panic!("variable unproperly deinitialized")
}
}
}
2024-10-26 05:09:53 -05:00
}
// makes sure value inside is laways locked for this instance of variable
#[derive(Default, Clone)]
struct Variable {
id: Ident,
ty: ty::Id,
ptr: bool,
value: StrongRef,
}
2024-10-22 15:57:40 -05:00
2024-10-26 05:09:53 -05:00
impl Variable {
fn new(id: Ident, ty: ty::Id, ptr: bool, value: Nid, nodes: &mut Nodes) -> Self {
Self { id, ty, ptr, value: StrongRef::new(value, nodes) }
2024-10-22 15:57:40 -05:00
}
2024-10-26 05:09:53 -05:00
fn value(&self) -> Nid {
self.value.get()
}
2024-10-22 15:57:40 -05:00
2024-10-26 05:09:53 -05:00
fn set_value(&mut self, new_value: Nid, nodes: &mut Nodes) -> Nid {
self.value.set(new_value, nodes)
}
fn dup(&self, nodes: &mut Nodes) -> Self {
Self { id: self.id, ty: self.ty, ptr: self.ptr, value: self.value.dup(nodes) }
}
2024-10-22 15:57:40 -05:00
2024-10-26 05:09:53 -05:00
fn remove(self, nodes: &mut Nodes) {
self.value.remove(nodes);
}
fn set_value_remove(&mut self, new_value: Nid, nodes: &mut Nodes) {
self.value.set_remove(new_value, nodes);
}
fn remove_ignore_arg(self, nodes: &mut Nodes) {
self.value.remove_ignore_arg(nodes);
}
}
#[derive(Default, Clone)]
pub struct Scope {
vars: Vec<Variable>,
loads: Vec<StrongRef>,
store: Variable,
}
impl Scope {
fn iter_mut(&mut self) -> impl Iterator<Item = &mut Variable> {
core::iter::once(&mut self.store).chain(self.vars.iter_mut())
}
fn dup(&self, nodes: &mut Nodes) -> Self {
Self {
vars: self.vars.iter().map(|v| v.dup(nodes)).collect(),
loads: self.loads.iter().map(|l| l.dup(nodes)).collect(),
store: self.store.dup(nodes),
2024-10-22 15:57:40 -05:00
}
2024-10-19 03:17:36 -05:00
}
2024-10-26 05:09:53 -05:00
fn clear(&mut self, nodes: &mut Nodes) {
self.vars.drain(..).for_each(|n| n.remove(nodes));
self.loads.drain(..).for_each(|l| _ = l.remove(nodes));
mem::take(&mut self.store).remove(nodes);
}
2024-10-18 06:11:11 -05:00
}
2024-10-21 11:57:23 -05:00
#[derive(Default, Clone)]
2024-09-02 17:07:20 -05:00
struct ItemCtx {
file: FileId,
ret: Option<ty::Id>,
task_base: usize,
2024-10-23 05:26:07 -05:00
inline_var_base: usize,
inline_depth: u16,
2024-10-26 05:09:53 -05:00
inline_ret: Option<(Value, StrongRef, Scope)>,
2024-09-03 10:51:28 -05:00
nodes: Nodes,
2024-10-26 05:09:53 -05:00
ctrl: StrongRef,
call_count: u16,
2024-09-02 17:07:20 -05:00
loops: Vec<Loop>,
2024-10-18 06:11:11 -05:00
scope: Scope,
2024-09-04 09:54:34 -05:00
ret_relocs: Vec<Reloc>,
relocs: Vec<TypedReloc>,
2024-09-15 13:14:56 -05:00
jump_relocs: Vec<(Nid, Reloc)>,
2024-09-04 09:54:34 -05:00
code: Vec<u8>,
}
impl ItemCtx {
2024-10-20 03:37:48 -05:00
fn init(&mut self, file: FileId, ret: Option<ty::Id>, task_base: usize) {
2024-10-19 12:37:02 -05:00
debug_assert_eq!(self.loops.len(), 0);
debug_assert_eq!(self.scope.vars.len(), 0);
debug_assert_eq!(self.ret_relocs.len(), 0);
debug_assert_eq!(self.relocs.len(), 0);
debug_assert_eq!(self.jump_relocs.len(), 0);
debug_assert_eq!(self.code.len(), 0);
2024-10-24 02:43:07 -05:00
self.call_count = 0;
2024-10-19 12:37:02 -05:00
self.file = file;
self.ret = ret;
self.task_base = task_base;
self.nodes.clear();
self.scope.vars.clear();
let start = self.nodes.new_node(ty::Id::VOID, Kind::Start, []);
debug_assert_eq!(start, VOID);
let end = self.nodes.new_node(ty::Id::NEVER, Kind::End, []);
debug_assert_eq!(end, NEVER);
self.nodes.lock(end);
2024-10-26 05:09:53 -05:00
self.ctrl =
StrongRef::new(self.nodes.new_node(ty::Id::VOID, Kind::Entry, [VOID]), &mut self.nodes);
debug_assert_eq!(self.ctrl.get(), ENTRY);
2024-10-19 12:37:02 -05:00
let mem = self.nodes.new_node(ty::Id::VOID, Kind::Mem, [VOID]);
debug_assert_eq!(mem, MEM);
self.nodes.lock(mem);
2024-10-27 05:32:34 -05:00
let loops = self.nodes.new_node(ty::Id::VOID, Kind::Loops, [VOID]);
debug_assert_eq!(loops, LOOPS);
self.nodes.lock(loops);
2024-10-27 07:57:00 -05:00
self.scope.store =
Variable::new(Ident::default(), ty::Id::VOID, false, MEM, &mut self.nodes);
2024-10-19 12:37:02 -05:00
}
2024-10-27 05:32:34 -05:00
fn finalize(&mut self, stack: &mut Vec<Nid>) {
2024-10-22 15:57:40 -05:00
self.scope.clear(&mut self.nodes);
2024-10-26 05:09:53 -05:00
mem::take(&mut self.ctrl).soft_remove(&mut self.nodes);
2024-10-24 03:21:10 -05:00
self.nodes.eliminate_stack_temporaries();
2024-10-27 05:32:34 -05:00
self.nodes.iter_peeps(1000, stack);
self.nodes.unlock(MEM);
self.nodes.unlock(NEVER);
self.nodes.unlock(LOOPS);
2024-10-19 12:37:02 -05:00
}
2024-09-02 17:07:20 -05:00
}
fn write_reloc(doce: &mut [u8], offset: usize, value: i64, size: u16) {
let value = value.to_ne_bytes();
doce[offset..offset + size as usize].copy_from_slice(&value[..size as usize]);
}
2024-09-04 09:54:34 -05:00
#[derive(Default, Debug)]
struct Ctx {
ty: Option<ty::Id>,
2024-09-02 17:07:20 -05:00
}
2024-09-04 09:54:34 -05:00
impl Ctx {
pub fn with_ty(self, ty: ty::Id) -> Self {
Self { ty: Some(ty) }
2024-09-02 17:07:20 -05:00
}
2024-09-04 09:54:34 -05:00
}
2024-09-02 17:07:20 -05:00
#[derive(Default)]
struct Pool {
cis: Vec<ItemCtx>,
2024-10-19 12:53:43 -05:00
used_cis: usize,
ralloc: Regalloc,
2024-10-27 05:32:34 -05:00
nid_stack: Vec<Nid>,
2024-10-19 12:53:43 -05:00
}
impl Pool {
pub fn push_ci(
&mut self,
file: FileId,
ret: Option<ty::Id>,
task_base: usize,
2024-10-20 03:37:48 -05:00
target: &mut ItemCtx,
2024-10-19 12:53:43 -05:00
) {
if let Some(slot) = self.cis.get_mut(self.used_cis) {
2024-10-26 05:09:53 -05:00
mem::swap(slot, target);
2024-10-19 12:53:43 -05:00
} else {
self.cis.push(ItemCtx::default());
2024-10-26 05:09:53 -05:00
mem::swap(self.cis.last_mut().unwrap(), target);
2024-10-19 12:53:43 -05:00
}
2024-10-20 03:37:48 -05:00
target.init(file, ret, task_base);
2024-10-19 12:53:43 -05:00
self.used_cis += 1;
}
pub fn pop_ci(&mut self, target: &mut ItemCtx) {
self.used_cis -= 1;
2024-10-26 05:09:53 -05:00
mem::swap(&mut self.cis[self.used_cis], target);
2024-10-19 12:53:43 -05:00
}
2024-10-21 11:57:23 -05:00
fn save_ci(&mut self, ci: &ItemCtx) {
if let Some(slot) = self.cis.get_mut(self.used_cis) {
slot.clone_from(ci);
} else {
self.cis.push(ci.clone());
}
self.used_cis += 1;
}
fn restore_ci(&mut self, dst: &mut ItemCtx) {
self.used_cis -= 1;
2024-10-22 15:57:40 -05:00
dst.scope.clear(&mut dst.nodes);
2024-10-26 05:09:53 -05:00
mem::take(&mut dst.ctrl).remove(&mut dst.nodes);
*dst = mem::take(&mut self.cis[self.used_cis]);
2024-10-21 11:57:23 -05:00
}
fn clear(&mut self) {
debug_assert_eq!(self.used_cis, 0);
}
2024-09-02 17:07:20 -05:00
}
2024-09-27 09:53:28 -05:00
struct Regalloc {
env: regalloc2::MachineEnv,
ctx: regalloc2::Ctx,
}
impl Default for Regalloc {
fn default() -> Self {
Self {
env: regalloc2::MachineEnv {
preferred_regs_by_class: [
(1..13).map(|i| regalloc2::PReg::new(i, regalloc2::RegClass::Int)).collect(),
vec![],
vec![],
],
non_preferred_regs_by_class: [
(13..64).map(|i| regalloc2::PReg::new(i, regalloc2::RegClass::Int)).collect(),
vec![],
vec![],
],
scratch_by_class: Default::default(),
fixed_stack_slots: Default::default(),
},
ctx: Default::default(),
}
}
}
2024-10-19 12:37:02 -05:00
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
2024-10-17 12:32:10 -05:00
struct Value {
ty: ty::Id,
var: bool,
ptr: bool,
id: Nid,
}
impl Value {
const NEVER: Option<Value> =
2024-10-18 06:11:11 -05:00
Some(Self { ty: ty::Id::NEVER, var: false, ptr: false, id: NEVER });
const VOID: Value = Self { ty: ty::Id::VOID, var: false, ptr: false, id: VOID };
2024-10-17 12:32:10 -05:00
pub fn new(id: Nid) -> Self {
Self { id, ..Default::default() }
}
pub fn var(id: usize) -> Self {
2024-10-17 15:29:09 -05:00
Self { id: u16::MAX - (id as Nid), var: true, ..Default::default() }
}
pub fn ptr(id: Nid) -> Self {
Self { id, ptr: true, ..Default::default() }
2024-10-17 12:32:10 -05:00
}
#[inline(always)]
pub fn ty(self, ty: impl Into<ty::Id>) -> Self {
Self { ty: ty.into(), ..self }
}
}
2024-09-02 17:07:20 -05:00
#[derive(Default)]
pub struct CodegenCtx {
pub parser: parser::Ctx,
2024-09-02 17:07:20 -05:00
tys: Types,
pool: Pool,
2024-10-20 03:37:48 -05:00
ct: Comptime,
2024-09-02 17:07:20 -05:00
}
impl CodegenCtx {
pub fn clear(&mut self) {
self.parser.clear();
self.tys.clear();
self.pool.clear();
self.ct.clear();
}
}
2024-10-25 16:05:43 -05:00
pub struct Errors<'a>(&'a RefCell<String>);
impl Deref for Errors<'_> {
type Target = RefCell<String>;
fn deref(&self) -> &Self::Target {
self.0
}
}
impl Drop for Errors<'_> {
fn drop(&mut self) {
if debug::panicking() && !self.0.borrow().is_empty() {
log::error!("{}", self.0.borrow());
}
}
}
pub struct Codegen<'a> {
pub files: &'a [parser::Ast],
2024-10-25 16:05:43 -05:00
pub errors: Errors<'a>,
tys: &'a mut Types,
ci: ItemCtx,
pool: &'a mut Pool,
ct: &'a mut Comptime,
}
impl<'a> Codegen<'a> {
pub fn new(files: &'a [parser::Ast], ctx: &'a mut CodegenCtx) -> Self {
Self {
files,
2024-10-25 16:05:43 -05:00
errors: Errors(&ctx.parser.errors),
tys: &mut ctx.tys,
ci: Default::default(),
pool: &mut ctx.pool,
ct: &mut ctx.ct,
2024-10-20 09:43:25 -05:00
}
}
fn emit_and_eval(&mut self, file: FileId, ret: ty::Id, ret_loc: &mut [u8]) -> u64 {
2024-10-27 07:57:00 -05:00
let mut rets =
self.ci.nodes[NEVER].inputs.iter().filter(|&&i| self.ci.nodes[i].kind == Kind::Return);
if let Some(&ret) = rets.next()
&& rets.next().is_none()
&& let Kind::CInt { value } = self.ci.nodes[self.ci.nodes[ret].inputs[1]].kind
{
if let len @ 1..=8 = ret_loc.len() {
ret_loc.copy_from_slice(&value.to_ne_bytes()[..len])
}
return value as _;
}
if !self.complete_call_graph() {
return 1;
}
2024-10-27 08:29:14 -05:00
self.ci.emit_ct_body(
2024-10-26 03:25:42 -05:00
self.tys,
self.files,
Sig { args: Tuple::empty(), ret },
&mut self.pool.ralloc,
);
let func = Func {
file,
2024-10-26 05:09:53 -05:00
relocs: mem::take(&mut self.ci.relocs),
code: mem::take(&mut self.ci.code),
..Default::default()
};
// TODO: return them back
let fuc = self.tys.ins.funcs.len() as ty::Func;
self.tys.ins.funcs.push(func);
self.tys.dump_reachable(fuc, &mut self.ct.code);
self.dump_ct_asm();
self.ct.run(ret_loc, self.tys.ins.funcs[fuc as usize].offset)
}
fn dump_ct_asm(&self) {
#[cfg(debug_assertions)]
{
let mut vc = String::new();
if let Err(e) = self.tys.disasm(&self.ct.code, self.files, &mut vc, |_| {}) {
panic!("{e} {}", vc);
} else {
log::trace!("{}", vc);
}
}
}
2024-10-21 11:57:23 -05:00
pub fn push_embeds(&mut self, embeds: Vec<Vec<u8>>) {
self.tys.ins.globals = embeds
.into_iter()
.map(|data| Global {
ty: self.tys.make_array(ty::Id::U8, data.len() as _),
data,
..Default::default()
})
.collect();
}
2024-10-24 02:43:07 -05:00
fn store_mem(&mut self, region: Nid, ty: ty::Id, value: Nid) -> Nid {
2024-10-19 03:17:36 -05:00
if value == NEVER {
return NEVER;
}
2024-10-22 05:40:41 -05:00
debug_assert!(
self.ci.nodes[region].kind != Kind::Load || self.ci.nodes[region].ty.is_pointer()
);
debug_assert!(self.ci.nodes[region].kind != Kind::Stre);
2024-10-19 03:17:36 -05:00
self.ci.nodes.load_loop_store(&mut self.ci.scope.store, &mut self.ci.loops);
let mut vc = Vc::from([VOID, value, region, self.ci.scope.store.value()]);
2024-10-18 06:11:11 -05:00
for load in self.ci.scope.loads.drain(..) {
2024-10-26 05:09:53 -05:00
if load.get() == value {
load.soft_remove(&mut self.ci.nodes);
2024-10-17 15:29:09 -05:00
continue;
}
2024-10-26 05:09:53 -05:00
if let Some(load) = load.remove(&mut self.ci.nodes) {
2024-10-17 15:29:09 -05:00
vc.push(load);
2024-09-28 08:13:32 -05:00
}
2024-09-27 09:53:28 -05:00
}
2024-10-24 02:43:07 -05:00
let store = self.ci.nodes.new_node_nop(ty, Kind::Stre, vc);
2024-10-22 15:57:40 -05:00
self.ci.scope.store.set_value(store, &mut self.ci.nodes);
2024-10-26 03:45:50 -05:00
let opted = self.ci.nodes.late_peephole(store).unwrap_or(store);
2024-10-22 15:57:40 -05:00
self.ci.scope.store.set_value_remove(opted, &mut self.ci.nodes);
opted
2024-09-27 09:53:28 -05:00
}
2024-10-18 02:52:50 -05:00
fn load_mem(&mut self, region: Nid, ty: ty::Id) -> Nid {
2024-10-19 03:17:36 -05:00
debug_assert_ne!(region, VOID);
2024-10-23 05:26:07 -05:00
debug_assert_ne!({ self.ci.nodes[region].ty }, ty::Id::VOID, "{:?}", {
self.ci.nodes[region].lock_rc = Nid::MAX;
self.ci.nodes.graphviz_in_browser(self.tys, self.files);
2024-10-23 05:26:07 -05:00
});
2024-10-22 05:40:41 -05:00
debug_assert!(
2024-10-23 05:26:07 -05:00
self.ci.nodes[region].kind != Kind::Load || self.ci.nodes[region].ty.is_pointer(),
"{:?} {} {}",
self.ci.nodes.graphviz_in_browser(self.tys, self.files),
2024-10-26 08:18:00 -05:00
self.file().path,
2024-10-23 05:26:07 -05:00
self.ty_display(self.ci.nodes[region].ty)
2024-10-22 05:40:41 -05:00
);
debug_assert!(self.ci.nodes[region].kind != Kind::Stre);
2024-10-19 03:17:36 -05:00
self.ci.nodes.load_loop_store(&mut self.ci.scope.store, &mut self.ci.loops);
let vc = [VOID, region, self.ci.scope.store.value()];
2024-10-18 02:52:50 -05:00
let load = self.ci.nodes.new_node(ty, Kind::Load, vc);
2024-10-26 05:09:53 -05:00
self.ci.scope.loads.push(StrongRef::new(load, &mut self.ci.nodes));
2024-10-17 15:29:09 -05:00
load
2024-09-30 12:09:17 -05:00
}
2024-10-22 05:50:54 -05:00
pub fn generate(&mut self, entry: FileId) {
self.find_type(0, entry, entry, Err("main"), self.files);
if self.tys.ins.funcs.is_empty() {
return;
}
2024-09-03 10:51:28 -05:00
self.make_func_reachable(0);
2024-09-19 06:40:03 -05:00
self.complete_call_graph();
2024-09-02 17:07:20 -05:00
}
2024-10-27 07:57:00 -05:00
pub fn assemble_comptime(&mut self) -> Comptime {
self.ct.code.clear();
self.tys.reassemble(&mut self.ct.code);
self.ct.reset();
core::mem::take(self.ct)
}
2024-10-22 05:50:54 -05:00
pub fn assemble(&mut self, buf: &mut Vec<u8>) {
self.tys.reassemble(buf);
}
pub fn disasm(&mut self, output: &mut String) -> Result<(), DisasmError> {
let mut bin = Vec::new();
self.assemble(&mut bin);
self.tys.disasm(&bin, self.files, output, |_| {})
}
2024-09-03 10:51:28 -05:00
fn make_func_reachable(&mut self, func: ty::Func) {
2024-10-01 15:53:03 -05:00
let fuc = &mut self.tys.ins.funcs[func as usize];
2024-09-03 10:51:28 -05:00
if fuc.offset == u32::MAX {
fuc.offset = task::id(self.tys.tasks.len() as _);
self.tys.tasks.push(Some(FTask { file: fuc.file, id: func }));
2024-09-03 10:51:28 -05:00
}
}
2024-10-17 12:32:10 -05:00
fn raw_expr(&mut self, expr: &Expr) -> Option<Value> {
2024-10-04 14:44:29 -05:00
self.raw_expr_ctx(expr, Ctx::default())
2024-09-02 17:07:20 -05:00
}
2024-10-17 12:32:10 -05:00
fn raw_expr_ctx(&mut self, expr: &Expr, ctx: Ctx) -> Option<Value> {
// ordered by complexity of the expression
2024-09-03 10:51:28 -05:00
match *expr {
Expr::Idk { pos } => {
let Some(ty) = ctx.ty else {
self.report(
pos,
"resulting value cannot be inferred from context, \
consider using `@as(<ty>, idk)` to hint the type",
);
return Value::NEVER;
};
if matches!(ty.expand(), ty::Kind::Struct(_) | ty::Kind::Slice(_)) {
let stck = self.ci.nodes.new_node(ty, Kind::Stck, [VOID, MEM]);
Some(Value::ptr(stck).ty(ty))
} else {
self.report(
pos,
fa!(
"type '{}' cannot be uninitialized, use a zero \
value instead ('@bitcast(0)' in case of pointers)",
self.ty_display(ty)
),
);
Value::NEVER
}
}
Expr::Bool { value, .. } => Some(self.ci.nodes.new_node_lit(
ty::Id::BOOL,
Kind::CInt { value: value as i64 },
[VOID],
)),
2024-10-20 05:22:28 -05:00
Expr::Number { value, .. } => Some(self.ci.nodes.new_node_lit(
2024-10-25 07:51:33 -05:00
ctx.ty.filter(|ty| ty.is_integer()).unwrap_or(ty::Id::DEFAULT_INT),
2024-10-20 05:22:28 -05:00
Kind::CInt { value },
[VOID],
)),
2024-10-19 12:37:02 -05:00
Expr::Ident { id, .. }
if let Some(index) = self.ci.scope.vars.iter().rposition(|v| v.id == id) =>
{
let var = &mut self.ci.scope.vars[index];
2024-10-23 05:26:07 -05:00
self.ci.nodes.load_loop_var(index + 1, var, &mut self.ci.loops);
2024-09-05 18:17:54 -05:00
2024-10-19 12:37:02 -05:00
Some(Value::var(index).ty(var.ty))
}
Expr::Ident { id, pos, .. } => {
let decl = self.find_type(pos, self.ci.file, self.ci.file, Ok(id), self.files);
match decl.expand() {
ty::Kind::Builtin(ty::NEVER) => Value::NEVER,
2024-10-20 05:22:28 -05:00
ty::Kind::Global(global) => {
let gl = &self.tys.ins.globals[global as usize];
let value = self.ci.nodes.new_node(gl.ty, Kind::Global { global }, [VOID]);
Some(Value::ptr(value).ty(gl.ty))
2024-10-20 03:37:48 -05:00
}
2024-10-23 05:26:07 -05:00
_ => Some(Value::new(Nid::MAX).ty(decl)),
2024-10-20 03:37:48 -05:00
}
2024-09-05 18:17:54 -05:00
}
2024-10-20 05:22:28 -05:00
Expr::Comment { .. } => Some(Value::VOID),
Expr::String { pos, literal } => {
let literal = &literal[1..literal.len() - 1];
let report = |bytes: &core::str::Bytes, message: &str| {
self.report(pos + (literal.len() - bytes.len()) as u32 - 1, message)
};
let mut data = Vec::<u8>::with_capacity(literal.len());
crate::endoce_string(literal, &mut data, report).unwrap();
let ty = self.tys.make_ptr(ty::Id::U8);
let global = match self.tys.strings.entry(&data, &self.tys.ins.globals) {
(hash_map::RawEntryMut::Occupied(occupied_entry), _) => {
occupied_entry.get_key_value().0.value.0
}
(hash_map::RawEntryMut::Vacant(vacant_entry), hash) => {
2024-10-24 02:43:07 -05:00
let global = self.tys.ins.globals.len() as ty::Global;
self.tys.ins.globals.push(Global { data, ty, ..Default::default() });
vacant_entry
.insert(crate::ctx_map::Key { value: StringRef(global), hash }, ())
.0
.value
.0
2024-10-24 02:43:07 -05:00
}
};
2024-10-20 05:22:28 -05:00
let global = self.ci.nodes.new_node(ty, Kind::Global { global }, [VOID]);
Some(Value::new(global).ty(ty))
}
Expr::Return { pos, val } => {
let mut value = if let Some(val) = val {
self.expr_ctx(val, Ctx { ty: self.ci.ret })?
} else {
2024-10-17 12:32:10 -05:00
Value { ty: ty::Id::VOID, ..Default::default() }
};
let expected = *self.ci.ret.get_or_insert(value.ty);
self.assert_ty(pos, &mut value, expected, "return value");
if self.ci.inline_depth == 0 {
2024-10-26 05:09:53 -05:00
debug_assert_ne!(self.ci.ctrl.get(), VOID);
let mut inps = Vc::from([self.ci.ctrl.get(), value.id]);
self.ci.nodes.load_loop_store(&mut self.ci.scope.store, &mut self.ci.loops);
inps.push(self.ci.scope.store.value());
2024-10-26 05:09:53 -05:00
self.ci.ctrl.set(
self.ci.nodes.new_node(ty::Id::VOID, Kind::Return, inps),
&mut self.ci.nodes,
);
2024-10-26 05:09:53 -05:00
self.ci.nodes[NEVER].inputs.push(self.ci.ctrl.get());
self.ci.nodes[self.ci.ctrl.get()].outputs.push(NEVER);
2024-10-23 05:26:07 -05:00
} else if let Some((pv, ctrl, scope)) = &mut self.ci.inline_ret {
2024-10-26 05:09:53 -05:00
ctrl.set(
self.ci
.nodes
.new_node(ty::Id::VOID, Kind::Region, [self.ci.ctrl.get(), ctrl.get()]),
2024-10-23 05:26:07 -05:00
&mut self.ci.nodes,
);
2024-10-26 05:09:53 -05:00
self.ci.nodes.merge_scopes(&mut self.ci.loops, ctrl, scope, &mut self.ci.scope);
self.ci.nodes.unlock(pv.id);
2024-10-26 05:09:53 -05:00
pv.id =
self.ci.nodes.new_node(value.ty, Kind::Phi, [ctrl.get(), value.id, pv.id]);
self.ci.nodes.lock(pv.id);
2024-10-26 05:09:53 -05:00
self.ci.ctrl.set(NEVER, &mut self.ci.nodes);
} else {
self.ci.nodes.lock(value.id);
2024-10-23 05:26:07 -05:00
let mut scope = self.ci.scope.dup(&mut self.ci.nodes);
scope
.vars
.drain(self.ci.inline_var_base..)
.for_each(|v| v.remove(&mut self.ci.nodes));
2024-10-26 05:09:53 -05:00
let repl = StrongRef::new(NEVER, &mut self.ci.nodes);
self.ci.inline_ret =
Some((value, mem::replace(&mut self.ci.ctrl, repl), scope));
}
None
}
2024-10-17 15:29:09 -05:00
Expr::Field { target, name, pos } => {
let mut vtarget = self.raw_expr(target)?;
self.strip_var(&mut vtarget);
let tty = vtarget.ty;
2024-10-17 12:32:10 -05:00
2024-10-23 05:26:07 -05:00
if let ty::Kind::Module(m) = tty.expand() {
return match self
.find_type(pos, self.ci.file, m, Err(name), self.files)
.expand()
{
2024-10-23 05:26:07 -05:00
ty::Kind::Builtin(ty::NEVER) => Value::NEVER,
ty::Kind::Global(global) => {
let gl = &self.tys.ins.globals[global as usize];
let value =
self.ci.nodes.new_node(gl.ty, Kind::Global { global }, [VOID]);
Some(Value::ptr(value).ty(gl.ty))
}
v => Some(Value::new(Nid::MAX).ty(v.compress())),
};
}
2024-10-17 15:29:09 -05:00
let ty::Kind::Struct(s) = self.tys.base_of(tty).unwrap_or(tty).expand() else {
self.report(
pos,
fa!(
"the '{}' is not a struct, or pointer to one, \
but accessing fields is only possible on structs",
self.ty_display(tty)
),
);
return Value::NEVER;
};
let Some((offset, ty)) = OffsetIter::offset_of(self.tys, s, name) else {
2024-10-17 15:29:09 -05:00
let field_list = self
.tys
.struct_fields(s)
.iter()
.map(|f| self.tys.names.ident_str(f.name))
.intersperse("', '")
.collect::<String>();
self.report(
pos,
fa!(
"the '{}' does not have this field, \
but it does have '{field_list}'",
self.ty_display(tty)
),
);
return Value::NEVER;
};
Some(Value::ptr(self.offset(vtarget.id, offset)).ty(ty))
2024-10-17 15:29:09 -05:00
}
Expr::UnOp { op: TokenKind::Band, val, .. } => {
let ctx = Ctx { ty: ctx.ty.and_then(|ty| self.tys.base_of(ty)) };
2024-10-04 14:44:29 -05:00
let mut val = self.raw_expr_ctx(val, ctx)?;
2024-10-17 12:32:10 -05:00
self.strip_var(&mut val);
if val.ptr {
val.ptr = false;
val.ty = self.tys.make_ptr(val.ty);
return Some(val);
}
2024-10-17 12:32:10 -05:00
let stack = self.ci.nodes.new_node_nop(val.ty, Kind::Stck, [VOID, MEM]);
2024-10-24 02:43:07 -05:00
self.store_mem(stack, val.ty, val.id);
2024-10-17 12:32:10 -05:00
Some(Value::new(stack).ty(self.tys.make_ptr(val.ty)))
}
Expr::UnOp { op: TokenKind::Mul, val, pos } => {
let ctx = Ctx { ty: ctx.ty.map(|ty| self.tys.make_ptr(ty)) };
2024-10-17 12:32:10 -05:00
let mut val = self.expr_ctx(val, ctx)?;
let Some(base) = self.tys.base_of(val.ty) else {
self.report(
pos,
2024-10-17 12:32:10 -05:00
fa!("the '{}' can not be dereferneced", self.ty_display(val.ty)),
);
2024-10-17 12:32:10 -05:00
return Value::NEVER;
};
2024-10-17 12:32:10 -05:00
val.ptr = true;
val.ty = base;
Some(val)
}
Expr::UnOp { pos, op: op @ TokenKind::Sub, val } => {
let val =
self.expr_ctx(val, Ctx::default().with_ty(ctx.ty.unwrap_or(ty::Id::INT)))?;
2024-10-17 12:32:10 -05:00
if !val.ty.is_integer() {
self.report(pos, fa!("cant negate '{}'", self.ty_display(val.ty)));
}
2024-10-17 12:32:10 -05:00
Some(self.ci.nodes.new_node_lit(val.ty, Kind::UnOp { op }, [VOID, val.id]))
}
Expr::BinOp { left, op: TokenKind::Decl, right, .. } => {
let mut right = self.expr(right)?;
if right.ty.loc(self.tys) == Loc::Stack {
let stck = self.ci.nodes.new_node_nop(right.ty, Kind::Stck, [VOID, MEM]);
2024-10-24 02:43:07 -05:00
self.store_mem(stck, right.ty, right.id);
right.id = stck;
right.ptr = true;
}
self.assign_pattern(left, right);
2024-10-17 12:32:10 -05:00
Some(Value::VOID)
2024-09-04 16:46:32 -05:00
}
Expr::BinOp { left, pos, op: TokenKind::Assign, right } => {
2024-10-18 06:11:11 -05:00
let dest = self.raw_expr(left)?;
let mut value = self.expr_ctx(right, Ctx::default().with_ty(dest.ty))?;
2024-09-04 16:46:32 -05:00
self.assert_ty(pos, &mut value, dest.ty, "assignment source");
2024-09-04 16:46:32 -05:00
2024-10-17 12:32:10 -05:00
if dest.var {
2024-10-18 06:11:11 -05:00
let var = &mut self.ci.scope.vars[(u16::MAX - dest.id) as usize];
2024-10-22 05:40:41 -05:00
if var.ptr {
2024-10-22 15:57:40 -05:00
let val = var.value();
2024-10-24 02:43:07 -05:00
let ty = var.ty;
self.store_mem(val, ty, value.id);
2024-10-22 05:40:41 -05:00
} else {
2024-10-22 15:57:40 -05:00
var.set_value_remove(value.id, &mut self.ci.nodes);
2024-10-22 05:40:41 -05:00
}
2024-10-17 12:32:10 -05:00
} else if dest.ptr {
2024-10-24 02:43:07 -05:00
self.store_mem(dest.id, dest.ty, value.id);
2024-10-17 12:32:10 -05:00
} else {
self.report(pos, "cannot assign to this expression");
2024-10-17 12:32:10 -05:00
}
Some(Value::VOID)
}
Expr::BinOp { left, pos, op, right }
if !matches!(op, TokenKind::Assign | TokenKind::Decl) =>
{
2024-10-22 05:40:41 -05:00
let mut lhs = self.raw_expr_ctx(left, ctx)?;
self.strip_var(&mut lhs);
match lhs.ty.expand() {
_ if lhs.ty.is_pointer() || lhs.ty.is_integer() || lhs.ty == ty::Id::BOOL => {
self.strip_ptr(&mut lhs);
2024-10-22 05:40:41 -05:00
self.ci.nodes.lock(lhs.id);
let rhs = self.expr_ctx(right, Ctx::default().with_ty(lhs.ty));
self.ci.nodes.unlock(lhs.id);
let mut rhs = rhs?;
self.strip_var(&mut rhs);
let ty = self.binop_ty(pos, &mut lhs, &mut rhs, op);
2024-10-22 05:40:41 -05:00
let inps = [VOID, lhs.id, rhs.id];
2024-10-27 07:57:00 -05:00
Some(self.ci.nodes.new_node_lit(ty.bin_ret(op), Kind::BinOp { op }, inps))
2024-10-22 05:40:41 -05:00
}
ty::Kind::Struct(s) if op.is_homogenous() => {
self.ci.nodes.lock(lhs.id);
let rhs = self.raw_expr_ctx(right, Ctx::default().with_ty(lhs.ty));
self.ci.nodes.unlock(lhs.id);
let mut rhs = rhs?;
self.strip_var(&mut rhs);
self.assert_ty(pos, &mut rhs, lhs.ty, "struct operand");
2024-10-22 05:40:41 -05:00
let dst = self.ci.nodes.new_node(lhs.ty, Kind::Stck, [VOID, MEM]);
self.struct_op(left.pos(), op, s, dst, lhs.id, rhs.id);
Some(Value::ptr(dst).ty(lhs.ty))
}
_ => {
self.report(
pos,
fa!("'{} {op} _' is not supported", self.ty_display(lhs.ty)),
2024-10-22 05:40:41 -05:00
);
Value::NEVER
}
}
2024-09-03 10:51:28 -05:00
}
2024-10-19 12:37:02 -05:00
Expr::Index { base, index } => {
let mut bs = self.raw_expr(base)?;
self.strip_var(&mut bs);
if let Some(base) = self.tys.base_of(bs.ty) {
bs.ptr = true;
bs.ty = base;
}
let ty::Kind::Slice(s) = bs.ty.expand() else {
self.report(
base.pos(),
fa!(
"cant index into '{}' which is not array nor slice",
self.ty_display(bs.ty)
),
);
return Value::NEVER;
};
let elem = self.tys.ins.slices[s as usize].elem;
let mut idx = self.expr_ctx(index, Ctx::default().with_ty(ty::Id::DEFAULT_INT))?;
self.assert_ty(index.pos(), &mut idx, ty::Id::DEFAULT_INT, "subscript");
2024-10-19 12:37:02 -05:00
let value = self.tys.size_of(elem) as i64;
let size = self.ci.nodes.new_node_nop(ty::Id::INT, Kind::CInt { value }, [VOID]);
let inps = [VOID, idx.id, size];
let offset =
self.ci.nodes.new_node(ty::Id::INT, Kind::BinOp { op: TokenKind::Mul }, inps);
let inps = [VOID, bs.id, offset];
let ptr =
self.ci.nodes.new_node(ty::Id::INT, Kind::BinOp { op: TokenKind::Add }, inps);
2024-10-19 12:37:02 -05:00
Some(Value::ptr(ptr).ty(elem))
}
2024-10-21 11:57:23 -05:00
Expr::Embed { id, .. } => {
let glob = &self.tys.ins.globals[id as usize];
2024-10-21 12:57:55 -05:00
let g = self.ci.nodes.new_node(glob.ty, Kind::Global { global: id }, [VOID]);
Some(Value::ptr(g).ty(glob.ty))
2024-10-21 11:57:23 -05:00
}
Expr::Directive { name: "sizeof", args: [ty], .. } => {
let ty = self.ty(ty);
2024-10-17 12:32:10 -05:00
Some(self.ci.nodes.new_node_lit(
2024-10-25 07:51:33 -05:00
ctx.ty.filter(|ty| ty.is_integer()).unwrap_or(ty::Id::DEFAULT_INT),
Kind::CInt { value: self.tys.size_of(ty) as _ },
[VOID],
))
2024-09-27 09:53:28 -05:00
}
2024-10-21 11:57:23 -05:00
Expr::Directive { name: "alignof", args: [ty], .. } => {
let ty = self.ty(ty);
Some(self.ci.nodes.new_node_lit(
2024-10-25 07:51:33 -05:00
ctx.ty.filter(|ty| ty.is_integer()).unwrap_or(ty::Id::DEFAULT_INT),
2024-10-21 11:57:23 -05:00
Kind::CInt { value: self.tys.align_of(ty) as _ },
[VOID],
))
}
Expr::Directive { name: "bitcast", args: [val], pos } => {
let mut val = self.raw_expr(val)?;
self.strip_var(&mut val);
let Some(ty) = ctx.ty else {
self.report(
pos,
"resulting type cannot be inferred from context, \
consider using `@as(<ty>, @bitcast(<expr>))` to hint the type",
);
return Value::NEVER;
};
let (got, expected) = (self.tys.size_of(val.ty), self.tys.size_of(ty));
if got != expected {
self.report(
pos,
fa!(
"cast from '{}' to '{}' is not supported, \
sizes dont match ({got} != {expected})",
self.ty_display(val.ty),
self.ty_display(ty)
),
);
}
match ty.loc(self.tys) {
2024-10-26 05:09:53 -05:00
Loc::Reg if mem::take(&mut val.ptr) => val.id = self.load_mem(val.id, ty),
2024-10-24 06:58:58 -05:00
Loc::Stack if !val.ptr => {
let stack = self.ci.nodes.new_node_nop(ty, Kind::Stck, [VOID, MEM]);
self.store_mem(stack, val.ty, val.id);
val.id = stack;
val.ptr = true;
}
_ => {}
}
2024-10-21 11:57:23 -05:00
val.ty = ty;
Some(val)
}
Expr::Directive { name: "intcast", args: [expr], pos } => {
2024-10-25 07:51:33 -05:00
let mut val = self.expr(expr)?;
2024-10-19 12:37:02 -05:00
if !val.ty.is_integer() {
self.report(
expr.pos(),
fa!(
"only integers can be truncated ('{}' is not an integer)",
self.ty_display(val.ty)
),
);
return Value::NEVER;
}
let Some(ty) = ctx.ty else {
self.report(
pos,
"resulting integer cannot be inferred from context, \
2024-10-21 11:57:23 -05:00
consider using `@as(<int_ty>, @intcast(<expr>))` to hint the type",
2024-10-19 12:37:02 -05:00
);
return Value::NEVER;
};
2024-10-25 07:51:33 -05:00
if !ty.is_integer() {
self.report(
expr.pos(),
fa!(
"intcast is inferred to output '{}', which is not an integer",
2024-10-25 09:08:20 -05:00
self.ty_display(ty)
2024-10-25 07:51:33 -05:00
),
);
}
2024-10-19 12:37:02 -05:00
if self.tys.size_of(val.ty) <= self.tys.size_of(ty) {
2024-10-25 07:51:33 -05:00
val.ty = ty;
2024-10-24 02:43:07 -05:00
return Some(val);
2024-10-19 12:37:02 -05:00
}
2024-10-24 09:26:28 -05:00
let value = (1i64 << (self.tys.size_of(ty) * 8)) - 1;
2024-10-19 12:37:02 -05:00
let mask = self.ci.nodes.new_node_nop(val.ty, Kind::CInt { value }, [VOID]);
let inps = [VOID, val.id, mask];
Some(self.ci.nodes.new_node_lit(ty, Kind::BinOp { op: TokenKind::Band }, inps))
}
2024-10-19 03:17:36 -05:00
Expr::Directive { name: "as", args: [ty, expr], .. } => {
2024-10-21 12:57:55 -05:00
let ty = self.ty(ty);
let ctx = Ctx::default().with_ty(ty);
2024-10-24 07:08:17 -05:00
let mut val = self.raw_expr_ctx(expr, ctx)?;
self.strip_var(&mut val);
2024-10-24 02:43:07 -05:00
self.assert_ty(expr.pos(), &mut val, ty, "hinted expr");
2024-10-21 12:57:55 -05:00
Some(val)
2024-10-19 03:17:36 -05:00
}
2024-10-21 11:57:23 -05:00
Expr::Directive { pos, name: "eca", args } => {
let Some(ty) = ctx.ty else {
self.report(
pos,
"return type cannot be inferred from context, \
consider using `@as(<return_ty>, @eca(<expr>...))` to hint the type",
);
return Value::NEVER;
};
2024-10-23 05:26:07 -05:00
let mut inps = Vc::from([NEVER]);
2024-10-24 02:43:07 -05:00
let arg_base = self.tys.tmp.args.len();
2024-10-25 09:33:56 -05:00
let mut has_ptr_arg = false;
2024-10-21 11:57:23 -05:00
for arg in args {
let value = self.expr(arg)?;
has_ptr_arg |= value.ty.has_pointers(self.tys);
2024-10-24 02:43:07 -05:00
self.tys.tmp.args.push(value.ty);
2024-10-21 11:57:23 -05:00
debug_assert_ne!(self.ci.nodes[value.id].kind, Kind::Stre);
self.ci.nodes.lock(value.id);
inps.push(value.id);
}
2024-10-24 02:43:07 -05:00
let args = self.tys.pack_args(arg_base).expect("TODO");
2024-10-21 11:57:23 -05:00
for &n in inps.iter().skip(1) {
self.ci.nodes.unlock(n);
}
2024-10-25 09:33:56 -05:00
if has_ptr_arg {
inps.push(self.ci.scope.store.value());
2024-10-26 05:09:53 -05:00
self.ci.scope.loads.retain_mut(|load| {
if inps.contains(&load.get()) {
2024-10-25 09:33:56 -05:00
return true;
}
2024-10-21 11:57:23 -05:00
2024-10-26 05:09:53 -05:00
if let Some(load) = mem::take(load).remove(&mut self.ci.nodes) {
2024-10-25 09:33:56 -05:00
inps.push(load);
}
2024-10-21 11:57:23 -05:00
2024-10-25 09:33:56 -05:00
false
});
}
2024-10-21 11:57:23 -05:00
let alt_value = match ty.loc(self.tys) {
2024-10-21 11:57:23 -05:00
Loc::Reg => None,
Loc::Stack => {
let stck = self.ci.nodes.new_node_nop(ty, Kind::Stck, [VOID, MEM]);
inps.push(stck);
Some(Value::ptr(stck).ty(ty))
}
};
2024-10-26 05:09:53 -05:00
inps[0] = self.ci.ctrl.get();
self.ci.ctrl.set(
self.ci.nodes.new_node(ty, Kind::Call { func: ty::ECA, args }, inps),
&mut self.ci.nodes,
);
2024-10-21 11:57:23 -05:00
2024-10-25 09:33:56 -05:00
if has_ptr_arg {
self.store_mem(VOID, ty::Id::VOID, VOID);
}
2024-10-21 11:57:23 -05:00
2024-10-26 05:09:53 -05:00
alt_value.or(Some(Value::new(self.ci.ctrl.get()).ty(ty)))
2024-10-21 11:57:23 -05:00
}
Expr::Call { func, args, .. } => {
self.ci.call_count += 1;
let ty = self.ty(func);
2024-10-22 00:20:08 -05:00
let ty::Kind::Func(mut fu) = ty.expand() else {
2024-09-28 08:13:32 -05:00
self.report(
func.pos(),
fa!("compiler cant (yet) call '{}'", self.ty_display(ty)),
2024-09-28 08:13:32 -05:00
);
2024-10-17 12:32:10 -05:00
return Value::NEVER;
2024-09-27 09:53:28 -05:00
};
2024-10-22 00:20:08 -05:00
let Some(sig) = self.compute_signature(&mut fu, func.pos(), args) else {
return Value::NEVER;
};
self.make_func_reachable(fu);
let fuc = &self.tys.ins.funcs[fu as usize];
2024-10-19 12:37:02 -05:00
let ast = &self.files[fuc.file as usize];
let &Expr::Closure { args: cargs, .. } = fuc.expr.get(ast) else { unreachable!() };
if args.len() != cargs.len() {
self.report(
func.pos(),
fa!(
"expected {} function argumenr{}, got {}",
cargs.len(),
if cargs.len() == 1 { "" } else { "s" },
args.len()
),
);
}
2024-10-23 05:26:07 -05:00
let mut inps = Vc::from([NEVER]);
2024-10-24 02:43:07 -05:00
let mut tys = sig.args.args();
let mut cargs = cargs.iter();
let mut args = args.iter();
2024-10-24 05:28:18 -05:00
let mut has_ptr_arg = false;
while let Some(ty) = tys.next(self.tys) {
2024-10-24 02:43:07 -05:00
let carg = cargs.next().unwrap();
let Some(arg) = args.next() else { break };
2024-10-24 02:43:07 -05:00
let Arg::Value(ty) = ty else { continue };
has_ptr_arg |= ty.has_pointers(self.tys);
2024-10-24 02:43:07 -05:00
let mut value = self.expr_ctx(arg, Ctx::default().with_ty(ty))?;
2024-10-19 12:37:02 -05:00
debug_assert_ne!(self.ci.nodes[value.id].kind, Kind::Stre);
self.assert_ty(arg.pos(), &mut value, ty, fa!("argument {}", carg.name));
2024-10-17 12:32:10 -05:00
self.ci.nodes.lock(value.id);
2024-10-17 12:32:10 -05:00
inps.push(value.id);
}
2024-10-17 15:29:09 -05:00
for &n in inps.iter().skip(1) {
self.ci.nodes.unlock(n);
}
2024-10-24 05:28:18 -05:00
if has_ptr_arg {
inps.push(self.ci.scope.store.value());
2024-10-26 05:09:53 -05:00
self.ci.scope.loads.retain_mut(|load| {
if inps.contains(&load.get()) {
2024-10-24 05:28:18 -05:00
return true;
}
2024-10-17 15:29:09 -05:00
2024-10-26 05:09:53 -05:00
if let Some(load) = mem::take(load).remove(&mut self.ci.nodes) {
2024-10-24 05:28:18 -05:00
inps.push(load);
}
2024-10-19 12:37:02 -05:00
2024-10-24 05:28:18 -05:00
false
});
}
let alt_value = match sig.ret.loc(self.tys) {
Loc::Reg => None,
Loc::Stack => {
let stck = self.ci.nodes.new_node_nop(sig.ret, Kind::Stck, [VOID, MEM]);
inps.push(stck);
Some(Value::ptr(stck).ty(sig.ret))
}
};
2024-10-26 05:09:53 -05:00
inps[0] = self.ci.ctrl.get();
self.ci.ctrl.set(
self.ci.nodes.new_node(sig.ret, Kind::Call { func: fu, args: sig.args }, inps),
&mut self.ci.nodes,
);
2024-10-19 12:37:02 -05:00
2024-10-24 05:28:18 -05:00
if has_ptr_arg {
self.store_mem(VOID, ty::Id::VOID, VOID);
}
2024-10-26 05:09:53 -05:00
alt_value.or(Some(Value::new(self.ci.ctrl.get()).ty(sig.ret)))
2024-10-17 12:32:10 -05:00
}
Expr::Directive { name: "inline", args: [func, args @ ..], .. } => {
let ty = self.ty(func);
2024-10-22 00:20:08 -05:00
let ty::Kind::Func(mut fu) = ty.expand() else {
self.report(
func.pos(),
fa!(
"first argument to @inline should be a function,
2024-10-24 02:43:07 -05:00
but here its '{}'",
self.ty_display(ty)
),
);
return Value::NEVER;
};
2024-10-22 00:20:08 -05:00
let Some(sig) = self.compute_signature(&mut fu, func.pos(), args) else {
return Value::NEVER;
};
2024-10-22 09:53:48 -05:00
let Func { expr, file, .. } = self.tys.ins.funcs[fu as usize];
let ast = &self.files[file as usize];
let &Expr::Closure { args: cargs, body, .. } = expr.get(ast) else {
unreachable!()
};
if args.len() != cargs.len() {
self.report(
func.pos(),
fa!(
"expected {} inline function argumenr{}, got {}",
cargs.len(),
if cargs.len() == 1 { "" } else { "s" },
args.len()
),
);
}
2024-10-24 02:43:07 -05:00
let mut tys = sig.args.args();
let mut args = args.iter();
let mut cargs = cargs.iter();
let var_base = self.ci.scope.vars.len();
while let Some(aty) = tys.next(self.tys) {
2024-10-24 02:43:07 -05:00
let carg = cargs.next().unwrap();
let Some(arg) = args.next() else { break };
2024-10-24 02:43:07 -05:00
match aty {
Arg::Type(id) => {
self.ci.scope.vars.push(Variable::new(
carg.id,
id,
false,
NEVER,
&mut self.ci.nodes,
));
}
Arg::Value(ty) => {
let mut value = self.raw_expr_ctx(arg, Ctx::default().with_ty(ty))?;
self.strip_var(&mut value);
debug_assert_ne!(self.ci.nodes[value.id].kind, Kind::Stre);
debug_assert_ne!(value.id, 0);
self.assert_ty(
arg.pos(),
&mut value,
ty,
fa!("argument {}", carg.name),
);
2024-10-24 02:43:07 -05:00
self.ci.scope.vars.push(Variable::new(
carg.id,
ty,
value.ptr,
value.id,
&mut self.ci.nodes,
));
}
}
}
2024-10-24 02:43:07 -05:00
let prev_var_base =
2024-10-26 05:09:53 -05:00
mem::replace(&mut self.ci.inline_var_base, self.ci.scope.vars.len());
let prev_ret = self.ci.ret.replace(sig.ret);
let prev_inline_ret = self.ci.inline_ret.take();
2024-10-26 05:09:53 -05:00
let prev_file = mem::replace(&mut self.ci.file, file);
self.ci.inline_depth += 1;
2024-10-27 05:32:34 -05:00
if self.expr(body).is_some() && sig.ret != ty::Id::VOID {
self.report(
body.pos(),
"expected all paths in the fucntion to return \
2024-10-24 02:43:07 -05:00
or the return type to be 'void'",
);
}
self.ci.ret = prev_ret;
2024-10-22 09:53:48 -05:00
self.ci.file = prev_file;
self.ci.inline_depth -= 1;
2024-10-24 02:43:07 -05:00
self.ci.inline_var_base = prev_var_base;
for var in self.ci.scope.vars.drain(var_base..) {
2024-10-22 15:57:40 -05:00
var.remove(&mut self.ci.nodes);
}
2024-10-23 05:26:07 -05:00
2024-10-26 05:09:53 -05:00
mem::replace(&mut self.ci.inline_ret, prev_inline_ret).map(|(v, ctrl, scope)| {
self.ci.nodes.unlock(v.id);
self.ci.scope.clear(&mut self.ci.nodes);
self.ci.scope = scope;
self.ci.scope.vars.drain(var_base..).for_each(|v| v.remove(&mut self.ci.nodes));
mem::replace(&mut self.ci.ctrl, ctrl).remove(&mut self.ci.nodes);
v
})
}
2024-10-19 03:17:36 -05:00
Expr::Tupl { pos, ty, fields, .. } => {
let Some(sty) = ty.map(|ty| self.ty(ty)).or(ctx.ty) else {
self.report(
pos,
"the type of struct cannot be inferred from context, \
use an explicit type instead: <type>.{ ... }",
);
return Value::NEVER;
};
2024-10-19 12:37:02 -05:00
match sty.expand() {
ty::Kind::Struct(s) => {
let mem = self.ci.nodes.new_node(sty, Kind::Stck, [VOID, MEM]);
let mut offs = OffsetIter::new(s, self.tys);
2024-10-19 12:37:02 -05:00
for field in fields {
let Some((ty, offset)) = offs.next_ty(self.tys) else {
2024-10-19 12:37:02 -05:00
self.report(
field.pos(),
"this init argumen overflows the field count",
);
break;
};
2024-10-19 03:17:36 -05:00
2024-10-24 02:43:07 -05:00
let mut value = self.expr_ctx(field, Ctx::default().with_ty(ty))?;
_ = self.assert_ty(field.pos(), &mut value, ty, "tuple field");
let mem = self.offset(mem, offset);
2024-10-24 02:43:07 -05:00
self.store_mem(mem, ty, value.id);
2024-10-19 12:37:02 -05:00
}
2024-10-19 03:17:36 -05:00
2024-10-19 12:37:02 -05:00
let field_list = offs
.into_iter(self.tys)
2024-10-19 12:37:02 -05:00
.map(|(f, ..)| self.tys.names.ident_str(f.name))
.intersperse(", ")
.collect::<String>();
2024-10-19 03:17:36 -05:00
2024-10-19 12:37:02 -05:00
if !field_list.is_empty() {
self.report(
pos,
fa!("the struct initializer is missing {field_list} \
(append them to the end of the constructor)"),
);
}
Some(Value::ptr(mem).ty(sty))
}
ty::Kind::Slice(s) => {
let slice = &self.tys.ins.slices[s as usize];
let len = slice.len().unwrap_or(fields.len());
let elem = slice.elem;
let elem_size = self.tys.size_of(elem);
let aty = slice
.len()
.map_or_else(|| self.tys.make_array(elem, len as ArrayLen), |_| sty);
if len != fields.len() {
self.report(
pos,
fa!(
"expected '{}' but constructor has {} elements",
self.ty_display(aty),
fields.len()
),
);
return Value::NEVER;
}
2024-10-19 03:17:36 -05:00
2024-10-19 12:37:02 -05:00
let mem = self.ci.nodes.new_node(aty, Kind::Stck, [VOID, MEM]);
2024-10-19 03:17:36 -05:00
2024-10-19 12:37:02 -05:00
for (field, offset) in
fields.iter().zip((0u32..).step_by(elem_size as usize))
{
let mut value = self.expr_ctx(field, Ctx::default().with_ty(elem))?;
_ = self.assert_ty(field.pos(), &mut value, elem, "array value");
let mem = self.offset(mem, offset);
2024-10-24 02:43:07 -05:00
self.store_mem(mem, elem, value.id);
2024-10-19 12:37:02 -05:00
}
Some(Value::ptr(mem).ty(aty))
}
_ => {
let inferred = if ty.is_some() { "" } else { "inferred " };
self.report(
pos,
fa!(
"the {inferred}type of the constructor is `{}`, \
but thats not a struct nor slice or array",
self.ty_display(sty)
),
);
Value::NEVER
}
}
2024-10-19 03:17:36 -05:00
}
Expr::Struct { .. } => {
let value = self.ty(expr).repr() as i64;
Some(self.ci.nodes.new_node_lit(ty::Id::TYPE, Kind::CInt { value }, [VOID]))
}
2024-10-17 15:29:09 -05:00
Expr::Ctor { pos, ty, fields, .. } => {
let Some(sty) = ty.map(|ty| self.ty(ty)).or(ctx.ty) else {
self.report(
pos,
"the type of struct cannot be inferred from context, \
use an explicit type instead: <type>.{ ... }",
);
return Value::NEVER;
};
2024-10-17 12:32:10 -05:00
2024-10-17 15:29:09 -05:00
let ty::Kind::Struct(s) = sty.expand() else {
let inferred = if ty.is_some() { "" } else { "inferred " };
self.report(
pos,
fa!(
"the {inferred}type of the constructor is `{}`, \
but thats not a struct",
self.ty_display(sty)
),
);
return Value::NEVER;
};
// TODO: dont allocate
let mut offs = OffsetIter::new(s, self.tys)
.into_iter(self.tys)
2024-10-17 15:29:09 -05:00
.map(|(f, o)| (f.ty, o))
.collect::<Vec<_>>();
let mem = self.ci.nodes.new_node(sty, Kind::Stck, [VOID, MEM]);
for field in fields {
let Some(index) = self.tys.find_struct_field(s, field.name) else {
self.report(
field.pos,
fa!("struct '{}' does not have this field", self.ty_display(sty)),
);
continue;
};
let (ty, offset) =
2024-10-26 05:09:53 -05:00
mem::replace(&mut offs[index], (ty::Id::UNDECLARED, field.pos));
2024-10-17 15:29:09 -05:00
if ty == ty::Id::UNDECLARED {
self.report(field.pos, "the struct field is already initialized");
self.report(offset, "previous initialization is here");
continue;
}
let mut value = self.expr_ctx(&field.value, Ctx::default().with_ty(ty))?;
self.assert_ty(field.pos, &mut value, ty, fa!("field {}", field.name));
let mem = self.offset(mem, offset);
2024-10-24 02:43:07 -05:00
self.store_mem(mem, ty, value.id);
2024-10-17 15:29:09 -05:00
}
let field_list = self
.tys
.struct_fields(s)
.iter()
.zip(offs)
.filter(|&(_, (ty, _))| ty != ty::Id::UNDECLARED)
.map(|(f, _)| self.tys.names.ident_str(f.name))
.intersperse(", ")
.collect::<String>();
if !field_list.is_empty() {
self.report(pos, fa!("the struct initializer is missing {field_list}"));
}
Some(Value::ptr(mem).ty(sty))
}
Expr::Block { stmts, .. } => {
2024-10-18 06:11:11 -05:00
let base = self.ci.scope.vars.len();
2024-09-08 10:11:33 -05:00
2024-10-17 12:32:10 -05:00
let mut ret = Some(Value::VOID);
for stmt in stmts {
ret = ret.and(self.expr(stmt));
if let Some(mut id) = ret {
self.assert_ty(stmt.pos(), &mut id, ty::Id::VOID, "statement");
} else {
break;
}
}
2024-10-18 06:11:11 -05:00
for var in self.ci.scope.vars.drain(base..) {
2024-10-22 15:57:40 -05:00
var.remove(&mut self.ci.nodes);
}
ret
}
2024-09-05 18:17:54 -05:00
Expr::Loop { body, .. } => {
2024-10-26 05:09:53 -05:00
self.ci.ctrl.set(
2024-10-27 05:32:34 -05:00
self.ci.nodes.new_node(ty::Id::VOID, Kind::Loop, [
self.ci.ctrl.get(),
self.ci.ctrl.get(),
LOOPS,
]),
2024-10-26 05:09:53 -05:00
&mut self.ci.nodes,
);
2024-09-05 18:17:54 -05:00
self.ci.loops.push(Loop {
2024-10-26 05:09:53 -05:00
node: self.ci.ctrl.get(),
ctrl: [StrongRef::DEFAULT; 2],
2024-10-18 06:11:11 -05:00
ctrl_scope: core::array::from_fn(|_| Default::default()),
2024-10-22 15:57:40 -05:00
scope: self.ci.scope.dup(&mut self.ci.nodes),
2024-09-05 18:17:54 -05:00
});
2024-10-22 15:57:40 -05:00
for var in &mut self.ci.scope.iter_mut() {
var.set_value(VOID, &mut self.ci.nodes);
2024-09-05 18:17:54 -05:00
}
self.expr(body);
let Loop { ctrl: [con, ..], ctrl_scope: [cons, ..], .. } =
self.ci.loops.last_mut().unwrap();
2024-10-26 05:09:53 -05:00
let mut cons = mem::take(cons);
2024-09-08 10:11:33 -05:00
2024-10-26 05:09:53 -05:00
if let Some(con) = mem::take(con).unwrap(&mut self.ci.nodes) {
self.ci.ctrl.set(
self.ci
.nodes
.new_node(ty::Id::VOID, Kind::Region, [con, self.ci.ctrl.get()]),
2024-09-15 13:14:56 -05:00
&mut self.ci.nodes,
2024-10-26 05:09:53 -05:00
);
self.ci.nodes.merge_scopes(
2024-09-15 13:14:56 -05:00
&mut self.ci.loops,
2024-10-26 05:09:53 -05:00
&self.ci.ctrl,
2024-10-18 06:11:11 -05:00
&mut self.ci.scope,
2024-09-15 13:14:56 -05:00
&mut cons,
);
2024-10-22 15:57:40 -05:00
cons.clear(&mut self.ci.nodes);
2024-09-15 13:14:56 -05:00
}
let Loop { node, ctrl: [.., bre], ctrl_scope: [.., mut bres], mut scope } =
self.ci.loops.pop().unwrap();
2024-10-26 05:09:53 -05:00
self.ci.nodes.modify_input(node, 1, self.ci.ctrl.get());
2024-09-05 18:17:54 -05:00
2024-10-22 15:57:40 -05:00
if let Some(idx) =
self.ci.nodes[node].outputs.iter().position(|&n| self.ci.nodes.is_cfg(n))
{
self.ci.nodes[node].outputs.swap(idx, 0);
}
2024-09-12 11:42:21 -05:00
2024-10-26 05:09:53 -05:00
let Some(bre) = bre.unwrap(&mut self.ci.nodes) else {
2024-10-23 05:26:07 -05:00
for (loop_var, scope_var) in self.ci.scope.iter_mut().zip(scope.iter_mut()) {
if self.ci.nodes[scope_var.value()].is_lazy_phi(node) {
if loop_var.value() != scope_var.value() {
scope_var.set_value(
self.ci.nodes.modify_input(
scope_var.value(),
2,
loop_var.value(),
),
&mut self.ci.nodes,
);
} else {
let phi = &self.ci.nodes[scope_var.value()];
let prev = phi.inputs[1];
self.ci.nodes.replace(scope_var.value(), prev);
scope_var.set_value(prev, &mut self.ci.nodes);
}
}
}
2024-10-22 15:57:40 -05:00
scope.clear(&mut self.ci.nodes);
2024-10-26 05:09:53 -05:00
self.ci.ctrl.set(NEVER, &mut self.ci.nodes);
2024-10-27 05:32:34 -05:00
2024-09-05 18:17:54 -05:00
return None;
2024-10-26 05:09:53 -05:00
};
self.ci.ctrl.set(bre, &mut self.ci.nodes);
2024-09-05 18:17:54 -05:00
2024-10-26 05:09:53 -05:00
mem::swap(&mut self.ci.scope, &mut bres);
2024-09-06 15:00:23 -05:00
debug_assert_eq!(self.ci.scope.vars.len(), scope.vars.len());
debug_assert_eq!(self.ci.scope.vars.len(), bres.vars.len());
2024-10-22 15:57:40 -05:00
self.ci.nodes.lock(node);
2024-10-19 03:17:36 -05:00
2024-10-22 15:57:40 -05:00
for ((dest_var, scope_var), loop_var) in
self.ci.scope.iter_mut().zip(scope.iter_mut()).zip(bres.iter_mut())
{
if self.ci.nodes[scope_var.value()].is_lazy_phi(node) {
if loop_var.value() != scope_var.value() {
scope_var.set_value(
self.ci.nodes.modify_input(scope_var.value(), 2, loop_var.value()),
&mut self.ci.nodes,
);
2024-09-08 05:00:07 -05:00
} else {
2024-10-22 15:57:40 -05:00
if dest_var.value() == scope_var.value() {
dest_var.set_value(VOID, &mut self.ci.nodes);
2024-09-22 11:17:30 -05:00
}
2024-10-22 15:57:40 -05:00
let phi = &self.ci.nodes[scope_var.value()];
2024-09-08 05:00:07 -05:00
let prev = phi.inputs[1];
2024-10-22 15:57:40 -05:00
self.ci.nodes.replace(scope_var.value(), prev);
scope_var.set_value(prev, &mut self.ci.nodes);
2024-09-08 05:00:07 -05:00
}
}
2024-09-05 18:17:54 -05:00
2024-10-22 15:57:40 -05:00
if dest_var.value() == VOID {
dest_var.set_value(scope_var.value(), &mut self.ci.nodes);
2024-09-05 18:17:54 -05:00
}
2024-10-22 15:57:40 -05:00
debug_assert!(!self.ci.nodes[dest_var.value()].is_lazy_phi(node));
}
2024-10-22 15:57:40 -05:00
scope.clear(&mut self.ci.nodes);
bres.clear(&mut self.ci.nodes);
2024-10-26 05:09:53 -05:00
self.ci.scope.loads.drain(..).for_each(|l| _ = l.remove(&mut self.ci.nodes));
2024-10-20 05:22:28 -05:00
2024-10-22 15:57:40 -05:00
self.ci.nodes.unlock(node);
2024-10-26 03:45:50 -05:00
let rpl = self.ci.nodes.late_peephole(node).unwrap_or(node);
2024-10-26 05:09:53 -05:00
if self.ci.ctrl.get() == node {
self.ci.ctrl.set_remove(rpl, &mut self.ci.nodes);
2024-10-22 15:57:40 -05:00
}
2024-10-17 12:32:10 -05:00
Some(Value::VOID)
2024-09-05 18:17:54 -05:00
}
2024-09-08 10:11:33 -05:00
Expr::Break { pos } => self.jump_to(pos, 1),
Expr::Continue { pos } => self.jump_to(pos, 0),
Expr::If { cond, then, else_, .. } => {
let mut cnd = self.expr_ctx(cond, Ctx::default().with_ty(ty::Id::BOOL))?;
self.assert_ty(cond.pos(), &mut cnd, ty::Id::BOOL, "condition");
2024-09-04 16:46:32 -05:00
2024-10-17 12:32:10 -05:00
let if_node =
2024-10-26 05:09:53 -05:00
self.ci.nodes.new_node(ty::Id::VOID, Kind::If, [self.ci.ctrl.get(), cnd.id]);
'b: {
2024-10-27 05:32:34 -05:00
let branch = match self.ci.nodes[if_node].ty {
ty::Id::LEFT_UNREACHABLE => else_,
ty::Id::RIGHT_UNREACHABLE => Some(then),
_ => break 'b,
};
2024-09-04 16:46:32 -05:00
self.ci.nodes.remove(if_node);
2024-09-04 16:46:32 -05:00
if let Some(branch) = branch {
return self.expr(branch);
} else {
2024-10-17 12:32:10 -05:00
return Some(Value::VOID);
2024-09-28 08:13:32 -05:00
}
2024-09-04 16:46:32 -05:00
}
2024-10-19 03:17:36 -05:00
self.ci.nodes.load_loop_store(&mut self.ci.scope.store, &mut self.ci.loops);
2024-10-22 15:57:40 -05:00
let orig_store = self.ci.scope.store.dup(&mut self.ci.nodes);
let else_scope = self.ci.scope.dup(&mut self.ci.nodes);
2024-10-26 05:09:53 -05:00
self.ci.ctrl.set(
self.ci.nodes.new_node(ty::Id::VOID, Kind::Then, [if_node]),
&mut self.ci.nodes,
);
let lcntrl = self.expr(then).map_or(Nid::MAX, |_| self.ci.ctrl.get());
2024-10-26 05:09:53 -05:00
let mut then_scope = mem::replace(&mut self.ci.scope, else_scope);
self.ci.ctrl.set(
self.ci.nodes.new_node(ty::Id::VOID, Kind::Else, [if_node]),
&mut self.ci.nodes,
);
let rcntrl = if let Some(else_) = else_ {
2024-10-26 05:09:53 -05:00
self.expr(else_).map_or(Nid::MAX, |_| self.ci.ctrl.get())
2024-09-03 10:51:28 -05:00
} else {
2024-10-26 05:09:53 -05:00
self.ci.ctrl.get()
2024-09-03 10:51:28 -05:00
};
2024-10-22 15:57:40 -05:00
orig_store.remove(&mut self.ci.nodes);
if lcntrl == Nid::MAX && rcntrl == Nid::MAX {
2024-10-22 15:57:40 -05:00
then_scope.clear(&mut self.ci.nodes);
return None;
} else if lcntrl == Nid::MAX {
2024-10-22 15:57:40 -05:00
then_scope.clear(&mut self.ci.nodes);
2024-10-17 12:32:10 -05:00
return Some(Value::VOID);
} else if rcntrl == Nid::MAX {
2024-10-22 15:57:40 -05:00
self.ci.scope.clear(&mut self.ci.nodes);
2024-10-18 06:11:11 -05:00
self.ci.scope = then_scope;
2024-10-26 05:09:53 -05:00
self.ci.ctrl.set(lcntrl, &mut self.ci.nodes);
2024-10-17 12:32:10 -05:00
return Some(Value::VOID);
2024-09-27 09:53:28 -05:00
}
2024-10-26 05:09:53 -05:00
self.ci.ctrl.set(
self.ci.nodes.new_node(ty::Id::VOID, Kind::Region, [lcntrl, rcntrl]),
&mut self.ci.nodes,
2024-10-26 05:09:53 -05:00
);
self.ci.nodes.merge_scopes(
&mut self.ci.loops,
2024-10-26 05:09:53 -05:00
&self.ci.ctrl,
&mut self.ci.scope,
&mut then_scope,
);
2024-10-22 15:57:40 -05:00
then_scope.clear(&mut self.ci.nodes);
2024-09-03 10:51:28 -05:00
2024-10-17 12:32:10 -05:00
Some(Value::VOID)
2024-09-03 10:51:28 -05:00
}
ref e => {
self.report_unhandled_ast(e, "bruh");
Some(Value::VOID)
}
2024-09-03 10:51:28 -05:00
}
}
2024-10-22 05:40:41 -05:00
fn struct_op(
&mut self,
pos: Pos,
op: TokenKind,
s: ty::Struct,
dst: Nid,
lhs: Nid,
rhs: Nid,
) -> bool {
let mut offs = OffsetIter::new(s, self.tys);
while let Some((ty, off)) = offs.next_ty(self.tys) {
2024-10-22 05:40:41 -05:00
let lhs = self.offset(lhs, off);
let rhs = self.offset(rhs, off);
let dst = self.offset(dst, off);
match ty.expand() {
_ if ty.is_pointer() || ty.is_integer() || ty == ty::Id::BOOL => {
let lhs = self.load_mem(lhs, ty);
let rhs = self.load_mem(rhs, ty);
let res = self.ci.nodes.new_node(ty, Kind::BinOp { op }, [VOID, lhs, rhs]);
2024-10-24 02:43:07 -05:00
self.store_mem(dst, ty, res);
2024-10-22 05:40:41 -05:00
}
ty::Kind::Struct(is) => {
if !self.struct_op(pos, op, is, dst, lhs, rhs) {
self.report(
pos,
fa!(
"... when appliing '{0} {op} {0}'",
self.ty_display(ty::Kind::Struct(s).compress())
),
);
}
}
_ => self.report(pos, fa!("'{0} {op} {0}' is not supported", self.ty_display(ty))),
}
}
true
}
2024-10-22 00:20:08 -05:00
fn compute_signature(&mut self, func: &mut ty::Func, pos: Pos, args: &[Expr]) -> Option<Sig> {
let fuc = &self.tys.ins.funcs[*func as usize];
let fast = self.files[fuc.file as usize].clone();
let &Expr::Closure { args: cargs, ret, .. } = fuc.expr.get(&fast) else {
unreachable!();
};
Some(if let Some(sig) = fuc.sig {
sig
} else {
let arg_base = self.tys.tmp.args.len();
let base = self.ci.scope.vars.len();
for (arg, carg) in args.iter().zip(cargs) {
let ty = self.ty(&carg.ty);
self.tys.tmp.args.push(ty);
let sym = parser::find_symbol(&fast.symbols, carg.id);
let ty = if sym.flags & idfl::COMPTIME == 0 {
// FIXME: could fuck us
ty::Id::UNDECLARED
} else {
2024-10-24 06:25:30 -05:00
if ty != ty::Id::TYPE {
self.report(
arg.pos(),
fa!(
"arbitrary comptime types are not supported yet \
(expected '{}' got '{}')",
self.ty_display(ty::Id::TYPE),
self.ty_display(ty)
),
);
return None;
}
2024-10-22 00:20:08 -05:00
let ty = self.ty(arg);
self.tys.tmp.args.push(ty);
ty
};
2024-10-22 15:57:40 -05:00
self.ci.scope.vars.push(Variable::new(
carg.id,
ty,
false,
NEVER,
&mut self.ci.nodes,
));
2024-10-22 00:20:08 -05:00
}
let Some(args) = self.tys.pack_args(arg_base) else {
self.report(pos, "function instance has too many arguments");
return None;
};
let ret = self.ty(ret);
2024-10-22 15:57:40 -05:00
self.ci.scope.vars.drain(base..).for_each(|v| v.remove(&mut self.ci.nodes));
2024-10-22 00:20:08 -05:00
let sym = SymKey::FuncInst(*func, args);
let ct = |ins: &mut crate::TypeIns| {
let func_id = ins.funcs.len();
let fuc = &ins.funcs[*func as usize];
ins.funcs.push(Func {
file: fuc.file,
name: fuc.name,
base: Some(*func),
sig: Some(Sig { args, ret }),
expr: fuc.expr,
..Default::default()
});
ty::Kind::Func(func_id as _).compress()
};
*func = self.tys.syms.get_or_insert(sym, &mut self.tys.ins, ct).expand().inner();
Sig { args, ret }
})
}
fn assign_pattern(&mut self, pat: &Expr, right: Value) {
match *pat {
Expr::Ident { id, .. } => {
2024-10-22 15:57:40 -05:00
self.ci.scope.vars.push(Variable::new(
id,
2024-10-22 15:57:40 -05:00
right.ty,
right.ptr,
right.id,
&mut self.ci.nodes,
));
}
Expr::Ctor { pos, fields, .. } => {
let ty::Kind::Struct(idx) = right.ty.expand() else {
self.report(pos, "can't use struct destruct on non struct value (TODO: shold work with modules)");
return;
};
for &CtorField { pos, name, ref value } in fields {
let Some((offset, ty)) = OffsetIter::offset_of(self.tys, idx, name) else {
self.report(pos, format_args!("field not found: {name:?}"));
continue;
};
let off = self.offset(right.id, offset);
self.assign_pattern(value, Value::ptr(off).ty(ty));
}
}
ref pat => self.report_unhandled_ast(pat, "pattern"),
}
}
2024-10-17 12:32:10 -05:00
fn expr_ctx(&mut self, expr: &Expr, ctx: Ctx) -> Option<Value> {
let mut n = self.raw_expr_ctx(expr, ctx)?;
self.strip_var(&mut n);
self.strip_ptr(&mut n);
2024-10-04 14:44:29 -05:00
Some(n)
}
fn expr(&mut self, expr: &Expr) -> Option<Value> {
self.expr_ctx(expr, Default::default())
}
fn strip_ptr(&mut self, target: &mut Value) {
if mem::take(&mut target.ptr) {
target.id = self.load_mem(target.id, target.ty);
}
}
fn offset(&mut self, val: Nid, off: Offset) -> Nid {
2024-10-18 06:11:11 -05:00
if off == 0 {
return val;
2024-10-18 02:52:50 -05:00
}
2024-10-18 06:11:11 -05:00
let off = self.ci.nodes.new_node_nop(ty::Id::INT, Kind::CInt { value: off as i64 }, [VOID]);
let inps = [VOID, val, off];
self.ci.nodes.new_node(ty::Id::INT, Kind::BinOp { op: TokenKind::Add }, inps)
2024-10-18 02:52:50 -05:00
}
2024-10-17 12:32:10 -05:00
fn strip_var(&mut self, n: &mut Value) {
2024-10-26 05:09:53 -05:00
if mem::take(&mut n.var) {
2024-10-17 15:29:09 -05:00
let id = (u16::MAX - n.id) as usize;
2024-10-19 12:37:02 -05:00
n.ptr = self.ci.scope.vars[id].ptr;
2024-10-22 15:57:40 -05:00
n.id = self.ci.scope.vars[id].value();
2024-10-17 12:32:10 -05:00
}
}
fn jump_to(&mut self, pos: Pos, id: usize) -> Option<Value> {
2024-09-15 13:14:56 -05:00
let Some(mut loob) = self.ci.loops.last_mut() else {
2024-09-08 10:11:33 -05:00
self.report(pos, "break outside a loop");
return None;
};
2024-10-26 05:09:53 -05:00
if loob.ctrl[id].is_live() {
loob.ctrl[id].set(
self.ci.nodes.new_node(ty::Id::VOID, Kind::Region, [
self.ci.ctrl.get(),
loob.ctrl[id].get(),
]),
2024-09-15 13:14:56 -05:00
&mut self.ci.nodes,
);
2024-10-26 05:09:53 -05:00
let mut scope = mem::take(&mut loob.ctrl_scope[id]);
let ctrl = mem::take(&mut loob.ctrl[id]);
self.ci.nodes.merge_scopes(&mut self.ci.loops, &ctrl, &mut scope, &mut self.ci.scope);
2024-09-08 10:11:33 -05:00
2024-09-15 13:14:56 -05:00
loob = self.ci.loops.last_mut().unwrap();
loob.ctrl_scope[id] = scope;
2024-10-26 05:09:53 -05:00
loob.ctrl[id] = ctrl;
self.ci.ctrl.set(NEVER, &mut self.ci.nodes);
} else {
let term = StrongRef::new(NEVER, &mut self.ci.nodes);
loob.ctrl[id] = mem::replace(&mut self.ci.ctrl, term);
loob.ctrl_scope[id] = self.ci.scope.dup(&mut self.ci.nodes);
loob.ctrl_scope[id]
.vars
.drain(loob.scope.vars.len()..)
.for_each(|v| v.remove(&mut self.ci.nodes));
2024-09-08 10:11:33 -05:00
}
None
}
fn complete_call_graph(&mut self) -> bool {
let prev_err_len = self.errors.borrow().len();
while self.ci.task_base < self.tys.tasks.len()
&& let Some(task_slot) = self.tys.tasks.pop()
2024-09-02 17:07:20 -05:00
{
let Some(task) = task_slot else { continue };
2024-09-15 13:14:56 -05:00
self.emit_func(task);
2024-09-02 17:07:20 -05:00
}
self.errors.borrow().len() == prev_err_len
2024-09-02 17:07:20 -05:00
}
2024-09-15 13:14:56 -05:00
fn emit_func(&mut self, FTask { file, id }: FTask) {
2024-10-01 15:53:03 -05:00
let func = &mut self.tys.ins.funcs[id as usize];
2024-10-19 12:53:43 -05:00
debug_assert_eq!(func.file, file);
2024-10-19 12:37:02 -05:00
func.offset = u32::MAX - 1;
let sig = func.sig.expect("to emmit only concrete functions");
let ast = &self.files[file as usize];
let expr = func.expr.get(ast);
2024-09-03 10:51:28 -05:00
2024-10-20 03:37:48 -05:00
self.pool.push_ci(file, Some(sig.ret), 0, &mut self.ci);
let prev_err_len = self.errors.borrow().len();
2024-09-03 10:51:28 -05:00
let &Expr::Closure { body, args, .. } = expr else {
2024-09-30 12:09:17 -05:00
unreachable!("{}", self.ast_display(expr))
2024-09-03 10:51:28 -05:00
};
2024-10-24 02:43:07 -05:00
let mut tys = sig.args.args();
let mut args = args.iter();
while let Some(aty) = tys.next(self.tys) {
2024-10-24 02:43:07 -05:00
let arg = args.next().unwrap();
match aty {
Arg::Type(ty) => {
self.ci.scope.vars.push(Variable::new(
arg.id,
ty,
false,
NEVER,
&mut self.ci.nodes,
));
}
Arg::Value(ty) => {
let mut deps = Vc::from([VOID]);
if ty.loc(self.tys) == Loc::Stack && self.tys.size_of(ty) <= 16 {
2024-10-24 02:43:07 -05:00
deps.push(MEM);
}
// TODO: whe we not using the deps?
let value = self.ci.nodes.new_node_nop(ty, Kind::Arg, deps);
let ptr = ty.loc(self.tys) == Loc::Stack;
2024-10-24 02:43:07 -05:00
self.ci.scope.vars.push(Variable::new(
arg.id,
ty,
ptr,
value,
&mut self.ci.nodes,
));
}
}
2024-09-03 10:51:28 -05:00
}
2024-10-27 05:32:34 -05:00
if self.expr(body).is_some() {
if sig.ret == ty::Id::VOID {
self.expr(&Expr::Return { pos: body.pos(), val: None });
} else {
self.report(
body.pos(),
fa!(
"expected all paths in the fucntion to return \
or the return type to be 'void' (return type is '{}')",
self.ty_display(sig.ret),
),
);
}
2024-09-03 10:51:28 -05:00
}
2024-10-22 15:57:40 -05:00
self.ci.scope.vars.drain(..).for_each(|v| v.remove_ignore_arg(&mut self.ci.nodes));
2024-10-27 05:32:34 -05:00
self.ci.finalize(&mut self.pool.nid_stack);
2024-09-30 12:09:17 -05:00
if self.errors.borrow().len() == prev_err_len {
2024-10-26 03:25:42 -05:00
self.ci.emit_body(self.tys, self.files, sig, &mut self.pool.ralloc);
2024-10-20 03:37:48 -05:00
self.tys.ins.funcs[id as usize].code.append(&mut self.ci.code);
self.tys.ins.funcs[id as usize].relocs.append(&mut self.ci.relocs);
2024-09-04 09:54:34 -05:00
}
2024-10-19 12:53:43 -05:00
self.pool.pop_ci(&mut self.ci);
2024-09-04 09:54:34 -05:00
}
2024-09-02 17:07:20 -05:00
fn ty(&mut self, expr: &Expr) -> ty::Id {
self.parse_ty(self.ci.file, expr, None, self.files)
2024-09-02 17:07:20 -05:00
}
fn ty_display(&self, ty: ty::Id) -> ty::Display {
ty::Display::new(self.tys, self.files, ty)
2024-09-02 17:07:20 -05:00
}
2024-10-19 12:37:02 -05:00
fn ast_display(&self, ast: &'a Expr<'a>) -> parser::Display<'a> {
2024-10-26 08:18:00 -05:00
parser::Display::new(&self.file().file, ast)
2024-09-30 12:09:17 -05:00
}
2024-09-02 17:07:20 -05:00
#[must_use]
#[track_caller]
fn binop_ty(&mut self, pos: Pos, lhs: &mut Value, rhs: &mut Value, op: TokenKind) -> ty::Id {
2024-10-27 07:57:00 -05:00
if let Some(upcasted) = lhs.ty.try_upcast(rhs.ty) {
let to_correct = if lhs.ty != upcasted {
Some(lhs)
} else if rhs.ty != upcasted {
Some(rhs)
} else {
None
};
if let Some(oper) = to_correct {
self.strip_ptr(oper);
oper.ty = upcasted;
oper.id = self.ci.nodes.new_node(upcasted, Kind::Extend, [VOID, oper.id]);
if matches!(op, TokenKind::Add | TokenKind::Sub)
&& let Some(elem) = self.tys.base_of(upcasted)
{
let value = self.tys.size_of(elem) as i64;
let cnst =
self.ci.nodes.new_node_nop(ty::Id::INT, Kind::CInt { value }, [VOID]);
oper.id =
self.ci.nodes.new_node(upcasted, Kind::BinOp { op: TokenKind::Mul }, [
VOID, oper.id, cnst,
]);
}
}
upcasted
2024-09-02 17:07:20 -05:00
} else {
let ty = self.ty_display(lhs.ty);
let expected = self.ty_display(rhs.ty);
2024-10-19 12:37:02 -05:00
self.report(pos, fa!("'{ty} {op} {expected}' is not supported"));
ty::Id::NEVER
}
}
#[track_caller]
fn assert_ty(
&mut self,
pos: Pos,
src: &mut Value,
expected: ty::Id,
hint: impl fmt::Display,
) -> bool {
2024-10-27 07:57:00 -05:00
if let Some(upcasted) = src.ty.try_upcast(expected)
&& upcasted == expected
{
if src.ty != upcasted {
debug_assert!(
src.ty.is_integer() || src.ty == ty::Id::NEVER,
"{} {}",
self.ty_display(src.ty),
self.ty_display(upcasted)
);
debug_assert!(
upcasted.is_integer() || src.ty == ty::Id::NEVER,
"{} {}",
self.ty_display(src.ty),
self.ty_display(upcasted)
);
self.strip_ptr(src);
src.ty = upcasted;
src.id = self.ci.nodes.new_node(upcasted, Kind::Extend, [VOID, src.id]);
}
true
} else {
let ty = self.ty_display(src.ty);
2024-09-02 17:07:20 -05:00
let expected = self.ty_display(expected);
self.report(pos, fa!("expected {hint} to be of type {expected}, got {ty}"));
false
2024-09-02 17:07:20 -05:00
}
}
2024-09-06 11:50:28 -05:00
#[track_caller]
2024-09-30 12:09:17 -05:00
fn report(&self, pos: Pos, msg: impl core::fmt::Display) {
2024-10-10 12:01:12 -05:00
let mut buf = self.errors.borrow_mut();
2024-10-26 08:18:00 -05:00
write!(buf, "{}", self.file().report(pos, msg)).unwrap();
2024-09-02 17:07:20 -05:00
}
#[track_caller]
fn report_unhandled_ast(&self, ast: &Expr, hint: impl Display) {
2024-10-19 12:37:02 -05:00
log::info!("{ast:#?}");
self.report(ast.pos(), fa!("compiler does not (yet) know how to handle ({hint})"));
2024-09-02 17:07:20 -05:00
}
2024-10-26 08:18:00 -05:00
fn file(&self) -> &'a parser::Ast {
2024-09-02 17:07:20 -05:00
&self.files[self.ci.file as usize]
}
}
impl TypeParser for Codegen<'_> {
fn tys(&mut self) -> &mut Types {
self.tys
}
fn eval_const(&mut self, file: FileId, expr: &Expr, ret: ty::Id) -> u64 {
2024-10-26 05:09:53 -05:00
let mut scope = mem::take(&mut self.ci.scope.vars);
self.pool.push_ci(file, Some(ret), self.tys.tasks.len(), &mut self.ci);
self.ci.scope.vars = scope;
let prev_err_len = self.errors.borrow().len();
self.expr(&Expr::Return { pos: expr.pos(), val: Some(expr) });
2024-10-26 05:09:53 -05:00
scope = mem::take(&mut self.ci.scope.vars);
2024-10-27 05:32:34 -05:00
self.ci.finalize(&mut self.pool.nid_stack);
let res = if self.errors.borrow().len() == prev_err_len {
self.emit_and_eval(file, ret, &mut [])
} else {
1
};
self.pool.pop_ci(&mut self.ci);
self.ci.scope.vars = scope;
res
}
fn infer_type(&mut self, expr: &Expr) -> ty::Id {
self.pool.save_ci(&self.ci);
let ty = self.expr(expr).map_or(ty::Id::NEVER, |v| v.ty);
2024-10-26 05:09:53 -05:00
self.pool.restore_ci(&mut self.ci);
ty
}
fn on_reuse(&mut self, existing: ty::Id) {
if let ty::Kind::Func(id) = existing.expand()
&& let func = &mut self.tys.ins.funcs[id as usize]
&& let Err(idx) = task::unpack(func.offset)
&& idx < self.tys.tasks.len()
{
func.offset = task::id(self.tys.tasks.len());
let task = self.tys.tasks[idx].take();
self.tys.tasks.push(task);
}
}
fn eval_global(&mut self, file: FileId, name: Ident, expr: &Expr) -> ty::Id {
let gid = self.tys.ins.globals.len() as ty::Global;
self.tys.ins.globals.push(Global { file, name, ..Default::default() });
let ty = ty::Kind::Global(gid);
self.pool.push_ci(file, None, self.tys.tasks.len(), &mut self.ci);
let prev_err_len = self.errors.borrow().len();
self.expr(&(Expr::Return { pos: expr.pos(), val: Some(expr) }));
2024-09-02 17:07:20 -05:00
2024-10-27 05:32:34 -05:00
self.ci.finalize(&mut self.pool.nid_stack);
let ret = self.ci.ret.expect("for return type to be infered");
if self.errors.borrow().len() == prev_err_len {
let mut mem = vec![0u8; self.tys.size_of(ret) as usize];
self.emit_and_eval(file, ret, &mut mem);
self.tys.ins.globals[gid as usize].data = mem;
}
self.pool.pop_ci(&mut self.ci);
self.tys.ins.globals[gid as usize].ty = ret;
ty.compress()
}
fn report(&self, file: FileId, pos: Pos, msg: impl Display) -> ty::Id {
let mut buf = self.errors.borrow_mut();
write!(buf, "{}", self.files[file as usize].report(pos, msg)).unwrap();
ty::Id::NEVER
}
fn find_local_ty(&mut self, ident: Ident) -> Option<ty::Id> {
self.ci.scope.vars.iter().rfind(|v| (v.id == ident && v.value() == NEVER)).map(|v| v.ty)
2024-09-06 11:50:28 -05:00
}
2024-09-15 13:14:56 -05:00
}
2024-09-12 11:42:21 -05:00
2024-09-20 01:09:29 -05:00
// FIXME: make this more efficient (allocated with arena)
2024-09-15 13:14:56 -05:00
fn loop_depth(target: Nid, nodes: &mut Nodes) -> LoopDepth {
if nodes[target].loop_depth != 0 {
return nodes[target].loop_depth;
}
nodes[target].loop_depth = match nodes[target].kind {
2024-09-27 09:53:28 -05:00
Kind::Entry | Kind::Then | Kind::Else | Kind::Call { .. } | Kind::Return | Kind::If => {
let dpth = loop_depth(nodes[target].inputs[0], nodes);
if nodes[target].loop_depth != 0 {
return nodes[target].loop_depth;
}
dpth
2024-09-15 13:14:56 -05:00
}
Kind::Region => {
let l = loop_depth(nodes[target].inputs[0], nodes);
let r = loop_depth(nodes[target].inputs[1], nodes);
2024-09-27 09:53:28 -05:00
debug_assert_eq!(l, r);
2024-09-15 13:14:56 -05:00
l
}
Kind::Loop => {
let depth = loop_depth(nodes[target].inputs[0], nodes) + 1;
nodes[target].loop_depth = depth;
let mut cursor = nodes[target].inputs[1];
while cursor != target {
nodes[cursor].loop_depth = depth;
let next = if nodes[cursor].kind == Kind::Region {
loop_depth(nodes[cursor].inputs[0], nodes);
nodes[cursor].inputs[1]
} else {
idom(nodes, cursor)
};
debug_assert_ne!(next, VOID);
2024-09-27 09:53:28 -05:00
if matches!(nodes[cursor].kind, Kind::Then | Kind::Else) {
2024-09-15 13:14:56 -05:00
let other = *nodes[next]
.outputs
.iter()
2024-09-27 09:53:28 -05:00
.find(|&&n| nodes[n].kind != nodes[cursor].kind)
2024-09-15 13:14:56 -05:00
.unwrap();
if nodes[other].loop_depth == 0 {
nodes[other].loop_depth = depth - 1;
2024-09-12 11:42:21 -05:00
}
}
2024-09-15 13:14:56 -05:00
cursor = next;
}
depth
2024-09-12 11:42:21 -05:00
}
2024-09-15 13:14:56 -05:00
Kind::Start | Kind::End => 1,
2024-10-19 03:17:36 -05:00
u => unreachable!("{u:?}"),
2024-09-15 13:14:56 -05:00
};
nodes[target].loop_depth
}
fn idepth(nodes: &mut Nodes, target: Nid) -> IDomDepth {
if target == VOID {
2024-09-15 13:14:56 -05:00
return 0;
}
if nodes[target].depth == 0 {
nodes[target].depth = match nodes[target].kind {
2024-10-20 05:22:28 -05:00
Kind::End | Kind::Start => unreachable!("{:?}", nodes[target].kind),
2024-09-15 13:14:56 -05:00
Kind::Region => {
idepth(nodes, nodes[target].inputs[0]).max(idepth(nodes, nodes[target].inputs[1]))
}
_ => idepth(nodes, nodes[target].inputs[0]),
2024-09-15 13:14:56 -05:00
} + 1;
}
nodes[target].depth
}
2024-09-12 11:42:21 -05:00
2024-10-27 05:32:34 -05:00
fn fix_loops(nodes: &mut Nodes) {
'o: for l in nodes[LOOPS].outputs.clone() {
let mut cursor = nodes[l].inputs[1];
while cursor != l {
if nodes[cursor].kind == Kind::If
&& nodes[cursor]
.outputs
.clone()
.into_iter()
.any(|b| loop_depth(b, nodes) < loop_depth(cursor, nodes))
{
continue 'o;
}
cursor = idom(nodes, cursor);
}
nodes[l].outputs.push(NEVER);
nodes[NEVER].inputs.push(l);
}
}
2024-10-19 03:17:36 -05:00
fn push_up(nodes: &mut Nodes) {
fn collect_rpo(node: Nid, nodes: &mut Nodes, rpo: &mut Vec<Nid>) {
if !nodes.is_cfg(node) || !nodes.visited.set(node) {
return;
}
for i in 0..nodes[node].outputs.len() {
collect_rpo(nodes[node].outputs[i], nodes, rpo);
}
rpo.push(node);
2024-09-15 13:14:56 -05:00
}
2024-10-19 03:17:36 -05:00
fn push_up_impl(node: Nid, nodes: &mut Nodes) {
if !nodes.visited.set(node) {
return;
2024-09-15 13:14:56 -05:00
}
2024-10-19 03:17:36 -05:00
for i in 1..nodes[node].inputs.len() {
2024-10-19 03:17:36 -05:00
let inp = nodes[node].inputs[i];
if !nodes[inp].kind.is_pinned() {
push_up_impl(inp, nodes);
}
}
2024-10-19 03:17:36 -05:00
if nodes[node].kind.is_pinned() {
return;
}
let mut deepest = VOID;
for i in 1..nodes[node].inputs.len() {
let inp = nodes[node].inputs[i];
if idepth(nodes, inp) > idepth(nodes, deepest) {
deepest = idom(nodes, inp);
}
}
2024-10-19 03:17:36 -05:00
if deepest == VOID {
2024-09-15 13:14:56 -05:00
return;
}
2024-09-15 13:14:56 -05:00
let index = nodes[0].outputs.iter().position(|&p| p == node).unwrap();
nodes[0].outputs.remove(index);
2024-10-19 03:17:36 -05:00
nodes[node].inputs[0] = deepest;
2024-09-15 13:14:56 -05:00
debug_assert!(
2024-10-19 03:17:36 -05:00
!nodes[deepest].outputs.contains(&node)
|| matches!(nodes[deepest].kind, Kind::Call { .. }),
"{node} {:?} {deepest} {:?}",
2024-09-15 13:14:56 -05:00
nodes[node],
2024-10-19 03:17:36 -05:00
nodes[deepest]
2024-09-15 13:14:56 -05:00
);
2024-10-19 03:17:36 -05:00
nodes[deepest].outputs.push(node);
}
let mut rpo = vec![];
collect_rpo(VOID, nodes, &mut rpo);
for node in rpo.into_iter().rev() {
loop_depth(node, nodes);
for i in 0..nodes[node].inputs.len() {
push_up_impl(nodes[node].inputs[i], nodes);
}
if matches!(nodes[node].kind, Kind::Loop | Kind::Region) {
for i in 0..nodes[node].outputs.len() {
let usage = nodes[node].outputs[i];
if nodes[usage].kind == Kind::Phi {
push_up_impl(usage, nodes);
}
}
}
2024-09-15 13:14:56 -05:00
}
debug_assert_eq!(
nodes
.iter()
.map(|(n, _)| n)
2024-10-27 05:32:34 -05:00
.filter(|&n| !nodes.visited.get(n)
&& !matches!(nodes[n].kind, Kind::Arg | Kind::Mem | Kind::Loops))
.collect::<Vec<_>>(),
vec![],
"{:?}",
nodes
.iter()
2024-10-27 05:32:34 -05:00
.filter(|&(n, nod)| !nodes.visited.get(n)
&& !matches!(nod.kind, Kind::Arg | Kind::Mem | Kind::Loops))
.collect::<Vec<_>>()
);
2024-09-15 13:14:56 -05:00
}
2024-09-15 13:14:56 -05:00
fn push_down(nodes: &mut Nodes, node: Nid) {
2024-10-19 03:17:36 -05:00
fn is_forward_edge(usage: Nid, def: Nid, nodes: &mut Nodes) -> bool {
match nodes[usage].kind {
Kind::Phi => {
nodes[usage].inputs[2] != def || nodes[nodes[usage].inputs[0]].kind != Kind::Loop
}
Kind::Loop => nodes[usage].inputs[1] != def,
_ => true,
}
}
fn better(nodes: &mut Nodes, is: Nid, then: Nid) -> bool {
debug_assert_ne!(idepth(nodes, is), idepth(nodes, then), "{is} {then}");
2024-10-19 03:17:36 -05:00
loop_depth(is, nodes) < loop_depth(then, nodes)
|| idepth(nodes, is) > idepth(nodes, then)
|| nodes[then].kind == Kind::If
}
2024-09-15 13:14:56 -05:00
if !nodes.visited.set(node) {
return;
}
for usage in nodes[node].outputs.clone() {
if is_forward_edge(usage, node, nodes) && nodes[node].kind == Kind::Stre {
push_down(nodes, usage);
}
}
2024-10-19 03:17:36 -05:00
for usage in nodes[node].outputs.clone() {
if is_forward_edge(usage, node, nodes) {
push_down(nodes, usage);
}
}
2024-09-15 13:14:56 -05:00
if nodes[node].kind.is_pinned() {
2024-10-19 03:17:36 -05:00
return;
}
2024-10-19 03:17:36 -05:00
let mut min = None::<Nid>;
for i in 0..nodes[node].outputs.len() {
let usage = nodes[node].outputs[i];
let ub = use_block(node, usage, nodes);
min = min.map(|m| common_dom(ub, m, nodes)).or(Some(ub));
}
let mut min = min.unwrap();
2024-09-15 13:14:56 -05:00
2024-10-19 03:17:36 -05:00
debug_assert!(nodes.dominates(nodes[node].inputs[0], min));
2024-10-19 03:17:36 -05:00
let mut cursor = min;
while cursor != nodes[node].inputs[0] {
cursor = idom(nodes, cursor);
2024-10-19 03:17:36 -05:00
if better(nodes, cursor, min) {
min = cursor;
2024-09-15 13:14:56 -05:00
}
2024-10-19 03:17:36 -05:00
}
if nodes[min].kind.ends_basic_block() {
min = idom(nodes, min);
}
2024-09-12 11:42:21 -05:00
2024-10-19 12:37:02 -05:00
nodes.check_dominance(node, min, true);
2024-10-19 03:17:36 -05:00
let prev = nodes[node].inputs[0];
debug_assert!(idepth(nodes, min) >= idepth(nodes, prev));
let index = nodes[prev].outputs.iter().position(|&p| p == node).unwrap();
nodes[prev].outputs.remove(index);
nodes[node].inputs[0] = min;
nodes[min].outputs.push(node);
2024-09-15 13:14:56 -05:00
}
2024-09-15 13:14:56 -05:00
fn use_block(target: Nid, from: Nid, nodes: &mut Nodes) -> Nid {
if nodes[from].kind != Kind::Phi {
return idom(nodes, from);
}
2024-09-15 13:14:56 -05:00
let index = nodes[from].inputs.iter().position(|&n| n == target).unwrap();
nodes[nodes[from].inputs[0]].inputs[index - 1]
}
2024-09-12 11:42:21 -05:00
2024-09-15 13:14:56 -05:00
fn idom(nodes: &mut Nodes, target: Nid) -> Nid {
match nodes[target].kind {
Kind::Start => VOID,
2024-09-15 13:14:56 -05:00
Kind::End => unreachable!(),
Kind::Region => {
let &[lcfg, rcfg] = nodes[target].inputs.as_slice() else { unreachable!() };
common_dom(lcfg, rcfg, nodes)
}
_ => nodes[target].inputs[0],
2024-09-15 13:14:56 -05:00
}
}
2024-09-12 11:42:21 -05:00
2024-09-15 13:14:56 -05:00
fn common_dom(mut a: Nid, mut b: Nid, nodes: &mut Nodes) -> Nid {
while a != b {
let [ldepth, rdepth] = [idepth(nodes, a), idepth(nodes, b)];
if ldepth >= rdepth {
a = idom(nodes, a);
}
if ldepth <= rdepth {
b = idom(nodes, b);
2024-09-12 11:42:21 -05:00
}
2024-09-15 13:14:56 -05:00
}
a
}
2024-09-12 11:42:21 -05:00
2024-09-02 17:07:20 -05:00
#[cfg(test)]
mod tests {
2024-09-30 12:09:17 -05:00
use {
2024-10-27 05:32:34 -05:00
super::CodegenCtx,
2024-09-30 12:09:17 -05:00
alloc::{string::String, vec::Vec},
2024-10-27 05:32:34 -05:00
core::fmt::Write,
2024-09-30 12:09:17 -05:00
};
2024-09-02 17:07:20 -05:00
fn generate(ident: &'static str, input: &'static str, output: &mut String) {
2024-10-04 14:44:29 -05:00
_ = log::set_logger(&crate::fs::Logger);
log::set_max_level(log::LevelFilter::Info);
//log::set_max_level(log::LevelFilter::Trace);
let mut ctx = CodegenCtx::default();
let (ref files, embeds) = crate::test_parse_files(ident, input, &mut ctx.parser);
let mut codegen = super::Codegen::new(files, &mut ctx);
2024-10-21 11:57:23 -05:00
codegen.push_embeds(embeds);
2024-09-02 17:27:50 -05:00
2024-10-22 05:57:49 -05:00
codegen.generate(0);
2024-09-03 10:51:28 -05:00
2024-09-06 11:50:28 -05:00
{
let errors = codegen.errors.borrow();
if !errors.is_empty() {
output.push_str(&errors);
return;
}
}
2024-09-04 16:46:32 -05:00
let mut out = Vec::new();
2024-10-20 03:37:48 -05:00
codegen.tys.reassemble(&mut out);
2024-09-04 16:46:32 -05:00
2024-10-19 12:37:02 -05:00
let err = codegen.tys.disasm(&out, codegen.files, output, |_| {});
2024-09-04 16:46:32 -05:00
if let Err(e) = err {
writeln!(output, "!!! asm is invalid: {e}").unwrap();
return;
}
2024-10-27 08:29:14 -05:00
super::hbvm::test_run_vm(&out, output);
2024-09-02 17:07:20 -05:00
}
crate::run_tests! { generate:
// Tour Examples
main_fn;
2024-09-28 09:34:08 -05:00
arithmetic;
functions;
comments;
if_statements;
variables;
2024-09-28 09:34:08 -05:00
loops;
pointers;
structs;
hex_octal_binary_literals;
2024-10-22 05:40:41 -05:00
struct_operators;
2024-10-19 12:37:02 -05:00
global_variables;
2024-10-21 11:57:23 -05:00
directives;
2024-10-20 05:22:28 -05:00
c_strings;
struct_patterns;
2024-10-19 03:17:36 -05:00
arrays;
inline;
idk;
2024-10-22 00:20:08 -05:00
generic_functions;
// Incomplete Examples;
//comptime_pointers;
2024-10-22 03:17:16 -05:00
generic_types;
fb_driver;
// Purely Testing Examples;
reading_idk;
nonexistent_ident_import;
2024-10-25 17:34:22 -05:00
big_array_crash;
2024-10-24 06:25:30 -05:00
returning_global_struct;
2024-10-24 06:58:58 -05:00
small_struct_bitcast;
small_struct_assignment;
2024-10-24 09:26:28 -05:00
intcast_store;
2024-10-24 12:57:36 -05:00
string_flip;
2024-10-25 08:45:00 -05:00
signed_to_unsigned_upcast;
wide_ret;
2024-10-20 05:22:28 -05:00
comptime_min_reg_leak;
different_types;
2024-10-21 12:57:55 -05:00
struct_return_from_module_function;
sort_something_viredly;
//structs_in_registers;
comptime_function_from_another_file;
inline_test;
2024-10-22 00:20:08 -05:00
inlined_generic_functions;
some_generic_code;
2024-10-21 12:57:55 -05:00
integer_inference_issues;
writing_into_string;
2024-10-21 12:57:55 -05:00
request_page;
tests_ptr_to_ptr_copy;
// Just Testing Optimizations;
const_folding_with_arg;
branch_assignments;
exhaustive_loop_testing;
2024-09-28 09:34:08 -05:00
pointer_opts;
2024-10-18 06:11:11 -05:00
conditional_stores;
loop_stores;
2024-10-26 13:29:31 -05:00
dead_code_in_loop;
2024-10-27 05:32:34 -05:00
infinite_loop_after_peephole;
2024-09-02 17:07:20 -05:00
}
}