depyler-analysis 4.1.1

Analysis, type inference, and optimization passes for the Depyler transpiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
#[cfg(test)]
use depyler_hir::hir::AssignTarget;
use depyler_hir::hir::{BinOp, HirExpr, HirFunction, HirStmt};
use depyler_annotations::{OptimizationLevel, PerformanceHint};

/// Performance optimizer that applies transformations based on annotations
pub struct PerformanceOptimizer {
    optimizations_applied: Vec<String>,
}

impl Default for PerformanceOptimizer {
    fn default() -> Self {
        Self::new()
    }
}

impl PerformanceOptimizer {
    pub fn new() -> Self {
        Self {
            optimizations_applied: Vec::new(),
        }
    }

    /// Optimize a function based on its annotations
    pub fn optimize_function(&mut self, func: &mut HirFunction) {
        match func.annotations.optimization_level {
            OptimizationLevel::Conservative => {
                self.apply_conservative_optimizations(func);
            }
            OptimizationLevel::Standard => {
                self.apply_standard_optimizations(func);
            }
            OptimizationLevel::Aggressive => {
                self.apply_aggressive_optimizations(func);
            }
        }

        // Apply specific performance hints
        let hints = func.annotations.performance_hints.clone();
        for hint in &hints {
            self.apply_performance_hint(func, hint);
        }
    }

    fn apply_conservative_optimizations(&mut self, func: &mut HirFunction) {
        // Only apply safe, guaranteed optimizations
        self.constant_folding(&mut func.body);
        self.dead_code_elimination(&mut func.body);
    }

    fn apply_standard_optimizations(&mut self, func: &mut HirFunction) {
        // Apply conservative optimizations plus more
        self.apply_conservative_optimizations(func);
        self.common_subexpression_elimination(&mut func.body);
        self.strength_reduction(&mut func.body);
    }

    fn apply_aggressive_optimizations(&mut self, func: &mut HirFunction) {
        // Apply all optimizations
        self.apply_standard_optimizations(func);
        self.loop_unrolling(&mut func.body, 4);
        self.inline_small_functions(&mut func.body);

        // If bounds checking is disabled, remove bounds checks
        if func.annotations.bounds_checking == depyler_annotations::BoundsChecking::Disabled {
            self.remove_bounds_checks(&mut func.body);
        }
    }

    fn apply_performance_hint(&mut self, func: &mut HirFunction, hint: &PerformanceHint) {
        match hint {
            PerformanceHint::Vectorize => {
                self.vectorize_loops(&mut func.body);
            }
            PerformanceHint::UnrollLoops(factor) => {
                self.loop_unrolling(&mut func.body, *factor as usize);
            }
            PerformanceHint::OptimizeForLatency => {
                self.optimize_for_latency(&mut func.body);
            }
            PerformanceHint::OptimizeForThroughput => {
                self.optimize_for_throughput(&mut func.body);
            }
            PerformanceHint::PerformanceCritical => {
                // Apply all applicable optimizations
                self.inline_small_functions(&mut func.body);
                self.vectorize_loops(&mut func.body);
            }
        }
    }

    /// Constant folding optimization
    fn constant_folding(&mut self, stmts: &mut Vec<HirStmt>) {
        for stmt in stmts {
            self.fold_constants_in_stmt(stmt);
        }

        self.optimizations_applied
            .push("constant_folding".to_string());
    }

    fn fold_constants_in_stmt(&mut self, stmt: &mut HirStmt) {
        match stmt {
            HirStmt::Assign { value, .. } => {
                self.fold_constants_expr(value);
            }
            HirStmt::Return(Some(expr)) => {
                self.fold_constants_expr(expr);
            }
            HirStmt::If {
                condition,
                then_body,
                else_body,
            } => {
                self.fold_constants_in_if(condition, then_body, else_body);
            }
            HirStmt::While { condition, body } => {
                self.fold_constants_in_while(condition, body);
            }
            HirStmt::For { body, .. } => {
                self.constant_folding(body);
            }
            _ => {}
        }
    }

    fn fold_constants_in_if(
        &mut self,
        condition: &mut HirExpr,
        then_body: &mut Vec<HirStmt>,
        else_body: &mut Option<Vec<HirStmt>>,
    ) {
        self.fold_constants_expr(condition);
        self.constant_folding(then_body);
        if let Some(else_stmts) = else_body {
            self.constant_folding(else_stmts);
        }
    }

    fn fold_constants_in_while(&mut self, condition: &mut HirExpr, body: &mut Vec<HirStmt>) {
        self.fold_constants_expr(condition);
        self.constant_folding(body);
    }

    fn fold_constants_expr(&self, expr: &mut HirExpr) {
        if let HirExpr::Binary { op, left, right } = expr {
            // Recursively fold constants in operands
            self.fold_constants_expr(left);
            self.fold_constants_expr(right);

            // If both operands are constants, evaluate the operation
            if let (HirExpr::Literal(left_lit), HirExpr::Literal(right_lit)) =
                (left.as_ref(), right.as_ref())
            {
                if let Some(folded) = self.evaluate_binary_op(*op, left_lit, right_lit) {
                    *expr = HirExpr::Literal(folded);
                }
            }
        }
    }

