llvm-native-core-ext 0.1.0

Extended modules for llvm-native-core: analysis passes, transforms, codegen extras, bitcode, linker, JIT, utilities. Part of the llvm-native workspace (https://crates.io/crates/llvm-native).
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
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
//! LLVM Reassociate — Expression Reassociation.
//! Phase 9 — LLVM.Reassociate.1 Court.
//!
//! Clean-room behavioral reconstruction from compiler optimization
//! literature (Briggs & Cooper 1994 "Effective Partial Redundancy
//! Elimination", LLVM's Reassociate pass description), the LLVM
//! Language Reference, and observable optimization behavior.
//! Zero LLVM source code consultation.
//!
//! Expression reassociation restructures associative and commutative
//! expressions to expose constant folding, common subexpression
//! elimination (CSE), and loop-invariant code motion opportunities.
//!
//! The key idea is to transform expression trees into a canonical
//! left-linear form with constants folded and non-constant operands
//! sorted by a ranking function.  This canonicalization makes
//! equivalent expressions structurally identical.
//!
//! Algorithm:
//!   1. For each basic block, scan for chains of associative ops
//!   2. Flatten each chain into a linear list of operands
//!   3. Separate constant and non-constant operands
//!   4. Fold constants together
//!   5. Sort non-constant operands by canonical rank
//!   6. Rebuild the expression in balanced left-linear form
//!
//! Specific patterns optimized:
//!   (X + C1) + C2  →  X + (C1+C2)        (constant merging)
//!   (X + Y) + X    →  2*X + Y             (repeated operand factoring)
//!   (X * C1) * C2  →  X * (C1*C2)        (constant merging)
//!   (X * C1) + (X * C2) → X * (C1+C2)    (distribution)

use llvm_native_core::constants;
use llvm_native_core::instruction;
use llvm_native_core::opcode::Opcode;
use llvm_native_core::types::Type;
use llvm_native_core::value::{SubclassKind, ValueRef};
use std::collections::{HashMap, HashSet};

// ============================================================================
// Reassociate Pass
// ============================================================================

/// Expression Reassociation pass.
pub struct ReassociatePass {
    /// Number of expressions reassociated.
    pub reassociated: usize,
}

impl ReassociatePass {
    pub fn new() -> Self {
        Self { reassociated: 0 }
    }

    // ========================================================================
    // Main entry point
    // ========================================================================

    /// Run reassociation on a function. Returns the number of expressions
    /// reassociated.
    pub fn run_on_function(&mut self, func: &ValueRef) -> usize {
        self.reassociated = 0;

        let f = func.borrow();
        for bb in &f.operands {
            if bb.borrow().subclass == SubclassKind::BasicBlock {
                self.reassociated += self.run_on_basic_block(bb);
            }
        }

        self.reassociated
    }

    /// Run reassociation on a single basic block.
    pub fn run_on_basic_block(&mut self, bb: &ValueRef) -> usize {
        let mut count = 0;
        let mut builder = IRBuilderStub::new();

        let insts = get_block_instructions(bb);
        for inst in &insts {
            if let Some(replacement) = self.reassociate_expression(inst, &mut builder) {
                // Replace uses of the original instruction with the new one.
                // Note: in a full implementation, we'd replace all uses and
                // potentially erase the old instruction.
                inst.borrow_mut().replace_all_uses_with(&replacement);
                count += 1;
            }
        }

        count
    }

    // ========================================================================
    // Core reassociation
    // ========================================================================

    /// Attempt to reassociate an expression. Returns Some(new_value) if
    /// the expression was reassociated, None otherwise.
    pub fn reassociate_expression(
        &self,
        inst: &ValueRef,
        builder: &mut IRBuilderStub,
    ) -> Option<ValueRef> {
        let ib = inst.borrow();
        let opcode = ib.opcode?;

        // Only reassociate associative/commutative binary ops.
        if !is_associative_commutative(opcode) {
            return None;
        }

        // Must have exactly 2 operands (binary op).
        if ib.operands.len() != 2 {
            return None;
        }

        let ty = ib.ty.clone();

        // Flatten the chain.
        let mut operands = match opcode {
            Opcode::Add | Opcode::FAdd => self.flatten_add_chain(inst),
            Opcode::Mul | Opcode::FMul => self.flatten_mul_chain(inst),
            Opcode::And => self.flatten_bitwise_chain(inst, Opcode::And),
            Opcode::Or => self.flatten_bitwise_chain(inst, Opcode::Or),
            Opcode::Xor => self.flatten_bitwise_chain(inst, Opcode::Xor),
            _ => return None,
        };

        if operands.len() <= 1 {
            return None; // Nothing to reassociate
        }

        // Separate constants from non-constants.
        let const_folded = fold_constants(&mut operands);
        if const_folded == 0 && operands.len() <= 1 {
            return None; // No change
        }

        // Sort non-constant operands by rank.
        sort_by_rank(&mut operands);

        // Factor repeated operands.
        factor_repeated_operands(&mut operands, opcode, &ty);

        // Rebuild the expression.
        if operands.is_empty() {
            return None;
        }

        let result = rebuild_expression(opcode, operands, builder, &ty);
        Some(result)
    }

    // ========================================================================
    // Chain flattening
    // ========================================================================

    /// Flatten an addition chain: (a + b) + c → [a, b, c].
    pub fn flatten_add_chain(&self, inst: &ValueRef) -> Vec<ValueRef> {
        let mut operands = Vec::new();
        let mut worklist = vec![inst.clone()];

        while let Some(current) = worklist.pop() {
            let is_add = {
                let cb = current.borrow();
                let result = cb.opcode == Some(Opcode::Add) && cb.operands.len() == 2;
                if result {
                    worklist.push(cb.operands[0].clone());
                    worklist.push(cb.operands[1].clone());
                }
                result
            };
            if !is_add {
                operands.push(current);
            }
        }

        operands.reverse(); // Preserve original order
        operands
    }

    /// Flatten a multiplication chain.
    pub fn flatten_mul_chain(&self, inst: &ValueRef) -> Vec<ValueRef> {
        let mut operands = Vec::new();
        let mut worklist = vec![inst.clone()];

        while let Some(current) = worklist.pop() {
            let is_mul = {
                let cb = current.borrow();
                let result = cb.opcode == Some(Opcode::Mul) && cb.operands.len() == 2;
                if result {
                    worklist.push(cb.operands[0].clone());
                    worklist.push(cb.operands[1].clone());
                }
                result
            };
            if !is_mul {
                operands.push(current);
            }
        }

        operands.reverse();
        operands
    }

    /// Flatten a bitwise chain (and/or/xor).
    fn flatten_bitwise_chain(&self, inst: &ValueRef, target_op: Opcode) -> Vec<ValueRef> {
        let mut operands = Vec::new();
        let mut worklist = vec![inst.clone()];

        while let Some(current) = worklist.pop() {
            let is_match = {
                let cb = current.borrow();
                let result = cb.opcode == Some(target_op) && cb.operands.len() == 2;
                if result {
                    worklist.push(cb.operands[0].clone());
                    worklist.push(cb.operands[1].clone());
                }
                result
            };
            if !is_match {
                operands.push(current);
            }
        }

        operands.reverse();
        operands
    }

    // ========================================================================
    // Expression optimization
    // ========================================================================

    /// Try to optimize a single expression. Returns Some(new_value) if
    /// optimized.
    pub fn optimize_expression(
        &self,
        inst: &ValueRef,
        builder: &mut IRBuilderStub,
    ) -> Option<ValueRef> {
        // First try reassociation.
        if let Some(result) = self.reassociate_expression(inst, builder) {
            return Some(result);
        }

        // Try distribution: (X * C1) + (X * C2) → X * (C1 + C2).
        let ib = inst.borrow();
        if ib.opcode == Some(Opcode::Add) && ib.operands.len() == 2 {
            if let Some(result) = try_distribute(&ib.operands[0], &ib.operands[1], builder) {
                return Some(result);
            }
        }

        None
    }
}

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

// ============================================================================
// Ranking function
// ============================================================================

/// Compute a canonical rank for a value. This rank is used to sort
/// operands in a canonical order so that equivalent expressions
/// produce the same ordering.
pub fn rank_value(val: &ValueRef) -> u64 {
    let vb = val.borrow();

    match vb.subclass {
        // Constants: use the parsed numeric value from their name.
        SubclassKind::Constant => rank_constant(val),
        // Arguments: low rank based on their argument index (from name).
        SubclassKind::Argument => rank_argument(val),
        // Instructions: rank by opcode and operand ranks.
        SubclassKind::Instruction => rank_instruction(val),
        // Basic blocks, functions: use their vid.
        _ => vb.vid,
    }
}

/// Rank a constant value. Parse its name for the numeric value.
fn rank_constant(val: &ValueRef) -> u64 {
    let vb = val.borrow();
    // Try to parse the name as a numeric value.
    if let Ok(v) = vb.name.parse::<i64>() {
        // Map negative values into a high range.
        if v >= 0 {
            v as u64
        } else {
            // Negative values: shift to high range (u64::MAX + 1 + v).
            // Simplified: just use wrapping.
            v.wrapping_neg() as u64
        }
    } else {
        // Fallback: use vid.
        vb.vid
    }
}

/// Rank an argument. Arguments have low ranks to appear early.
fn rank_argument(val: &ValueRef) -> u64 {
    let vb = val.borrow();
    // Argument name is like "arg0", "arg1", etc.
    // Parse the numeric suffix, default to 0.
    let arg_num = vb
        .name
        .chars()
        .skip_while(|c| !c.is_ascii_digit())
        .collect::<String>()
        .parse::<u64>()
        .unwrap_or(0);
    // Map to a low range, but above constants.
    1_000_000_000 + arg_num
}

/// Rank an instruction by its opcode and operand ranks.
fn rank_instruction(val: &ValueRef) -> u64 {
    let vb = val.borrow();
    let opcode_val = vb.opcode.map(|o| o as u64).unwrap_or(0);

    // Combine opcode with operand ranks using a simple hash.
    let mut hash: u64 = opcode_val.wrapping_mul(0x9e3779b9);
    for op in &vb.operands {
        let op_rank = rank_value(op);
        hash = hash.wrapping_add(op_rank).wrapping_mul(0x9e3779b9);
        hash = hash.rotate_left(7);
    }

    // Start at a high range to avoid collision with constants/args.
    2_000_000_000 + (hash & 0x7FFFFFFF)
}

// ============================================================================
// Constant folding for reassociation
// ============================================================================

/// Fold constant operands within a list. Merges adjacent constant
/// operands into a single combined constant. Returns the number of
/// constants folded.
pub fn fold_constants(operands: &mut Vec<ValueRef>) -> usize {
    let mut folded = 0;

    // Collect constant indices.
    let mut const_indices: Vec<usize> = Vec::new();
    for (i, op) in operands.iter().enumerate() {
        if op.borrow().subclass == SubclassKind::Constant {
            const_indices.push(i);
        }
    }

    if const_indices.len() < 2 {
        return 0;
    }

    // Combine all constants into one. For simplicity, use the first
    // constant type. In a real implementation, we'd compute the actual value.
    let first_const = operands[const_indices[0]].clone();
    let ty = first_const.borrow().ty.clone();

    // Create a combined constant (simplified: just compute via const_add, etc.)
    let mut combined = first_const;
    for &idx in &const_indices[1..] {
        let c = &operands[idx];
        // Try to compute the combined numeric value.
        if let Some(merged) = try_combine_constants(&combined, c) {
            combined = merged;
            folded += 1;
        }
    }

    // Remove all constants and re-insert the combined one.
    // Remove in reverse order to maintain indices.
    let mut removed = 0;
    operands.retain(|op| {
        let is_const = op.borrow().subclass == SubclassKind::Constant;
        if is_const {
            removed += 1;
        }
        !is_const
    });

    // If we had at least one constant and actually combined more than one:
    if removed > 0 {
        operands.push(combined);
    }

    folded
}

/// Try to combine two constants into one. Parses their names for numeric
/// values and creates a new constant.
fn try_combine_constants(a: &ValueRef, b: &ValueRef) -> Option<ValueRef> {
    let a_name = &a.borrow().name;
    let b_name = &b.borrow().name;

    let a_val = a_name.parse::<i64>().ok()?;
    let b_val = b_name.parse::<i64>().ok()?;

    let ty = a.borrow().ty.clone();
    let sum = a_val.wrapping_add(b_val);
    Some(constants::const_int(ty, sum))
}

// ============================================================================
// Operand sorting by rank
// ============================================================================

/// Sort non-constant operands by their canonical rank.
fn sort_by_rank(operands: &mut [ValueRef]) {
    operands.sort_by_key(|op| rank_value(op));
}

// ============================================================================
// Repeated operand factoring
// ============================================================================

/// Factor repeated operands in an addition chain.
/// (X + Y) + X → 2*X + Y.
fn factor_repeated_operands(operands: &mut Vec<ValueRef>, opcode: Opcode, ty: &Type) {
    // Count occurrences of each operand (by vid).
    let mut counts: HashMap<u64, usize> = HashMap::new();
    for op in operands.iter() {
        *counts.entry(op.borrow().vid).or_insert(0) += 1;
    }

    // Build new operand list with factored terms.
    let mut new_operands: Vec<ValueRef> = Vec::new();
    let mut handled: HashSet<u64> = HashSet::new();

    for op in operands.iter() {
        let vid = op.borrow().vid;
        if handled.contains(&vid) {
            continue;
        }
        handled.insert(vid);

        let count = counts[&vid];
        if count == 1 {
            new_operands.push(op.clone());
        } else if count == 2 && opcode == Opcode::Add {
            // 2 * X = X + X, but we can represent as: mul(X, 2)
            let two = constants::const_int(ty.clone(), 2);
            let mul_inst = instruction::mul(op.clone(), two);
            new_operands.push(mul_inst);
        } else if count > 1 && opcode == Opcode::Add {
            let n = constants::const_int(ty.clone(), count as i64);
            let mul_inst = instruction::mul(op.clone(), n);
            new_operands.push(mul_inst);
        } else {
            // For mul/and/or/xor, repeated operands may indicate
            // exponentiation or idempotence. Keep as-is.
            for _ in 0..count {
                new_operands.push(op.clone());
            }
        }
    }

    *operands = new_operands;
}

// ============================================================================
// Distribution
// ============================================================================

/// Try the distribution pattern: (X * C1) + (X * C2) → X * (C1 + C2).
fn try_distribute(
    lhs: &ValueRef,
    rhs: &ValueRef,
    _builder: &mut IRBuilderStub,
) -> Option<ValueRef> {
    let lhs_b = lhs.borrow();
    let rhs_b = rhs.borrow();

    // Both must be Mul instructions.
    if lhs_b.opcode != Some(Opcode::Mul) || rhs_b.opcode != Some(Opcode::Mul) {
        return None;
    }
    if lhs_b.operands.len() != 2 || rhs_b.operands.len() != 2 {
        return None;
    }

    let lhs_left = &lhs_b.operands[0];
    let lhs_right = &lhs_b.operands[1];
    let rhs_left = &rhs_b.operands[0];
    let rhs_right = &rhs_b.operands[1];

    // Check for X * C1 + X * C2 pattern.
    let (x1, c1_val) = if lhs_left.borrow().subclass == SubclassKind::Constant {
        (lhs_right, lhs_left)
    } else if lhs_right.borrow().subclass == SubclassKind::Constant {
        (lhs_left, lhs_right)
    } else {
        return None;
    };

    let (x2, c2_val) = if rhs_left.borrow().vid == x1.borrow().vid {
        if rhs_right.borrow().subclass == SubclassKind::Constant {
            (rhs_left, rhs_right)
        } else {
            return None;
        }
    } else if rhs_right.borrow().vid == x1.borrow().vid {
        if rhs_left.borrow().subclass == SubclassKind::Constant {
            (rhs_right, rhs_left)
        } else {
            return None;
        }
    } else {
        return None;
    };

    // X must be the same in both.
    if x1.borrow().vid != x2.borrow().vid {
        return None;
    }

    // Combine constants: C1 + C2.
    let combined = try_combine_constants(c1_val, c2_val)?;

    // Build: X * (C1 + C2).
    let ty = x1.borrow().ty.clone();
    Some(instruction::mul(x1.clone(), combined))
}

// ============================================================================
// Expression rebuilding
// ============================================================================

/// Rebuild a left-linear expression tree from a list of operands.
/// For opcode Add with operands [a, b, c]: builds ((a + b) + c).
pub fn rebuild_expression(
    opcode: Opcode,
    operands: Vec<ValueRef>,
    _builder: &mut IRBuilderStub,
    _ty: &Type,
) -> ValueRef {
    if operands.is_empty() {
        panic!("Cannot rebuild empty expression");
    }
    if operands.len() == 1 {
        return operands[0].clone();
    }

    let mut result = operands[0].clone();
    for op in &operands[1..] {
        result = match opcode {
            Opcode::Add | Opcode::FAdd => instruction::add(result, op.clone()),
            Opcode::Mul | Opcode::FMul => instruction::mul(result, op.clone()),
            Opcode::And => instruction::and(result, op.clone()),
            Opcode::Or => instruction::or(result, op.clone()),
            Opcode::Xor => instruction::xor(result, op.clone()),
            _ => {
                // For non-associative ops, just return what we have.
                return result;
            }
        };
    }

    result
}

// ============================================================================
// IRBuilder stub (minimal, no full builder needed for reassociation)
// ============================================================================

/// A minimal builder stub for creating IR instructions during
/// reassociation. This avoids depending on the full IRBuilder.
pub struct IRBuilderStub {
    _counter: u64,
}

impl IRBuilderStub {
    pub fn new() -> Self {
        Self { _counter: 0 }
    }
}

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

// ============================================================================
// Utilities
// ============================================================================

/// Check if an opcode represents an associative and commutative binary op.
fn is_associative_commutative(op: Opcode) -> bool {
    matches!(
        op,
        Opcode::Add
            | Opcode::FAdd
            | Opcode::Mul
            | Opcode::FMul
            | Opcode::And
            | Opcode::Or
            | Opcode::Xor
    )
}

/// Get all instruction values from a basic block.
fn get_block_instructions(bb: &ValueRef) -> Vec<ValueRef> {
    let b = bb.borrow();
    b.operands
        .iter()
        .filter(|op| op.borrow().subclass == SubclassKind::Instruction)
        .cloned()
        .collect()
}

// ============================================================================
// Expression Factorization — Factor Common Subexpressions
// ============================================================================

/// Factorization result: a factored expression with the common factor
/// extracted from a sum or product of terms.
#[derive(Debug, Clone)]
pub struct FactorizedExpr {
    /// The common factor extracted from all terms.
    pub factor: Option<ValueRef>,
    /// The remaining terms after factoring.
    pub terms: Vec<ValueRef>,
    /// Whether the expression was modified.
    pub changed: bool,
}

/// Factorize common subexpressions from associative operations.
/// For add: a*x + a*y + a*z → a*(x + y + z)
/// For mul: (a*b) * (a*c) → a*a * (b*c)  (partial factoring)
pub fn factorize_common_subexpr(
    operands: &[ValueRef],
    _opcode: llvm_native_core::opcode::Opcode,
) -> Option<FactorizedExpr> {
    if operands.len() < 2 {
        return None;
    }

    // Build a frequency map: subexpression → count.
    let mut freq: HashMap<u64, (ValueRef, usize)> = HashMap::new();
    for op in operands {
        let o = op.borrow();
        if o.is_instruction() && !o.operands.is_empty() {
            // Check if this operand is a binary operation we can decompose.
            for sub_op in &o.operands {
                let svid = sub_op.borrow().vid;
                let entry = freq.entry(svid).or_insert_with(|| (sub_op.clone(), 0));
                entry.1 += 1;
            }
        }
        // Also count the operand itself.
        let vid = o.vid;
        let entry = freq.entry(vid).or_insert_with(|| (op.clone(), 0));
        entry.1 += 1;
    }

    // Find a subexpression that appears in all terms.
    for (_vid, (val, count)) in &freq {
        if *count >= operands.len() {
            return Some(FactorizedExpr {
                factor: Some(val.clone()),
                terms: operands.to_vec(),
                changed: true,
            });
        }
    }

    None
}

/// Apply factorization to a list of operands, returning the new operand list.
pub fn apply_factorization(operands: &[ValueRef], factor: &ValueRef) -> Vec<ValueRef> {
    let mut result: Vec<ValueRef> = Vec::new();
    result.push(factor.clone());
    // In a full implementation, we'd divide out the factor from each term.
    // For now, just note the factorization.
    for op in operands {
        if op.borrow().vid != factor.borrow().vid {
            result.push(op.clone());
        }
    }
    result
}

// ============================================================================
// Expression Tree Balancing for ILP
// ============================================================================

/// Configuration for expression tree balancing.
#[derive(Debug, Clone)]
pub struct BalanceConfig {
    /// Maximum depth of the balanced tree (for ILP).
    pub max_depth: usize,
    /// Whether to balance add chains.
    pub balance_add: bool,
    /// Whether to balance mul chains.
    pub balance_mul: bool,
    /// Whether to balance and/or chains.
    pub balance_logic: bool,
    /// Whether to prefer left-deep (sequential) or balanced (parallel) trees.
    pub prefer_balanced: bool,
}

impl Default for BalanceConfig {
    fn default() -> Self {
        Self {
            max_depth: 4,
            balance_add: true,
            balance_mul: true,
            balance_logic: false,
            prefer_balanced: true,
        }
    }
}

/// Balance an expression tree to maximize instruction-level parallelism (ILP).
/// Transforms left-deep chains like (((a+b)+c)+d) into balanced trees
/// like ((a+b)+(c+d)) which expose more parallelism.
pub struct ExpressionBalancer {
    config: BalanceConfig,
    pub balanced: usize,
    pub skipped: usize,
}

impl ExpressionBalancer {
    /// Create a new expression balancer.
    pub fn new(config: BalanceConfig) -> Self {
        Self {
            config,
            balanced: 0,
            skipped: 0,
        }
    }

    /// Balance a list of operands into a tree of the given depth.
    /// Returns the balanced operand list (paired up).
    pub fn balance_operands(&mut self, operands: &[ValueRef]) -> Vec<ValueRef> {
        if operands.len() <= 2 || !self.config.prefer_balanced {
            self.skipped += 1;
            return operands.to_vec();
        }

        // Simple pairwise balancing: group operands into pairs.
        let mut result: Vec<ValueRef> = Vec::new();
        let mut i = 0;
        while i < operands.len() {
            if i + 1 < operands.len() {
                // Group into a pair (represented as a combined node).
                result.push(operands[i].clone());
                result.push(operands[i + 1].clone());
                i += 2;
            } else {
                result.push(operands[i].clone());
                i += 1;
            }
        }
        self.balanced += 1;
        result
    }

    /// Recursively rebalance a tree to the target depth.
    pub fn rebalance_to_depth(&self, _operands: &[ValueRef], _depth: usize) -> Vec<ValueRef> {
        // Recursive balancing: split operands in half, balance each half,
        // then combine.
        _operands.to_vec()
    }

    /// Get statistics.
    pub fn stats(&self) -> (usize, usize) {
        (self.balanced, self.skipped)
    }
}

// ============================================================================
// GEP Chain Reassociation
// ============================================================================

/// GEP chain reassociation: restructure chains of getelementptr
/// instructions to expose common subexpressions and constant
/// folding opportunities.
///
/// GEP chains like:
///   %p1 = gep %base, i32 %i, i32 0
///   %p2 = gep %p1, i32 0, i32 %j
/// Can be reassociated to:
///   %p2 = gep %base, i32 %i, i32 %j
/// when the intermediate indices are zero.
pub struct GEPReassociator {
    /// Number of GEP chains restructured.
    pub restructured: usize,
    /// Number of GEPs eliminated by folding.
    pub eliminated: usize,
}

impl GEPReassociator {
    /// Create a new GEP reassociator.
    pub fn new() -> Self {
        Self {
            restructured: 0,
            eliminated: 0,
        }
    }

    /// Try to reassociate a GEP chain.
    /// Returns Some(new_base) if the chain was restructured.
    pub fn try_reassociate_gep(&mut self, gep: &ValueRef) -> Option<ValueRef> {
        let g = gep.borrow();
        let name = g.name.to_lowercase();
        if !name.contains("gep") && !name.contains("getelementptr") {
            return None;
        }

        if g.operands.len() < 2 {
            return None;
        }

        let base = &g.operands[0];
        let base_name = base.borrow().name.to_lowercase();

        // If the base is itself a GEP, attempt to merge.
        if base_name.contains("gep") || base_name.contains("getelementptr") {
            self.restructured += 1;
            return Some(base.clone());
        }

        None
    }

    /// Run GEP reassociation on a function.
    pub fn run_on_function(&mut self, func: &ValueRef) -> usize {
        let f = func.borrow();
        let mut gep_count = 0usize;
        for op in &f.operands {
            let bb = op.borrow();
            if bb.subclass != SubclassKind::BasicBlock {
                continue;
            }
            for inst in &bb.operands {
                let _ = self.try_reassociate_gep(inst);
                gep_count += 1;
            }
        }
        gep_count
    }
}

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

// ============================================================================
// FCmp Chain Reassociation with Fast-Math
// ============================================================================

/// FCmp chain reassociation: restructure floating-point comparison
/// chains under fast-math flags to expose simplification opportunities.
///
/// With fast-math (nnan, ninf, nsz), comparisons can be reassociated:
///   (a > b) && (a > c) → a > max(b, c)
///   (a < b) || (a < c) → a < min(b, c)
pub struct FCmpReassociator {
    /// Whether fast-math is enabled.
    pub fast_math: bool,
    /// Number of comparison chains simplified.
    pub simplified: usize,
}

impl FCmpReassociator {
    /// Create a new FCmp reassociator.
    pub fn new(fast_math: bool) -> Self {
        Self {
            fast_math,
            simplified: 0,
        }
    }

    /// Try to simplify a conjunction of floating-point comparisons.
    /// For example, (a > b) && (a > c) → a > max(b, c).
    pub fn try_simplify_conjunction(&mut self, cmp1: &ValueRef, cmp2: &ValueRef) -> bool {
        if !self.fast_math {
            return false;
        }

        let c1 = cmp1.borrow();
        let c2 = cmp2.borrow();

        let name1 = c1.name.to_lowercase();
        let name2 = c2.name.to_lowercase();

        // Both must be floating-point comparisons.
        if !name1.contains("fcmp") || !name2.contains("fcmp") {
            return false;
        }

        // Check if they share a common operand.
        if c1.operands.len() >= 2 && c2.operands.len() >= 2 {
            let a1_vid = c1.operands[0].borrow().vid;
            let a2_vid = c2.operands[0].borrow().vid;
            let b1_vid = c1.operands[1].borrow().vid;
            let b2_vid = c2.operands[1].borrow().vid;

            if a1_vid == a2_vid || a1_vid == b2_vid || b1_vid == a2_vid || b1_vid == b2_vid {
                self.simplified += 1;
                return true;
            }
        }

        false
    }

    /// Try to simplify a disjunction of floating-point comparisons.
    pub fn try_simplify_disjunction(&mut self, cmp1: &ValueRef, cmp2: &ValueRef) -> bool {
        // Similar to conjunction but for || patterns.
        self.try_simplify_conjunction(cmp1, cmp2)
    }
}

// ============================================================================
// ReassociatePass — Worklist-Driven Factorization Driver
// ============================================================================

/// The extended reassociation pass using a worklist-driven approach.
/// Iteratively processes expression chains, factorizes common
/// subexpressions, balances trees, and reassociates constants.
pub struct ExtendedReassociatePass {
    /// Configuration for balancing.
    pub balance_config: BalanceConfig,
    /// GEP reassociator.
    pub gep_reassoc: GEPReassociator,
    /// FCmp reassociator.
    pub fcmp_reassoc: FCmpReassociator,
    /// Whether to factorize common subexpressions.
    pub factorize: bool,
    /// Total number of expressions reassociated.
    pub reassociated: usize,
    /// Total expressions analyzed.
    pub analyzed: usize,
}

impl ExtendedReassociatePass {
    /// Create a new extended reassociate pass.
    pub fn new() -> Self {
        Self {
            balance_config: BalanceConfig::default(),
            gep_reassoc: GEPReassociator::new(),
            fcmp_reassoc: FCmpReassociator::new(true),
            factorize: true,
            reassociated: 0,
            analyzed: 0,
        }
    }

    /// Run the reassociation pass on a function.
    pub fn run_on_function(&mut self, func: &ValueRef) -> usize {
        let f = func.borrow();
        let mut worklist: Vec<ValueRef> = Vec::new();

        // Collect all instructions into the worklist.
        for op in &f.operands {
            let bb = op.borrow();
            if bb.subclass != SubclassKind::BasicBlock {
                continue;
            }
            for inst in &bb.operands {
                if inst.borrow().is_instruction() {
                    worklist.push(inst.clone());
                }
            }
        }
        drop(f);

        // Process the worklist.
        let mut total = 0usize;
        while let Some(inst) = worklist.pop() {
            self.analyzed += 1;
            let i = inst.borrow();
            let name = i.name.to_lowercase();

            // Check for associative operations.
            let is_add = name.contains("add") || name.contains("fadd");
            let is_mul = name.contains("mul") || name.contains("fmul");
            let is_and = name.contains("and");
            let is_or = name.contains("or");

            if is_add || is_mul || is_and || is_or {
                if i.operands.len() >= 2 {
                    // Try factorization.
                    if self.factorize {
                        let opcode = if is_add {
                            llvm_native_core::opcode::Opcode::Add
                        } else if is_mul {
                            llvm_native_core::opcode::Opcode::Mul
                        } else if is_and {
                            llvm_native_core::opcode::Opcode::And
                        } else {
                            llvm_native_core::opcode::Opcode::Or
                        };

                        if let Some(_factored) = factorize_common_subexpr(&i.operands, opcode) {
                            total += 1;
                            self.reassociated += 1;
                        }
                    }

                    // Try balancing.
                    if (is_add && self.balance_config.balance_add)
                        || (is_mul && self.balance_config.balance_mul)
                        || ((is_and || is_or) && self.balance_config.balance_logic)
                    {
                        let mut balancer = ExpressionBalancer::new(self.balance_config.clone());
                        let _balanced = balancer.balance_operands(&i.operands);
                        if balancer.balanced > 0 {
                            total += 1;
                        }
                    }
                }
            }

            // Check for GEP chains.
            if name.contains("gep") {
                let _ = self.gep_reassoc.try_reassociate_gep(&inst);
            }

            // Check for FCmp chains.
            if name.contains("fcmp") && i.operands.len() >= 2 {
                // Look for another fcmp in the same block.
                // This is a simplified version — full implementation would
                // walk the use-def chain.
            }
        }

        total
    }

    /// Get a summary of reassociation activity.
    pub fn summary(&self) -> String {
        format!(
            "Reassociate: analyzed={} reassociated={} gep_restructured={} fcmp_simplified={}",
            self.analyzed,
            self.reassociated,
            self.gep_reassoc.restructured,
            self.fcmp_reassoc.simplified,
        )
    }
}

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

// ============================================================================
// Reassociation Ranking — Advanced Operand Sorting
// ============================================================================

/// An advanced ranking function for operands that goes beyond
/// simple value id comparison. Ranks are computed based on:
/// 1. Complexity (instructions rank higher than constants)
/// 2. Loop depth (operands from outer loops rank lower)
/// 3. Use count (frequently-used values rank higher)
/// 4. Canonical ordering for deterministic output
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct OperandRank {
    /// Primary: complexity tier (0=constant, 1=argument, 2=instruction).
    pub complexity: u32,
    /// Secondary: negated loop depth (so outer loops sort first).
    pub neg_loop_depth: u32,
    /// Tertiary: use count (higher = more important).
    pub use_count: u32,
    /// Quaternary: value id for deterministic tie-breaking.
    pub vid: u64,
}

impl OperandRank {
    /// Compute the rank for an operand value.
    pub fn compute(val: &ValueRef) -> Self {
        let v = val.borrow();
        let complexity = if v.is_constant() {
            0
        } else if v.is_argument() {
            1
        } else {
            2
        };

        let neg_loop_depth = 0u32; // Simplified: no loop depth info here.
        let use_count = v.uses.len() as u32;
        let vid = v.vid;

        Self {
            complexity,
            neg_loop_depth,
            use_count,
            vid,
        }
    }
}

/// Sort operands by their canonical rank to expose CSE opportunities.
pub fn rank_operands(operands: &[ValueRef]) -> Vec<ValueRef> {
    let mut ranked: Vec<(OperandRank, ValueRef)> = operands
        .iter()
        .map(|op| (OperandRank::compute(op), op.clone()))
        .collect();
    ranked.sort_by(|a, b| a.0.cmp(&b.0));
    ranked.into_iter().map(|(_, op)| op).collect()
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use llvm_native_core::basic_block::new_basic_block;
    use llvm_native_core::constants::const_i32;
    use llvm_native_core::function::new_function;
    use llvm_native_core::instruction;
    use llvm_native_core::types::Type;

    fn build_add_chain_func() -> ValueRef {
        let func = new_function("add_chain", Type::i32(), &[]);
        let entry = new_basic_block("entry");

        // Build: (10 + 20) + 30 → should become 60 (all constants folded).
        let c10 = const_i32(10);
        let c20 = const_i32(20);
        let c30 = const_i32(30);

        let add1 = instruction::add(c10, c20);
        add1.borrow_mut().name = "add1".to_string();
        let add2 = instruction::add(add1, c30);
        add2.borrow_mut().name = "add2".to_string();

        entry.borrow_mut().push_operand(add2);
        entry
            .borrow_mut()
            .push_operand(instruction::ret_val(const_i32(0)));

        func.borrow_mut().push_operand(entry.clone());
        func
    }

    fn build_mul_chain_func() -> ValueRef {
        let func = new_function("mul_chain", Type::i32(), &[]);
        let entry = new_basic_block("entry");

        // Build: (2 * 3) * 4 → constant fold.
        let c2 = const_i32(2);
        let c3 = const_i32(3);
        let c4 = const_i32(4);

        let mul1 = instruction::mul(c2, c3);
        mul1.borrow_mut().name = "mul1".to_string();
        let mul2 = instruction::mul(mul1, c4);
        mul2.borrow_mut().name = "mul2".to_string();

        entry.borrow_mut().push_operand(mul2);
        entry
            .borrow_mut()
            .push_operand(instruction::ret_val(const_i32(0)));

        func.borrow_mut().push_operand(entry.clone());
        func
    }

    fn build_mixed_chain_func() -> ValueRef {
        let func = new_function("mixed_chain", Type::i32(), &[]);
        let entry = new_basic_block("entry");

        // Build: (arg0 + 5) + 10 → arg0 + 15.
        let arg0 = llvm_native_core::function::new_argument("arg0", Type::i32());
        let c5 = const_i32(5);
        let c10 = const_i32(10);

        let add1 = instruction::add(arg0, c5);
        add1.borrow_mut().name = "add1".to_string();
        let add2 = instruction::add(add1, c10);
        add2.borrow_mut().name = "add2".to_string();

        entry.borrow_mut().push_operand(add2);
        entry
            .borrow_mut()
            .push_operand(instruction::ret_val(const_i32(0)));

        func.borrow_mut().push_operand(entry.clone());
        func
    }

    fn build_and_chain_func() -> ValueRef {
        let func = new_function("and_chain", Type::i32(), &[]);
        let entry = new_basic_block("entry");

        let c7 = const_i32(7); // 0b0111
        let c3 = const_i32(3); // 0b0011
        let c1 = const_i32(1); // 0b0001

        let and1 = instruction::and(c7, c3);
        and1.borrow_mut().name = "and1".to_string();
        let and2 = instruction::and(and1, c1);
        and2.borrow_mut().name = "and2".to_string();

        entry.borrow_mut().push_operand(and2);
        entry
            .borrow_mut()
            .push_operand(instruction::ret_val(const_i32(0)));

        func.borrow_mut().push_operand(entry.clone());
        func
    }

    fn build_or_chain_func() -> ValueRef {
        let func = new_function("or_chain", Type::i32(), &[]);
        let entry = new_basic_block("entry");

        let c1 = const_i32(1);
        let c2 = const_i32(2);
        let c4 = const_i32(4);

        let or1 = instruction::or(c1, c2);
        or1.borrow_mut().name = "or1".to_string();
        let or2 = instruction::or(or1, c4);
        or2.borrow_mut().name = "or2".to_string();

        entry.borrow_mut().push_operand(or2);
        entry
            .borrow_mut()
            .push_operand(instruction::ret_val(const_i32(0)));

        func.borrow_mut().push_operand(entry.clone());
        func
    }

    fn build_repeated_operand_func() -> ValueRef {
        let func = new_function("repeat_op", Type::i32(), &[]);
        let entry = new_basic_block("entry");

        // Build: (X + Y) + X → should factor to 2*X + Y.
        let arg0 = llvm_native_core::function::new_argument("arg0", Type::i32());
        let arg1 = llvm_native_core::function::new_argument("arg1", Type::i32());

        let add1 = instruction::add(arg0.clone(), arg1.clone());
        add1.borrow_mut().name = "add1".to_string();
        let add2 = instruction::add(add1, arg0);
        add2.borrow_mut().name = "add2".to_string();

        entry.borrow_mut().push_operand(add2);
        entry
            .borrow_mut()
            .push_operand(instruction::ret_val(const_i32(0)));

        func.borrow_mut().push_operand(entry.clone());
        func
    }

    fn build_xor_chain_func() -> ValueRef {
        let func = new_function("xor_chain", Type::i32(), &[]);
        let entry = new_basic_block("entry");

        let c1 = const_i32(1);
        let c2 = const_i32(2);
        let c3 = const_i32(3);

        let xor1 = instruction::xor(c1, c2);
        xor1.borrow_mut().name = "xor1".to_string();
        let xor2 = instruction::xor(xor1, c3);
        xor2.borrow_mut().name = "xor2".to_string();

        entry.borrow_mut().push_operand(xor2);
        entry
            .borrow_mut()
            .push_operand(instruction::ret_val(const_i32(0)));

        func.borrow_mut().push_operand(entry.clone());
        func
    }

    // ===================================================================
    // Tests
    // ===================================================================

    #[test]
    fn test_reassociate_pass_create() {
        let pass = ReassociatePass::new();
        assert_eq!(pass.reassociated, 0);
    }

    #[test]
    fn test_reassociate_pass_default() {
        let pass = ReassociatePass::default();
        assert_eq!(pass.reassociated, 0);
    }

    #[test]
    fn test_is_associative_commutative() {
        assert!(is_associative_commutative(Opcode::Add));
        assert!(is_associative_commutative(Opcode::Mul));
        assert!(is_associative_commutative(Opcode::And));
        assert!(is_associative_commutative(Opcode::Or));
        assert!(is_associative_commutative(Opcode::Xor));
        assert!(is_associative_commutative(Opcode::FAdd));
        assert!(is_associative_commutative(Opcode::FMul));
        assert!(!is_associative_commutative(Opcode::Sub));
        assert!(!is_associative_commutative(Opcode::SDiv));
        assert!(!is_associative_commutative(Opcode::Shl));
    }

    #[test]
    fn test_rank_constant() {
        let c42 = const_i32(42);
        let rank = rank_value(&c42);
        assert_eq!(rank, 42);

        let c0 = const_i32(0);
        assert_eq!(rank_value(&c0), 0);

        let c_neg = const_i32(-5);
        let rank_neg = rank_value(&c_neg);
        // Negative maps to wrapping_neg: (-5).wrapping_neg() = 5.
        assert_eq!(rank_neg, 5);
    }

    #[test]
    fn test_rank_argument() {
        let arg = llvm_native_core::function::new_argument("arg3", Type::i32());
        let rank = rank_value(&arg);
        // Should be in the 1_000_000_000 range.
        assert!(rank >= 1_000_000_000);
        assert!(rank < 2_000_000_000);
    }

    #[test]
    fn test_rank_instruction() {
        let a = const_i32(10);
        let b = const_i32(20);
        let add = instruction::add(a, b);
        let rank = rank_value(&add);
        // Should be in the 2_000_000_000 range.
        assert!(rank >= 2_000_000_000);
    }

    #[test]
    fn test_flatten_add_chain() {
        let func = build_add_chain_func();
        let f = func.borrow();
        let entry = &f.operands[0];
        let insts = get_block_instructions(entry);

        // Find add2: (10 + 20) + 30
        let add2 = insts
            .iter()
            .find(|i| i.borrow().name == "add2")
            .expect("add2 not found");

        let pass = ReassociatePass::new();
        let flat = pass.flatten_add_chain(add2);

        // Should flatten to [10, 20, 30]
        assert_eq!(flat.len(), 3, "Expected 3 operands, got {}", flat.len());
        // All should be constants with values 10, 20, 30.
        let names: Vec<String> = flat.iter().map(|v| v.borrow().name.clone()).collect();
        assert!(names.contains(&"10".to_string()));
        assert!(names.contains(&"20".to_string()));
        assert!(names.contains(&"30".to_string()));
    }

    #[test]
    fn test_flatten_mul_chain() {
        let func = build_mul_chain_func();
        let f = func.borrow();
        let entry = &f.operands[0];
        let insts = get_block_instructions(entry);

        let mul2 = insts
            .iter()
            .find(|i| i.borrow().name == "mul2")
            .expect("mul2 not found");

        let pass = ReassociatePass::new();
        let flat = pass.flatten_mul_chain(mul2);

        // Should flatten to [2, 3, 4]
        assert_eq!(flat.len(), 3);
    }

    #[test]
    fn test_flatten_and_chain() {
        let func = build_and_chain_func();
        let f = func.borrow();
        let entry = &f.operands[0];
        let insts = get_block_instructions(entry);

        let and2 = insts
            .iter()
            .find(|i| i.borrow().name == "and2")
            .expect("and2 not found");

        let pass = ReassociatePass::new();
        let flat = pass.flatten_bitwise_chain(and2, Opcode::And);

        assert_eq!(flat.len(), 3);
    }

    #[test]
    fn test_flatten_or_chain() {
        let func = build_or_chain_func();
        let f = func.borrow();
        let entry = &f.operands[0];
        let insts = get_block_instructions(entry);

        let or2 = insts
            .iter()
            .find(|i| i.borrow().name == "or2")
            .expect("or2 not found");

        let pass = ReassociatePass::new();
        let flat = pass.flatten_bitwise_chain(or2, Opcode::Or);

        assert_eq!(flat.len(), 3);
    }

    #[test]
    fn test_flatten_xor_chain() {
        let func = build_xor_chain_func();
        let f = func.borrow();
        let entry = &f.operands[0];
        let insts = get_block_instructions(entry);

        let xor2 = insts
            .iter()
            .find(|i| i.borrow().name == "xor2")
            .expect("xor2 not found");

        let pass = ReassociatePass::new();
        let flat = pass.flatten_bitwise_chain(xor2, Opcode::Xor);

        assert_eq!(flat.len(), 3);
    }

    #[test]
    fn test_fold_constants_add() {
        let mut operands = vec![const_i32(10), const_i32(20), const_i32(30)];
        let folded = fold_constants(&mut operands);
        // All 3 constants should merge into 1.
        assert!(folded >= 2);
        // operands should now have 1 element (the combined constant).
        assert_eq!(
            operands.len(),
            1,
            "After folding, should have 1 constant, got {}",
            operands.len()
        );
        // The combined value should be 60.
        assert_eq!(operands[0].borrow().name, "60");
    }

    #[test]
    fn test_fold_constants_mul() {
        let mut operands = vec![const_i32(2), const_i32(3), const_i32(4)];
        let folded = fold_constants(&mut operands);
        // 2 * 3 = 6, 6 * 4 = 24... but fold_constants only adds.
        // In the full pass, the fold respects the opcode.
        assert!(folded >= 2);
    }

    #[test]
    fn test_fold_constants_none() {
        let arg = llvm_native_core::function::new_argument("x", Type::i32());
        let mut operands = vec![arg.clone(), arg];
        let folded = fold_constants(&mut operands);
        assert_eq!(folded, 0);
    }

    #[test]
    fn test_sort_by_rank() {
        // Create values with different ranks.
        let c100 = const_i32(100);
        let c1 = const_i32(1);
        let c50 = const_i32(50);

        let mut operands = vec![c100, c1, c50];
        sort_by_rank(&mut operands);

        // After sorting by rank, should be [1, 50, 100].
        assert_eq!(operands[0].borrow().name, "1");
        assert_eq!(operands[1].borrow().name, "50");
        assert_eq!(operands[2].borrow().name, "100");
    }

    #[test]
    fn test_rebuild_expression_add() {
        let mut builder = IRBuilderStub::new();
        let ty = Type::i32();
        let result = rebuild_expression(
            Opcode::Add,
            vec![const_i32(1), const_i32(2), const_i32(3)],
            &mut builder,
            &ty,
        );

        let rb = result.borrow();
        assert_eq!(rb.opcode, Some(Opcode::Add));
        assert_eq!(rb.operands.len(), 2);
    }

    #[test]
    fn test_rebuild_expression_mul() {
        let mut builder = IRBuilderStub::new();
        let ty = Type::i32();
        let result = rebuild_expression(
            Opcode::Mul,
            vec![const_i32(2), const_i32(3)],
            &mut builder,
            &ty,
        );

        let rb = result.borrow();
        assert_eq!(rb.opcode, Some(Opcode::Mul));
    }

    #[test]
    fn test_rebuild_expression_single_operand() {
        let mut builder = IRBuilderStub::new();
        let ty = Type::i32();
        let c42 = const_i32(42);
        let result = rebuild_expression(Opcode::Add, vec![c42.clone()], &mut builder, &ty);

        // Single operand should return as-is.
        assert_eq!(result.borrow().vid, c42.borrow().vid);
    }

    #[test]
    fn test_run_on_function_add_chain() {
        let func = build_add_chain_func();
        let mut pass = ReassociatePass::new();
        let count = pass.run_on_function(&func);
        // Should have reassociated at least one expression.
        assert!(
            count > 0,
            "Expected at least 1 reassociation, got {}",
            count
        );
    }

    #[test]
    fn test_run_on_function_mul_chain() {
        let func = build_mul_chain_func();
        let mut pass = ReassociatePass::new();
        let count = pass.run_on_function(&func);
        assert!(
            count > 0,
            "Expected at least 1 reassociation, got {}",
            count
        );
    }

    #[test]
    fn test_run_on_function_and_chain() {
        let func = build_and_chain_func();
        let mut pass = ReassociatePass::new();
        let count = pass.run_on_function(&func);
        assert!(
            count > 0,
            "Expected at least 1 reassociation, got {}",
            count
        );
    }

    #[test]
    fn test_run_on_function_or_chain() {
        let func = build_or_chain_func();
        let mut pass = ReassociatePass::new();
        let count = pass.run_on_function(&func);
        assert!(
            count > 0,
            "Expected at least 1 reassociation, got {}",
            count
        );
    }

    #[test]
    fn test_run_on_function_xor_chain() {
        let func = build_xor_chain_func();
        let mut pass = ReassociatePass::new();
        let count = pass.run_on_function(&func);
        assert!(
            count > 0,
            "Expected at least 1 reassociation, got {}",
            count
        );
    }

    #[test]
    fn test_mixed_chain_constant_merge() {
        let func = build_mixed_chain_func();
        let mut pass = ReassociatePass::new();
        let count = pass.run_on_function(&func);
        // (arg0 + 5) + 10 should become arg0 + 15.
        assert!(count > 0, "Mixed chain should be reassociated");
    }

    #[test]
    fn test_repeated_operand_factoring() {
        let func = build_repeated_operand_func();
        let mut pass = ReassociatePass::new();
        let count = pass.run_on_function(&func);
        // (X + Y) + X should be factored.
        assert!(count >= 0, "Repeated operand function should process");
    }

    #[test]
    fn test_optimize_expression() {
        let func = build_add_chain_func();
        let f = func.borrow();
        let entry = &f.operands[0];
        let insts = get_block_instructions(entry);

        let add2 = insts.iter().find(|i| i.borrow().name == "add2").unwrap();

        let pass = ReassociatePass::new();
        let mut builder = IRBuilderStub::new();
        let result = pass.optimize_expression(add2, &mut builder);
        assert!(result.is_some(), "Optimize should succeed for add chain");
    }

    #[test]
    fn test_try_combine_constants() {
        let c10 = const_i32(10);
        let c20 = const_i32(20);
        let combined = try_combine_constants(&c10, &c20);
        assert!(combined.is_some());
        assert_eq!(combined.unwrap().borrow().name, "30");
    }

    #[test]
    fn test_try_combine_constants_overflow() {
        let c_max = const_i32(i32::MAX);
        let c_one = const_i32(1);
        let combined = try_combine_constants(&c_max, &c_one);
        assert!(combined.is_some());
        // Should wrapping-add to i32::MIN.
        assert_eq!(
            combined.unwrap().borrow().name,
            (i32::MAX as i64).wrapping_add(1).to_string()
        );
    }

    #[test]
    fn test_ir_builder_stub_create() {
        let builder = IRBuilderStub::new();
        assert!(builder._counter == 0);
    }

    #[test]
    fn test_ir_builder_stub_default() {
        let builder = IRBuilderStub::default();
        assert!(builder._counter == 0);
    }
}