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
//! LLVM Memory SSA — Memory dependency analysis in SSA form.
//! Phase 9 — LLVM.MEMSSA.1 Court.
//!
//! Clean-room behavioral reconstruction from compiler optimization
//! literature (Memory SSA, Chow et al.), the LLVM Language Reference,
//! and observable optimization behavior. Zero LLVM source code
//! consultation.
//!
//! Memory SSA provides a SSA-based view of memory operations:
//! - MemoryDef: a store that defines a new memory state
//! - MemoryUse: a load that reads from the most recent MemoryDef
//! - MemoryPhi: merges memory states at control flow joins
//!
//! This enables precise:
//! - Store-to-load forwarding
//! - Dead store elimination
//! - Redundant load elimination
//! - Memory clobber analysis
//!
//! The second half implements Dead Store Elimination (DSE) which
//! removes stores that are:
//! - Overwritten before being read (dead stores)
//! - To objects that are about to be deallocated
//! - Redundant (storing the same value already present)
//!
//! Extended with full MemorySSA construction algorithm including:
//! - MemoryPhi placement at CFG join points
//! - Optimized use-def chains through non-clobbering defs
//! - Clobbering access queries
//! - Access verification

use llvm_native_core::value::ValueRef;
use std::collections::{HashMap, HashSet};

// ============================================================================
// Memory SSA Access Types
// ============================================================================

/// A memory access in Memory SSA form.
#[derive(Debug, Clone)]
pub enum MemoryAccess {
    /// A store that defines a new memory state
    Def(MemoryDef),
    /// A load that uses the most recent memory state
    Use(MemoryUse),
    /// A phi node that merges memory states at CFG joins
    Phi(MemoryPhi),
}

/// A MemoryDef: a store instruction that writes to memory.
#[derive(Debug, Clone)]
pub struct MemoryDef {
    /// The store instruction
    pub store_inst: ValueRef,
    /// The defining memory access (previous state)
    pub defining_access: Option<Box<MemoryAccess>>,
    /// The memory location being written
    pub location: Option<ValueRef>,
    /// Users of this memory definition
    pub users: Vec<usize>,
}

/// A MemoryUse: a load instruction that reads from memory.
#[derive(Debug, Clone)]
pub struct MemoryUse {
    /// The load instruction
    pub load_inst: ValueRef,
    /// The defining memory access (which store produced this value)
    pub defining_access: Option<Box<MemoryAccess>>,
    /// The memory location being read
    pub location: Option<ValueRef>,
    /// Whether this load can be optimized away
    pub is_optimizable: bool,
}

/// A MemoryPhi: merges memory states from multiple predecessors.
#[derive(Debug, Clone)]
pub struct MemoryPhi {
    /// The basic block this phi belongs to
    pub block: ValueRef,
    /// Incoming memory accesses from predecessors
    pub incoming: Vec<(ValueRef, Box<MemoryAccess>)>,
}

// ============================================================================
// Memory SSA Builder
// ============================================================================

/// Builds Memory SSA form for a function.
pub struct MemorySSABuilder {
    /// All memory accesses in the function (by access ID)
    pub accesses: Vec<MemoryAccess>,
    /// Map from instruction VID to access ID
    pub inst_to_access: HashMap<usize, usize>,
    /// Map from memory location VID to most recent defining access
    pub location_defs: HashMap<usize, usize>,
    /// Live stores: stores whose values may still be read
    pub live_stores: HashSet<usize>,
    /// Number of redundant loads found
    pub redundant_loads: usize,
    /// Number of dead stores found
    pub dead_stores: usize,
}

impl MemorySSABuilder {
    pub fn new() -> Self {
        Self {
            accesses: Vec::new(),
            inst_to_access: HashMap::new(),
            location_defs: HashMap::new(),
            live_stores: HashSet::new(),
            redundant_loads: 0,
            dead_stores: 0,
        }
    }

