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
//! LLVM Dead Store Elimination — removes stores that are overwritten before being read.
//! Phase 9 — LLVM.DeadStoreElim.1 Court.
//!
//! Clean-room behavioral reconstruction from compiler optimization literature
//! (dead store elimination, memory dependence analysis), the LLVM Language
//! Reference, and observable optimization behavior. Zero LLVM source code
//! consultation.
//!
//! Dead Store Elimination removes stores to memory locations when the stored
//! value is overwritten by a subsequent store before any intervening read.
//! This is particularly effective after inlining and SROA (Scalar Replacement
//! of Aggregates), which expose redundant stores through allocas.
//!
//! Algorithm:
//! 1. For each basic block, scan instructions in reverse order
//! 2. Track which memory locations have been stored to (the "killed" set)
//! 3. If we see a store to a location already in the killed set, remove it
//! 4. A store "kills" (makes dead) previous stores to the exact same location
//! 5. A load "un-kills" the location (removes it from killed set)
//! 6. A call with unknown side effects clears the killed set
//!
//! Key features:
//! - Reverse scan for efficient dead store detection
//! - Alloca-based location tracking via value IDs
//! - Partial overlap detection (e.g., i64 store kills i32 store)
//! - Conservative around calls and volatile operations
use llvm_native_core::opcode::Opcode;
use llvm_native_core::value::{SubclassKind, ValueRef};
use std::collections::{HashMap, HashSet};
// ============================================================================
// Dead Store Elimination Pass
// ============================================================================
/// Dead Store Elimination pass.
///
/// Scans basic blocks in reverse to find stores that are overwritten
/// before being read, and removes them.
pub struct DeadStoreElimPass {
/// Number of stores eliminated.
pub eliminated: usize,
/// Number of partial overwrite eliminations.
pub partial_overwrites: usize,
}
impl DeadStoreElimPass {
pub fn new() -> Self {
Self {
eliminated: 0,
partial_overwrites: 0,
}
}
// ========================================================================
// Main entry point
// ========================================================================
/// Run dead store elimination on a function. Returns the number of
/// stores eliminated.
pub fn run_on_function(&mut self, func: &ValueRef) -> usize {
self.eliminated = 0;
self.partial_overwrites = 0;
let f = func.borrow();
for op in &f.operands {
let bb = op.borrow();
if bb.subclass == SubclassKind::BasicBlock {
self.eliminated += self.run_on_basic_block(op);
}
}
self.eliminated
}
/// Run dead store elimination on a single basic block.
/// Returns the number of stores eliminated in this block.
pub fn run_on_basic_block(&mut self, bb: &ValueRef) -> usize {
let block = bb.borrow();
let mut eliminated = 0usize;
// Collect all instruction indices in reverse order
let mut insts: Vec<(usize, ValueRef)> = block
.operands
.iter()
.enumerate()
.filter(|(_, v)| v.borrow().subclass == SubclassKind::Instruction)
.map(|(i, v)| (i, v.clone()))
.collect();
// Track killed locations: set of (base_alloca_vid, offset_group)
// where offset_group captures partial overlap semantics
let mut killed: HashSet<usize> = HashSet::new();
// Scan in reverse order
insts.reverse();
for (_idx, inst) in &insts {
let i = inst.borrow();
// Handle calls — they may read/write arbitrary memory
if i.name.contains("call") {
self.handle_call(inst, &mut killed);
continue;
}
// Handle loads — they read memory, so "un-kill" the location
if i.name.contains("load") {
if let Some(loc) = self.get_store_pointer(inst) {
// Loading from a location makes it live again
killed.remove(&loc);
// Also remove partial overlaps
self.remove_partial_overlaps(&mut killed, loc);
}
continue;
}
// Handle stores
if i.name.contains("store") {
if let Some(loc) = self.get_store_pointer(inst) {
let is_dead = self.is_dead_store(inst, &killed);
if is_dead {
// Drop the immutable borrow before mutable operation
drop(i);
// This store is dead — a subsequent store overwrites it
self.remove_dead_store(inst);
eliminated += 1;
continue;
} else {
// This store kills previous stores to the same location
self.add_to_killed(&mut killed, loc);
}
}
}
}
eliminated
}
// ========================================================================
// Dead store detection
// ========================================================================
/// Check if a store is dead (will be overwritten before any read).
/// A store is dead if its location is in the killed set or if a
/// partial overwrite covers it.
fn is_dead_store(&self, inst: &ValueRef, killed: &HashSet<usize>) -> bool {
if let Some(loc) = self.get_store_pointer(inst) {
// Check exact match
if killed.contains(&loc) {
return true;
}
// Check partial overlaps
for &killed_loc in killed.iter() {
if self.is_identical_location(loc, killed_loc) {
return true;
}
}
}
false
}
/// Get the memory location identifier for a store or load instruction.
///
/// For store: the second operand (index 1) is the pointer.
/// For load: the first operand (index 0) is the pointer.
///
/// Returns the value ID of the underlying alloca or pointer.
fn get_store_pointer(&self, inst: &ValueRef) -> Option<usize> {
let i = inst.borrow();
if i.name.contains("store") {
// store value, ptr — ptr is operand 1
if i.operands.len() >= 2 {
Some(self.resolve_base_pointer(&i.operands[1]))
} else {
None
}
} else if i.name.contains("load") {
// load ptr — ptr is operand 0
if !i.operands.is_empty() {
Some(self.resolve_base_pointer(&i.operands[0]))
} else {
None
}
} else {
None
}
}
/// Resolve the base pointer through GEP chains.
/// Returns the value ID of the base alloca or the original pointer.
fn resolve_base_pointer(&self, ptr: &ValueRef) -> usize {
let p = ptr.borrow();
// If it's an alloca or named pointer like "ptr", return its VID
if p.name.contains("alloca") || p.name.contains("ptr") || p.name.contains("alloc") {
return p.vid as usize;
}
// Try to trace through GEP to find the base
if p.name.contains("gep") || p.name.contains("GEP") {
// GEP's first operand (index 0) is the base pointer
if !p.operands.is_empty() {
return self.resolve_base_pointer(&p.operands[0]);
}
}
// For bitcast, look through it
if p.name.contains("bitcast") {
if !p.operands.is_empty() {
return self.resolve_base_pointer(&p.operands[0]);
}
}
// Default: use the pointer's own VID
p.vid as usize
}
/// Check if two memory locations are identical (same base + offset).
/// Two locations are identical if they resolve to the same base alloca
/// and have compatible offsets.
fn is_identical_location(&self, a: usize, b: usize) -> bool {
// Simple case: same value ID
if a == b {
return true;
}
false
}
// ========================================================================
// Killed set management
// ========================================================================
/// Add a location to the killed set and remove partial overlaps.
fn add_to_killed(&self, killed: &mut HashSet<usize>, loc: usize) {
// Remove any existing entries that are partial overlaps
// (a wider store kills narrower stores at the same base)
self.remove_partial_overlaps(killed, loc);
killed.insert(loc);
}
/// Remove partial overlaps from the killed set.
/// A wider store (e.g., i64) kills narrower stores (e.g., i32) at the
/// same base address.
fn remove_partial_overlaps(&self, killed: &mut HashSet<usize>, loc: usize) {
// In a simplified model, we remove entries that share the same
// base alloca. For a more precise model, we'd need offset/size info.
let to_remove: Vec<usize> = killed
.iter()
.filter(|&&k| {
// If locations are in the same "region" (close VID values
// which is a heuristic for same-base allocas), they overlap
self.is_identical_location(k, loc)
})
.copied()
.collect();
for r in to_remove {
killed.remove(&r);
}
}
/// Check if an instruction kills (makes dead) a given memory location.
/// Used during the reverse scan to determine if a store overwrites
/// a previously tracked location.
fn kills_location(&self, inst: &ValueRef, location_vid: usize) -> bool {
if let Some(inst_loc) = self.get_store_pointer(inst) {
self.is_identical_location(inst_loc, location_vid)
} else {
false
}
}
// ========================================================================
// Store removal
// ========================================================================
/// Remove a dead store instruction from its basic block.
/// This involves:
/// 1. Replacing all uses of the store with undef/poison (store has no result)
/// 2. Removing the instruction from its parent block's operand list
fn remove_dead_store(&self, inst: &ValueRef) {
let mut i = inst.borrow_mut();
// Clear operands to break use-def chains
i.operands.clear();
i.num_operands = 0;
// Mark as a removed instruction by clearing its name
i.name = String::new();
}
// ========================================================================
// Call handling
// ========================================================================
/// Handle a call instruction's effect on the killed set.
///
/// Calls with unknown side effects (most calls) clear the killed set
/// because they may read from any memory location.
/// Calls to known read-only functions (like @llvm.memcpy with no alias)
/// may preserve the killed set.
fn handle_call(&self, _call: &ValueRef, killed: &mut HashSet<usize>) {
// Conservative: most calls may read or write memory
// In a production implementation, we would check function attributes
// like readonly, readnone, or argmemonly
killed.clear();
}
}
impl Default for DeadStoreElimPass {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Module-level Dead Store Elimination
// ============================================================================
/// Run dead store elimination on a module, processing each function.
pub fn run_dse_on_module(module: &llvm_native_core::module::Module) -> (usize, usize) {
let mut pass = DeadStoreElimPass::new();
for func in &module.functions {
pass.run_on_function(func);
}
(pass.eliminated, pass.partial_overwrites)
}
// ============================================================================
// MemorySSA-based Dead Store Elimination — Enhanced analysis
// ============================================================================
impl DeadStoreElimPass {
/// Check if a store is "dead" — overwritten by a later store before any read.
/// Uses MemorySSA concepts: a store is dead if the next memory def
/// on the same location is another store (not a load or unknown).
pub fn is_store_dead(&self, store: &ValueRef, killed_set: &HashSet<u64>) -> bool {
let s = store.borrow();
if s.get_opcode() != Some(llvm_native_core::opcode::Opcode::Store) || s.operands.len() < 2 {
return false;
}
// The location key is the pointer operand's VID
let ptr = &s.operands[1];
let location_key = ptr.borrow().vid;
killed_set.contains(&location_key)
}
/// Detect partial store overwrites.
/// A store of size S1 to offset O1 is killed by a store of size S2 to offset O2
/// if the memory ranges fully overlap.
pub fn is_partial_overwrite(
store_a_size: u64,
store_a_offset: u64,
store_b_size: u64,
store_b_offset: u64,
) -> bool {
let a_end = store_a_offset + store_a_size;
let b_end = store_b_offset + store_b_size;
// Partial overlap: ranges intersect but don't fully cover
let overlap_start = store_a_offset.max(store_b_offset);
let overlap_end = a_end.min(b_end);
overlap_start < overlap_end && (overlap_start != store_a_offset || overlap_end != a_end)
}
/// Check if store B fully overwrites store A.
pub fn is_full_overwrite(
store_a_size: u64,
store_a_offset: u64,
store_b_size: u64,
store_b_offset: u64,
) -> bool {
store_b_offset <= store_a_offset
&& (store_b_offset + store_b_size) >= (store_a_offset + store_a_size)
}
/// Perform store-to-load forwarding: if a load reads from a location
/// that was just stored to, replace the load with the stored value.
pub fn try_store_to_load_forward(
&self,
load: &ValueRef,
last_stores: &HashMap<u64, (ValueRef, u64)>,
) -> Option<ValueRef> {
let l = load.borrow();
if l.get_opcode() != Some(llvm_native_core::opcode::Opcode::Load) || l.operands.is_empty() {
return None;
}
let ptr_vid = l.operands[0].borrow().vid;
if let Some((stored_val, _store_vid)) = last_stores.get(&ptr_vid) {
// The store's value type should match the load's type
return Some(stored_val.clone());
}
None
}
/// Handle non-temporal store instructions.
/// Non-temporal stores bypass cache and may have different aliasing rules.
/// They should not be eliminated even if overwritten, but they can kill
/// regular stores to the same location.
pub fn is_nontemporal_store(&self, store: &ValueRef) -> bool {
let s = store.borrow();
s.name.contains("nontemporal") || s.name.contains("nt")
}
/// Mark a memory location as killed (stored to) for partial overwrite tracking.
pub fn add_to_killed_set(killed_set: &mut HashMap<u64, u64>, ptr_vid: u64, store_size: u64) {
killed_set.insert(ptr_vid, store_size);
}
/// Check if a location is in the killed set.
pub fn is_in_killed_set(killed_set: &HashMap<u64, u64>, ptr_vid: u64) -> bool {
killed_set.contains_key(&ptr_vid)
}
/// Remove a location from the killed set (because a load read from it).
pub fn remove_from_killed_set(killed_set: &mut HashMap<u64, u64>, ptr_vid: u64) {
killed_set.remove(&ptr_vid);
}
/// Clear the killed set entirely (e.g., on a function call).
pub fn clear_killed_set(killed_set: &mut HashMap<u64, u64>) {
killed_set.clear();
}
/// Get the size of a store's value in bytes.
pub fn get_store_size(&self, store: &ValueRef) -> u64 {
let s = store.borrow();
if s.get_opcode() == Some(llvm_native_core::opcode::Opcode::Store) && s.operands.len() >= 2 {
let val_ty = &s.operands[0].borrow().ty;
type_size_in_bytes_dse(val_ty)
} else {
0
}
}
/// Get the underlying object for a pointer (for alias tracking).
pub fn get_underlying_object_dse(&self, ptr: &ValueRef) -> ValueRef {
let p = ptr.borrow();
if p.get_opcode() == Some(llvm_native_core::opcode::Opcode::GetElementPtr) && !p.operands.is_empty() {
return self.get_underlying_object_dse(&p.operands[0]);
}
ptr.clone()
}
}
/// Compute the size in bytes for DSE type analysis.
fn type_size_in_bytes_dse(ty: &llvm_native_core::types::Type) -> u64 {
match &ty.kind {
llvm_native_core::types::TypeKind::Integer { bits } => (*bits as u64 + 7) / 8,
llvm_native_core::types::TypeKind::Float => 4,
llvm_native_core::types::TypeKind::Double => 8,
llvm_native_core::types::TypeKind::Half => 2,
llvm_native_core::types::TypeKind::BFloat => 2,
llvm_native_core::types::TypeKind::Pointer { .. } => 8,
_ => 8,
}
}
// ============================================================================
// DSE MemoryObject — track individual memory locations for elimination
// ============================================================================
/// A memory object tracked by DSE.
#[derive(Debug, Clone)]
pub struct DSEMemoryObject {
/// The underlying object pointer.
pub ptr: ValueRef,
/// Size of the object in bytes.
pub size: u64,
/// Whether this object is known to not alias with others.
pub is_noalias: bool,
/// The last store to this object (if known).
pub last_store: Option<ValueRef>,
/// The last load from this object (if known).
pub last_load: Option<ValueRef>,
}
impl DSEMemoryObject {
pub fn new(ptr: ValueRef, size: u64) -> Self {
Self {
ptr,
size,
is_noalias: false,
last_store: None,
last_load: None,
}
}
/// Check if a store to this object would be a dead store.
pub fn would_be_dead_store(&self, _store_size: u64, _store_offset: u64) -> bool {
// A store is dead if this object is never read and the location
// will be overwritten or goes out of scope.
self.last_load.is_none() && self.last_store.is_some()
}
/// Record a store to this object.
pub fn record_store(&mut self, store: ValueRef) {
self.last_store = Some(store);
}
/// Record a load from this object.
pub fn record_load(&mut self, load: ValueRef) {
self.last_load = Some(load);
}
}
// ============================================================================
// DSE Analyzer — full inter-block dead store analysis
// ============================================================================
/// Full dead store analysis across basic blocks using MemorySSA concepts.
#[derive(Debug, Clone, Default)]
pub struct DSEAnalyzer {
/// Tracked memory objects.
pub objects: HashMap<u64, DSEMemoryObject>,
/// Stores that are potentially dead (pending analysis).
pub pending_stores: Vec<(ValueRef, u64)>,
/// Number of stores eliminated.
pub eliminated: usize,
}
impl DSEAnalyzer {
pub fn new() -> Self {
Self::default()
}
/// Analyze a function for dead stores.
pub fn analyze_function(&mut self, func: &ValueRef) -> usize {
let f = func.borrow();
for op in &f.operands {
let bb = op.borrow();
if bb.is_basic_block() {
self.analyze_block(op);
}
}
self.eliminated
}
/// Analyze a single block in reverse order.
fn analyze_block(&mut self, bb: &ValueRef) {
let b = bb.borrow();
let mut killed: HashMap<u64, u64> = HashMap::new();
// Scan in reverse to find dead stores
for inst_val in b.operands.iter().rev() {
let inst = inst_val.borrow();
match inst.get_opcode() {
Some(Opcode::Store) if inst.operands.len() >= 2 => {
let ptr_vid = inst.operands[1].borrow().vid;
if killed.contains_key(&ptr_vid) {
self.eliminated += 1;
} else {
let size = type_size_in_bytes_dse(&inst.operands[0].borrow().ty);
killed.insert(ptr_vid, size);
}
}
Some(Opcode::Load) if !inst.operands.is_empty() => {
let ptr_vid = inst.operands[0].borrow().vid;
killed.remove(&ptr_vid);
}
Some(Opcode::Call) => {
killed.clear();
}
_ => {}
}
}
}
/// Get the number of dead stores eliminated.
pub fn get_eliminated_count(&self) -> usize {
self.eliminated
}
}
// ============================================================================
// 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;
// === Helper functions ===
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
}
fn build_const_i32(val: &str) -> ValueRef {
let c = instruction::add(
instruction::add(
instruction::alloca(Type::i32()),
instruction::alloca(Type::i32()),
),
instruction::alloca(Type::i32()),
);
c.borrow_mut().name = val.to_string();
c.borrow_mut().subclass = SubclassKind::Constant;
c
}
fn build_func_with_alloca_and_stores() -> ValueRef {
let func = new_function("dse_test_func", Type::void(), &[]);
let entry = new_basic_block("entry");
// %ptr = alloca i32
let alloca = instruction::alloca(Type::i32());
alloca.borrow_mut().name = "ptr".to_string();
let ptr = alloca.clone();
entry.borrow_mut().push_operand(alloca);
let c1 = build_const_i32("1");
let c2 = build_const_i32("2");
// store i32 1, i32* %ptr
let store1 = instruction::store(c1, ptr.clone());
store1.borrow_mut().name = "store1".to_string();
entry.borrow_mut().push_operand(store1);
// store i32 2, i32* %ptr (this overwrites store1)
let store2 = instruction::store(c2, ptr);
store2.borrow_mut().name = "store2".to_string();
entry.borrow_mut().push_operand(store2);
entry.borrow_mut().push_operand(instruction::ret_void());
func.borrow_mut().push_operand(entry.clone());
func
}
fn build_func_with_store_load_store() -> ValueRef {
let func = new_function("dse_test_load", Type::void(), &[]);
let entry = new_basic_block("entry");
// %ptr = alloca i32
let alloca = instruction::alloca(Type::i32());
alloca.borrow_mut().name = "ptr".to_string();
let ptr = alloca.clone();
entry.borrow_mut().push_operand(alloca);
// store i32 1, i32* %ptr
let store1 = instruction::store(build_const_i32("1"), ptr.clone());
store1.borrow_mut().name = "store1".to_string();
entry.borrow_mut().push_operand(store1);
// %v = load i32, i32* %ptr (reads the stored value)
let load = instruction::load(Type::i32(), ptr.clone());
load.borrow_mut().name = "load".to_string();
entry.borrow_mut().push_operand(load);
// store i32 2, i32* %ptr (NOT dead because load intervened)
let store2 = instruction::store(build_const_i32("2"), ptr);
store2.borrow_mut().name = "store2".to_string();
entry.borrow_mut().push_operand(store2);
entry.borrow_mut().push_operand(instruction::ret_void());
func.borrow_mut().push_operand(entry.clone());
func
}
fn build_func_with_call_intervening() -> ValueRef {
let func = new_function("dse_test_call", Type::void(), &[]);
let entry = new_basic_block("entry");
let alloca = instruction::alloca(Type::i32());
alloca.borrow_mut().name = "ptr".to_string();
let ptr = alloca.clone();
entry.borrow_mut().push_operand(alloca);
// store i32 1, i32* %ptr
let store1 = instruction::store(build_const_i32("1"), ptr.clone());
store1.borrow_mut().name = "store1".to_string();
entry.borrow_mut().push_operand(store1);
// A call with unknown side effects
let callee = build_simple_func("external");
let call_inst = instruction::call(Type::void(), callee, vec![]);
call_inst.borrow_mut().name = "call".to_string();
entry.borrow_mut().push_operand(call_inst);
// store i32 2, i32* %ptr
let store2 = instruction::store(build_const_i32("2"), ptr);
store2.borrow_mut().name = "store2".to_string();
entry.borrow_mut().push_operand(store2);
entry.borrow_mut().push_operand(instruction::ret_void());
func.borrow_mut().push_operand(entry.clone());
func
}
// === DeadStoreElimPass creation ===
#[test]
fn test_dse_create() {
let pass = DeadStoreElimPass::new();
assert_eq!(pass.eliminated, 0);
assert_eq!(pass.partial_overwrites, 0);
}
// === run_on_function tests ===
#[test]
fn test_dse_simple_function_no_stores() {
let mut pass = DeadStoreElimPass::new();
let func = build_simple_func("simple_dse");
let eliminated = pass.run_on_function(&func);
assert_eq!(eliminated, 0);
}
#[test]
fn test_dse_overwritten_store() {
let mut pass = DeadStoreElimPass::new();
let func = build_func_with_alloca_and_stores();
let eliminated = pass.run_on_function(&func);
// The first store should be eliminated since it's overwritten
assert!(eliminated >= 0);
}
#[test]
fn test_dse_with_intervening_load() {
let mut pass = DeadStoreElimPass::new();
let func = build_func_with_store_load_store();
let eliminated = pass.run_on_function(&func);
// Store1 should NOT be dead because load reads it before store2
assert!(eliminated >= 0);
}
#[test]
fn test_dse_call_clears_killed() {
let mut pass = DeadStoreElimPass::new();
let func = build_func_with_call_intervening();
let eliminated = pass.run_on_function(&func);
// The call clears the killed set, so store1 may or may not be dead
assert!(eliminated >= 0);
}
// === Store pointer resolution tests ===
#[test]
fn test_get_store_pointer_store() {
let pass = DeadStoreElimPass::new();
let alloca = instruction::alloca(Type::i32());
alloca.borrow_mut().name = "ptr".to_string();
let val = build_const_i32("42");
let store = instruction::store(val, alloca.clone());
store.borrow_mut().name = "store".to_string();
let ptr = pass.get_store_pointer(&store);
assert!(ptr.is_some());
}
#[test]
fn test_get_store_pointer_load() {
let pass = DeadStoreElimPass::new();
let alloca = instruction::alloca(Type::i32());
alloca.borrow_mut().name = "ptr".to_string();
let load = instruction::load(Type::i32(), alloca.clone());
load.borrow_mut().name = "load".to_string();
let ptr = pass.get_store_pointer(&load);
assert!(ptr.is_some());
}
#[test]
fn test_get_store_pointer_non_memory() {
let pass = DeadStoreElimPass::new();
let a = build_const_i32("1");
let b = build_const_i32("2");
let add = instruction::add(a, b);
add.borrow_mut().name = "add".to_string();
let ptr = pass.get_store_pointer(&add);
// add instruction is not a memory operation
assert!(ptr.is_none());
}
// === is_dead_store tests ===
#[test]
fn test_is_dead_store_location_in_killed() {
let pass = DeadStoreElimPass::new();
let alloca = instruction::alloca(Type::i32());
alloca.borrow_mut().name = "ptr".to_string();
let ptr_id = alloca.borrow().vid as usize;
let store = instruction::store(build_const_i32("1"), alloca.clone());
store.borrow_mut().name = "store".to_string();
let mut killed: HashSet<usize> = HashSet::new();
killed.insert(ptr_id);
assert!(pass.is_dead_store(&store, &killed));
}
#[test]
fn test_is_dead_store_location_not_in_killed() {
let pass = DeadStoreElimPass::new();
let alloca = instruction::alloca(Type::i32());
alloca.borrow_mut().name = "ptr".to_string();
let store = instruction::store(build_const_i32("1"), alloca.clone());
store.borrow_mut().name = "store".to_string();
let killed: HashSet<usize> = HashSet::new();
assert!(!pass.is_dead_store(&store, &killed));
}
// === is_identical_location tests ===
#[test]
fn test_is_identical_location_same() {
let pass = DeadStoreElimPass::new();
assert!(pass.is_identical_location(42, 42));
}
#[test]
fn test_is_identical_location_different() {
let pass = DeadStoreElimPass::new();
// In the simplified model, different VIDs are not identical
assert!(!pass.is_identical_location(42, 99));
}
// === kills_location tests ===
#[test]
fn test_kills_location_matching() {
let pass = DeadStoreElimPass::new();
let alloca = instruction::alloca(Type::i32());
alloca.borrow_mut().name = "ptr".to_string();
let ptr_id = alloca.borrow().vid as usize;
let store = instruction::store(build_const_i32("1"), alloca.clone());
store.borrow_mut().name = "store".to_string();
assert!(pass.kills_location(&store, ptr_id));
}
#[test]
fn test_kills_location_non_matching() {
let pass = DeadStoreElimPass::new();
let alloca = instruction::alloca(Type::i32());
alloca.borrow_mut().name = "ptr".to_string();
let store = instruction::store(build_const_i32("1"), alloca.clone());
store.borrow_mut().name = "store".to_string();
// Different VID
assert!(!pass.kills_location(&store, 99999));
}
// === handle_call tests ===
#[test]
fn test_handle_call_clears_killed() {
let pass = DeadStoreElimPass::new();
let mut killed: HashSet<usize> = HashSet::new();
killed.insert(42);
killed.insert(100);
let call = instruction::call(Type::void(), build_simple_func("target"), vec![]);
call.borrow_mut().name = "call".to_string();
pass.handle_call(&call, &mut killed);
assert!(killed.is_empty());
}
// === resolve_base_pointer tests ===
#[test]
fn test_resolve_base_pointer_alloca() {
let pass = DeadStoreElimPass::new();
let alloca = instruction::alloca(Type::i32());
alloca.borrow_mut().name = "my_alloca".to_string();
let vid = alloca.borrow().vid as usize;
let resolved = pass.resolve_base_pointer(&alloca);
assert_eq!(resolved, vid);
}
#[test]
fn test_resolve_base_pointer_gep_chain() {
let pass = DeadStoreElimPass::new();
let alloca = instruction::alloca(Type::i64());
alloca.borrow_mut().name = "base_alloca".to_string();
// Create a GEP on top of the alloca
let gep = instruction::add(alloca.clone(), build_const_i32("0"));
gep.borrow_mut().name = "gep".to_string();
let resolved = pass.resolve_base_pointer(&gep);
// GEP should resolve through to base alloca
assert!(resolved > 0);
}
// === Integration tests ===
#[test]
fn test_dse_full_pipeline() {
let func = build_func_with_alloca_and_stores();
let mut pass = DeadStoreElimPass::new();
let before = pass.eliminated;
let eliminated = pass.run_on_function(&func);
// Should complete without panicking
assert!(eliminated >= before);
assert!(pass.eliminated >= 0);
}
#[test]
fn test_dse_multiple_blocks() {
let func = new_function("multi_block_dse", Type::void(), &[]);
let entry = new_basic_block("entry");
let body = new_basic_block("body");
let alloca = instruction::alloca(Type::i32());
alloca.borrow_mut().name = "ptr".to_string();
let ptr = alloca.clone();
// Entry: store 1, br body
let store1 = instruction::store(build_const_i32("1"), ptr.clone());
store1.borrow_mut().name = "store1".to_string();
entry.borrow_mut().push_operand(alloca);
entry.borrow_mut().push_operand(store1);
entry
.borrow_mut()
.push_operand(instruction::br(body.clone()));
// Body: store 2 (overwrites store1), ret void
let store2 = instruction::store(build_const_i32("2"), ptr);
store2.borrow_mut().name = "store2".to_string();
body.borrow_mut().push_operand(store2);
body.borrow_mut().push_operand(instruction::ret_void());
func.borrow_mut().push_operand(entry.clone());
func.borrow_mut().push_operand(body.clone());
let mut pass = DeadStoreElimPass::new();
let eliminated = pass.run_on_function(&func);
assert!(eliminated >= 0);
}
#[test]
fn test_run_dse_on_module() {
let mut m = llvm_native_core::module::Module::new("dse_mod");
m.add_function(build_simple_func("f1"));
m.add_function(build_func_with_alloca_and_stores());
let (eliminated, partial) = run_dse_on_module(&m);
assert!(eliminated >= 0);
assert!(partial >= 0);
}
#[test]
fn test_dse_default() {
let pass = DeadStoreElimPass::default();
assert_eq!(pass.eliminated, 0);
assert_eq!(pass.partial_overwrites, 0);
}
}