    fn evaluate_binary_op(
        &self,
        op: BinOp,
        left: &depyler_hir::hir::Literal,
        right: &depyler_hir::hir::Literal,
    ) -> Option<depyler_hir::hir::Literal> {
        use depyler_hir::hir::Literal;

        match (op, left, right) {
            (BinOp::Add, Literal::Int(a), Literal::Int(b)) => Some(Literal::Int(a + b)),
            (BinOp::Sub, Literal::Int(a), Literal::Int(b)) => Some(Literal::Int(a - b)),
            (BinOp::Mul, Literal::Int(a), Literal::Int(b)) => Some(Literal::Int(a * b)),
            (BinOp::Add, Literal::Float(a), Literal::Float(b)) => Some(Literal::Float(a + b)),
            (BinOp::Sub, Literal::Float(a), Literal::Float(b)) => Some(Literal::Float(a - b)),
            (BinOp::Mul, Literal::Float(a), Literal::Float(b)) => Some(Literal::Float(a * b)),
            _ => None,
        }
    }

    /// Dead code elimination
    fn dead_code_elimination(&mut self, stmts: &mut Vec<HirStmt>) {
        // Simple DCE: remove statements after unconditional return
        let mut found_return = false;
        stmts.retain(|stmt| {
            if found_return {
                false
            } else {
                if matches!(stmt, HirStmt::Return(_)) {
                    found_return = true;
                }
                true
            }
        });

        self.optimizations_applied
            .push("dead_code_elimination".to_string());
    }

    /// Common subexpression elimination
    fn common_subexpression_elimination(&mut self, _stmts: &mut [HirStmt]) {
        // Simplified CSE - would need data flow analysis for real implementation
        self.optimizations_applied
            .push("common_subexpression_elimination".to_string());
    }

    /// Strength reduction (e.g., x * 2 -> x << 1)
    fn strength_reduction(&mut self, stmts: &mut [HirStmt]) {
        for stmt in stmts {
            match stmt {
                HirStmt::Assign { value, .. } => {
                    self.reduce_strength_expr(value);
                }
                HirStmt::Return(Some(expr)) => {
                    self.reduce_strength_expr(expr);
                }
                _ => {}
            }
        }

        self.optimizations_applied
            .push("strength_reduction".to_string());
    }

    fn reduce_strength_expr(&self, expr: &mut HirExpr) {
        match expr {
            HirExpr::Binary {
                op: BinOp::Mul,
                left: _,
                right,
            } => {
                // DISABLED: Replace multiplication by power of 2 with left shift
                // This optimization is unsafe as it changes semantics for negative numbers
                // Re-enable only when we can prove values are non-negative through type analysis
                if let HirExpr::Literal(depyler_hir::hir::Literal::Int(_n)) = right.as_ref() {
                    // Strength reduction disabled for semantic correctness
                    // Left shift and multiplication have different overflow/underflow behavior
                }
            }
            HirExpr::Binary {
                op: BinOp::Div,
                left: _,
                right,
            } => {
                // DISABLED: Replace division by power of 2 with right shift
                // This optimization is unsafe as it changes semantics for negative numbers
                // Re-enable only when we can prove values are non-negative through type analysis
                if let HirExpr::Literal(depyler_hir::hir::Literal::Int(_n)) = right.as_ref() {
                    // Strength reduction disabled for semantic correctness
                    // Right shift and division have different rounding behavior for negative numbers
                }
            }
            _ => {}
        }
    }

    /// Loop unrolling
    fn loop_unrolling(&mut self, stmts: &mut Vec<HirStmt>, factor: usize) {
        for stmt in stmts {
            if let HirStmt::For { body, .. } = stmt {
                // Simple unrolling - duplicate loop body
                let original_body = body.clone();
                for _ in 1..factor {
                    body.extend(original_body.clone());
                }
            }
        }

        self.optimizations_applied
            .push(format!("loop_unrolling_{factor}"));
    }

    /// Vectorization for SIMD operations
    fn vectorize_loops(&mut self, _stmts: &mut [HirStmt]) {
        // Simplified vectorization - would need pattern matching for real implementation
        self.optimizations_applied
            .push("vectorize_loops".to_string());
    }

    /// Inline small functions
    fn inline_small_functions(&mut self, _stmts: &mut [HirStmt]) {
        // Simplified inlining - would need call graph analysis
        self.optimizations_applied
            .push("inline_small_functions".to_string());
    }

    /// Remove bounds checks (unsafe optimization)
    fn remove_bounds_checks(&mut self, _stmts: &mut [HirStmt]) {
        // Would remove array bounds checks - requires careful analysis
        self.optimizations_applied
            .push("remove_bounds_checks".to_string());
    }

    /// Optimize for low latency
    fn optimize_for_latency(&mut self, _stmts: &mut [HirStmt]) {
        // Prioritize reducing critical path length
        self.optimizations_applied
            .push("optimize_for_latency".to_string());
    }