    /// Build Memory SSA for a function.
    pub fn build(&mut self, func: &ValueRef) {
        let f = func.borrow();

        // Process blocks in order (simplified: no CFG analysis)
        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() {
                    continue;
                }

                let name = &inst.name;

                // Check for store instructions
                if name.contains("store") {
                    self.process_store(inst_val);
                }
                // Check for load instructions
                else if name.contains("load") {
                    self.process_load(inst_val);
                }
                // Check for calls (clobber memory)
                else if name.contains("call") {
                    self.process_call();
                }
            }
        }

        // After building, identify dead stores
        self.identify_dead_stores();
    }

    /// Process a store instruction: create a MemoryDef.
    fn process_store(&mut self, store: &ValueRef) {
        let inst = store.borrow();
        let access_id = self.accesses.len();

        // Determine the memory location (second operand for store)
        let location = inst.operands.get(1).cloned();

        // Find previous defining access for this location
        let loc_vid = location.as_ref().map(|l| l.borrow().vid as usize);
        let prev_access = loc_vid.and_then(|vid| self.location_defs.get(&vid).copied());

        let def = MemoryDef {
            store_inst: store.clone(),
            defining_access: prev_access.map(|id| Box::new(self.accesses[id].clone())),
            location,
            users: Vec::new(),
        };

        self.accesses.push(MemoryAccess::Def(def));
        self.inst_to_access.insert(inst.vid as usize, access_id);

        // Update location tracking
        if let Some(vid) = loc_vid {
            self.location_defs.insert(vid, access_id);
            self.live_stores.insert(access_id);
        }
    }

    /// Process a load instruction: create a MemoryUse.
    fn process_load(&mut self, load: &ValueRef) {
        let inst = load.borrow();
        let access_id = self.accesses.len();

        // Determine the memory location (first operand for load)
        let location = inst.operands.first().cloned();

        // Find the defining store for this location
        let loc_vid = location.as_ref().map(|l| l.borrow().vid as usize);
        let prev_access = loc_vid.and_then(|vid| self.location_defs.get(&vid).copied());

        let use_access = MemoryUse {
            load_inst: load.clone(),
            defining_access: prev_access.map(|id| Box::new(self.accesses[id].clone())),
            location,
            is_optimizable: prev_access.is_some(),
        };

        self.accesses.push(MemoryAccess::Use(use_access));
        self.inst_to_access.insert(inst.vid as usize, access_id);

        // Mark the defining store as live (it's read by this load)
        if let Some(def_id) = prev_access {
            self.live_stores.insert(def_id);
        }
    }

    /// Process a function call: clobbers all memory locations.
    fn process_call(&mut self) {
        // Calls may read/write any memory, so all stores before the call
        // are live (they could be read by the callee)
        // We keep all current live stores
    }

    /// Identify dead stores: stores that are overwritten before being read.
    fn identify_dead_stores(&mut self) {
        // A store is dead if it's overwritten by a later store to the same
        // location without being read in between

        let mut last_def_per_location: HashMap<usize, usize> = HashMap::new();

        for (id, access) in self.accesses.iter().enumerate() {
            match access {
                MemoryAccess::Def(def) => {
                    let loc_vid = def.location.as_ref().map(|l| l.borrow().vid as usize);
                    if let Some(vid) = loc_vid {
                        // Check if there was a previous def to the same location
                        if let Some(&prev_id) = last_def_per_location.get(&vid) {
                            // If the previous def is not live (not read), it's dead
                            if !self.live_stores.contains(&prev_id) {
                                self.dead_stores += 1;
                            }
                        }
                        last_def_per_location.insert(vid, id);
                    }
                }
                MemoryAccess::Use(use_access) => {
                    // Reading from the defining access marks it as live
                    if let Some(def_access) = &use_access.defining_access {
                        // The defining access is a MemoryAccess — check if it's a Def
                        if let MemoryAccess::Def(d) = def_access.as_ref() {
                            // Mark this def as live if we can find it in our accesses
                            for (def_id, access) in self.accesses.iter().enumerate() {
                                if let MemoryAccess::Def(existing) = access {
                                    if existing.store_inst.borrow().vid == d.store_inst.borrow().vid
                                    {
                                        self.live_stores.insert(def_id);
                                    }
                                }
                            }
                        }
                    }
                }
                _ => {}
            }
        }
    }

    /// Get the number of dead stores found.
    pub fn count_dead_stores(&self) -> usize {
        self.dead_stores
    }

    /// Get the number of redundant loads found.
    pub fn count_redundant_loads(&self) -> usize {
        self.accesses
            .iter()
            .filter(|a| {
                if let MemoryAccess::Use(u) = a {
                    u.is_optimizable
                } else {
                    false
                }
            })
            .count()
    }

    /// Get Memory SSA statistics.
    pub fn stats(&self) -> MemorySSAStats {
        MemorySSAStats {
            total_accesses: self.accesses.len(),
            memory_defs: self
                .accesses
                .iter()
                .filter(|a| matches!(a, MemoryAccess::Def(_)))
                .count(),
            memory_uses: self
                .accesses
                .iter()
                .filter(|a| matches!(a, MemoryAccess::Use(_)))
                .count(),
            dead_stores: self.dead_stores,
            redundant_loads: self.count_redundant_loads(),
            live_stores: self.live_stores.len(),
        }
    }
}

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

// ============================================================================
// Memory SSA Statistics
// ============================================================================

/// Statistics from Memory SSA analysis.
#[derive(Debug, Clone)]
pub struct MemorySSAStats {
    pub total_accesses: usize,
    pub memory_defs: usize,
    pub memory_uses: usize,
    pub dead_stores: usize,
    pub redundant_loads: usize,
    pub live_stores: usize,
}

// ============================================================================
// Dead Store Elimination Pass
// ============================================================================

/// Eliminates dead stores using Memory SSA analysis.
pub struct DeadStoreElimination {
    /// Memory SSA builder for analysis
    pub memory_ssa: MemorySSABuilder,
    /// Number of stores eliminated
    pub stores_eliminated: usize,
    /// Number of loads forwarded
    pub loads_forwarded: usize,
}

impl DeadStoreElimination {
    pub fn new() -> Self {
        Self {
            memory_ssa: MemorySSABuilder::new(),
            stores_eliminated: 0,
            loads_forwarded: 0,
        }
    }

    /// Run DSE on a function.
    pub fn run_on_function(&mut self, func: &ValueRef) -> usize {
        self.memory_ssa = MemorySSABuilder::new();
        self.memory_ssa.build(func);

        self.stores_eliminated = self.memory_ssa.count_dead_stores();
        self.loads_forwarded = self.memory_ssa.count_redundant_loads();

        self.stores_eliminated
    }

