leo_passes/ssa_const_propagation/mod.rs
1// Copyright (C) 2019-2025 Provable Inc.
2// This file is part of the Leo library.
3
4// The Leo library is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// The Leo library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
16
17//! The SSA Const Propagation pass propagates constant values through the program.
18//! This pass runs after SSA formation, so each variable has a unique name.
19//!
20//! The pass tracks variables that are assigned literal values and replaces
21//! uses of those variables with their constant values.
22
23use crate::Pass;
24
25use leo_ast::ProgramReconstructor as _;
26use leo_errors::Result;
27
28mod ast;
29
30mod program;
31
32mod visitor;
33pub use visitor::SsaConstPropagationVisitor;
34
35pub struct SsaConstPropagation;
36
37impl Pass for SsaConstPropagation {
38 type Input = ();
39 type Output = ();
40
41 const NAME: &str = "SsaConstPropagation";
42
43 fn do_pass(_input: Self::Input, state: &mut crate::CompilerState) -> Result<Self::Output> {
44 // Run the pass in a loop until no changes are made.
45 for _ in 0..1024 {
46 let mut ast = std::mem::take(&mut state.ast);
47 let mut visitor = SsaConstPropagationVisitor { state, constants: Default::default(), changed: false };
48 ast.ast = visitor.reconstruct_program(ast.ast);
49 visitor.state.handler.last_err()?;
50 visitor.state.ast = ast;
51
52 // If no changes were made, we're done.
53 if !visitor.changed {
54 return Ok(());
55 }
56 }
57 panic!("ran out of loops");
58 }
59}