    /// Optimize for high throughput
    fn optimize_for_throughput(&mut self, _stmts: &mut [HirStmt]) {
        // Prioritize parallelism and vectorization
        self.optimizations_applied
            .push("optimize_for_throughput".to_string());
    }

    /// Get list of optimizations that were applied
    pub fn get_applied_optimizations(&self) -> &[String] {
        &self.optimizations_applied
    }
}

/// Apply optimizations to a module based on annotations
pub fn optimize_module(module: &mut depyler_hir::hir::HirModule) -> Vec<String> {
    let mut all_optimizations = Vec::new();

    for func in &mut module.functions {
        let mut optimizer = PerformanceOptimizer::new();
        optimizer.optimize_function(func);
        all_optimizations.extend(optimizer.get_applied_optimizations().to_vec());
    }

    all_optimizations
}

#[cfg(test)]
mod tests {
    use super::*;
    use depyler_hir::hir::{FunctionProperties, HirModule, HirParam, Literal, Type};
    use depyler_annotations::{BoundsChecking, TranspilationAnnotations};
    use smallvec::smallvec;

    // Helper to create a basic function for testing
    fn create_test_func(body: Vec<HirStmt>, opt_level: OptimizationLevel) -> HirFunction {
        HirFunction {
            name: "test".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body,
            properties: FunctionProperties::default(),
            annotations: TranspilationAnnotations {
                optimization_level: opt_level,
                ..Default::default()
            },
            docstring: None,
        }
    }

    // === PerformanceOptimizer construction tests ===

    #[test]
    fn test_performance_optimizer_new() {
        let optimizer = PerformanceOptimizer::new();
        assert!(optimizer.get_applied_optimizations().is_empty());
    }

    #[test]
    fn test_performance_optimizer_default() {
        let optimizer = PerformanceOptimizer::default();
        assert!(optimizer.get_applied_optimizations().is_empty());
    }

    #[test]
    fn test_get_applied_optimizations_empty() {
        let optimizer = PerformanceOptimizer::new();
        let applied = optimizer.get_applied_optimizations();
        assert!(applied.is_empty());
    }

    // === Optimization level tests ===

    #[test]
    fn test_conservative_optimizations() {
        let mut optimizer = PerformanceOptimizer::new();
        let mut func = create_test_func(vec![], OptimizationLevel::Conservative);

        optimizer.optimize_function(&mut func);

        let applied = optimizer.get_applied_optimizations();
        assert!(applied.contains(&"constant_folding".to_string()));
        assert!(applied.contains(&"dead_code_elimination".to_string()));
        // Should NOT contain aggressive optimizations
        assert!(!applied.contains(&"inline_small_functions".to_string()));
    }

    #[test]
    fn test_standard_optimizations() {
        let mut optimizer = PerformanceOptimizer::new();
        let mut func = create_test_func(vec![], OptimizationLevel::Standard);

        optimizer.optimize_function(&mut func);

        let applied = optimizer.get_applied_optimizations();
        // Should contain conservative + standard optimizations
        assert!(applied.contains(&"constant_folding".to_string()));
        assert!(applied.contains(&"dead_code_elimination".to_string()));
        assert!(applied.contains(&"common_subexpression_elimination".to_string()));
        assert!(applied.contains(&"strength_reduction".to_string()));
    }

    #[test]
    fn test_aggressive_optimizations_applied() {
        let mut optimizer = PerformanceOptimizer::new();
        let mut func = create_test_func(vec![], OptimizationLevel::Aggressive);

        optimizer.optimize_function(&mut func);

        let applied = optimizer.get_applied_optimizations();
        // Should contain all optimizations
        assert!(applied.contains(&"constant_folding".to_string()));
        assert!(applied.contains(&"inline_small_functions".to_string()));
        assert!(applied.iter().any(|s| s.starts_with("loop_unrolling")));
    }

    // === Constant folding tests ===

    #[test]
    fn test_constant_folding() {
        let mut optimizer = PerformanceOptimizer::new();

        let mut func = HirFunction {
            name: "test".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![HirStmt::Return(Some(HirExpr::Binary {
                op: BinOp::Add,
                left: Box::new(HirExpr::Literal(Literal::Int(2))),
                right: Box::new(HirExpr::Literal(Literal::Int(3))),
            }))],
            properties: Default::default(),
            annotations: TranspilationAnnotations {
                optimization_level: OptimizationLevel::Standard,
                ..Default::default()
            },
            docstring: None,
        };

        optimizer.optimize_function(&mut func);

        // Check that constant folding was applied
        if let HirStmt::Return(Some(HirExpr::Literal(Literal::Int(n)))) = &func.body[0] {
            assert_eq!(*n, 5);
        } else {
            panic!("Expected constant folding to produce literal 5");
        }
    }