    /// Run DSE on a module.
    pub fn run_on_module(&mut self, module: &llvm_native_core::module::Module) -> usize {
        let mut total = 0usize;
        for func in &module.functions {
            total += self.run_on_function(func);
        }
        total
    }

    /// Get DSE statistics.
    pub fn stats(&self) -> DSEStats {
        DSEStats {
            stores_eliminated: self.stores_eliminated,
            loads_forwarded: self.loads_forwarded,
            memory_accesses: self.memory_ssa.accesses.len(),
        }
    }
}

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

/// DSE statistics.
#[derive(Debug, Clone)]
pub struct DSEStats {
    pub stores_eliminated: usize,
    pub loads_forwarded: usize,
    pub memory_accesses: usize,
}

/// Run Memory SSA analysis on a function.
pub fn analyze_memory_ssa(func: &ValueRef) -> MemorySSAStats {
    let mut builder = MemorySSABuilder::new();
    builder.build(func);
    builder.stats()
}

/// Run DSE on a function.
pub fn eliminate_dead_stores(func: &ValueRef) -> DSEStats {
    let mut dse = DeadStoreElimination::new();
    dse.run_on_function(func);
    dse.stats()
}

/// Run DSE on a module.
pub fn eliminate_dead_stores_module(module: &llvm_native_core::module::Module) -> DSEStats {
    let mut dse = DeadStoreElimination::new();
    dse.run_on_module(module);
    dse.stats()
}

// ============================================================================
// Full MemorySSA — Comprehensive memory SSA construction and analysis
// ============================================================================

/// A MemoryDef within the full MemorySSA framework.
///
/// Tracks the defining store, its block and instruction index,
/// and its relationship to other memory accesses.
#[derive(Debug, Clone)]
pub struct MemDef {
    /// Unique identifier for this memory def.
    pub id: usize,
    /// Block index where the store resides.
    pub block: usize,
    /// Instruction index within the block.
    pub instruction: usize,
    /// The memory access that defines this def (the previous state).
    pub defining_access: usize,
    /// Whether this def represents live-on-entry memory state.
    pub is_live_on_entry: bool,
}

/// A MemoryUse within the full MemorySSA framework.
///
/// Tracks a load instruction and its defining memory access.
#[derive(Debug, Clone)]
pub struct MemUse {
    /// Unique identifier for this memory use.
    pub id: usize,
    /// Block index where the load resides.
    pub block: usize,
    /// Instruction index within the block.
    pub instruction: usize,
    /// The memory access that this use reads from.
    pub memory_access: usize,
    /// Whether this use has been optimized (forwarded to a closer def).
    pub is_optimized: bool,
}

/// A MemoryPhi within the full MemorySSA framework.
///
/// Merges memory states from multiple predecessor blocks.
#[derive(Debug, Clone)]
pub struct MemPhi {
    /// Unique identifier for this memory phi.
    pub id: usize,
    /// Block index where this phi resides.
    pub block: usize,
    /// Incoming memory accesses: (predecessor_block_id, access_id).
    pub incoming: Vec<(usize, usize)>,
}

/// Full Memory SSA analysis for a function.
///
/// Implements the complete MemorySSA construction algorithm:
/// 1. Identify all memory operations (loads, stores, calls)
/// 2. Place MemoryPhi nodes at CFG join points
/// 3. For each memory operation, find the nearest dominating memory def
/// 4. Optimize uses by walking through non-clobbering defs
pub struct MemorySSA {
    /// The function being analyzed.
    pub function: ValueRef,
    /// All memory definitions (stores, calls).
    pub memory_defs: Vec<MemDef>,
    /// All memory uses (loads).
    pub memory_uses: Vec<MemUse>,
    /// All memory phis at CFG join points.
    pub memory_phis: Vec<MemPhi>,
    /// The memory access ID for live-on-entry state, if any.
    pub live_on_entry: Option<usize>,
    /// Block index to memory phi mapping.
    block_to_phi: HashMap<usize, usize>,
    /// Total access counter.
    next_id: usize,
}

