Skip to content

Commit

Permalink
feat: Perform sorting of constant arrays at compile time (#2195)
Browse files Browse the repository at this point in the history
* feat: perform any sorting of constant arrays at compile-time

* chore: rebuild artifacts

* chore: avoid double check for array elements being constants
  • Loading branch information
TomAFrench authored Aug 7, 2023
1 parent b0def14 commit c46d7a0
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "comptime_sort"
type = "bin"
authors = [""]
compiler_version = "0.6.0"

[dependencies]
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
fn main() {
let unsorted: [u8; 3] = [3,1,2];
let sorted = unsorted.sort();
assert(sorted[0] == 1);
assert(sorted[1] == 2);
assert(sorted[2] == 3);
}
2 changes: 1 addition & 1 deletion crates/nargo_cli/tests/test_data
20 changes: 19 additions & 1 deletion crates/noirc_evaluator/src/ssa/ir/instruction/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,8 @@ pub(super) fn simplify_call(
}
}
Intrinsic::BlackBox(bb_func) => simplify_black_box_func(bb_func, arguments, dfg),
Intrinsic::Println | Intrinsic::Sort => SimplifyResult::None,
Intrinsic::Sort => simplify_sort(dfg, arguments),
Intrinsic::Println => SimplifyResult::None,
}
}

Expand Down Expand Up @@ -366,3 +367,20 @@ fn simplify_signature(
_ => SimplifyResult::None,
}
}

fn simplify_sort(dfg: &mut DataFlowGraph, arguments: &[ValueId]) -> SimplifyResult {
match dfg.get_array_constant(arguments[0]) {
Some((input, _)) => {
let inputs: Option<Vec<FieldElement>> =
input.iter().map(|id| dfg.get_numeric_constant(*id)).collect();

let Some(mut sorted_inputs) = inputs else { return SimplifyResult::None };
sorted_inputs.sort_unstable();

let (_, element_type) = dfg.get_numeric_constant_with_type(input[0]).unwrap();
let result_array = make_constant_array(dfg, sorted_inputs, element_type);
SimplifyResult::SimplifiedTo(result_array)
}
_ => SimplifyResult::None,
}
}

0 comments on commit c46d7a0

Please sign in to comment.