    #[test]
    fn test_constant_folding_subtraction() {
        let mut optimizer = PerformanceOptimizer::new();
        let body = vec![HirStmt::Return(Some(HirExpr::Binary {
            op: BinOp::Sub,
            left: Box::new(HirExpr::Literal(Literal::Int(10))),
            right: Box::new(HirExpr::Literal(Literal::Int(3))),
        }))];
        let mut func = create_test_func(body, OptimizationLevel::Conservative);

        optimizer.optimize_function(&mut func);

        if let HirStmt::Return(Some(HirExpr::Literal(Literal::Int(n)))) = &func.body[0] {
            assert_eq!(*n, 7);
        } else {
            panic!("Expected constant folding to produce literal 7");
        }
    }

    #[test]
    fn test_constant_folding_multiplication() {
        let mut optimizer = PerformanceOptimizer::new();
        let body = vec![HirStmt::Return(Some(HirExpr::Binary {
            op: BinOp::Mul,
            left: Box::new(HirExpr::Literal(Literal::Int(4))),
            right: Box::new(HirExpr::Literal(Literal::Int(5))),
        }))];
        let mut func = create_test_func(body, OptimizationLevel::Conservative);

        optimizer.optimize_function(&mut func);

        if let HirStmt::Return(Some(HirExpr::Literal(Literal::Int(n)))) = &func.body[0] {
            assert_eq!(*n, 20);
        } else {
            panic!("Expected constant folding to produce literal 20");
        }
    }

    #[test]
    fn test_constant_folding_float_add() {
        let mut optimizer = PerformanceOptimizer::new();
        let body = vec![HirStmt::Return(Some(HirExpr::Binary {
            op: BinOp::Add,
            left: Box::new(HirExpr::Literal(Literal::Float(1.5))),
            right: Box::new(HirExpr::Literal(Literal::Float(2.5))),
        }))];
        let mut func = create_test_func(body, OptimizationLevel::Conservative);

        optimizer.optimize_function(&mut func);

        if let HirStmt::Return(Some(HirExpr::Literal(Literal::Float(n)))) = &func.body[0] {
            assert!((n - 4.0).abs() < f64::EPSILON);
        } else {
            panic!("Expected constant folding to produce float literal");
        }
    }

    #[test]
    fn test_constant_folding_float_sub() {
        let mut optimizer = PerformanceOptimizer::new();
        let body = vec![HirStmt::Return(Some(HirExpr::Binary {
            op: BinOp::Sub,
            left: Box::new(HirExpr::Literal(Literal::Float(5.0))),
            right: Box::new(HirExpr::Literal(Literal::Float(2.0))),
        }))];
        let mut func = create_test_func(body, OptimizationLevel::Conservative);

        optimizer.optimize_function(&mut func);

        if let HirStmt::Return(Some(HirExpr::Literal(Literal::Float(n)))) = &func.body[0] {
            assert!((n - 3.0).abs() < f64::EPSILON);
        } else {
            panic!("Expected constant folding to produce float literal");
        }
    }

    #[test]
    fn test_constant_folding_float_mul() {
        let mut optimizer = PerformanceOptimizer::new();
        let body = vec![HirStmt::Return(Some(HirExpr::Binary {
            op: BinOp::Mul,
            left: Box::new(HirExpr::Literal(Literal::Float(2.0))),
            right: Box::new(HirExpr::Literal(Literal::Float(3.0))),
        }))];
        let mut func = create_test_func(body, OptimizationLevel::Conservative);

        optimizer.optimize_function(&mut func);

        if let HirStmt::Return(Some(HirExpr::Literal(Literal::Float(n)))) = &func.body[0] {
            assert!((n - 6.0).abs() < f64::EPSILON);
        } else {
            panic!("Expected constant folding to produce float literal");
        }
    }

    #[test]
    fn test_constant_folding_nested_expressions() {
        let mut optimizer = PerformanceOptimizer::new();
        // (2 + 3) + 4 = 5 + 4 = 9
        let body = vec![HirStmt::Return(Some(HirExpr::Binary {
            op: BinOp::Add,
            left: Box::new(HirExpr::Binary {
                op: BinOp::Add,
                left: Box::new(HirExpr::Literal(Literal::Int(2))),
                right: Box::new(HirExpr::Literal(Literal::Int(3))),
            }),
            right: Box::new(HirExpr::Literal(Literal::Int(4))),
        }))];
        let mut func = create_test_func(body, OptimizationLevel::Conservative);

        optimizer.optimize_function(&mut func);

        if let HirStmt::Return(Some(HirExpr::Literal(Literal::Int(n)))) = &func.body[0] {
            assert_eq!(*n, 9);
        } else {
            panic!("Expected nested constant folding to produce literal 9");
        }
    }

    #[test]
    fn test_constant_folding_in_assign() {
        let mut optimizer = PerformanceOptimizer::new();
        let body = vec![HirStmt::Assign {
            target: AssignTarget::Symbol("x".to_string()),
            value: HirExpr::Binary {
                op: BinOp::Add,
                left: Box::new(HirExpr::Literal(Literal::Int(10))),
                right: Box::new(HirExpr::Literal(Literal::Int(20))),
            },
            type_annotation: None,
        }];
        let mut func = create_test_func(body, OptimizationLevel::Conservative);

        optimizer.optimize_function(&mut func);

        if let HirStmt::Assign { value, .. } = &func.body[0] {
            if let HirExpr::Literal(Literal::Int(n)) = value {
                assert_eq!(*n, 30);
            } else {
                panic!("Expected constant folding in assign");
            }
        }
    }