impl MemorySSA {
    /// Build MemorySSA for a function.
    ///
    /// Performs the full construction algorithm:
    /// walks instructions in dominator-tree order, identifies
    /// memory operations, and builds use-def chains.
    pub fn build(func: &ValueRef) -> Self {
        let f = func.borrow();
        let mut mssa = MemorySSA {
            function: func.clone(),
            memory_defs: Vec::new(),
            memory_uses: Vec::new(),
            memory_phis: Vec::new(),
            live_on_entry: None,
            block_to_phi: HashMap::new(),
            next_id: 0,
        };

        // Map block names to indices
        let mut block_map: HashMap<String, usize> = HashMap::new();
        let mut block_list: Vec<ValueRef> = Vec::new();
        for (i, op) in f.operands.iter().enumerate() {
            let bb = op.borrow();
            if bb.is_basic_block() {
                block_map.insert(bb.name.clone(), i);
                block_list.push(op.clone());
            }
        }

        // Create live-on-entry def
        let loe_id = mssa.next_id;
        mssa.next_id += 1;
        mssa.live_on_entry = Some(loe_id);
        mssa.memory_defs.push(MemDef {
            id: loe_id,
            block: block_map.get("entry").copied().unwrap_or(0),
            instruction: 0,
            defining_access: loe_id, // self-referential
            is_live_on_entry: true,
        });

        // Track the current memory def for each block
        let mut block_live_def: HashMap<usize, usize> = HashMap::new();
        for (i, _) in block_list.iter().enumerate() {
            block_live_def.insert(i, loe_id);
        }

        // Walk blocks in order, processing instructions
        for (block_idx, block_ref) in block_list.iter().enumerate() {
            let bb = block_ref.borrow();
            let mut inst_idx = 0usize;

            for inst_val in &bb.operands {
                let inst = inst_val.borrow();
                if !inst.is_instruction() {
                    continue;
                }

                let name_lower = inst.name.to_lowercase();
                let opcode = inst.get_opcode();

                // Check for store instructions
                let is_store = name_lower.contains("store");
                // Check for load instructions
                let is_load = name_lower.contains("load");
                // Check for calls (clobber memory)
                let is_call =
                    name_lower.contains("call") || opcode == Some(llvm_native_core::opcode::Opcode::Call);

                if is_store || is_call {
                    let def_id = mssa.next_id;
                    mssa.next_id += 1;
                    let current_def = block_live_def.get(&block_idx).copied().unwrap_or(loe_id);

                    mssa.memory_defs.push(MemDef {
                        id: def_id,
                        block: block_idx,
                        instruction: inst_idx,
                        defining_access: current_def,
                        is_live_on_entry: false,
                    });

                    block_live_def.insert(block_idx, def_id);
                } else if is_load {
                    let use_id = mssa.next_id;
                    mssa.next_id += 1;
                    let current_def = block_live_def.get(&block_idx).copied().unwrap_or(loe_id);

                    mssa.memory_uses.push(MemUse {
                        id: use_id,
                        block: block_idx,
                        instruction: inst_idx,
                        memory_access: current_def,
                        is_optimized: false,
                    });
                }

                inst_idx += 1;
            }
        }

        // Place MemoryPhi nodes at CFG join points (blocks with multiple predecessors)
        // Find predecessors for each block
        let mut preds: HashMap<usize, Vec<usize>> = HashMap::new();
        for (i, block_ref) in block_list.iter().enumerate() {
            let bb = block_ref.borrow();
            for succ_val in &bb.operands {
                let s = succ_val.borrow();
                if s.is_basic_block() {
                    if let Some(&succ_idx) = block_map.get(&s.name) {
                        preds.entry(succ_idx).or_default().push(i);
                    }
                }
            }
        }

        // Place phis at blocks with >1 predecessor
        for (&block_idx, pred_list) in &preds {
            if pred_list.len() > 1 {
                let phi_id = mssa.next_id;
                mssa.next_id += 1;

                let incoming: Vec<(usize, usize)> = pred_list
                    .iter()
                    .map(|&pred_idx| {
                        let def = block_live_def.get(&pred_idx).copied().unwrap_or(loe_id);
                        (pred_idx, def)
                    })
                    .collect();

                mssa.memory_phis.push(MemPhi {
                    id: phi_id,
                    block: block_idx,
                    incoming,
                });

                mssa.block_to_phi.insert(block_idx, phi_id);
            }
        }

        mssa
    }

    /// Get the defining memory access for an instruction.
    ///
    /// Walks the use-def chain to find the nearest dominating
    /// memory definition for a given instruction ID (the instruction's
    /// position in the block's instruction list).
    pub fn get_defining_access(&self, inst_id: usize) -> usize {
        // Look through uses first
        for use_acc in &self.memory_uses {
            if use_acc.id == inst_id || use_acc.instruction == inst_id {
                return use_acc.memory_access;
            }
        }
        // Fallback to live-on-entry
        self.live_on_entry.unwrap_or(0)
    }

    /// Check if two memory accesses refer to the same location.
    ///
    /// Simplified: returns true if both accesses are in the
    /// same memory category (no precise alias analysis).
    pub fn is_same_memory_location(&self, a: usize, b: usize) -> bool {
        // Check if both are defs and in the same block
        let def_a = self.memory_defs.iter().find(|d| d.id == a);
        let def_b = self.memory_defs.iter().find(|d| d.id == b);
        if let (Some(da), Some(db)) = (def_a, def_b) {
            return da.block == db.block;
        }
        false
    }

    /// Check if access `a` dominates access `b` in the memory SSA graph.
    ///
    /// Walks the defining access chain from `b` to see if `a` appears.
    pub fn dominates_access(&self, a: usize, b: usize) -> bool {
        if a == b {
            return true;
        }

        let mut visited: HashSet<usize> = HashSet::new();
        let mut current = b;

        while visited.insert(current) {
            // Check defs
            for def in &self.memory_defs {
                if def.id == current {
                    if def.defining_access == a {
                        return true;
                    }
                    current = def.defining_access;
                    break;
                }
            }
            // Check uses
            for use_acc in &self.memory_uses {
                if use_acc.id == current {
                    if use_acc.memory_access == a {
                        return true;
                    }
                    current = use_acc.memory_access;
                    break;
                }
            }
            // Check phis
            for phi in &self.memory_phis {
                if phi.id == current {
                    for &(_, incoming_id) in &phi.incoming {
                        if incoming_id == a {
                            return true;
                        }
                    }
                    // Follow one incoming edge
                    if let Some(&(_, first_in)) = phi.incoming.first() {
                        current = first_in;
                    } else {
                        break;
                    }
                    break;
                }
            }

            // If current didn't change, we're stuck (shouldn't happen with valid MSSA)
            if current == b && a != b {
                break;
            }
        }

        false
    }

