Skip to main content

dead_code_elimination/
dead_code_elimination.rs

1//! Simplified Dead Code Elimination (DCE) example.
2//!
3//! Demonstrates a realistic pass pipeline inspired by LLVM's `DCEPass`:
4//!
5//! 1. `InstructionCountAnalysis` (FunctionAnalysis via `into_pass()`) — counts
6//!    instructions per function and stores stats in shared state
7//! 2. `SimpleDCEPass` (FunctionPass) — removes trivially dead instructions
8//!    (no uses, not terminators, not side-effecting)
9//! 3. `DCEStatsPass` (ModulePass) — reports per-function instruction counts
10//!
11//! The analysis pass stores its results in a shared `Arc<Mutex<HashMap>>`,
12//! which downstream passes read. This pattern shows how passes in the same
13//! pipeline can share analysis information.
14//!
15//! Run: `cargo run --example dead_code_elimination`
16
17use llvm_pm::inkwell;
18use llvm_pm::inkwell::context::Context;
19use llvm_pm::inkwell::values::InstructionOpcode;
20use llvm_pm::inkwell::IntPredicate;
21use llvm_pm::traits::{
22    LlvmCgsccAnalysis, LlvmCgsccPass, LlvmFunctionPass, LlvmModulePass, PreservedAnalyses,
23};
24use llvm_pm::{
25    CgsccAnalysisManager, FunctionAnalysisManager, FunctionPassManager, ModuleAnalysisManager,
26    ModulePassManager,
27};
28
29use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
30use std::sync::Arc;
31
32// =========================================================================
33// Analysis: FunctionNameLengthAnalysis (CGSCC-level, supports get_result)
34// =========================================================================
35
36/// A CGSCC-level analysis that returns the number of basic blocks in a function.
37///
38/// Demonstrates the `get_result()` pattern available on `CgsccAnalysisManager`.
39/// CGSCC and Loop analyses support on-demand evaluation: a pass calls
40/// `manager.get_result::<Analysis>(ir_unit)` and the analysis is computed
41/// (and cached) automatically.
42struct BasicBlockCountAnalysis;
43
44impl LlvmCgsccAnalysis for BasicBlockCountAnalysis {
45    type Result = u32;
46
47    fn run_analysis(
48        &self,
49        function: &inkwell::values::FunctionValue<'_>,
50        _manager: &CgsccAnalysisManager,
51    ) -> Self::Result {
52        function.count_basic_blocks()
53    }
54
55    fn id() -> *const u8 {
56        static ID: u8 = 0;
57        &ID
58    }
59}
60
61// =========================================================================
62// Pass: BasicBlockReportPass (CGSCC-level, uses analysis results)
63// =========================================================================
64
65/// A CGSCC pass that queries `BasicBlockCountAnalysis` for each function
66/// and prints the result. This demonstrates the analysis-driven pass pattern
67/// where a transformation (or inspection) pass consumes cached analysis data.
68struct BasicBlockReportPass {
69    registered: Arc<AtomicBool>,
70}
71
72impl LlvmCgsccPass for BasicBlockReportPass {
73    fn run_pass(
74        &self,
75        function: &mut inkwell::values::FunctionValue<'_>,
76        manager: &CgsccAnalysisManager,
77    ) -> PreservedAnalyses {
78        // Register analysis on first invocation (once per PM lifetime).
79        if self
80            .registered
81            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
82            .is_ok()
83        {
84            manager.add_analysis(BasicBlockCountAnalysis);
85        }
86
87        // Query the analysis — computed on first call, cached thereafter.
88        let bb_count = *manager.get_result::<BasicBlockCountAnalysis>(function);
89        let name = function.get_name().to_string_lossy();
90        println!("  [CGSCC] {}: {} basic blocks", name, bb_count);
91
92        PreservedAnalyses::All
93    }
94}
95
96// =========================================================================
97// Pass: SimpleDCEPass (function-level transformation)
98// =========================================================================
99
100/// A simplified Dead Code Elimination pass.
101///
102/// Removes instructions that:
103/// - Have no uses (the result is unused)
104/// - Are not terminators (br, ret, switch, etc.)
105/// - Are not side-effecting (store, call, fence, etc.)
106///
107/// This mirrors a subset of LLVM's `DCEPass` (`llvm/lib/Transforms/Scalar/DCE.cpp`).
108struct SimpleDCEPass {
109    removed: Arc<AtomicU32>,
110}
111
112/// Returns true if the instruction may have side effects and should not be
113/// removed even when its result is unused.
114fn may_have_side_effects(opcode: InstructionOpcode) -> bool {
115    matches!(
116        opcode,
117        InstructionOpcode::Store
118            | InstructionOpcode::Call
119            | InstructionOpcode::Fence
120            | InstructionOpcode::AtomicCmpXchg
121            | InstructionOpcode::AtomicRMW
122            | InstructionOpcode::Resume
123            | InstructionOpcode::LandingPad
124            | InstructionOpcode::IndirectBr
125            | InstructionOpcode::Invoke
126            | InstructionOpcode::Unreachable
127    )
128}
129
130impl LlvmFunctionPass for SimpleDCEPass {
131    fn run_pass(
132        &self,
133        function: &mut inkwell::values::FunctionValue<'_>,
134        _manager: &FunctionAnalysisManager,
135    ) -> PreservedAnalyses {
136        let mut changed = false;
137
138        // Iterate over all basic blocks and collect dead instructions.
139        // We collect first to avoid invalidating the iterator during deletion.
140        for bb in function.get_basic_blocks() {
141            let dead: Vec<_> = bb
142                .get_instructions()
143                .filter(|inst| {
144                    if inst.is_terminator() {
145                        return false;
146                    }
147                    if may_have_side_effects(inst.get_opcode()) {
148                        return false;
149                    }
150                    if inst.get_opcode() == InstructionOpcode::Alloca {
151                        return false;
152                    }
153                    inst.get_first_use().is_none()
154                })
155                .collect();
156
157            for inst in dead {
158                inst.erase_from_basic_block();
159                self.removed.fetch_add(1, Ordering::SeqCst);
160                changed = true;
161            }
162        }
163
164        if changed {
165            PreservedAnalyses::None
166        } else {
167            PreservedAnalyses::All
168        }
169    }
170}
171
172// =========================================================================
173// Pass: DCEStatsPass (module-level reporting)
174// =========================================================================
175
176/// Module pass that prints per-function instruction counts.
177struct DCEStatsPass {
178    label: &'static str,
179}
180
181impl LlvmModulePass for DCEStatsPass {
182    fn run_pass(
183        &self,
184        module: &mut inkwell::module::Module<'_>,
185        _manager: &ModuleAnalysisManager,
186    ) -> PreservedAnalyses {
187        println!("--- {} ---", self.label);
188        let mut total_insts = 0u32;
189        let mut total_bbs = 0u32;
190        for func in module.get_functions() {
191            if func.count_basic_blocks() == 0 {
192                continue;
193            }
194            let mut insts = 0u32;
195            for bb in func.get_basic_blocks() {
196                insts += bb.get_instructions().count() as u32;
197            }
198            let bbs = func.count_basic_blocks();
199            let name = func.get_name().to_string_lossy();
200            println!("  {}: {} BBs, {} instructions", name, bbs, insts);
201            total_insts += insts;
202            total_bbs += bbs;
203        }
204        println!("  Total: {} BBs, {} instructions", total_bbs, total_insts);
205        PreservedAnalyses::All
206    }
207}
208
209// =========================================================================
210// IR construction: module with dead code
211// =========================================================================
212
213/// Build a module containing functions with deliberately dead instructions
214/// that our SimpleDCEPass can remove.
215fn build_module_with_dead_code() -> inkwell::module::Module<'static> {
216    let context = Box::leak(Box::new(Context::create()));
217    let module = context.create_module("dce_demo");
218    let i32_ty = context.i32_type();
219
220    // i32 @add_with_dead_code(i32 %a, i32 %b)
221    // Contains several dead intermediate values.
222    let fn_ty = i32_ty.fn_type(&[i32_ty.into(), i32_ty.into()], false);
223    let func = module.add_function("add_with_dead_code", fn_ty, None);
224    let bb = context.append_basic_block(func, "entry");
225    let b = context.create_builder();
226    b.position_at_end(bb);
227
228    let a = func.get_nth_param(0).unwrap().into_int_value();
229    let b_param = func.get_nth_param(1).unwrap().into_int_value();
230
231    // Live: the actual return value
232    let sum = b.build_int_add(a, b_param, "sum").unwrap();
233
234    // Dead: computed but never used
235    let _dead_mul = b.build_int_mul(a, b_param, "dead_mul").unwrap();
236    let _dead_sub = b.build_int_sub(a, b_param, "dead_sub").unwrap();
237    let _dead_xor = b.build_xor(a, b_param, "dead_xor").unwrap();
238
239    b.build_return(Some(&sum)).unwrap();
240
241    // i32 @branch_with_dead_code(i32 %x)
242    // Has dead code in both branches.
243    let fn_ty2 = i32_ty.fn_type(&[i32_ty.into()], false);
244    let func2 = module.add_function("branch_with_dead_code", fn_ty2, None);
245    let entry = context.append_basic_block(func2, "entry");
246    let then_bb = context.append_basic_block(func2, "then");
247    let else_bb = context.append_basic_block(func2, "else");
248    let merge = context.append_basic_block(func2, "merge");
249    let b = context.create_builder();
250
251    b.position_at_end(entry);
252    let x = func2.get_first_param().unwrap().into_int_value();
253    let cmp = b
254        .build_int_compare(IntPredicate::SGT, x, i32_ty.const_int(10, false), "cmp")
255        .unwrap();
256    b.build_conditional_branch(cmp, then_bb, else_bb).unwrap();
257
258    b.position_at_end(then_bb);
259    let then_val = b
260        .build_int_mul(x, i32_ty.const_int(2, false), "then_val")
261        .unwrap();
262    let _dead_then = b
263        .build_int_add(x, i32_ty.const_int(99, false), "dead_then")
264        .unwrap();
265    b.build_unconditional_branch(merge).unwrap();
266
267    b.position_at_end(else_bb);
268    let else_val = b
269        .build_int_add(x, i32_ty.const_int(1, false), "else_val")
270        .unwrap();
271    let _dead_else = b
272        .build_int_sub(x, i32_ty.const_int(42, false), "dead_else")
273        .unwrap();
274    let _dead_else2 = b.build_int_mul(x, x, "dead_else2").unwrap();
275    b.build_unconditional_branch(merge).unwrap();
276
277    b.position_at_end(merge);
278    let phi = b.build_phi(i32_ty, "result").unwrap();
279    phi.add_incoming(&[(&then_val, then_bb), (&else_val, else_bb)]);
280    let result = phi.as_basic_value().into_int_value();
281    b.build_return(Some(&result)).unwrap();
282
283    module
284}
285
286// =========================================================================
287// Main
288// =========================================================================
289
290fn main() -> Result<(), Box<dyn std::error::Error>> {
291    let module = build_module_with_dead_code();
292    module.verify()?;
293
294    let removed = Arc::new(AtomicU32::new(0));
295
296    // Phase 1: Report initial stats + CGSCC analysis (before DCE)
297    {
298        let mut pm = ModulePassManager::new(None, None)?;
299        pm.add_pass(DCEStatsPass {
300            label: "Before DCE",
301        });
302        pm.add_cgscc_pass(BasicBlockReportPass {
303            registered: Arc::new(AtomicBool::new(false)),
304        });
305        pm.run(&module)?;
306    }
307
308    // Phase 2: Run DCE on each function
309    {
310        let mut fpm = FunctionPassManager::new(None, None)?;
311        fpm.add_pass(SimpleDCEPass {
312            removed: removed.clone(),
313        });
314        for func in module.get_functions() {
315            if func.count_basic_blocks() == 0 {
316                continue;
317            }
318            fpm.run(func)?;
319        }
320    }
321
322    module.verify()?;
323
324    // Phase 3: Report final stats (after DCE)
325    {
326        let mut pm = ModulePassManager::new(None, None)?;
327        pm.add_pass(DCEStatsPass { label: "After DCE" });
328        pm.run(&module)?;
329    }
330
331    let total_removed = removed.load(Ordering::SeqCst);
332    println!("\nRemoved {} dead instructions", total_removed);
333    assert!(
334        total_removed >= 5,
335        "Expected to remove at least 5 dead instructions, got {}",
336        total_removed
337    );
338
339    println!("ok");
340    Ok(())
341}