Skip to content

Commit

Permalink
fix: Add locations to most SSA instructions (#5697)
Browse files Browse the repository at this point in the history
# Description

## Problem\*

Resolves #5322

## Summary\*

Previously we added call stacks as a way to give better error reporting
on SSA instructions. Since these were just for errors, they only needed
to be on instructions which could emit errors. Since then, these call
stacks have also been used for profiling Noir code which revealed many
instructions without locations - many of them being instructions
inserted by the compiler rather than the user during intermediate
compiler passes like flatten_cfg.

I've went through and gotten rid of each case of `CallStack::new()`. As
far as I can tell all the remaining locations are either the intended
use case of an initial, empty value, or are used in some error messages
where the location is unknown.

Anyways - because many of the instructions without locations were not
introduced by the user I've had to decide which location best describes
them. These instructions are largely internal compiler details so many
users would be surprised if they knew e.g. we inserted extra `Store`
instructions to _undo_ previous store instructions when going between an
if expression's then and else branches. In this case, I set the location
of this undo store instruction the same as the original store, but an
argument could be made that it should actually be in the else branch or
share location with the whole if expression. Similarly, when an `if`
expression is used we merge the return value of the then & else branches
to get the return value of the `if` expression itself. For these values
I've opted to use the location of the entire `if` expression.

## Additional Context

@vezenovm I think this covers all the work needed for this issue after
all.

## Documentation\*

Check one:
- [x] No documentation needed.
- [ ] Documentation included in this PR.
- [ ] **[For Experimental Features]** Documentation to be submitted in a
separate PR.

# PR Checklist\*

- [x] I have tested the changes locally.
- [x] I have formatted the changes with [Prettier](https://prettier.io/)
and/or `cargo fmt` on default settings.
  • Loading branch information
jfecher authored Aug 8, 2024
1 parent af5acf4 commit 986f69c
Show file tree
Hide file tree
Showing 12 changed files with 184 additions and 58 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,12 @@ impl<'block> BrilligBlock<'block> {
dfg: &DataFlowGraph,
) {
match terminator_instruction {
TerminatorInstruction::JmpIf { condition, then_destination, else_destination } => {
TerminatorInstruction::JmpIf {
condition,
then_destination,
else_destination,
call_stack: _,
} => {
let condition = self.convert_ssa_single_addr_value(*condition, dfg);
self.brillig_context.jump_if_instruction(
condition.address,
Expand Down
2 changes: 2 additions & 0 deletions compiler/noirc_evaluator/src/ssa/function_builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,10 +371,12 @@ impl FunctionBuilder {
then_destination: BasicBlockId,
else_destination: BasicBlockId,
) {
let call_stack = self.call_stack.clone();
self.terminate_block_with(TerminatorInstruction::JmpIf {
condition,
then_destination,
else_destination,
call_stack,
});
}

Expand Down
3 changes: 3 additions & 0 deletions compiler/noirc_evaluator/src/ssa/ir/cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,11 +168,13 @@ mod tests {
condition: cond,
then_destination: block2_id,
else_destination: block1_id,
call_stack: CallStack::new(),
});
func.dfg[block1_id].set_terminator(TerminatorInstruction::JmpIf {
condition: cond,
then_destination: block1_id,
else_destination: block2_id,
call_stack: CallStack::new(),
});
func.dfg[block2_id].set_terminator(TerminatorInstruction::Return {
return_values: vec![],
Expand Down Expand Up @@ -235,6 +237,7 @@ mod tests {
condition: cond,
then_destination: block1_id,
else_destination: ret_block_id,
call_stack: CallStack::new(),
});

// Recompute new and changed blocks
Expand Down
19 changes: 17 additions & 2 deletions compiler/noirc_evaluator/src/ssa/ir/instruction.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use noirc_errors::Location;
use serde::{Deserialize, Serialize};
use std::hash::{Hash, Hasher};

Expand Down Expand Up @@ -808,7 +809,12 @@ pub(crate) enum TerminatorInstruction {
///
/// If the condition is true: jump to the specified `then_destination`.
/// Otherwise, jump to the specified `else_destination`.
JmpIf { condition: ValueId, then_destination: BasicBlockId, else_destination: BasicBlockId },
JmpIf {
condition: ValueId,
then_destination: BasicBlockId,
else_destination: BasicBlockId,
call_stack: CallStack,
},

/// Unconditional Jump
///
Expand All @@ -835,10 +841,11 @@ impl TerminatorInstruction {
) -> TerminatorInstruction {
use TerminatorInstruction::*;
match self {
JmpIf { condition, then_destination, else_destination } => JmpIf {
JmpIf { condition, then_destination, else_destination, call_stack } => JmpIf {
condition: f(*condition),
then_destination: *then_destination,
else_destination: *else_destination,
call_stack: call_stack.clone(),
},
Jmp { destination, arguments, call_stack } => Jmp {
destination: *destination,
Expand Down Expand Up @@ -906,6 +913,14 @@ impl TerminatorInstruction {
Return { .. } => (),
}
}

pub(crate) fn call_stack(&self) -> im::Vector<Location> {
match self {
TerminatorInstruction::JmpIf { call_stack, .. }
| TerminatorInstruction::Jmp { call_stack, .. }
| TerminatorInstruction::Return { call_stack, .. } => call_stack.clone(),
}
}
}

/// Contains the result to Instruction::simplify, specifying how the instruction
Expand Down
23 changes: 16 additions & 7 deletions compiler/noirc_evaluator/src/ssa/ir/instruction/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,14 @@ pub(super) fn simplify_call(
return SimplifyResult::SimplifiedToMultiple(vec![new_slice_length, new_slice]);
}

simplify_slice_push_back(slice, element_type, arguments, dfg, block)
simplify_slice_push_back(
slice,
element_type,
arguments,
dfg,
block,
call_stack.clone(),
)
} else {
SimplifyResult::None
}
Expand All @@ -149,7 +156,7 @@ pub(super) fn simplify_call(
Intrinsic::SlicePopBack => {
let slice = dfg.get_array_constant(arguments[1]);
if let Some((_, typ)) = slice {
simplify_slice_pop_back(typ, arguments, dfg, block)
simplify_slice_pop_back(typ, arguments, dfg, block, call_stack.clone())
} else {
SimplifyResult::None
}
Expand Down Expand Up @@ -348,12 +355,12 @@ fn simplify_slice_push_back(
arguments: &[ValueId],
dfg: &mut DataFlowGraph,
block: BasicBlockId,
call_stack: CallStack,
) -> SimplifyResult {
// The capacity must be an integer so that we can compare it against the slice length
let capacity = dfg.make_constant((slice.len() as u128).into(), Type::length_type());
let len_equals_capacity_instr =
Instruction::Binary(Binary { lhs: arguments[0], operator: BinaryOp::Eq, rhs: capacity });
let call_stack = dfg.get_value_call_stack(arguments[0]);
let len_equals_capacity = dfg
.insert_instruction_and_results(len_equals_capacity_instr, block, None, call_stack.clone())
.first();
Expand Down Expand Up @@ -384,15 +391,16 @@ fn simplify_slice_push_back(
};

let set_last_slice_value = dfg
.insert_instruction_and_results(set_last_slice_value_instr, block, None, call_stack)
.insert_instruction_and_results(set_last_slice_value_instr, block, None, call_stack.clone())
.first();

let mut slice_sizes = HashMap::default();
slice_sizes.insert(set_last_slice_value, slice_size / element_size);
slice_sizes.insert(new_slice, slice_size / element_size);

let unknown = &mut HashMap::default();
let mut value_merger = ValueMerger::new(dfg, block, &mut slice_sizes, unknown, None);
let mut value_merger =
ValueMerger::new(dfg, block, &mut slice_sizes, unknown, None, call_stack);

let new_slice = value_merger.merge_values(
len_not_equals_capacity,
Expand All @@ -409,6 +417,7 @@ fn simplify_slice_pop_back(
arguments: &[ValueId],
dfg: &mut DataFlowGraph,
block: BasicBlockId,
call_stack: CallStack,
) -> SimplifyResult {
let element_types = match element_type.clone() {
Type::Slice(element_types) | Type::Array(element_types, _) => element_types,
Expand All @@ -425,7 +434,7 @@ fn simplify_slice_pop_back(
let element_size = dfg.make_constant((element_count as u128).into(), Type::length_type());
let flattened_len_instr = Instruction::binary(BinaryOp::Mul, arguments[0], element_size);
let mut flattened_len = dfg
.insert_instruction_and_results(flattened_len_instr, block, None, CallStack::new())
.insert_instruction_and_results(flattened_len_instr, block, None, call_stack.clone())
.first();
flattened_len = update_slice_length(flattened_len, dfg, BinaryOp::Sub, block);

Expand All @@ -438,7 +447,7 @@ fn simplify_slice_pop_back(
get_last_elem_instr,
block,
Some(element_types.to_vec()),
CallStack::new(),
call_stack.clone(),
)
.first();
results.push_front(get_last_elem);
Expand Down
7 changes: 6 additions & 1 deletion compiler/noirc_evaluator/src/ssa/ir/printer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,12 @@ pub(crate) fn display_terminator(
Some(TerminatorInstruction::Jmp { destination, arguments, call_stack: _ }) => {
writeln!(f, " jmp {}({})", destination, value_list(function, arguments))
}
Some(TerminatorInstruction::JmpIf { condition, then_destination, else_destination }) => {
Some(TerminatorInstruction::JmpIf {
condition,
then_destination,
else_destination,
call_stack: _,
}) => {
writeln!(
f,
" jmpif {} then: {}, else: {}",
Expand Down
Loading

0 comments on commit 986f69c

Please sign in to comment.