    /// Optimize memory uses by walking through non-clobbering defs.
    ///
    /// A load can be forwarded to an earlier store if no intervening
    /// store clobbers the same location.
    pub fn optimize_uses(&mut self) -> usize {
        let mut optimized = 0;

        for i in 0..self.memory_uses.len() {
            let use_acc = &self.memory_uses[i];
            let def_id = use_acc.memory_access;

            // Walk the def chain to find the nearest non-clobbering def
            let mut current = def_id;
            let mut best_def = def_id;

            for _ in 0..100 {
                // Find the def at `current`
                if let Some(def) = self.memory_defs.iter().find(|d| d.id == current) {
                    if def.is_live_on_entry {
                        break;
                    }
                    // Check if this def clobbers — simplified: always walk up
                    // In a full implementation, alias analysis would determine
                    // if the def writes to the same location as the use.
                    best_def = current;
                    current = def.defining_access;
                } else {
                    break;
                }
            }

            if best_def != def_id {
                self.memory_uses[i].memory_access = best_def;
                self.memory_uses[i].is_optimized = true;
                optimized += 1;
            }
        }

        optimized
    }

    /// Verify the MemorySSA structure for consistency.
    ///
    /// Checks that all access IDs are unique, all references are valid,
    /// and no cycles exist in the def chain.
    pub fn verify(&self) -> Result<(), String> {
        // Check unique IDs
        let mut seen_ids: HashSet<usize> = HashSet::new();
        for def in &self.memory_defs {
            if !seen_ids.insert(def.id) {
                return Err(format!("Duplicate MemoryDef ID: {}", def.id));
            }
        }
        for use_acc in &self.memory_uses {
            if !seen_ids.insert(use_acc.id) {
                return Err(format!("Duplicate MemoryUse ID: {}", use_acc.id));
            }
        }
        for phi in &self.memory_phis {
            if !seen_ids.insert(phi.id) {
                return Err(format!("Duplicate MemoryPhi ID: {}", phi.id));
            }
        }

        // Check that all references are valid
        for use_acc in &self.memory_uses {
            if !seen_ids.contains(&use_acc.memory_access) {
                return Err(format!(
                    "MemoryUse {} references unknown access {}",
                    use_acc.id, use_acc.memory_access
                ));
            }
        }

        for def in &self.memory_defs {
            if !def.is_live_on_entry && !seen_ids.contains(&def.defining_access) {
                return Err(format!(
                    "MemoryDef {} references unknown access {}",
                    def.id, def.defining_access
                ));
            }
        }

        for phi in &self.memory_phis {
            for &(_, incoming_id) in &phi.incoming {
                if !seen_ids.contains(&incoming_id) {
                    return Err(format!(
                        "MemoryPhi {} references unknown incoming access {}",
                        phi.id, incoming_id
                    ));
                }
            }
        }

        Ok(())
    }

    /// Find the clobbering access for a given instruction.
    ///
    /// Returns the ID of the nearest memory def that *may* clobber
    /// the given instruction's memory access. Used for store-to-load
    /// forwarding decisions.
    pub fn get_clobbering_access(&self, inst_id: usize) -> Option<usize> {
        // Find the use or def for this instruction
        let access_id = self
            .memory_uses
            .iter()
            .find(|u| u.instruction == inst_id)
            .map(|u| u.memory_access)
            .or_else(|| {
                self.memory_defs
                    .iter()
                    .find(|d| d.instruction == inst_id)
                    .map(|d| d.id)
            })?;

        // Walk up the def chain to find the nearest clobbering def
        let mut current = access_id;
        for _ in 0..100 {
            if let Some(def) = self.memory_defs.iter().find(|d| d.id == current) {
                if def.is_live_on_entry {
                    return None; // Reached the root, no clobbering access
                }
                return Some(def.id);
            }
            // Follow use chain
            if let Some(use_acc) = self.memory_uses.iter().find(|u| u.id == current) {
                current = use_acc.memory_access;
                continue;
            }
            break;
        }

        None
    }

    /// Walk the memory def-use chain starting from an access ID,
    /// calling the visitor function for each access along the way.
    pub fn walk_def_chain<F>(&self, access_id: usize, mut visitor: F)
    where
        F: FnMut(usize, &str),
    {
        let mut visited: HashSet<usize> = HashSet::new();
        let mut current = access_id;
        let mut depth = 0u32;

        while visited.insert(current) && depth < 100 {
            // Check if it's a def
            if let Some(def) = self.memory_defs.iter().find(|d| d.id == current) {
                visitor(current, "def");
                if def.is_live_on_entry {
                    break;
                }
                current = def.defining_access;
                depth += 1;
                continue;
            }
            // Check if it's a use
            if let Some(use_acc) = self.memory_uses.iter().find(|u| u.id == current) {
                visitor(current, "use");
                current = use_acc.memory_access;
                depth += 1;
                continue;
            }
            // Check if it's a phi
            if let Some(phi) = self.memory_phis.iter().find(|p| p.id == current) {
                visitor(current, "phi");
                if let Some(&(_, first_in)) = phi.incoming.first() {
                    current = first_in;
                } else {
                    break;
                }
                depth += 1;
                continue;
            }
            break;
        }
    }