    #[test]
    fn test_constant_folding_in_if_condition() {
        let mut optimizer = PerformanceOptimizer::new();
        let body = vec![HirStmt::If {
            condition: HirExpr::Binary {
                op: BinOp::Add,
                left: Box::new(HirExpr::Literal(Literal::Int(1))),
                right: Box::new(HirExpr::Literal(Literal::Int(2))),
            },
            then_body: vec![],
            else_body: None,
        }];
        let mut func = create_test_func(body, OptimizationLevel::Conservative);

        optimizer.optimize_function(&mut func);

        if let HirStmt::If { condition, .. } = &func.body[0] {
            assert!(matches!(condition, HirExpr::Literal(Literal::Int(3))));
        }
    }

    #[test]
    fn test_constant_folding_in_while_condition() {
        let mut optimizer = PerformanceOptimizer::new();
        let body = vec![HirStmt::While {
            condition: HirExpr::Binary {
                op: BinOp::Add,
                left: Box::new(HirExpr::Literal(Literal::Int(5))),
                right: Box::new(HirExpr::Literal(Literal::Int(5))),
            },
            body: vec![],
        }];
        let mut func = create_test_func(body, OptimizationLevel::Conservative);

        optimizer.optimize_function(&mut func);

        if let HirStmt::While { condition, .. } = &func.body[0] {
            assert!(matches!(condition, HirExpr::Literal(Literal::Int(10))));
        }
    }

    #[test]
    fn test_constant_folding_in_for_body() {
        let mut optimizer = PerformanceOptimizer::new();
        let body = vec![HirStmt::For {
            target: AssignTarget::Symbol("i".to_string()),
            iter: HirExpr::Var("range".to_string()),
            body: vec![HirStmt::Assign {
                target: AssignTarget::Symbol("x".to_string()),
                value: HirExpr::Binary {
                    op: BinOp::Add,
                    left: Box::new(HirExpr::Literal(Literal::Int(1))),
                    right: Box::new(HirExpr::Literal(Literal::Int(1))),
                },
                type_annotation: None,
            }],
        }];
        let mut func = create_test_func(body, OptimizationLevel::Conservative);

        optimizer.optimize_function(&mut func);

        if let HirStmt::For { body, .. } = &func.body[0] {
            if let HirStmt::Assign { value, .. } = &body[0] {
                assert!(matches!(value, HirExpr::Literal(Literal::Int(2))));
            }
        }
    }

    #[test]
    fn test_constant_folding_no_fold_for_division() {
        // Division is not supported in constant folding
        let mut optimizer = PerformanceOptimizer::new();
        let body = vec![HirStmt::Return(Some(HirExpr::Binary {
            op: BinOp::Div,
            left: Box::new(HirExpr::Literal(Literal::Int(10))),
            right: Box::new(HirExpr::Literal(Literal::Int(2))),
        }))];
        let mut func = create_test_func(body, OptimizationLevel::Conservative);

        optimizer.optimize_function(&mut func);

        // Should NOT be folded since Div is not implemented
        if let HirStmt::Return(Some(expr)) = &func.body[0] {
            assert!(matches!(expr, HirExpr::Binary { op: BinOp::Div, .. }));
        }
    }

    // === Strength reduction tests ===

    #[test]
    fn test_strength_reduction() {
        let mut optimizer = PerformanceOptimizer::new();

        let mut func = HirFunction {
            name: "test".to_string(),
            params: smallvec![HirParam::new("x".to_string(), Type::Int)],
            ret_type: Type::Int,
            body: vec![HirStmt::Return(Some(HirExpr::Binary {
                op: BinOp::Mul,
                left: Box::new(HirExpr::Var("x".to_string())),
                right: Box::new(HirExpr::Literal(Literal::Int(8))),
            }))],
            properties: Default::default(),
            annotations: TranspilationAnnotations {
                optimization_level: OptimizationLevel::Standard,
                ..Default::default()
            },
            docstring: None,
        };

        optimizer.optimize_function(&mut func);

        // Check that multiplication by 8 is NOT replaced with left shift for correctness
        // Strength reduction is disabled to maintain semantic equivalence
        if let HirStmt::Return(Some(HirExpr::Binary { op, right, .. })) = &func.body[0] {
            assert_eq!(
                *op,
                BinOp::Mul,
                "Should preserve multiplication for semantic correctness"
            );
            if let HirExpr::Literal(Literal::Int(n)) = right.as_ref() {
                assert_eq!(*n, 8, "Should preserve original multiplication operand");
            }
        } else {
            panic!("Expected multiplication to be preserved");
        }
    }

