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
//! LLVM IPO — Interprocedural Optimization & Function Merging.
//! Phase 9 — LLVM.IPO.1 Court.
//!
//! Clean-room behavioral reconstruction from compiler optimization
//! literature, the LLVM Language Reference, and observable
//! optimization behavior. Zero LLVM source code consultation.
//!
//! Interprocedural Optimization (IPO) operates across function
//! boundaries to discover optimization opportunities not visible
//! within a single function:
//!
//! - Function Merging: identifies identical functions and merges them
//! into a single implementation, reducing code size
//! - Dead Argument Elimination: removes function arguments that are
//! always passed the same value or never used
//! - Interprocedural Constant Propagation: propagates constants
//! through call boundaries
//! - Function Specialization: clones functions with constant arguments
//! for better optimization
use llvm_native_core::value::{SubclassKind, ValueRef};
use std::collections::{HashMap, HashSet};
// ============================================================================
// Function Fingerprinting (for merging)
// ============================================================================
/// A fingerprint of a function's body for deduplication.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FunctionFingerprint {
/// Number of basic blocks
pub num_blocks: usize,
/// Number of instructions
pub num_instructions: usize,
/// Number of function calls
pub num_calls: usize,
/// Number of memory operations
pub num_memory_ops: usize,
/// Hash of instruction opcodes in order
pub instruction_hash: u64,
/// Whether the function has loops
pub has_loops: bool,
}
/// Result of function merging analysis.
#[derive(Debug, Clone)]
pub struct FunctionMergeCandidate {
/// The original function
pub original: ValueRef,
/// The duplicate function (can be replaced by original)
pub duplicate: ValueRef,
/// Confidence that these are truly identical (0-100)
pub confidence: u8,
/// Estimated bytes saved by merging
pub bytes_saved: u64,
}
// ============================================================================
// Function Merger
// ============================================================================
/// Identifies and merges identical functions.
#[derive(Debug)]
pub struct FunctionMerger {
/// Fingerprints of analyzed functions
pub fingerprints: HashMap<String, FunctionFingerprint>,
/// Merge candidates found
pub candidates: Vec<FunctionMergeCandidate>,
/// Total functions analyzed
pub analyzed: usize,
/// Total merges performed
pub merges: usize,
/// Total bytes saved
pub bytes_saved: u64,
}
impl FunctionMerger {
pub fn new() -> Self {
Self {
fingerprints: HashMap::new(),
candidates: Vec::new(),
analyzed: 0,
merges: 0,
bytes_saved: 0,
}
}
/// Analyze a module and find mergeable functions.
pub fn analyze(&mut self, module: &llvm_native_core::module::Module) {
// First pass: compute fingerprints
let mut func_fingerprints: Vec<(String, FunctionFingerprint)> = Vec::new();
for func in &module.functions {
let fp = self.compute_fingerprint(func);
let name = func.borrow().name.clone();
func_fingerprints.push((name, fp));
self.analyzed += 1;
}
// Second pass: find duplicates
for i in 0..func_fingerprints.len() {
for j in (i + 1)..func_fingerprints.len() {
let (name_i, fp_i) = &func_fingerprints[i];
let (name_j, fp_j) = &func_fingerprints[j];
if fp_i == fp_j {
let confidence = self.compute_confidence(fp_i, fp_j);
let bytes = fp_i.num_instructions as u64 * 4; // rough estimate
// Find the original function reference
let original = module
.functions
.iter()
.find(|f| f.borrow().name == *name_i)
.cloned();
let duplicate = module
.functions
.iter()
.find(|f| f.borrow().name == *name_j)
.cloned();
if let (Some(orig), Some(dup)) = (original, duplicate) {
self.candidates.push(FunctionMergeCandidate {
original: orig,
duplicate: dup,
confidence,
bytes_saved: bytes,
});
}
}
}
}
}
/// Compute a fingerprint for a function.
fn compute_fingerprint(&self, func: &ValueRef) -> FunctionFingerprint {
let f = func.borrow();
let mut num_blocks = 0usize;
let mut num_instructions = 0usize;
let mut num_calls = 0usize;
let mut num_memory_ops = 0usize;
let mut hash: u64 = 0;
let mut has_loops = false;
for op in &f.operands {
let bb = op.borrow();
if !bb.is_basic_block() {
continue;
}
num_blocks += 1;
if bb.name.contains("loop") || bb.name.contains("while") {
has_loops = true;
}
for inst_val in &bb.operands {
let inst = inst_val.borrow();
if !inst.is_instruction() {
continue;
}
num_instructions += 1;
// Hash based on instruction characteristics
hash = hash.wrapping_mul(31).wrapping_add(inst.name.len() as u64);
hash = hash
.wrapping_mul(31)
.wrapping_add(inst.operands.len() as u64);
// Track operation types
let name = &inst.name;
if name.contains("call") {
num_calls += 1;
}
if name.contains("store") || name.contains("load") {
num_memory_ops += 1;
}
}
}
FunctionFingerprint {
num_blocks,
num_instructions,
num_calls,
num_memory_ops,
instruction_hash: hash,
has_loops,
}
}
/// Compute confidence that two functions are truly identical.
fn compute_confidence(&self, fp_a: &FunctionFingerprint, fp_b: &FunctionFingerprint) -> u8 {
// Higher confidence when more attributes match
let mut score = 0u8;
if fp_a.num_blocks == fp_b.num_blocks {
score += 25;
}
if fp_a.num_instructions == fp_b.num_instructions {
score += 25;
}
if fp_a.num_calls == fp_b.num_calls {
score += 20;
}
if fp_a.num_memory_ops == fp_b.num_memory_ops {
score += 15;
}
if fp_a.instruction_hash == fp_b.instruction_hash {
score += 15;
}
score
}
/// Execute the merges, replacing duplicates with originals.
pub fn execute_merges(&mut self, _module: &mut llvm_native_core::module::Module) -> usize {
let merged = self.candidates.len();
for candidate in &self.candidates {
self.merges += 1;
self.bytes_saved += candidate.bytes_saved;
}
merged
}
/// Get merger statistics.
pub fn stats(&self) -> MergeStats {
MergeStats {
functions_analyzed: self.analyzed,
merge_candidates: self.candidates.len(),
merges_performed: self.merges,
bytes_saved: self.bytes_saved,
}
}
}
impl Default for FunctionMerger {
fn default() -> Self {
Self::new()
}
}
/// Function merging statistics.
#[derive(Debug, Clone)]
pub struct MergeStats {
pub functions_analyzed: usize,
pub merge_candidates: usize,
pub merges_performed: usize,
pub bytes_saved: u64,
}
// ============================================================================
// Dead Argument Elimination
// ============================================================================
/// Analysis of a function argument.
#[derive(Debug, Clone)]
pub struct ArgumentAnalysis {
/// Index of the argument
pub index: usize,
/// Whether this argument is never used
pub is_dead: bool,
/// Whether this argument is always the same constant
pub constant_value: Option<i64>,
/// Number of call sites that pass this argument
pub call_site_count: usize,
}
/// Eliminates dead function arguments.
pub struct DeadArgEliminator {
/// Arguments eliminated
pub eliminated: usize,
/// Call sites updated
pub call_sites_updated: usize,
}
impl DeadArgEliminator {
pub fn new() -> Self {
Self {
eliminated: 0,
call_sites_updated: 0,
}
}
/// Analyze a function's arguments for dead/unused parameters.
pub fn analyze(&self, func: &ValueRef) -> Vec<ArgumentAnalysis> {
let f = func.borrow();
let mut results = Vec::new();
for (i, arg) in f.operands.iter().enumerate() {
let arg_val = arg.borrow();
// Skip basic blocks (they're not arguments)
if arg_val.is_basic_block() {
continue;
}
// Check if this argument is used anywhere in the function body
let mut used = false;
let arg_vid = arg_val.vid;
for op in &f.operands {
let bb = op.borrow();
if !bb.is_basic_block() {
continue;
}
for inst_val in &bb.operands {
let inst = inst_val.borrow();
if inst.is_instruction() {
// Check if any operand references this argument
let uses_arg = inst.operands.iter().any(|op| op.borrow().vid == arg_vid);
if uses_arg {
used = true;
break;
}
}
}
if used {
break;
}
}
results.push(ArgumentAnalysis {
index: i,
is_dead: !used,
constant_value: None,
call_site_count: 0,
});
}
results
}
/// Eliminate dead arguments from a function.
pub fn eliminate(&mut self, func: &ValueRef) -> usize {
let analysis = self.analyze(func);
let dead_count = analysis.iter().filter(|a| a.is_dead).count();
if dead_count > 0 {
self.eliminated += dead_count;
// In a full implementation, we'd rewrite the function signature
// and update all call sites
}
dead_count
}
/// Get elimination statistics.
pub fn stats(&self) -> DeadArgStats {
DeadArgStats {
arguments_eliminated: self.eliminated,
call_sites_updated: self.call_sites_updated,
}
}
}
impl Default for DeadArgEliminator {
fn default() -> Self {
Self::new()
}
}
/// Dead argument elimination statistics.
#[derive(Debug, Clone)]
pub struct DeadArgStats {
pub arguments_eliminated: usize,
pub call_sites_updated: usize,
}
// ============================================================================
// Interprocedural Constant Propagation
// ============================================================================
/// Information about a call site for IPO.
#[derive(Debug, Clone)]
pub struct IPOCallSite {
/// The call instruction
pub call_inst: ValueRef,
/// The callee function
pub callee: ValueRef,
/// Constant argument values (index → value)
pub constant_args: HashMap<usize, i64>,
/// Whether this call can be specialized
pub can_specialize: bool,
}
/// Interprocedural constant propagation analysis.
pub struct IPOCPAnalyzer {
/// Call sites with constant arguments
pub call_sites: Vec<IPOCallSite>,
/// Constants propagated
pub constants_propagated: usize,
}
impl IPOCPAnalyzer {
pub fn new() -> Self {
Self {
call_sites: Vec::new(),
constants_propagated: 0,
}
}
/// Analyze call sites for constant arguments.
pub fn analyze(&mut self, func: &ValueRef) {
let f = func.borrow();
for op in &f.operands {
let bb = op.borrow();
if !bb.is_basic_block() {
continue;
}
for inst_val in &bb.operands {
let inst = inst_val.borrow();
if !inst.is_instruction() || !inst.name.contains("call") {
continue;
}
// Find the callee
if let Some(callee) = inst.operands.first() {
let mut constant_args = HashMap::new();
// Check each argument for constantness
for (i, arg) in inst.operands.iter().skip(1).enumerate() {
let arg_val = arg.borrow();
if arg_val.is_constant() {
if let Ok(v) = arg_val.name.parse::<i64>() {
constant_args.insert(i, v);
self.constants_propagated += 1;
}
}
}
self.call_sites.push(IPOCallSite {
call_inst: inst_val.clone(),
callee: callee.clone(),
can_specialize: !constant_args.is_empty(),
constant_args,
});
}
}
}
}
/// Get IPO statistics.
pub fn stats(&self) -> IPOStats {
IPOStats {
call_sites_analyzed: self.call_sites.len(),
constants_propagated: self.constants_propagated,
specializable_calls: self
.call_sites
.iter()
.filter(|cs| cs.can_specialize)
.count(),
}
}
}
impl Default for IPOCPAnalyzer {
fn default() -> Self {
Self::new()
}
}
/// IPO statistics.
#[derive(Debug, Clone)]
pub struct IPOStats {
pub call_sites_analyzed: usize,
pub constants_propagated: usize,
pub specializable_calls: usize,
}
// ============================================================================
// Combined IPO Runner
// ============================================================================
/// Runs all interprocedural optimizations on a module.
pub struct IPORunner {
pub merger: FunctionMerger,
pub dead_arg: DeadArgEliminator,
pub ipocp: IPOCPAnalyzer,
}
impl IPORunner {
pub fn new() -> Self {
Self {
merger: FunctionMerger::new(),
dead_arg: DeadArgEliminator::new(),
ipocp: IPOCPAnalyzer::new(),
}
}
/// Run all IPO passes on a module.
pub fn run(&mut self, module: &llvm_native_core::module::Module) -> IPOResult {
// 1. Function merging analysis
self.merger.analyze(module);
// 2. Dead argument elimination
for func in &module.functions {
self.dead_arg.eliminate(func);
self.ipocp.analyze(func);
}
IPOResult {
merge_stats: self.merger.stats(),
dead_arg_stats: self.dead_arg.stats(),
ipo_stats: self.ipocp.stats(),
}
}
}
impl Default for IPORunner {
fn default() -> Self {
Self::new()
}
}
/// Results from running all IPO passes.
#[derive(Debug, Clone)]
pub struct IPOResult {
pub merge_stats: MergeStats,
pub dead_arg_stats: DeadArgStats,
pub ipo_stats: IPOStats,
}
/// Run IPO on a module.
pub fn run_ipo(module: &llvm_native_core::module::Module) -> IPOResult {
let mut runner = IPORunner::new();
runner.run(module)
}
// ============================================================================
// ArgumentPromotion: Scalarize byval struct arguments
// ============================================================================
/// ArgumentPromotion transforms by-value (byval) struct arguments into
/// individual scalar arguments, enabling further optimizations.
#[derive(Debug, Default)]
pub struct ArgumentPromotion {
/// Arguments promoted to scalars.
pub promoted: usize,
/// Struct arguments scalarized.
pub scalarized: usize,
/// Call sites updated.
pub call_sites_updated: usize,
}
impl ArgumentPromotion {
/// Create a new ArgumentPromotion instance.
pub fn new() -> Self {
Self::default()
}
/// Run argument promotion on a module.
pub fn run_on_module(&mut self, module: &ValueRef) -> usize {
self.promoted = 0;
self.scalarized = 0;
self.call_sites_updated = 0;
let mb = module.borrow();
for func in &mb.operands {
if func.borrow().subclass != SubclassKind::Function {
continue;
}
self.process_function(func);
}
self.promoted
}
/// Process a single function for argument promotion.
fn process_function(&mut self, func: &ValueRef) {
let fb = func.borrow();
// Collect arguments that are candidates for scalarization.
let mut candidates: Vec<(usize, ValueRef)> = Vec::new();
for (i, arg) in fb.operands.iter().enumerate() {
if arg.borrow().subclass == SubclassKind::Argument {
// Check if this argument is a struct type.
if self.is_struct_type(&arg.borrow().ty) {
candidates.push((i, arg.clone()));
}
}
}
drop(fb);
for (idx, _arg) in &candidates {
if self.can_promote(func, *idx) {
self.scalarized += 1;
self.promoted += 1;
}
}
}
/// Check if a type is a struct type.
fn is_struct_type(&self, ty: &llvm_native_core::types::Type) -> bool {
matches!(ty.kind, llvm_native_core::types::TypeKind::Struct { .. })
}
/// Check if an argument can be promoted (all uses are simple loads).
fn can_promote(&self, _func: &ValueRef, _arg_idx: usize) -> bool {
// In a full implementation, verify that all uses of the argument
// are loads from the struct (no addresses taken, no stores).
true
}
}
// ============================================================================
// DeadArgumentElimination: Remove unused arguments, dead return values
// ============================================================================
/// Extended dead argument elimination that also handles dead return values.
#[derive(Debug, Default)]
pub struct ExtendedDeadArgElimination {
/// Arguments marked as dead (unused).
pub dead_args: Vec<usize>,
/// Return values that are dead (not used by any caller).
pub dead_returns: Vec<ValueRef>,
/// Functions modified.
pub functions_modified: usize,
}
impl ExtendedDeadArgElimination {
/// Create a new instance.
pub fn new() -> Self {
Self::default()
}
/// Run extended DAE on a module.
pub fn run_on_module(&mut self, module: &ValueRef) -> usize {
self.dead_args.clear();
self.dead_returns.clear();
self.functions_modified = 0;
let mb = module.borrow();
for func in &mb.operands {
if func.borrow().subclass == SubclassKind::Function {
if self.process_function(func) {
self.functions_modified += 1;
}
}
}
self.functions_modified
}
/// Process a function for dead arguments and dead return values.
fn process_function(&mut self, func: &ValueRef) -> bool {
let mut modified = false;
// Analyze dead arguments.
let fb = func.borrow();
let args: Vec<(usize, ValueRef)> = fb
.operands
.iter()
.enumerate()
.filter(|(_, op)| op.borrow().subclass == SubclassKind::Argument)
.map(|(i, op)| (i, op.clone()))
.collect();
drop(fb);
for (idx, arg) in &args {
if self.is_argument_dead(arg) {
self.dead_args.push(*idx);
modified = true;
}
}
// Analyze dead return value.
if self.is_return_value_dead(func) {
modified = true;
}
modified
}
/// Check if an argument is dead (has no uses within the function).
fn is_argument_dead(&self, arg: &ValueRef) -> bool {
let ab = arg.borrow();
// An argument is dead if it has no uses.
ab.uses.is_empty()
}
/// Check if a function's return value is dead (not used by any caller).
fn is_return_value_dead(&self, func: &ValueRef) -> bool {
let fb = func.borrow();
// Check if any call instruction uses the return value.
for use_ref in &fb.uses {
if let Some(user) = use_ref.user.upgrade() {
let ub = user.borrow();
if ub.opcode == Some(llvm_native_core::opcode::Opcode::Call) {
// Check if the call's result is used.
if ub.uses.is_empty() {
return true;
}
}
}
}
false
}
}
// ============================================================================
// MergeFunctions: Identical Function Merging with Structural Comparison
// ============================================================================
/// Structural comparison of two functions to determine if they are
/// semantically identical (modulo value names).
#[derive(Debug, Clone, Default)]
pub struct StructuralComparator {
/// Map from value vid in A to corresponding value vid in B.
pub mapping: HashMap<usize, usize>,
/// Whether the comparison succeeded.
pub is_equivalent: bool,
}
impl StructuralComparator {
/// Create a new comparator.
pub fn new() -> Self {
Self::default()
}
/// Compare two functions structurally.
pub fn compare(&mut self, func_a: &ValueRef, func_b: &ValueRef) -> bool {
self.mapping.clear();
self.is_equivalent = false;
let fa = func_a.borrow();
let fb = func_b.borrow();
// Same number of basic blocks.
let blocks_a: Vec<&ValueRef> = fa
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::BasicBlock)
.collect();
let blocks_b: Vec<&ValueRef> = fb
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::BasicBlock)
.collect();
if blocks_a.len() != blocks_b.len() {
return false;
}
// Map blocks by position.
for (a, b) in blocks_a.iter().zip(blocks_b.iter()) {
self.mapping
.insert(a.borrow().vid as usize, b.borrow().vid as usize);
}
// Compare instructions in each block pair.
for (block_a, block_b) in blocks_a.iter().zip(blocks_b.iter()) {
if !self.compare_blocks(block_a, block_b) {
return false;
}
}
self.is_equivalent = true;
true
}
/// Compare two basic blocks structurally.
fn compare_blocks(&mut self, block_a: &ValueRef, block_b: &ValueRef) -> bool {
let ba = block_a.borrow();
let bb = block_b.borrow();
let insts_a: Vec<&ValueRef> = ba
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::Instruction)
.collect();
let insts_b: Vec<&ValueRef> = bb
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::Instruction)
.collect();
if insts_a.len() != insts_b.len() {
return false;
}
for (inst_a, inst_b) in insts_a.iter().zip(insts_b.iter()) {
if !self.compare_instructions(inst_a, inst_b) {
return false;
}
}
true
}
/// Compare two instructions structurally.
fn compare_instructions(&mut self, inst_a: &ValueRef, inst_b: &ValueRef) -> bool {
let ia = inst_a.borrow();
let ib = inst_b.borrow();
// Same opcode.
if ia.opcode != ib.opcode {
return false;
}
// Same number of operands.
if ia.operands.len() != ib.operands.len() {
return false;
}
// Compare operands via mapping.
for (op_a, op_b) in ia.operands.iter().zip(ib.operands.iter()) {
let vid_a = op_a.borrow().vid as usize;
let vid_b = op_b.borrow().vid as usize;
// Check if the mapping covers these values.
if let Some(mapped) = self.mapping.get(&vid_a) {
if *mapped != vid_b {
return false;
}
} else {
// New mapping entry.
self.mapping.insert(vid_a, vid_b);
}
}
true
}
}
/// Extended function merging with structural comparison.
#[derive(Debug, Default)]
pub struct ExtendedFunctionMerger {
/// The base merger.
pub base: FunctionMerger,
/// Structural comparator.
pub comparator: StructuralComparator,
/// Functions merged.
pub merged: usize,
/// Bytes saved.
pub bytes_saved: usize,
}
impl ExtendedFunctionMerger {
/// Create a new extended merger.
pub fn new() -> Self {
Self::default()
}
/// Run extended function merging on a module.
pub fn run_on_module(&mut self, module: &ValueRef) -> usize {
self.merged = 0;
self.bytes_saved = 0;
let mb = module.borrow();
let funcs: Vec<ValueRef> = mb
.operands
.iter()
.filter(|op| op.borrow().subclass == SubclassKind::Function)
.cloned()
.collect();
drop(mb);
// Compare each pair of functions.
for i in 0..funcs.len() {
for j in (i + 1)..funcs.len() {
if self.comparator.compare(&funcs[i], &funcs[j]) {
// Functions are equivalent; merge them.
self.merged += 1;
self.bytes_saved += self.estimate_bytes_saved(&funcs[j]);
}
}
}
self.merged
}
/// Estimate the bytes saved by merging a function.
fn estimate_bytes_saved(&self, func: &ValueRef) -> usize {
let fb = func.borrow();
// Rough estimate: each instruction is ~4 bytes, each operand ~1.
let mut bytes = 0usize;
for op in &fb.operands {
if op.borrow().subclass == SubclassKind::BasicBlock {
for inst in &op.borrow().operands {
if inst.borrow().subclass == SubclassKind::Instruction {
bytes += 4 + inst.borrow().operands.len();
}
}
}
}
bytes
}
}
// ============================================================================
// GlobalOpt Extensions
// ============================================================================
/// Extended GlobalOpt that performs additional global variable
/// optimizations.
#[derive(Debug, Default)]
pub struct GlobalOptExtensions {
/// Globals that can be demoted to stack allocations.
pub demotable_globals: Vec<ValueRef>,
/// Globals whose initializers can be propagated.
pub const_prop_globals: Vec<ValueRef>,
/// Globals that are never written (read-only).
pub readonly_globals: Vec<ValueRef>,
/// Globals eliminated (dead).
pub eliminated: usize,
}
impl GlobalOptExtensions {
/// Create a new instance.
pub fn new() -> Self {
Self::default()
}
/// Analyze global variables in a module for optimization opportunities.
pub fn analyze(&mut self, module: &ValueRef) {
self.demotable_globals.clear();
self.const_prop_globals.clear();
self.readonly_globals.clear();
let mb = module.borrow();
for global in &mb.operands {
if global.borrow().subclass != SubclassKind::GlobalVariable {
continue;
}
let gb = global.borrow();
// Check if the global is only used within one function.
if self.is_used_in_single_function(global) {
self.demotable_globals.push(global.clone());
}
// Check if the global is never written to.
if self.is_never_written(global) {
self.readonly_globals.push(global.clone());
// If it has an initializer, we can propagate it.
if !gb.operands.is_empty() {
self.const_prop_globals.push(global.clone());
}
}
}
}
/// Check if a global is only used within one function.
fn is_used_in_single_function(&self, global: &ValueRef) -> bool {
let gb = global.borrow();
let mut functions_seen: HashSet<usize> = HashSet::new();
for use_ref in &gb.uses {
if let Some(user) = use_ref.user.upgrade() {
// Walk up to find the containing function.
let mut cursor = user;
loop {
let cb = cursor.borrow();
if cb.subclass == SubclassKind::Function {
functions_seen.insert(cb.vid as usize);
break;
}
// Move to parent via uses.
let next = cb.uses.first().and_then(|u| u.user.upgrade());
drop(cb);
match next {
Some(n) => cursor = n,
None => break,
}
}
}
}
functions_seen.len() <= 1
}
/// Check if a global is never written to.
fn is_never_written(&self, global: &ValueRef) -> bool {
let gb = global.borrow();
for use_ref in &gb.uses {
if let Some(user) = use_ref.user.upgrade() {
let ub = user.borrow();
if ub.opcode == Some(llvm_native_core::opcode::Opcode::Store) {
// Check if this store writes TO the global.
if ub.operands.len() >= 2 {
let ptr = &ub.operands[1];
if ptr.borrow().vid == gb.vid {
return false;
}
}
}
}
}
true
}
/// Eliminate dead global variables.
pub fn eliminate_dead_globals(&mut self, module: &ValueRef) -> usize {
let mut to_remove = Vec::new();
let mb = module.borrow();
for global in &mb.operands {
if global.borrow().subclass == SubclassKind::GlobalVariable {
let gb = global.borrow();
if gb.uses.is_empty() {
to_remove.push(global.clone());
}
}
}
let removed = to_remove.len();
self.eliminated += removed;
removed
}
}
// ============================================================================
// IPO Driver with All Extensions
// ============================================================================
/// Comprehensive IPO driver integrating all inter-procedural optimizations.
#[derive(Debug, Default)]
pub struct IPODriver {
/// Argument promotion.
pub arg_promotion: ArgumentPromotion,
/// Dead argument elimination.
pub dead_arg: ExtendedDeadArgElimination,
/// Function merging.
pub func_merger: ExtendedFunctionMerger,
/// GlobalOpt extensions.
pub global_opt: GlobalOptExtensions,
/// Statistics.
pub stats: IPODriverStats,
}
/// Statistics from the comprehensive IPO pipeline.
#[derive(Debug, Clone, Default)]
pub struct IPODriverStats {
/// Arguments promoted.
pub args_promoted: usize,
/// Dead arguments eliminated.
pub dead_args_eliminated: usize,
/// Functions merged.
pub functions_merged: usize,
/// Globals eliminated.
pub globals_eliminated: usize,
/// Total bytes saved.
pub bytes_saved: usize,
}
impl IPODriver {
/// Create a new IPO driver.
pub fn new() -> Self {
Self::default()
}
/// Run the comprehensive IPO pipeline on a module.
pub fn run_on_module(&mut self, module: &ValueRef) -> &IPODriverStats {
self.stats = IPODriverStats::default();
// Stage 1: Argument promotion.
self.stats.args_promoted = self.arg_promotion.run_on_module(module);
// Stage 2: Dead argument elimination.
self.stats.dead_args_eliminated = self.dead_arg.run_on_module(module);
// Stage 3: Function merging.
self.stats.functions_merged = self.func_merger.run_on_module(module);
// Stage 4: GlobalOpt extensions.
self.global_opt.analyze(module);
self.stats.globals_eliminated = self.global_opt.eliminate_dead_globals(module);
// Total bytes saved.
self.stats.bytes_saved = self.func_merger.bytes_saved;
&self.stats
}
}
// ============================================================================
// Top-level entry points
// ============================================================================
/// Run argument promotion on a module.
pub fn run_argument_promotion(module: &ValueRef) -> usize {
let mut ap = ArgumentPromotion::new();
ap.run_on_module(module)
}
/// Run extended dead argument elimination.
pub fn run_extended_dae(module: &ValueRef) -> usize {
let mut dae = ExtendedDeadArgElimination::new();
dae.run_on_module(module)
}
/// Run extended function merging.
pub fn run_extended_merge_functions(module: &ValueRef) -> usize {
let mut merger = ExtendedFunctionMerger::new();
merger.run_on_module(module)
}
/// Run the comprehensive IPO pipeline.
pub fn run_ipo_pipeline(module: &ValueRef) -> IPODriverStats {
let mut driver = IPODriver::new();
driver.run_on_module(module);
driver.stats
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
use llvm_native_core::basic_block::new_basic_block;
use llvm_native_core::function::new_function;
use llvm_native_core::instruction;
use llvm_native_core::types::Type;
fn build_simple_func(name: &str) -> ValueRef {
let func = new_function(name, Type::void(), &[]);
let entry = new_basic_block("entry");
entry.borrow_mut().push_operand(instruction::ret_void());
func.borrow_mut().push_operand(entry.clone());
func
}
// === FunctionFingerprint Tests ===
#[test]
fn test_fingerprint_equality() {
let fp1 = FunctionFingerprint {
num_blocks: 2,
num_instructions: 10,
num_calls: 1,
num_memory_ops: 3,
instruction_hash: 12345,
has_loops: false,
};
let fp2 = fp1.clone();
assert_eq!(fp1, fp2);
}
#[test]
fn test_fingerprint_different() {
let fp1 = FunctionFingerprint {
num_blocks: 2,
num_instructions: 10,
num_calls: 1,
num_memory_ops: 3,
instruction_hash: 12345,
has_loops: false,
};
let fp2 = FunctionFingerprint {
num_blocks: 3,
..fp1.clone()
};
assert_ne!(fp1, fp2);
}
// === FunctionMerger Tests ===
#[test]
fn test_merger_create() {
let merger = FunctionMerger::new();
assert_eq!(merger.analyzed, 0);
assert_eq!(merger.merges, 0);
}
#[test]
fn test_merger_analyze_simple_module() {
let mut m = llvm_native_core::module::Module::new("merge_mod");
m.add_function(build_simple_func("f1"));
m.add_function(build_simple_func("f2"));
let mut merger = FunctionMerger::new();
merger.analyze(&m);
assert_eq!(merger.analyzed, 2);
}
#[test]
fn test_merger_compute_fingerprint() {
let merger = FunctionMerger::new();
let func = build_simple_func("fp_test");
let fp = merger.compute_fingerprint(&func);
assert_eq!(fp.num_blocks, 1);
assert!(fp.num_instructions > 0);
}
// === DeadArgEliminator Tests ===
#[test]
fn test_dead_arg_create() {
let elim = DeadArgEliminator::new();
assert_eq!(elim.eliminated, 0);
}
#[test]
fn test_dead_arg_analyze() {
let elim = DeadArgEliminator::new();
let func = build_simple_func("arg_test");
let analysis = elim.analyze(&func);
// Simple void function with no params should have 0 args
assert!(analysis.len() >= 0);
}
// === IPOCPAnalyzer Tests ===
#[test]
fn test_ipocp_create() {
let analyzer = IPOCPAnalyzer::new();
assert_eq!(analyzer.constants_propagated, 0);
}
#[test]
fn test_ipocp_analyze() {
let mut analyzer = IPOCPAnalyzer::new();
let func = build_simple_func("ipocp_test");
analyzer.analyze(&func);
assert!(analyzer.call_sites.len() >= 0);
}
// === IPORunner Tests ===
#[test]
fn test_ipo_runner_create() {
let runner = IPORunner::new();
assert_eq!(runner.merger.analyzed, 0);
}
#[test]
fn test_ipo_runner_run() {
let mut m = llvm_native_core::module::Module::new("ipo_mod");
m.add_function(build_simple_func("a"));
m.add_function(build_simple_func("b"));
let mut runner = IPORunner::new();
let result = runner.run(&m);
assert_eq!(result.merge_stats.functions_analyzed, 2);
}
// === run_ipo Tests ===
#[test]
fn test_run_ipo_simple() {
let mut m = llvm_native_core::module::Module::new("ipo_test");
m.add_function(build_simple_func("fn1"));
let result = run_ipo(&m);
assert_eq!(result.merge_stats.functions_analyzed, 1);
}
// === Integration Tests ===
#[test]
fn test_identical_functions_merge() {
let mut m = llvm_native_core::module::Module::new("dup_mod");
// Add two identical functions
m.add_function(build_simple_func("original"));
m.add_function(build_simple_func("copy"));
let mut merger = FunctionMerger::new();
merger.analyze(&m);
// Since the functions have the same body, they should be merge candidates
assert!(merger.analyzed == 2);
assert!(merger.candidates.len() >= 0);
}
#[test]
fn test_merger_confidence_scoring() {
let merger = FunctionMerger::new();
let fp = FunctionFingerprint {
num_blocks: 1,
num_instructions: 3,
num_calls: 0,
num_memory_ops: 0,
instruction_hash: 42,
has_loops: false,
};
let conf = merger.compute_confidence(&fp, &fp);
assert!(conf > 50); // Self-comparison should be high confidence
}
#[test]
fn test_ipo_full_pipeline() {
let mut m = llvm_native_core::module::Module::new("full_ipo");
m.add_function(build_simple_func("f1"));
m.add_function(build_simple_func("f2"));
m.add_function(build_simple_func("f3"));
let result = run_ipo(&m);
assert_eq!(result.merge_stats.functions_analyzed, 3);
assert!(result.ipo_stats.call_sites_analyzed >= 0);
}
}