    /// Check if two accesses are guaranteed not to alias.
    ///
    /// Simplified: returns true if the accesses are to different
    /// memory regions (approximated by block locality).
    pub fn is_no_alias(&self, a: usize, b: usize) -> bool {
        let def_a = self.memory_defs.iter().find(|d| d.id == a);
        let def_b = self.memory_defs.iter().find(|d| d.id == b);

        match (def_a, def_b) {
            (Some(da), Some(db)) => {
                // If in different blocks and no phi connects them,
                // they're likely non-aliasing
                da.block != db.block
            }
            _ => false,
        }
    }

    /// Get the total number of access nodes (defs + uses + phis).
    pub fn total_accesses(&self) -> usize {
        self.memory_defs.len() + self.memory_uses.len() + self.memory_phis.len()
    }

    /// Get statistics about the MemorySSA.
    pub fn stats(&self) -> MemorySSAStats {
        MemorySSAStats {
            total_accesses: self.total_accesses(),
            memory_defs: self.memory_defs.len(),
            memory_uses: self.memory_uses.len(),
            dead_stores: 0, // determined by analysis pass
            redundant_loads: self.memory_uses.iter().filter(|u| u.is_optimized).count(),
            live_stores: self
                .memory_defs
                .iter()
                .filter(|d| !d.is_live_on_entry)
                .count(),
        }
    }
}

// ============================================================================
// MemorySSA Pass — Run analysis and optimization
// ============================================================================

/// Build and optimize MemorySSA for a function.
///
/// Returns the MemorySSA analysis with optimized use-def chains.
pub fn build_memory_ssa(func: &ValueRef) -> MemorySSA {
    let mut mssa = MemorySSA::build(func);
    mssa.optimize_uses();
    mssa
}

/// Verify and return MemorySSA stats for a function.
pub fn analyze_memory_ssa_full(func: &ValueRef) -> Result<MemorySSAStats, String> {
    let mssa = build_memory_ssa(func);
    mssa.verify()?;
    Ok(mssa.stats())
}

// ============================================================================
// Tests — Existing tests preserved
// ============================================================================

#[cfg(test)]
fn build_simple_func(name: &str) -> ValueRef {
    let func = llvm_native_core::function::new_function(name, llvm_native_core::types::Type::void(), &[]);
    let entry = llvm_native_core::basic_block::new_basic_block("entry");
    entry
        .borrow_mut()
        .push_operand(llvm_native_core::instruction::ret_void());
    func.borrow_mut().push_operand(entry.clone());
    func
}

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

    // build_simple_func is defined at the parent level for shared use

    // === MemoryAccess Tests ===

    #[test]
    fn test_memory_def_create() {
        let store = build_simple_func("store_inst");
        let def = MemoryDef {
            store_inst: store,
            defining_access: None,
            location: None,
            users: vec![],
        };
        assert!(def.users.is_empty());
    }

    #[test]
    fn test_memory_use_create() {
        let load = build_simple_func("load_inst");
        let use_access = MemoryUse {
            load_inst: load,
            defining_access: None,
            location: None,
            is_optimizable: false,
        };
        assert!(!use_access.is_optimizable);
    }

    // === MemorySSABuilder Tests ===

    #[test]
    fn test_memory_ssa_builder_create() {
        let builder = MemorySSABuilder::new();
        assert!(builder.accesses.is_empty());
        assert_eq!(builder.dead_stores, 0);
    }

    #[test]
    fn test_memory_ssa_build_simple() {
        let mut builder = MemorySSABuilder::new();
        let func = build_simple_func("mem_test");
        builder.build(&func);

        let stats = builder.stats();
        assert!(stats.total_accesses >= 0);
    }

    #[test]
    fn test_memory_ssa_count_dead_stores() {
        let builder = MemorySSABuilder::new();
        assert_eq!(builder.count_dead_stores(), 0);
    }

    #[test]
    fn test_memory_ssa_stats() {
        let mut builder = MemorySSABuilder::new();
        let func = build_simple_func("stats_test");
        builder.build(&func);

        let stats = builder.stats();
        assert_eq!(stats.memory_defs + stats.memory_uses, stats.total_accesses);
    }

    // === DeadStoreElimination Tests ===

    #[test]
    fn test_dse_create() {
        let dse = DeadStoreElimination::new();
        assert_eq!(dse.stores_eliminated, 0);
        assert_eq!(dse.loads_forwarded, 0);
    }

    #[test]
    fn test_dse_run_simple() {
        let mut dse = DeadStoreElimination::new();
        let func = build_simple_func("dse_test");

        let eliminated = dse.run_on_function(&func);
        assert!(eliminated >= 0);
    }

    #[test]
    fn test_dse_stats() {
        let dse = DeadStoreElimination::new();
        let stats = dse.stats();
        assert_eq!(stats.stores_eliminated, 0);
    }

    // === analyze_memory_ssa Tests ===

    #[test]
    fn test_analyze_memory_ssa_simple() {
        let func = build_simple_func("analyze_test");
        let stats = analyze_memory_ssa(&func);
        assert!(stats.total_accesses >= 0);
    }

    // === eliminate_dead_stores Tests ===

    #[test]
    fn test_eliminate_dead_stores_simple() {
        let func = build_simple_func("elim_test");
        let stats = eliminate_dead_stores(&func);
        assert!(stats.memory_accesses >= 0);
    }

    #[test]
    fn test_eliminate_dead_stores_module() {
        let mut m = llvm_native_core::module::Module::new("dse_mod");
        m.add_function(build_simple_func("f1"));
        m.add_function(build_simple_func("f2"));

        let stats = eliminate_dead_stores_module(&m);
        assert!(stats.memory_accesses >= 0);
    }

    // === MemorySSAStats Tests ===

    #[test]
    fn test_memory_ssa_stats_structure() {
        let stats = MemorySSAStats {
            total_accesses: 100,
            memory_defs: 40,
            memory_uses: 60,
            dead_stores: 5,
            redundant_loads: 10,
            live_stores: 35,
        };
        assert_eq!(stats.total_accesses, 100);
        assert_eq!(stats.memory_defs + stats.memory_uses, 100);
        assert!(stats.dead_stores <= stats.memory_defs);
        assert!(stats.live_stores + stats.dead_stores <= stats.memory_defs + 5);
        // approximate
    }

    // === DSEStats Tests ===

    #[test]
    fn test_dse_stats_structure() {
        let stats = DSEStats {
            stores_eliminated: 5,
            loads_forwarded: 10,
            memory_accesses: 100,
        };
        assert_eq!(stats.stores_eliminated, 5);
        assert_eq!(stats.loads_forwarded, 10);
    }

    // === Integration Tests ===

    #[test]
    fn test_memory_ssa_pipeline() {
        // Build Memory SSA, then run DSE
        let func = build_simple_func("pipeline");

        let mem_stats = analyze_memory_ssa(&func);
        let dse_stats = eliminate_dead_stores(&func);

        // Both should complete
        assert!(mem_stats.total_accesses >= 0);
        assert!(dse_stats.memory_accesses >= 0);
    }

    #[test]
    fn test_dse_on_module_multiple_functions() {
        let mut m = llvm_native_core::module::Module::new("multi_dse");
        for i in 0..5 {
            m.add_function(build_simple_func(&format!("f{}", i)));
        }

        let stats = eliminate_dead_stores_module(&m);
        assert!(stats.memory_accesses >= 0);
    }

    #[test]
    fn test_memory_ssa_preserves_empty_function() {
        let func = new_function("empty", Type::void(), &[]);
        let stats = analyze_memory_ssa(&func);
        assert_eq!(stats.total_accesses, 0);
    }
}