    #[test]
    fn test_strength_reduction_division() {
        let mut optimizer = PerformanceOptimizer::new();
        let body = vec![HirStmt::Return(Some(HirExpr::Binary {
            op: BinOp::Div,
            left: Box::new(HirExpr::Var("x".to_string())),
            right: Box::new(HirExpr::Literal(Literal::Int(4))),
        }))];
        let mut func = create_test_func(body, OptimizationLevel::Standard);

        optimizer.optimize_function(&mut func);

        // Division should also be preserved
        if let HirStmt::Return(Some(HirExpr::Binary { op, .. })) = &func.body[0] {
            assert_eq!(*op, BinOp::Div);
        }
    }

    // === Dead code elimination tests ===

    #[test]
    fn test_dead_code_elimination() {
        let mut optimizer = PerformanceOptimizer::new();

        let mut func = HirFunction {
            name: "test".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![
                HirStmt::Return(Some(HirExpr::Literal(Literal::Int(42)))),
                HirStmt::Assign {
                    target: AssignTarget::Symbol("unreachable".to_string()),
                    value: HirExpr::Literal(Literal::Int(0)),
                    type_annotation: None,
                },
            ],
            properties: Default::default(),
            annotations: TranspilationAnnotations {
                optimization_level: OptimizationLevel::Conservative,
                ..Default::default()
            },
            docstring: None,
        };

        optimizer.optimize_function(&mut func);

        // Check that unreachable code was removed
        assert_eq!(func.body.len(), 1);
        assert!(matches!(func.body[0], HirStmt::Return(_)));
    }

    #[test]
    fn test_dead_code_elimination_multiple_statements() {
        let mut optimizer = PerformanceOptimizer::new();
        let body = vec![
            HirStmt::Assign {
                target: AssignTarget::Symbol("x".to_string()),
                value: HirExpr::Literal(Literal::Int(1)),
                type_annotation: None,
            },
            HirStmt::Return(Some(HirExpr::Var("x".to_string()))),
            HirStmt::Assign {
                target: AssignTarget::Symbol("y".to_string()),
                value: HirExpr::Literal(Literal::Int(2)),
                type_annotation: None,
            },
            HirStmt::Assign {
                target: AssignTarget::Symbol("z".to_string()),
                value: HirExpr::Literal(Literal::Int(3)),
                type_annotation: None,
            },
        ];
        let mut func = create_test_func(body, OptimizationLevel::Conservative);

        optimizer.optimize_function(&mut func);

        // Only first 2 statements should remain
        assert_eq!(func.body.len(), 2);
    }

    #[test]
    fn test_dead_code_elimination_no_return() {
        let mut optimizer = PerformanceOptimizer::new();
        let body = vec![
            HirStmt::Assign {
                target: AssignTarget::Symbol("x".to_string()),
                value: HirExpr::Literal(Literal::Int(1)),
                type_annotation: None,
            },
            HirStmt::Assign {
                target: AssignTarget::Symbol("y".to_string()),
                value: HirExpr::Literal(Literal::Int(2)),
                type_annotation: None,
            },
        ];
        let mut func = create_test_func(body, OptimizationLevel::Conservative);

        optimizer.optimize_function(&mut func);

        // All statements should remain (no return to trigger DCE)
        assert_eq!(func.body.len(), 2);
    }

    // === Performance hint tests ===

    #[test]
    fn test_aggressive_optimizations() {
        let mut optimizer = PerformanceOptimizer::new();

        let mut annotations = TranspilationAnnotations {
            optimization_level: OptimizationLevel::Aggressive,
            ..Default::default()
        };
        annotations
            .performance_hints
            .push(PerformanceHint::Vectorize);

        let mut func = HirFunction {
            name: "test".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![],
            properties: Default::default(),
            annotations,
            docstring: None,
        };

        optimizer.optimize_function(&mut func);

        // Check that multiple optimizations were applied
        let applied = optimizer.get_applied_optimizations();
        assert!(applied.contains(&"constant_folding".to_string()));
        assert!(applied.contains(&"vectorize_loops".to_string()));
    }

    #[test]
    fn test_performance_hint_vectorize() {
        let mut optimizer = PerformanceOptimizer::new();
        let mut annotations = TranspilationAnnotations::default();
        annotations
            .performance_hints
            .push(PerformanceHint::Vectorize);

        let mut func = HirFunction {
            name: "test".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![],
            properties: Default::default(),
            annotations,
            docstring: None,
        };

        optimizer.optimize_function(&mut func);

        let applied = optimizer.get_applied_optimizations();
        assert!(applied.contains(&"vectorize_loops".to_string()));
    }

    #[test]
    fn test_performance_hint_unroll_loops() {
        let mut optimizer = PerformanceOptimizer::new();
        let mut annotations = TranspilationAnnotations::default();
        annotations
            .performance_hints
            .push(PerformanceHint::UnrollLoops(8));

        let mut func = HirFunction {
            name: "test".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![],
            properties: Default::default(),
            annotations,
            docstring: None,
        };

        optimizer.optimize_function(&mut func);

        let applied = optimizer.get_applied_optimizations();
        assert!(applied.contains(&"loop_unrolling_8".to_string()));
    }

