Skip to main content

js2zig_core/zigir/passes/
dead_code.rs

1// zigir/passes/dead_code.rs
2// DeadCodeElimPass — removes unreachable code and unused top-level declarations.
3//
4// Three elimination strategies:
5//   1. Unreachable code after Return/Break/Continue/Throw in a block
6//   2. After @compileError: keep subsequent @compileError statements, remove the rest
7//   3. VarDecl with CompileError init → convert to IrStmt::CompileError
8//   4. Unused top-level variable declarations (const with no references)
9
10use crate::zigir::passes::{IrPass, PassResult};
11use crate::zigir::types::{IrAssignTarget, IrBlock, IrDecl, IrExpr, IrModule, IrStmt};
12
13use std::cell::RefCell;
14
15use super::{collect_idents, walk};
16
17/// Dead code elimination pass.
18///
19/// Removes:
20/// - Statements after Return/Break/Continue/Throw in blocks
21/// - After @compileError: keeps subsequent @compileError, removes other statements
22/// - VarDecl with CompileError init → IrStmt::CompileError
23/// - Unused top-level const variable declarations
24pub struct DeadCodeElimPass;
25
26/// Remove statements after the first terminator in a list.
27/// Returns true if any statements were removed.
28fn truncate_after_terminator(stmts: &mut Vec<IrStmt>) -> bool {
29    let terminator_idx = stmts.iter().position(is_terminator);
30    if let Some(idx) = terminator_idx {
31        let remaining = stmts.len() - idx - 1;
32        if remaining > 0 {
33            stmts.truncate(idx + 1);
34            return true;
35        }
36    }
37    false
38}
39
40/// After the first `IrStmt::CompileError`, merge any subsequent `IrStmt::CompileError`
41/// messages into the first one and remove all other statements. This eliminates
42/// "unreachable code" noise in the generated Zig output — Zig treats ALL code
43/// after `@compileError` as unreachable, even another `@compileError`.
44///
45/// Returns true if any statements were removed or merged.
46fn truncate_after_compile_error(stmts: &mut Vec<IrStmt>) -> bool {
47    let first_ce_idx = stmts.iter().position(is_compile_error_stmt);
48    if let Some(idx) = first_ce_idx {
49        let original_len = stmts.len();
50        if idx + 1 >= original_len {
51            return false; // nothing after the first compile error
52        }
53        // Collect additional messages from subsequent CompileError statements
54        let mut extra_msgs: Vec<String> = Vec::new();
55        for stmt in stmts.iter().skip(idx + 1) {
56            if let IrStmt::CompileError { msg, .. } = stmt {
57                extra_msgs.push(msg.clone());
58            }
59        }
60        // Merge extra messages into the first CompileError
61        if !extra_msgs.is_empty()
62            && let IrStmt::CompileError { msg, .. } = &mut stmts[idx]
63        {
64            msg.push_str("\n\nAlso: ");
65            msg.push_str(&extra_msgs.join("\nAlso: "));
66        }
67        // Truncate: keep only up to and including the first CompileError
68        stmts.truncate(idx + 1);
69        true
70    } else {
71        false
72    }
73}
74
75/// Check if a statement is `IrStmt::CompileError`.
76fn is_compile_error_stmt(stmt: &IrStmt) -> bool {
77    matches!(stmt, IrStmt::CompileError { .. })
78}
79
80/// Check if an expression is `IrExpr::CompileError`.
81fn is_compile_error_expr(expr: &IrExpr) -> bool {
82    matches!(expr, IrExpr::CompileError { .. })
83}
84
85/// Convert `IrStmt::VarDecl` with a `CompileError` init into `IrStmt::CompileError`.
86/// This handles patterns like `const r = @compileError("Unsupported NewExpression")`
87/// which would otherwise emit `const r = @compileError(...)` — valid Zig but produces
88/// "unreachable code" noise for subsequent statements referencing the variable.
89///
90/// Also converts `IrStmt::Return { value: Some(CompileError) }` into
91/// `IrStmt::CompileError`. Emitting `return @compileError(...)` is syntactically
92/// valid Zig, but `@compileError` has type `noreturn`, making the `return` keyword
93/// itself unreachable code — `zig ast-check` flags this.
94///
95/// Returns true if any conversions were made.
96fn convert_vardecl_compile_error(stmts: &mut [IrStmt]) -> bool {
97    use crate::zigir::source_span::SourceSpan;
98
99    // Phase 1: identify indices of VarDecls with CompileError init
100    // and Returns with CompileError value
101    let indices: Vec<usize> = stmts
102        .iter()
103        .enumerate()
104        .filter_map(|(i, stmt)| match stmt {
105            IrStmt::VarDecl(vd) if vd.init.as_ref().is_some_and(is_compile_error_expr) => Some(i),
106            IrStmt::Return { value } if value.as_ref().is_some_and(is_compile_error_expr) => {
107                Some(i)
108            }
109            _ => None,
110        })
111        .collect();
112
113    if indices.is_empty() {
114        return false;
115    }
116
117    // Phase 2: convert those statements to IrStmt::CompileError
118    for i in indices {
119        let old_stmt = std::mem::replace(
120            &mut stmts[i],
121            IrStmt::CompileError {
122                span: SourceSpan::default(),
123                msg: String::new(),
124            },
125        );
126        let msg = match old_stmt {
127            IrStmt::VarDecl(vd) => {
128                if let Some(IrExpr::CompileError { msg, .. }) = vd.init {
129                    msg
130                } else {
131                    String::new()
132                }
133            }
134            IrStmt::Return { value } => {
135                if let Some(IrExpr::CompileError { msg, .. }) = value {
136                    msg
137                } else {
138                    String::new()
139                }
140            }
141            _ => String::new(),
142        };
143        if let IrStmt::CompileError { span, msg: old_msg } = &mut stmts[i] {
144            *old_msg = msg;
145            // Keep the default span since we extracted from deconstructed stmt
146            let _ = span;
147        }
148    }
149    true
150}
151
152impl DeadCodeElimPass {
153    pub fn new() -> Self {
154        Self
155    }
156
157    /// Remove unreachable statements after a terminator in a block.
158    /// Returns true if any statements were removed.
159    fn eliminate_unreachable_in_block(block: &mut IrBlock) -> bool {
160        let mut changed = false;
161
162        // Phase 1: Convert VarDecl with CompileError init → IrStmt::CompileError
163        if convert_vardecl_compile_error(&mut block.stmts) {
164            changed = true;
165        }
166
167        // Phase 2: After a CompileError, keep subsequent CompileError stmts only
168        if truncate_after_compile_error(&mut block.stmts) {
169            changed = true;
170        }
171
172        // Phase 3: Find and truncate after the first traditional terminator
173        if truncate_after_terminator(&mut block.stmts) {
174            changed = true;
175        }
176
177        // Recurse into sub-blocks
178        for stmt in &mut block.stmts {
179            if eliminate_unreachable_in_stmt(stmt) {
180                changed = true;
181            }
182        }
183
184        changed
185    }
186
187    /// Remove unused top-level const declarations.
188    /// A const is "unused" if it has no side effects and is never referenced.
189    /// Returns true if any declarations were removed.
190    fn eliminate_unused_decls(module: &mut IrModule) -> bool {
191        // Collect all identifier references across the entire module
192        let mut referenced = std::collections::HashSet::new();
193
194        for decl in &module.declarations {
195            collect_idents::collect_decl_idents(decl, &mut referenced);
196        }
197        for cs in &module.closure_structs {
198            collect_idents::collect_block_idents(&cs.body, &mut referenced);
199        }
200
201        // Remove unused const declarations
202        let before = module.declarations.len();
203        module.declarations.retain(|decl| {
204            if let IrDecl::Var(v) = decl {
205                // Only remove const vars that are never referenced and have
206                // no side effects in their initializer
207                if v.is_const && !referenced.contains(&v.name.zig_name) && !v.is_json_parse {
208                    // Check if the init expression has side effects
209                    if let Some(init) = &v.init {
210                        if !expr_has_side_effects(init) {
211                            return false; // remove it
212                        }
213                    } else {
214                        return false; // no init, no side effects, remove
215                    }
216                }
217            }
218            true
219        });
220
221        module.declarations.len() != before
222    }
223}
224
225impl IrPass for DeadCodeElimPass {
226    fn name(&self) -> &'static str {
227        "dead-code-elim"
228    }
229
230    fn description(&self) -> &'static str {
231        "Removes unreachable code after terminators and unused top-level const declarations"
232    }
233
234    fn run(&mut self, module: &mut IrModule) -> PassResult {
235        let mut changed = false;
236
237        // Pass 1: Remove unreachable code in all blocks
238        for decl in &mut module.declarations {
239            if eliminate_unreachable_in_decl(decl) {
240                changed = true;
241            }
242        }
243        for cs in &mut module.closure_structs {
244            if Self::eliminate_unreachable_in_block(&mut cs.body) {
245                changed = true;
246            }
247        }
248
249        // Pass 2: Remove unused top-level declarations
250        if Self::eliminate_unused_decls(module) {
251            changed = true;
252        }
253
254        if changed {
255            PassResult::changed()
256        } else {
257            PassResult::unchanged()
258        }
259    }
260}
261
262impl Default for DeadCodeElimPass {
263    fn default() -> Self {
264        Self::new()
265    }
266}
267
268// ═══════════════════════════════════════════════════════
269//  Helpers
270// ═══════════════════════════════════════════════════════
271
272/// Whether a statement is a control flow terminator (after which nothing runs).
273fn is_terminator(stmt: &IrStmt) -> bool {
274    matches!(
275        stmt,
276        IrStmt::Return { .. }
277            | IrStmt::Break { .. }
278            | IrStmt::Continue { .. }
279            | IrStmt::Throw { .. }
280    )
281}
282
283/// Whether an expression may have side effects (function calls, assignments, etc.).
284fn expr_has_side_effects(expr: &IrExpr) -> bool {
285    // CompileError represents a Zig `@compileError` diagnostic that must
286    // always reach the Zig output. It MUST NOT be eliminated as dead —
287    // otherwise users silently lose diagnostics for unsupported constructs
288    // (e.g. `const X = someUnsupportedThing();` where X is unused would
289    // have its CompileError init stripped by eliminate_unused_decls).
290    // Check this BEFORE the is_leaf() short-circuit below, because
291    // `is_leaf()` currently classifies CompileError as a leaf (no
292    // sub-expressions), which would cause it to be treated as side-effect-free.
293    if matches!(expr, IrExpr::CompileError { .. }) {
294        return true;
295    }
296    if expr.is_leaf() {
297        return false;
298    }
299    match expr {
300        IrExpr::Call(_) | IrExpr::BuiltinCall(_) | IrExpr::HostCall(_) => true,
301        IrExpr::Assign { .. } | IrExpr::Update { .. } => true,
302        IrExpr::New(_) => true,
303        IrExpr::Await(_) => true,
304
305        IrExpr::Binary { left, right, .. } => {
306            expr_has_side_effects(left) || expr_has_side_effects(right)
307        }
308        IrExpr::Unary { operand, .. } => expr_has_side_effects(operand),
309        IrExpr::Logical { left, right, .. } => {
310            expr_has_side_effects(left) || expr_has_side_effects(right)
311        }
312        IrExpr::Conditional { cond, then, else_ } => {
313            expr_has_side_effects(cond)
314                || expr_has_side_effects(then)
315                || expr_has_side_effects(else_)
316        }
317        IrExpr::FieldAccess { object, .. } => expr_has_side_effects(object),
318        IrExpr::IndexAccess { object, index, .. } => {
319            expr_has_side_effects(object) || expr_has_side_effects(index)
320        }
321        IrExpr::ComputedField { object, key, .. } => {
322            expr_has_side_effects(object) || expr_has_side_effects(key)
323        }
324        IrExpr::ArrayLiteral(arr) => arr.elements.iter().any(expr_has_side_effects),
325        IrExpr::ObjectLiteral(obj) => {
326            use crate::zigir::types::IrObjectItem;
327            obj.items.iter().any(|item| match item {
328                IrObjectItem::Field(f) => expr_has_side_effects(&f.value),
329                IrObjectItem::Spread(e) => expr_has_side_effects(e),
330            })
331        }
332        IrExpr::TemplateLiteral { exprs, .. } => exprs.iter().any(expr_has_side_effects),
333        IrExpr::Closure(_) | IrExpr::ArrowFn(_) | IrExpr::FnExpr(_) => false,
334        IrExpr::BlockExpr { body, result, .. } => {
335            body.iter().any(stmt_has_side_effects) || expr_has_side_effects(result)
336        }
337        IrExpr::AllocPrint { args, .. } => args.iter().any(expr_has_side_effects),
338        IrExpr::Spread(e) | IrExpr::Typeof(e) | IrExpr::Void(e) | IrExpr::Paren(e) => {
339            expr_has_side_effects(e)
340        }
341        IrExpr::Sequence(exprs) => exprs.iter().any(expr_has_side_effects),
342        IrExpr::ArrayCallbackInline(inline_data) => {
343            inline_data.body.iter().any(stmt_has_side_effects)
344                || inline_data
345                    .obj_expr
346                    .as_ref()
347                    .is_some_and(|e| expr_has_side_effects(e))
348        }
349        IrExpr::ArrayMethodInline(inline_data) => {
350            // All array method inlines have side effects (loops, allocs, mutations)
351            let _ = inline_data;
352            true
353        }
354        IrExpr::OptionalChain {
355            object,
356            body,
357            needs_null_check,
358            ..
359        } => expr_has_side_effects(object) || (*needs_null_check || expr_has_side_effects(body)),
360        IrExpr::PowExpr { base, exp, .. } => {
361            expr_has_side_effects(base) || expr_has_side_effects(exp)
362        }
363        IrExpr::RemExpr { left, right, .. } => {
364            expr_has_side_effects(left) || expr_has_side_effects(right)
365        }
366        IrExpr::DivExpr { left, right, .. } => {
367            expr_has_side_effects(left) || expr_has_side_effects(right)
368        }
369        IrExpr::CompileError { .. } => true,
370        // Leaf expressions handled by is_leaf() early return above
371        _ => false,
372    }
373}
374
375/// Whether a statement has side effects.
376fn stmt_has_side_effects(stmt: &IrStmt) -> bool {
377    match stmt {
378        IrStmt::VarDecl(v) => v.init.as_ref().is_some_and(expr_has_side_effects),
379        IrStmt::Assign { .. } | IrStmt::Throw { .. } | IrStmt::Return { .. } => true,
380        IrStmt::Expr(e) => expr_has_side_effects(e),
381        IrStmt::If { cond, then, else_ } => {
382            expr_has_side_effects(cond)
383                || then.stmts.iter().any(stmt_has_side_effects)
384                || else_
385                    .as_ref()
386                    .is_some_and(|e| e.stmts.iter().any(stmt_has_side_effects))
387        }
388        IrStmt::While { cond, body, .. } => {
389            expr_has_side_effects(cond) || body.stmts.iter().any(stmt_has_side_effects)
390        }
391        IrStmt::DoWhile { body, cond, .. } => {
392            body.stmts.iter().any(stmt_has_side_effects) || expr_has_side_effects(cond)
393        }
394        IrStmt::For {
395            init,
396            cond,
397            update,
398            body,
399            ..
400        } => {
401            init.as_ref().is_some_and(|s| stmt_has_side_effects(s))
402                || cond.as_ref().is_some_and(expr_has_side_effects)
403                || update.as_ref().is_some_and(|s| stmt_has_side_effects(s))
404                || body.stmts.iter().any(stmt_has_side_effects)
405        }
406        IrStmt::Switch { expr, cases } => {
407            expr_has_side_effects(expr)
408                || cases
409                    .iter()
410                    .any(|c| c.body.iter().any(stmt_has_side_effects))
411        }
412        IrStmt::Try {
413            try_block,
414            catch_block,
415            finally,
416            ..
417        } => {
418            try_block.stmts.iter().any(stmt_has_side_effects)
419                || catch_block.stmts.iter().any(stmt_has_side_effects)
420                || finally
421                    .as_ref()
422                    .is_some_and(|f| f.stmts.iter().any(stmt_has_side_effects))
423        }
424        IrStmt::Break { .. } | IrStmt::Continue { .. } => true,
425        IrStmt::Block(b) => b.stmts.iter().any(stmt_has_side_effects),
426        IrStmt::ForIn { iterable, body, .. } => {
427            expr_has_side_effects(iterable) || body.stmts.iter().any(stmt_has_side_effects)
428        }
429        IrStmt::ForOf { iterable, body, .. } => {
430            expr_has_side_effects(iterable) || body.stmts.iter().any(stmt_has_side_effects)
431        }
432        // CompileError must be preserved: it carries a compile-time
433        // diagnostic that needs to surface to the user. Treating it as
434        // side-effect-free would let dead-code elimination drop it (and any
435        // preceding statements that the error is meant to flag).
436        IrStmt::CompileError { .. } => true,
437        IrStmt::Comment(_) => false,
438        IrStmt::DestructureDecl(data) => expr_has_side_effects(&data.init),
439        IrStmt::NestedFnDecl { .. } => true,
440    }
441}
442
443fn eliminate_unreachable_in_decl(decl: &mut IrDecl) -> bool {
444    let changed = RefCell::new(false);
445    walk::for_each_decl_child_mut(
446        decl,
447        &mut |block| {
448            *changed.borrow_mut() |= DeadCodeElimPass::eliminate_unreachable_in_block(block);
449        },
450        &mut |expr| {
451            *changed.borrow_mut() |= eliminate_unreachable_in_expr(expr);
452        },
453    );
454    changed.into_inner()
455}
456
457fn eliminate_unreachable_in_target(target: &mut IrAssignTarget) -> bool {
458    let mut changed = false;
459    walk::for_each_target_child_mut(target, &mut |expr| {
460        changed |= eliminate_unreachable_in_expr(expr);
461    });
462    changed
463}
464
465fn eliminate_unreachable_in_stmt(stmt: &mut IrStmt) -> bool {
466    match stmt {
467        IrStmt::VarDecl(v) => {
468            if let Some(e) = &mut v.init {
469                eliminate_unreachable_in_expr(e)
470            } else {
471                false
472            }
473        }
474        IrStmt::If { then, else_, .. } => {
475            let mut changed = false;
476            if DeadCodeElimPass::eliminate_unreachable_in_block(then) {
477                changed = true;
478            }
479            if let Some(e) = else_
480                && DeadCodeElimPass::eliminate_unreachable_in_block(e)
481            {
482                changed = true;
483            }
484            changed
485        }
486        IrStmt::While { body, .. } => DeadCodeElimPass::eliminate_unreachable_in_block(body),
487        IrStmt::DoWhile { body, .. } => DeadCodeElimPass::eliminate_unreachable_in_block(body),
488        IrStmt::For {
489            init, update, body, ..
490        } => {
491            let mut changed = false;
492            if let Some(i) = init
493                && eliminate_unreachable_in_stmt(i)
494            {
495                changed = true;
496            }
497            if let Some(u) = update
498                && eliminate_unreachable_in_stmt(u)
499            {
500                changed = true;
501            }
502            if DeadCodeElimPass::eliminate_unreachable_in_block(body) {
503                changed = true;
504            }
505            changed
506        }
507        IrStmt::ForIn { body, .. } => DeadCodeElimPass::eliminate_unreachable_in_block(body),
508        IrStmt::ForOf { body, .. } => DeadCodeElimPass::eliminate_unreachable_in_block(body),
509        IrStmt::Switch { cases, .. } => {
510            let mut changed = false;
511            for case in cases {
512                // Cases use Vec<IrStmt>, not IrBlock
513                if truncate_after_terminator(&mut case.body) {
514                    changed = true;
515                }
516                for s in &mut case.body {
517                    if eliminate_unreachable_in_stmt(s) {
518                        changed = true;
519                    }
520                }
521            }
522            changed
523        }
524        IrStmt::Try {
525            try_block,
526            catch_block,
527            finally,
528            ..
529        } => {
530            let mut changed = false;
531            if DeadCodeElimPass::eliminate_unreachable_in_block(try_block) {
532                changed = true;
533            }
534            if DeadCodeElimPass::eliminate_unreachable_in_block(catch_block) {
535                changed = true;
536            }
537            if let Some(f) = finally
538                && DeadCodeElimPass::eliminate_unreachable_in_block(f)
539            {
540                changed = true;
541            }
542            changed
543        }
544        IrStmt::Block(b) => DeadCodeElimPass::eliminate_unreachable_in_block(b),
545        IrStmt::Assign { value, .. } => eliminate_unreachable_in_expr(value),
546        IrStmt::Throw { value, .. } => eliminate_unreachable_in_expr(value),
547        IrStmt::Return { value } => {
548            if let Some(v) = value {
549                eliminate_unreachable_in_expr(v)
550            } else {
551                false
552            }
553        }
554        IrStmt::Expr(e) => eliminate_unreachable_in_expr(e),
555        IrStmt::Break { .. }
556        | IrStmt::Continue { .. }
557        | IrStmt::CompileError { .. }
558        | IrStmt::Comment(_) => false,
559        IrStmt::DestructureDecl(data) => eliminate_unreachable_in_expr(&mut data.init),
560        IrStmt::NestedFnDecl {
561            struct_def,
562            instance,
563        } => {
564            let mut changed =
565                DeadCodeElimPass::eliminate_unreachable_in_block(&mut struct_def.body);
566            if let Some(inst) = instance {
567                changed |= DeadCodeElimPass::eliminate_unreachable_in_block(&mut inst.body);
568            }
569            changed
570        }
571    }
572}
573
574fn eliminate_unreachable_in_expr(expr: &mut IrExpr) -> bool {
575    // Special case: BlockExpr needs truncate_before recursion + result visit
576    if let IrExpr::BlockExpr { body, result, .. } = expr {
577        let mut changed = false;
578        if truncate_after_terminator(body) {
579            changed = true;
580        }
581        for s in &mut *body {
582            if eliminate_unreachable_in_stmt(s) {
583                changed = true;
584            }
585        }
586        if eliminate_unreachable_in_expr(result) {
587            changed = true;
588        }
589        return changed;
590    }
591
592    // Standard walk for all other variants.
593    // Note: walk.rs visits BuiltinCall.obj_expr, ArrayCallbackInline.reduce_init,
594    // and Assign/Update targets — these were previously missed; visiting them
595    // is a correctness improvement (eliminates unreachable code in those sub-trees).
596    let changed = RefCell::new(false);
597    walk::for_each_expr_child_mut(
598        expr,
599        &mut |block| {
600            *changed.borrow_mut() |= DeadCodeElimPass::eliminate_unreachable_in_block(block);
601        },
602        &mut |stmt| {
603            *changed.borrow_mut() |= eliminate_unreachable_in_stmt(stmt);
604        },
605        &mut |expr| {
606            *changed.borrow_mut() |= eliminate_unreachable_in_expr(expr);
607        },
608        &mut |target| {
609            *changed.borrow_mut() |= eliminate_unreachable_in_target(target);
610        },
611    );
612    changed.into_inner()
613}
614
615// ═══════════════════════════════════════════════════════
616//  Tests
617// ═══════════════════════════════════════════════════════
618
619#[cfg(test)]
620mod tests {
621    use super::*;
622    use crate::types::ZigType;
623    use crate::zigir::ident::IrIdent;
624    use crate::zigir::types::{IrBlock, IrDecl, IrFnDecl, IrStmt, IrVarDecl};
625
626    #[test]
627    fn test_remove_unreachable_after_return() {
628        let mut module = IrModule::new("test".to_string());
629        module.declarations.push(IrDecl::Fn(IrFnDecl {
630            name: IrIdent::new("foo"),
631            params: vec![],
632            return_type: ZigType::Void,
633            body: IrBlock::new(vec![
634                IrStmt::Return { value: None },
635                IrStmt::Expr(IrExpr::IntLiteral(42)), // unreachable
636                IrStmt::Expr(IrExpr::IntLiteral(99)), // unreachable
637            ]),
638            is_export: false,
639            is_async: false,
640            can_throw: false,
641            is_cabi: false,
642            typeof_return_body: None,
643        }));
644
645        let mut pass = DeadCodeElimPass::new();
646        let result = pass.run(&mut module);
647        assert!(result.changed);
648
649        if let IrDecl::Fn(f) = &module.declarations[0] {
650            assert_eq!(f.body.stmts.len(), 1); // only the return remains
651        } else {
652            panic!("expected Fn decl");
653        }
654    }
655
656    #[test]
657    fn test_remove_unused_const() {
658        let mut module = IrModule::new("test".to_string());
659        module.declarations.push(IrDecl::Var(IrVarDecl::new_const(
660            "unused",
661            Some(ZigType::I64),
662            Some(IrExpr::IntLiteral(42)),
663        )));
664        module.declarations.push(IrDecl::Fn(IrFnDecl {
665            name: IrIdent::new("main"),
666            params: vec![],
667            return_type: ZigType::Void,
668            body: IrBlock::new(vec![IrStmt::Return { value: None }]),
669            is_export: true,
670            is_async: false,
671            can_throw: false,
672            is_cabi: false,
673            typeof_return_body: None,
674        }));
675
676        let mut pass = DeadCodeElimPass::new();
677        let result = pass.run(&mut module);
678        assert!(result.changed);
679        assert_eq!(module.declarations.len(), 1);
680        assert!(matches!(&module.declarations[0], IrDecl::Fn(_)));
681    }
682
683    #[test]
684    fn test_keep_used_const() {
685        let mut module = IrModule::new("test".to_string());
686        module.declarations.push(IrDecl::Var(IrVarDecl::new_const(
687            "x",
688            Some(ZigType::I64),
689            Some(IrExpr::IntLiteral(42)),
690        )));
691        module.declarations.push(IrDecl::Fn(IrFnDecl {
692            name: IrIdent::new("main"),
693            params: vec![],
694            return_type: ZigType::I64,
695            body: IrBlock::new(vec![IrStmt::Return {
696                value: Some(IrExpr::Ident(IrIdent::new("x"))),
697            }]),
698            is_export: true,
699            is_async: false,
700            can_throw: false,
701            is_cabi: false,
702            typeof_return_body: None,
703        }));
704
705        let mut pass = DeadCodeElimPass::new();
706        let result = pass.run(&mut module);
707        assert!(!result.changed);
708        assert_eq!(module.declarations.len(), 2);
709    }
710
711    #[test]
712    fn test_keep_const_with_side_effects() {
713        let mut module = IrModule::new("test".to_string());
714        module.declarations.push(IrDecl::Var(IrVarDecl::new_const(
715            "result",
716            Some(ZigType::I64),
717            Some(IrExpr::Call(crate::zigir::types::IrCallExpr {
718                callee: Box::new(IrExpr::Ident(IrIdent::new("compute"))),
719                args: vec![],
720                call_kind: crate::zigir::kinds::CallKind::Direct,
721            })),
722        )));
723
724        let mut pass = DeadCodeElimPass::new();
725        let result = pass.run(&mut module);
726        assert!(!result.changed); // call has side effects
727    }
728
729    #[test]
730    fn test_no_change_on_clean_code() {
731        let mut module = super::super::make_clean_add_module();
732
733        let mut pass = DeadCodeElimPass::new();
734        let result = pass.run(&mut module);
735        assert!(!result.changed);
736    }
737}