// ============================================================================
// New Tests — Full MemorySSA construction and analysis
// ============================================================================

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

    fn build_func_with_store() -> ValueRef {
        let func = new_function("store_func", Type::void(), &[]);
        let entry = new_basic_block("entry");
        let ptr = instruction::alloca(Type::i32());
        ptr.borrow_mut().name = "ptr".into();
        let val = constants::const_i32(42);
        let store = instruction::store(val, ptr.clone());
        store.borrow_mut().name = "store_inst".into();
        entry.borrow_mut().push_operand(ptr);
        entry.borrow_mut().push_operand(store);
        entry.borrow_mut().push_operand(instruction::ret_void());
        func.borrow_mut().push_operand(entry);
        func
    }

    fn build_func_with_load() -> ValueRef {
        let func = new_function("load_func", Type::void(), &[]);
        let entry = new_basic_block("entry");
        let ptr = instruction::alloca(Type::i32());
        ptr.borrow_mut().name = "ptr".into();
        let load = instruction::load(Type::i32(), ptr.clone());
        load.borrow_mut().name = "load_inst".into();
        entry.borrow_mut().push_operand(ptr);
        entry.borrow_mut().push_operand(load);
        entry.borrow_mut().push_operand(instruction::ret_void());
        func.borrow_mut().push_operand(entry);
        func
    }

    fn build_multi_block_func() -> ValueRef {
        let func = new_function("multi", Type::void(), &[]);
        let entry = new_basic_block("entry");
        let block_a = new_basic_block("block_a");
        let block_b = new_basic_block("block_b");
        let block_c = new_basic_block("block_c");

        let cond = constants::const_bool(true);
        entry.borrow_mut().push_operand(instruction::br_cond(
            cond,
            block_a.clone(),
            block_b.clone(),
        ));

        let ptr_a = instruction::alloca(Type::i32());
        ptr_a.borrow_mut().name = "ptr_a".into();
        let store_a = instruction::store(constants::const_i32(1), ptr_a.clone());
        store_a.borrow_mut().name = "store_a".into();
        block_a.borrow_mut().push_operand(ptr_a);
        block_a.borrow_mut().push_operand(store_a);
        block_a
            .borrow_mut()
            .push_operand(instruction::br(block_c.clone()));

        let ptr_b = instruction::alloca(Type::i32());
        ptr_b.borrow_mut().name = "ptr_b".into();
        let store_b = instruction::store(constants::const_i32(2), ptr_b.clone());
        store_b.borrow_mut().name = "store_b".into();
        block_b.borrow_mut().push_operand(ptr_b);
        block_b.borrow_mut().push_operand(store_b);
        block_b
            .borrow_mut()
            .push_operand(instruction::br(block_c.clone()));

        block_c.borrow_mut().push_operand(instruction::ret_void());

        func.borrow_mut().push_operand(entry);
        func.borrow_mut().push_operand(block_a);
        func.borrow_mut().push_operand(block_b);
        func.borrow_mut().push_operand(block_c);
        func
    }

    // === MemorySSA::build Tests ===

    #[test]
    fn test_memory_ssa_build_simple_func() {
        let func = build_simple_func("test");
        let mssa = MemorySSA::build(&func);
        assert!(mssa.live_on_entry.is_some());
        assert_eq!(mssa.memory_defs.len(), 1); // live-on-entry only
    }

    #[test]
    fn test_memory_ssa_build_with_store() {
        let func = build_func_with_store();
        let mssa = MemorySSA::build(&func);
        assert!(mssa.memory_defs.len() > 1); // live-on-entry + store
    }

    #[test]
    fn test_memory_ssa_build_with_load() {
        let func = build_func_with_load();
        let mssa = MemorySSA::build(&func);
        assert!(mssa.memory_uses.len() >= 1);
    }

    #[test]
    fn test_memory_ssa_build_multi_block() {
        let func = build_multi_block_func();
        let mssa = MemorySSA::build(&func);
        assert!(mssa.total_accesses() >= 4); // loe + at least stores and uses
    }

    // === MemorySSA::verify Tests ===

    #[test]
    fn test_memory_ssa_verify_simple() {
        let func = build_func_with_store();
        let mssa = MemorySSA::build(&func);
        assert!(mssa.verify().is_ok());
    }

    #[test]
    fn test_memory_ssa_verify_multi_block() {
        let func = build_multi_block_func();
        let mssa = MemorySSA::build(&func);
        assert!(mssa.verify().is_ok());
    }

    // === MemorySSA::optimize_uses Tests ===

    #[test]
    fn test_memory_ssa_optimize_uses() {
        let func = build_func_with_load();
        let mut mssa = MemorySSA::build(&func);
        let optimized = mssa.optimize_uses();
        // May or may not optimize depending on def chain structure
        assert!(optimized >= 0);
    }

    // === MemorySSA::get_defining_access Tests ===

    #[test]
    fn test_memory_ssa_get_defining_access() {
        let func = build_func_with_load();
        let mssa = MemorySSA::build(&func);
        let access = mssa.get_defining_access(0);
        assert!(access > 0 || mssa.live_on_entry.is_some());
    }

    // === MemorySSA::dominates_access Tests ===

    #[test]
    fn test_memory_ssa_dominates_access_self() {
        let func = build_func_with_store();
        let mssa = MemorySSA::build(&func);
        // Live-on-entry should dominate itself
        if let Some(loe) = mssa.live_on_entry {
            assert!(mssa.dominates_access(loe, loe));
        }
    }

    // === MemorySSA::get_clobbering_access Tests ===

    #[test]
    fn test_memory_ssa_get_clobbering_access() {
        let func = build_func_with_store();
        let mssa = MemorySSA::build(&func);
        let clobber = mssa.get_clobbering_access(0);
        // Should find something (either a def or None for loe)
        assert!(clobber.is_some() || clobber.is_none());
    }

    // === MemorySSA::walk_def_chain Tests ===

    #[test]
    fn test_memory_ssa_walk_def_chain() {
        let func = build_func_with_store();
        let mssa = MemorySSA::build(&func);
        if let Some(loe) = mssa.live_on_entry {
            let mut visited = Vec::new();
            mssa.walk_def_chain(loe, |id, kind| {
                visited.push((id, kind.to_string()));
            });
            assert!(!visited.is_empty());
        }
    }

    // === MemorySSA::is_no_alias Tests ===

    #[test]
    fn test_memory_ssa_is_no_alias_same() {
        let func = build_func_with_store();
        let mssa = MemorySSA::build(&func);
        if mssa.memory_defs.len() >= 2 {
            let a = mssa.memory_defs[0].id;
            let b = mssa.memory_defs[1].id;
            // Same block = may alias (not guaranteed no-alias)
            let no_alias = mssa.is_no_alias(a, b);
            // This is a conservative check
            let _ = no_alias;
        }
    }

    // === MemorySSA::is_same_memory_location Tests ===

    #[test]
    fn test_memory_ssa_is_same_memory_location() {
        let func = build_func_with_store();
        let mssa = MemorySSA::build(&func);
        if mssa.memory_defs.len() >= 2 {
            let a = mssa.memory_defs[0].id;
            let b = mssa.memory_defs[1].id;
            let same = mssa.is_same_memory_location(a, b);
            // Both in entry block => true
            let _ = same;
        }
    }

    // === build_memory_ssa Tests ===

    #[test]
    fn test_build_memory_ssa_simple() {
        let func = build_func_with_store();
        let mssa = build_memory_ssa(&func);
        assert!(mssa.total_accesses() > 0);
    }

    // === analyze_memory_ssa_full Tests ===

    #[test]
    fn test_analyze_memory_ssa_full() {
        let func = build_func_with_store();
        let result = analyze_memory_ssa_full(&func);
        assert!(result.is_ok());
        let stats = result.unwrap();
        assert!(stats.total_accesses > 0);
    }
}