    #[test]
    fn test_performance_hint_optimize_for_latency() {
        let mut optimizer = PerformanceOptimizer::new();
        let mut annotations = TranspilationAnnotations::default();
        annotations
            .performance_hints
            .push(PerformanceHint::OptimizeForLatency);

        let mut func = HirFunction {
            name: "test".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![],
            properties: Default::default(),
            annotations,
            docstring: None,
        };

        optimizer.optimize_function(&mut func);

        let applied = optimizer.get_applied_optimizations();
        assert!(applied.contains(&"optimize_for_latency".to_string()));
    }

    #[test]
    fn test_performance_hint_optimize_for_throughput() {
        let mut optimizer = PerformanceOptimizer::new();
        let mut annotations = TranspilationAnnotations::default();
        annotations
            .performance_hints
            .push(PerformanceHint::OptimizeForThroughput);

        let mut func = HirFunction {
            name: "test".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![],
            properties: Default::default(),
            annotations,
            docstring: None,
        };

        optimizer.optimize_function(&mut func);

        let applied = optimizer.get_applied_optimizations();
        assert!(applied.contains(&"optimize_for_throughput".to_string()));
    }

    #[test]
    fn test_performance_hint_performance_critical() {
        let mut optimizer = PerformanceOptimizer::new();
        let mut annotations = TranspilationAnnotations::default();
        annotations
            .performance_hints
            .push(PerformanceHint::PerformanceCritical);

        let mut func = HirFunction {
            name: "test".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![],
            properties: Default::default(),
            annotations,
            docstring: None,
        };

        optimizer.optimize_function(&mut func);

        let applied = optimizer.get_applied_optimizations();
        assert!(applied.contains(&"inline_small_functions".to_string()));
        assert!(applied.contains(&"vectorize_loops".to_string()));
    }

    // === Bounds checking tests ===

    #[test]
    fn test_aggressive_with_bounds_checking_disabled() {
        let mut optimizer = PerformanceOptimizer::new();
        let mut func = HirFunction {
            name: "test".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![],
            properties: Default::default(),
            annotations: TranspilationAnnotations {
                optimization_level: OptimizationLevel::Aggressive,
                bounds_checking: BoundsChecking::Disabled,
                ..Default::default()
            },
            docstring: None,
        };

        optimizer.optimize_function(&mut func);

        let applied = optimizer.get_applied_optimizations();
        assert!(applied.contains(&"remove_bounds_checks".to_string()));
    }

    #[test]
    fn test_aggressive_with_bounds_checking_explicit() {
        let mut optimizer = PerformanceOptimizer::new();
        let mut func = HirFunction {
            name: "test".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![],
            properties: Default::default(),
            annotations: TranspilationAnnotations {
                optimization_level: OptimizationLevel::Aggressive,
                bounds_checking: BoundsChecking::Explicit,
                ..Default::default()
            },
            docstring: None,
        };

        optimizer.optimize_function(&mut func);

        let applied = optimizer.get_applied_optimizations();
        // Should NOT contain remove_bounds_checks
        assert!(!applied.contains(&"remove_bounds_checks".to_string()));
    }

    // === Loop unrolling tests ===

    #[test]
    fn test_loop_unrolling_with_for_loop() {
        let mut optimizer = PerformanceOptimizer::new();
        let body = vec![HirStmt::For {
            target: AssignTarget::Symbol("i".to_string()),
            iter: HirExpr::Var("range".to_string()),
            body: vec![HirStmt::Assign {
                target: AssignTarget::Symbol("x".to_string()),
                value: HirExpr::Literal(Literal::Int(1)),
                type_annotation: None,
            }],
        }];
        let mut func = create_test_func(body, OptimizationLevel::Aggressive);

        optimizer.optimize_function(&mut func);

        // Loop body should be duplicated (default factor 4)
        if let HirStmt::For { body, .. } = &func.body[0] {
            // Body should now have 4 copies of the original statement
            assert_eq!(body.len(), 4);
        }
    }

    // === Module optimization tests ===

    #[test]
    fn test_optimize_module() {
        let mut module = HirModule {
            functions: vec![
                HirFunction {
                    name: "func1".to_string(),
                    params: smallvec![],
                    ret_type: Type::Int,
                    body: vec![],
                    properties: Default::default(),
                    annotations: TranspilationAnnotations {
                        optimization_level: OptimizationLevel::Standard,
                        ..Default::default()
                    },
                    docstring: None,
                },
                HirFunction {
                    name: "func2".to_string(),
                    params: smallvec![],
                    ret_type: Type::Int,
                    body: vec![],
                    properties: Default::default(),
                    annotations: TranspilationAnnotations {
                        optimization_level: OptimizationLevel::Aggressive,
                        ..Default::default()
                    },
                    docstring: None,
                },
            ],
            imports: vec![],
            type_aliases: vec![],
            protocols: vec![],
            classes: vec![],
            constants: vec![],
            top_level_stmts: vec![],
        };

        let optimizations = optimize_module(&mut module);

        // Both functions should have optimizations applied
        assert!(!optimizations.is_empty());
    }

