Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Recursive constant fix #18

Merged
merged 1 commit into from
Jun 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion crates/rue-compiler/src/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ impl<'a> Codegen<'a> {
Lir::Run(program, args) => self.gen_run(program, args),
Lir::Curry(body, args) => self.gen_apply(body, args),
Lir::Closure(body, args) => self.gen_closure(body, args),
Lir::FunctionBody(body) => self.gen_quote(body),
Lir::First(value) => self.gen_first(value),
Lir::Rest(value) => self.gen_rest(value),
Lir::Raise(value) => self.gen_raise(value),
Expand Down
1 change: 0 additions & 1 deletion crates/rue-compiler/src/lir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ pub enum Lir {
Quote(LirId),
Curry(LirId, Vec<LirId>),
Closure(LirId, Vec<LirId>),
FunctionBody(LirId),
First(LirId),
Rest(LirId),
Raise(Option<LirId>),
Expand Down
122 changes: 68 additions & 54 deletions crates/rue-compiler/src/optimizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ mod environment;

pub use dependency_graph::*;
pub use environment::*;
use indexmap::IndexSet;

pub struct Optimizer<'a> {
db: &'a mut Database,
Expand All @@ -34,21 +35,10 @@ impl<'a> Optimizer<'a> {
let Symbol::Function(fun) = self.db.symbol(main).clone() else {
unreachable!();
};

let env_id = self.graph.env(fun.scope_id);
let body = self.opt_hir(env_id, fun.hir_id);

let mut args = Vec::new();

for symbol_id in self.db.env(env_id).definitions() {
args.push(self.opt_definition(env_id, symbol_id));
}

for symbol_id in self.db.env(env_id).captures() {
args.push(self.opt_definition(env_id, symbol_id));
}

self.db.alloc_lir(Lir::Curry(body, args))
let mut definitions = self.db.env(env_id).definitions();
definitions.extend(self.db.env(env_id).captures());
self.opt_definitions(env_id, definitions, fun.hir_id)
}

fn opt_path(&mut self, env_id: EnvironmentId, symbol_id: SymbolId) -> LirId {
Expand All @@ -59,7 +49,7 @@ impl<'a> Optimizer<'a> {
}

let mut current_env_id = env_id;
let mut environment = self.db.env(env_id).build().clone();
let mut environment: Vec<SymbolId> = self.db.env(env_id).build().into_iter().collect();

while let Some(parent_env_id) = self.db.env(current_env_id).parent() {
assert!(self.db.env(current_env_id).parameters().is_empty());
Expand Down Expand Up @@ -99,19 +89,12 @@ impl<'a> Optimizer<'a> {
hir_id, scope_id, ..
}) => {
let function_env_id = self.graph.env(scope_id);

let mut body = self.opt_hir(function_env_id, hir_id);
let mut definitions = Vec::new();

for symbol_id in self.db.env(function_env_id).definitions() {
definitions.push(self.opt_definition(function_env_id, symbol_id));
}

if !definitions.is_empty() {
body = self.db.alloc_lir(Lir::Curry(body, definitions));
}

self.db.alloc_lir(Lir::FunctionBody(body))
let function = self.opt_definitions(
function_env_id,
self.db.env(function_env_id).definitions(),
hir_id,
);
self.db.alloc_lir(Lir::Quote(function))
}
Symbol::Const(Value { hir_id, .. }) => self.opt_hir(env_id, hir_id),
Symbol::Let(symbol) if self.graph.symbol_usages(symbol_id) > 0 => {
Expand All @@ -126,6 +109,52 @@ impl<'a> Optimizer<'a> {
}
}

fn opt_definitions(
&mut self,
mut env_id: EnvironmentId,
definitions: IndexSet<SymbolId>,
body: HirId,
) -> LirId {
let mut remaining: IndexSet<SymbolId> = definitions.into_iter().collect();
let mut curries = Vec::new();

while !remaining.is_empty() {
let no_references = remaining
.iter()
.filter(|&symbol_id| {
!self.db.symbol(*symbol_id).is_constant()
|| self
.graph
.constant_references(*symbol_id)
.intersection(&remaining)
.count()
== 0
})
.copied()
.collect::<Vec<_>>();

let mut args = Vec::new();

for &symbol_id in &no_references {
args.push(self.opt_definition(env_id, symbol_id));
}

curries.push(args);
remaining.retain(|&symbol_id| !no_references.contains(&symbol_id));
if !remaining.is_empty() {
env_id = self.db.alloc_env(Environment::binding(env_id));
}
}

let mut body = self.opt_hir(env_id, body);

for args in curries.into_iter().rev() {
body = self.db.alloc_lir(Lir::Curry(body, args));
}

body
}

fn opt_hir(&mut self, env_id: EnvironmentId, hir_id: HirId) -> LirId {
match self.db.hir(hir_id).clone() {
Hir::Unknown => self.db.alloc_lir(Lir::Atom(Vec::new())),
Expand All @@ -134,18 +163,6 @@ impl<'a> Optimizer<'a> {
Hir::Reference(symbol_id, ..) => self.opt_reference(env_id, symbol_id),
Hir::CheckExists(value) => self.opt_check_exists(env_id, value),
Hir::Definition { scope_id, hir_id } => {
let definition_env_id = self.graph.env(scope_id);
for symbol_id in self.db.env_mut(definition_env_id).definitions() {
let Symbol::Let(..) = self.db.symbol(symbol_id) else {
continue;
};

if self.graph.symbol_usages(symbol_id) == 1 {
self.db
.env_mut(definition_env_id)
.remove_definition(symbol_id);
}
}
self.opt_env_definition(env_id, scope_id, hir_id)
}
Hir::FunctionCall {
Expand Down Expand Up @@ -239,6 +256,17 @@ impl<'a> Optimizer<'a> {
scope_id: ScopeId,
hir_id: HirId,
) -> LirId {
let definition_env_id = self.graph.env(scope_id);
for symbol_id in self.db.env_mut(definition_env_id).definitions() {
let Symbol::Let(..) = self.db.symbol(symbol_id) else {
continue;
};
if self.graph.symbol_usages(symbol_id) == 1 {
self.db
.env_mut(definition_env_id)
.remove_definition(symbol_id);
}
}
let child_env_id = self.graph.env(scope_id);
let body = self.opt_hir(child_env_id, hir_id);

Expand Down Expand Up @@ -376,20 +404,6 @@ impl<'a> Optimizer<'a> {
let mut inline_parameter_map = HashMap::new();
let mut args = args;

let env = self.db.env(function_env_id).clone();
for symbol_id in env.definitions() {
if self.db.symbol(symbol_id).is_parameter() {
continue;
}
self.db.env_mut(env_id).define(symbol_id);
}
for symbol_id in env.captures() {
if self.db.symbol(symbol_id).is_parameter() {
continue;
}
self.db.env_mut(env_id).capture(symbol_id);
}

let param_len = self.db.env(function_env_id).parameters().len();

for (i, symbol_id) in self
Expand Down
48 changes: 41 additions & 7 deletions crates/rue-compiler/src/optimizer/dependency_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use super::Environment;
pub struct DependencyGraph {
env: IndexMap<ScopeId, EnvironmentId>,
symbol_usages: HashMap<SymbolId, usize>,
constant_references: HashMap<SymbolId, IndexSet<SymbolId>>,
}

impl DependencyGraph {
Expand All @@ -34,15 +35,22 @@ impl DependencyGraph {
}

pub fn symbol_usages(&self, symbol_id: SymbolId) -> usize {
*self.symbol_usages.get(&symbol_id).unwrap_or(&0)
self.symbol_usages.get(&symbol_id).copied().unwrap_or(0)
}

pub fn constant_references(&self, symbol_id: SymbolId) -> IndexSet<SymbolId> {
self.constant_references
.get(&symbol_id)
.cloned()
.unwrap_or_default()
}
}

struct GraphTraversal<'a> {
db: &'a mut Database,
graph: DependencyGraph,
edges: HashMap<ScopeId, IndexSet<ScopeId>>,
constant_reference_stack: HashSet<SymbolId>,
constant_reference_stack: IndexSet<SymbolId>,
}

impl<'a> GraphTraversal<'a> {
Expand All @@ -51,7 +59,7 @@ impl<'a> GraphTraversal<'a> {
db,
graph: DependencyGraph::default(),
edges: HashMap::new(),
constant_reference_stack: HashSet::new(),
constant_reference_stack: IndexSet::new(),
}
}

Expand Down Expand Up @@ -224,14 +232,22 @@ impl<'a> GraphTraversal<'a> {
) {
let symbol = self.db.symbol(symbol_id).clone();

for &definition_id in &self.constant_reference_stack {
self.graph
.constant_references
.entry(definition_id)
.or_default()
.insert(symbol_id);
}

if symbol.is_constant() && !self.constant_reference_stack.insert(symbol_id) {
return;
}

self.graph
.symbol_usages
.entry(symbol_id)
.and_modify(|count| *count += 1)
.and_modify(|usages| *usages += 1)
.or_insert(1);

self.propagate_capture(scope_id, symbol_id, &mut HashSet::new());
Expand Down Expand Up @@ -265,16 +281,34 @@ impl<'a> GraphTraversal<'a> {

// Functions are visited in the scope in which they are defined.
// TODO: For inline functions, should this be visited in the current scope?
Symbol::Function(fun) | Symbol::InlineFunction(fun) => {
Symbol::Function(fun) => {
self.visit_hir(fun.scope_id, fun.hir_id, visited);
}

Symbol::InlineFunction(fun) => {
self.visit_hir(fun.scope_id, fun.hir_id, visited);

let env = self.db.env(self.graph.env(fun.scope_id)).clone();
for symbol_id in env.definitions() {
if self.db.symbol(symbol_id).is_parameter() {
continue;
}
self.db.env_mut(self.graph.env(scope_id)).define(symbol_id);
}
for symbol_id in env.captures() {
if self.db.symbol(symbol_id).is_parameter() {
continue;
}
self.db.env_mut(self.graph.env(scope_id)).capture(symbol_id);
}
}

// Parameters don't need to be visited, since currently
// they are just a reference to the environment.
Symbol::Parameter(..) => {}
}

self.constant_reference_stack.remove(&symbol_id);
self.constant_reference_stack.shift_remove(&symbol_id);
}

fn compute_edges(&mut self, symbol_id: SymbolId) {
Expand Down Expand Up @@ -400,7 +434,7 @@ impl<'a> GraphTraversal<'a> {
}
}

self.constant_reference_stack.remove(&symbol_id);
self.constant_reference_stack.shift_remove(&symbol_id);
}
}
}
Expand Down
16 changes: 8 additions & 8 deletions crates/rue-compiler/src/optimizer/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,16 @@ impl Environment {
self.captured_symbols.insert(symbol_id);
}

pub fn definitions(&self) -> Vec<SymbolId> {
self.defined_symbols.iter().copied().collect()
pub fn definitions(&self) -> IndexSet<SymbolId> {
self.defined_symbols.clone()
}

pub fn captures(&self) -> Vec<SymbolId> {
self.captured_symbols.iter().copied().collect()
pub fn captures(&self) -> IndexSet<SymbolId> {
self.captured_symbols.clone()
}

pub fn parameters(&self) -> Vec<SymbolId> {
self.parameters.iter().copied().collect()
pub fn parameters(&self) -> IndexSet<SymbolId> {
self.parameters.clone()
}

pub fn rest_parameter(&self) -> bool {
Expand All @@ -59,8 +59,8 @@ impl Environment {
self.parent
}

pub fn build(&self) -> Vec<SymbolId> {
let mut symbol_ids = Vec::new();
pub fn build(&self) -> IndexSet<SymbolId> {
let mut symbol_ids = IndexSet::new();
symbol_ids.extend(self.defined_symbols.iter().copied());

if self.parent.is_none() {
Expand Down
Loading