    #[test]
    fn test_optimize_module_empty() {
        let mut module = HirModule {
            functions: vec![],
            imports: vec![],
            type_aliases: vec![],
            protocols: vec![],
            classes: vec![],
            constants: vec![],
            top_level_stmts: vec![],
        };

        let optimizations = optimize_module(&mut module);
        assert!(optimizations.is_empty());
    }

    #[test]
    fn test_optimize_module_single_function() {
        let mut module = HirModule {
            functions: vec![HirFunction {
                name: "single".to_string(),
                params: smallvec![],
                ret_type: Type::Int,
                body: vec![],
                properties: Default::default(),
                annotations: TranspilationAnnotations {
                    optimization_level: OptimizationLevel::Conservative,
                    ..Default::default()
                },
                docstring: None,
            }],
            imports: vec![],
            type_aliases: vec![],
            protocols: vec![],
            classes: vec![],
            constants: vec![],
            top_level_stmts: vec![],
        };

        let optimizations = optimize_module(&mut module);
        assert!(optimizations.contains(&"constant_folding".to_string()));
        assert!(optimizations.contains(&"dead_code_elimination".to_string()));
    }

    // === Evaluate binary op tests ===

    #[test]
    fn test_evaluate_binary_op_unsupported() {
        let optimizer = PerformanceOptimizer::new();

        // Test unsupported operation (Pow)
        let result = optimizer.evaluate_binary_op(BinOp::Pow, &Literal::Int(2), &Literal::Int(3));
        assert!(result.is_none());
    }

    #[test]
    fn test_evaluate_binary_op_mixed_types() {
        let optimizer = PerformanceOptimizer::new();

        // Test mixed types (Int + Float) - not supported
        let result =
            optimizer.evaluate_binary_op(BinOp::Add, &Literal::Int(2), &Literal::Float(3.0));
        assert!(result.is_none());
    }

    #[test]
    fn test_evaluate_binary_op_string_literal() {
        let optimizer = PerformanceOptimizer::new();

        // String literals not supported for binary ops
        let result = optimizer.evaluate_binary_op(
            BinOp::Add,
            &Literal::String("a".to_string()),
            &Literal::String("b".to_string()),
        );
        assert!(result.is_none());
    }

    // === If/else folding tests ===

    #[test]
    fn test_constant_folding_if_with_else() {
        let mut optimizer = PerformanceOptimizer::new();
        let body = vec![HirStmt::If {
            condition: HirExpr::Binary {
                op: BinOp::Add,
                left: Box::new(HirExpr::Literal(Literal::Int(1))),
                right: Box::new(HirExpr::Literal(Literal::Int(1))),
            },
            then_body: vec![HirStmt::Return(Some(HirExpr::Binary {
                op: BinOp::Add,
                left: Box::new(HirExpr::Literal(Literal::Int(2))),
                right: Box::new(HirExpr::Literal(Literal::Int(2))),
            }))],
            else_body: Some(vec![HirStmt::Return(Some(HirExpr::Binary {
                op: BinOp::Add,
                left: Box::new(HirExpr::Literal(Literal::Int(3))),
                right: Box::new(HirExpr::Literal(Literal::Int(3))),
            }))]),
        }];
        let mut func = create_test_func(body, OptimizationLevel::Conservative);

        optimizer.optimize_function(&mut func);

        // Check all constants are folded
        if let HirStmt::If {
            condition,
            then_body,
            else_body,
        } = &func.body[0]
        {
            assert!(matches!(condition, HirExpr::Literal(Literal::Int(2))));

            if let HirStmt::Return(Some(HirExpr::Literal(Literal::Int(n)))) = &then_body[0] {
                assert_eq!(*n, 4);
            }

            if let Some(else_stmts) = else_body {
                if let HirStmt::Return(Some(HirExpr::Literal(Literal::Int(n)))) = &else_stmts[0] {
                    assert_eq!(*n, 6);
                }
            }
        }
    }

    // === Multiple performance hints test ===

    #[test]
    fn test_multiple_performance_hints() {
        let mut optimizer = PerformanceOptimizer::new();
        let mut annotations = TranspilationAnnotations::default();
        annotations
            .performance_hints
            .push(PerformanceHint::Vectorize);
        annotations
            .performance_hints
            .push(PerformanceHint::OptimizeForLatency);
        annotations
            .performance_hints
            .push(PerformanceHint::UnrollLoops(2));

        let mut func = HirFunction {
            name: "test".to_string(),
            params: smallvec![],
            ret_type: Type::Int,
            body: vec![],
            properties: Default::default(),
            annotations,
            docstring: None,
        };

        optimizer.optimize_function(&mut func);

        let applied = optimizer.get_applied_optimizations();
        assert!(applied.contains(&"vectorize_loops".to_string()));
        assert!(applied.contains(&"optimize_for_latency".to_string()));
        assert!(applied.contains(&"loop_unrolling_2".to_string()));
    }
}