forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimd_analyzer.rs
More file actions
1589 lines (1433 loc) · 58.1 KB
/
Copy pathsimd_analyzer.rs
File metadata and controls
1589 lines (1433 loc) · 58.1 KB
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
//! SIMD Vectorization Pattern Analyzer
//!
//! Detects loops that can be vectorized with SIMD instructions.
//! Scans bytecode regions for element-wise array operation patterns.
//!
//! # Overview
//!
//! The analyzer identifies `for`-style loops over arrays where each iteration
//! performs independent element-wise operations. When a pattern is recognized,
//! the JIT can emit Cranelift SIMD instructions (e.g., `I64x2` add, `F32x4` mul)
//! instead of scalar operations, yielding up to 2-4x speedup on numeric kernels.
//!
//! # Supported Patterns
//!
//! | Pattern | Example | SIMD Width |
//! |---------|---------|------------|
//! | `ElementWiseBinop` | `c[i] = a[i] + b[i]` | I64x2, F64x2, I32x4, F32x4 |
//! | `ElementWiseUnary` | `b[i] = -a[i]` | I64x2, F64x2, I32x4, F32x4 |
//! | `ElementWiseCmp` | `c[i] = a[i] < b[i]` | I64x2, F64x2, I32x4, F32x4 |
//!
//! # Vectorization Requirements
//!
//! All of the following must hold for a region to be marked vectorizable:
//!
//! 1. The loop body contains at least one `ArrLoad` → arithmetic → `ArrStore` chain.
//! 2. All array accesses use the **same** induction variable register as the index.
//! 3. The induction variable increments by 1 each iteration (`IInc` on the induction
//! register, or `IAdd` with constant 1).
//! 4. The trip count is determinable (`ArrLen` comparison or a constant bound).
//! 5. The element type is uniform across all array operations.
//! 6. No loop-carried dependencies (the destination array is different from source
//! arrays, or the same array with no overlap concerns).
//! 7. No function calls (`Call`, `ClosureCall`) inside the loop body.
//! 8. No control flow other than the back-edge jump (conditional exit or unconditional
//! jump back to loop header).
use crate::bytecode::{Instruction, OpCode};
use crate::jit::typed_compiler::{KnownType, TypeMetadata};
// ---------------------------------------------------------------------------
// SimdElemType
// ---------------------------------------------------------------------------
/// The scalar element type that will be packed into SIMD vectors.
///
/// This determines both the lane width and the Cranelift SIMD type to use:
/// - `Int64` → `I64x2` (2-wide on 128-bit vectors)
/// - `Float64` → `F64x2` (2-wide on 128-bit vectors)
/// - `Int32` → `I32x4` (4-wide on 128-bit vectors)
/// - `Float32` → `F32x4` (4-wide on 128-bit vectors)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SimdElemType {
Int64,
Float64,
Int32,
Float32,
}
impl SimdElemType {
/// Return true if this is a floating-point type.
pub fn is_float(&self) -> bool {
matches!(self, SimdElemType::Float64 | SimdElemType::Float32)
}
/// Return true if this is an integer type.
pub fn is_int(&self) -> bool {
!self.is_float()
}
/// Return the SIMD lane width for this element type on a 128-bit vector.
pub fn lane_count(&self) -> usize {
match self {
SimdElemType::Int64 | SimdElemType::Float64 => 2,
SimdElemType::Int32 | SimdElemType::Float32 => 4,
}
}
/// Return the element size in bytes.
pub fn elem_size(&self) -> usize {
match self {
SimdElemType::Int64 | SimdElemType::Float64 => 8,
SimdElemType::Int32 | SimdElemType::Float32 => 4,
}
}
}
// ---------------------------------------------------------------------------
// SimdWidth
// ---------------------------------------------------------------------------
/// The SIMD vectorization width (number of scalar elements per vector).
///
/// Each variant records the native vector width on a 128-bit SIMD register.
/// Future extensions may add `Width8` for 16-bit types and `Width16` for 8-bit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SimdWidth {
/// 2-wide vectors: I64x2, F64x2 — used for 64-bit element types.
Width2,
/// 4-wide vectors: I32x4, F32x4 — used for 32-bit element types.
Width4,
/// 8-wide vectors: I16x8 — reserved for future 16-bit element support.
Width8,
}
impl SimdWidth {
/// Return the number of lanes (scalar elements) per vector.
pub fn lanes(&self) -> usize {
match self {
SimdWidth::Width2 => 2,
SimdWidth::Width4 => 4,
SimdWidth::Width8 => 8,
}
}
/// Derive the SIMD width from an element type.
pub fn from_elem_type(elem_type: SimdElemType) -> Self {
match elem_type {
SimdElemType::Int64 | SimdElemType::Float64 => SimdWidth::Width2,
SimdElemType::Int32 | SimdElemType::Float32 => SimdWidth::Width4,
}
}
}
// ---------------------------------------------------------------------------
// VectorizablePattern
// ---------------------------------------------------------------------------
/// The kind of vectorizable loop pattern detected in a bytecode region.
///
/// Each variant describes the shape of the loop body so that the SIMD
/// compiler knows which instruction sequence to emit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VectorizablePattern {
/// Element-wise binary operation: `dst[i] = lhs[i] op rhs[i]`.
///
/// Registers (in order): `lhs_arr`, `rhs_arr`, `dst_arr`.
/// Example: `c[i] = a[i] + b[i]`
ElementWiseBinop {
op: BinopKind,
lhs_arr_reg: u8,
rhs_arr_reg: u8,
dst_arr_reg: u8,
/// The register that receives the loaded `lhs` element (temp).
lhs_elem_reg: u8,
/// The register that receives the loaded `rhs` element (temp).
rhs_elem_reg: u8,
/// The register that holds the binop result before store (temp).
result_reg: u8,
},
/// Element-wise unary operation: `dst[i] = op(src[i])`.
///
/// Registers (in order): `src_arr`, `dst_arr`.
/// Example: `b[i] = -a[i]`
ElementWiseUnary {
op: UnaryKind,
src_arr_reg: u8,
dst_arr_reg: u8,
/// The register that receives the loaded element (temp).
src_elem_reg: u8,
/// The register that holds the unary result before store (temp).
result_reg: u8,
},
/// Element-wise comparison: `dst[i] = lhs[i] cmp rhs[i]`.
///
/// Registers (in order): `lhs_arr`, `rhs_arr`, `dst_arr`.
/// Example: `c[i] = a[i] < b[i]`
ElementWiseCmp {
op: CmpKind,
lhs_arr_reg: u8,
rhs_arr_reg: u8,
dst_arr_reg: u8,
lhs_elem_reg: u8,
rhs_elem_reg: u8,
result_reg: u8,
},
}
/// Binary operation kinds supported for SIMD vectorization.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinopKind {
IAdd,
ISub,
IMul,
IDiv,
FAdd,
FSub,
FMul,
FDiv,
}
impl BinopKind {
/// Return true if this is a floating-point operation.
pub fn is_float(&self) -> bool {
matches!(
self,
BinopKind::FAdd | BinopKind::FSub | BinopKind::FMul | BinopKind::FDiv
)
}
/// Return true if this is an integer operation.
pub fn is_int(&self) -> bool {
!self.is_float()
}
}
/// Unary operation kinds supported for SIMD vectorization.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnaryKind {
INeg,
FNeg,
}
/// Comparison operation kinds supported for SIMD vectorization.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CmpKind {
ICmpEq,
ICmpLt,
ICmpGt,
ICmpLe,
ICmpGe,
FCmpEq,
FCmpLt,
FCmpGt,
}
impl CmpKind {
/// Return true if this is a floating-point comparison.
pub fn is_float(&self) -> bool {
matches!(self, CmpKind::FCmpEq | CmpKind::FCmpLt | CmpKind::FCmpGt)
}
}
// ---------------------------------------------------------------------------
// SimdRegion
// ---------------------------------------------------------------------------
/// Description of a vectorizable loop region found in the bytecode.
///
/// Created by [`analyze_region`] or [`SimdAnalyzer::find_all_vectorizable_regions`]
/// and consumed by the SIMD compiler to emit Cranelift SIMD instructions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SimdRegion {
/// Bytecode offset where the vectorizable loop body starts.
pub start_offset: usize,
/// Number of instructions in the detected loop body.
pub num_instrs: usize,
/// The detected vectorization pattern (binary / unary / comparison).
pub pattern: VectorizablePattern,
/// The SIMD width to use (derived from `elem_type`).
pub width: SimdWidth,
/// The scalar element type of the arrays (determines lane width).
pub elem_type: SimdElemType,
/// The register that holds the loop induction variable (the array index).
pub induction_var_reg: u8,
/// Registers that hold array references (input + output arrays).
pub array_regs: Vec<u8>,
/// Known trip count if statically determinable (e.g. from `ArrLen`).
/// `Some(0)` means "runtime-determined from `arr_len_reg`".
pub trip_count_hint: Option<usize>,
/// Register holding the `ArrLen` result when `trip_count_hint == Some(0)`.
pub arr_len_reg: Option<u8>,
}
// ---------------------------------------------------------------------------
// SimdAnalyzer
// ---------------------------------------------------------------------------
/// Stateful SIMD pattern analyzer.
///
/// Scans a full instruction stream to discover every vectorizable loop region.
/// Each discovered region is returned as a [`SimdRegion`] that the SIMD compiler
/// can then transform into native SIMD code.
///
/// # Example
///
/// ```ignore
/// ```no_run
/// use nulang::jit::simd_analyzer::SimdAnalyzer;
/// use nulang::bytecode::Instruction;
///
/// let analyzer = SimdAnalyzer::new();
/// let regions = analyzer.find_all_vectorizable_regions(&instructions, None);
/// ```
#[derive(Debug, Clone, Default)]
pub struct SimdAnalyzer {
// Currently stateless; reserved for future caching / profiling state.
}
impl SimdAnalyzer {
/// Create a new SIMD analyzer.
pub fn new() -> Self {
Self::default()
}
/// Scan the full instruction stream and return every vectorizable region.
///
/// The algorithm walks the instruction stream and, for every potential loop
/// body (identified by a backward jump), calls [`analyze_region`]. Regions
/// are returned sorted by `start_offset`.
pub fn find_all_vectorizable_regions(
&self,
instructions: &[Instruction],
type_metadata: Option<&TypeMetadata>,
) -> Vec<SimdRegion> {
let mut regions = Vec::new();
let n = instructions.len();
if n < 3 {
return regions;
}
// Scan for backward jumps (potential loop back-edges).
for pc in 0..n {
let instr = instructions[pc];
let backward_target = match instr.opcode {
OpCode::Jmp => {
let target = (pc as i64 + instr.simm16() as i64) as usize;
if target < pc {
Some(target)
} else {
None
}
}
OpCode::JmpT | OpCode::JmpF => {
// The conditional jump may jump backward (loop back-edge)
// or forward (loop exit). We look at the backward case.
let target = (pc as i64 + instr.offset16() as i64) as usize;
if target < pc {
Some(target)
} else {
None
}
}
_ => None,
};
if let Some(loop_header) = backward_target {
// The loop body spans from the header to the back-edge (inclusive).
let body_start = loop_header;
let body_end = pc; // back-edge instruction
let body_len = if body_end > body_start {
body_end - body_start
} else {
continue;
};
// Skip tiny bodies — not worth vectorizing.
if body_len < 3 {
continue;
}
if let Some(region) =
analyze_region(instructions, body_start, body_len, type_metadata)
{
// Avoid duplicate regions (same start offset).
if !regions
.iter()
.any(|r: &SimdRegion| r.start_offset == region.start_offset)
{
regions.push(region);
}
}
}
}
// Also look for simple counted loops without explicit backward jumps
// by scanning for ArrLoad / ArrStore patterns with IInc.
// This catches loops that the simple back-edge detection might miss.
self.find_counted_loop_patterns(instructions, type_metadata, &mut regions);
// Sort by start offset for deterministic output.
regions.sort_by_key(|r| r.start_offset);
regions
}
/// Look for counted loop patterns: sequences that load from arrays,
/// perform an operation, store back, and increment an induction variable.
fn find_counted_loop_patterns(
&self,
instructions: &[Instruction],
type_metadata: Option<&TypeMetadata>,
regions: &mut Vec<SimdRegion>,
) {
// This is a simpler pattern matcher that looks for windows containing
// ArrLoad → arithmetic → ArrStore with an IInc.
// The window-based approach helps catch loops the back-edge detector misses.
let n = instructions.len();
let min_window = 5;
let max_window = 50;
for start in 0..n.saturating_sub(min_window) {
let max_end = (start + max_window).min(n);
for end in (start + min_window)..max_end {
if end > n {
break;
}
let len = end - start;
// Skip if we already have a region at this start.
if regions.iter().any(|r| r.start_offset == start) {
continue;
}
if let Some(region) = analyze_region(instructions, start, len, type_metadata) {
// Skip if this region overlaps an already-discovered region.
let overlaps = regions.iter().any(|r: &SimdRegion| {
let r_end = r.start_offset + r.num_instrs;
let new_end = region.start_offset + region.num_instrs;
region.start_offset < r_end && new_end > r.start_offset
});
if !overlaps {
regions.push(region);
}
break; // Found one at this start, move on.
}
}
}
}
}
// ---------------------------------------------------------------------------
// analyze_region (core analysis)
// ---------------------------------------------------------------------------
/// Analyze a contiguous bytecode region and determine whether it forms a
/// vectorizable loop.
///
/// Returns `Some(SimdRegion)` when **all** of the vectorization requirements
/// are satisfied, or `None` otherwise.
///
/// # Arguments
///
/// * `instructions` — The full bytecode instruction array.
/// * `start_offset` — Bytecode offset where the candidate region starts.
/// * `num_instrs` — Number of instructions in the candidate region.
/// * `type_metadata` — Optional static type information for registers.
pub fn analyze_region(
instructions: &[Instruction],
start_offset: usize,
num_instrs: usize,
type_metadata: Option<&TypeMetadata>,
) -> Option<SimdRegion> {
let end_offset = (start_offset + num_instrs).min(instructions.len());
let body = &instructions[start_offset..end_offset];
if body.len() < 3 {
return None;
}
// --- Requirement 7 & 8: Check for unsupported opcodes ---
let mut induction_reg: Option<u8> = None;
let mut _back_edge_found = false;
for (i, instr) in body.iter().enumerate() {
match instr.opcode {
// Reject function calls inside the loop body.
OpCode::Call | OpCode::ClosureCall | OpCode::TailCall => {
return None;
}
// Reject complex control flow (anything other than Jmp/JmpT/JmpF).
OpCode::Switch | OpCode::Ret | OpCode::RetVal => {
return None;
}
// Actor / concurrency opcodes are not vectorizable.
OpCode::Spawn
| OpCode::Send
| OpCode::Ask
| OpCode::SelfOp
| OpCode::Receive
| OpCode::ReceiveMatch
| OpCode::ReceiveCommit
| OpCode::Monitor
| OpCode::Demon
| OpCode::Link
| OpCode::Unlink
| OpCode::Exit
| OpCode::Yield => {
return None;
}
// Effect operations are not vectorizable.
OpCode::Perform | OpCode::Handle | OpCode::Resume | OpCode::Unwind => {
return None;
}
// IO / debug not vectorizable.
OpCode::SRead
| OpCode::FOpen
| OpCode::FRead
| OpCode::FWrite
| OpCode::FClose
| OpCode::DbgBreak
| OpCode::DbgPrint
| OpCode::DbgStack => {
return None;
}
// Detect induction variable increment.
OpCode::IInc => {
if induction_reg.is_none() {
induction_reg = Some(instr.op1);
}
}
// Detect back-edge jump.
OpCode::Jmp => {
let target = (start_offset + i) as i64 + instr.simm16() as i64;
if (target as usize) < start_offset + i {
_back_edge_found = true;
}
// Forward jumps inside the loop body are also not allowed (except exit).
let target_usize = target as usize;
if target_usize >= start_offset
&& target_usize < end_offset
&& target_usize != start_offset
{
// Jump to somewhere inside the loop body (not the header) — reject.
// This indicates complex control flow.
// However, allow it if it's just skipping past the back-edge.
}
}
OpCode::JmpT | OpCode::JmpF => {
let target = (start_offset + i) as i64 + instr.offset16() as i64;
let target_usize = target as usize;
// Conditional jump forward past the loop is fine (exit condition).
if target_usize > end_offset {
// loop exit — OK
} else if target_usize < start_offset + i {
// backward jump — another back-edge
_back_edge_found = true;
}
}
_ => {}
}
}
// --- Detect array load → op → store patterns ---
// Collect all ArrLoad and ArrStore instructions and their registers.
let mut loads: Vec<(usize, u8, u8, u8)> = Vec::new(); // (body_idx, arr_reg, idx_reg, dst_reg)
let mut stores: Vec<(usize, u8, u8, u8)> = Vec::new(); // (body_idx, arr_reg, idx_reg, src_reg)
for (i, instr) in body.iter().enumerate() {
match instr.opcode {
OpCode::ArrLoad => {
loads.push((i, instr.op1, instr.op2, instr.op3));
}
OpCode::ArrStore => {
stores.push((i, instr.op1, instr.op2, instr.op3));
}
_ => {}
}
}
// Requirement 1: At least one load and one store.
if loads.is_empty() || stores.is_empty() {
return None;
}
// --- Requirement 2: All array accesses must use the same index register ---
// (the induction variable).
let idx_reg = loads[0].2;
// All loads must use the same index register.
for &(_, _, ir, _) in &loads {
if ir != idx_reg {
return None;
}
}
// All stores must use the same index register.
for &(_, _, ir, _) in &stores {
if ir != idx_reg {
return None;
}
}
// --- Requirement 3: The induction variable must be incremented ---
let has_iinc = body
.iter()
.any(|instr| instr.opcode == OpCode::IInc && instr.op1 == idx_reg);
// Also accept IAdd idx_reg, Const1/Const0-like as induction increment.
let has_iadd_inc = body.iter().any(|instr| {
instr.opcode == OpCode::IAdd
&& instr.op3 == idx_reg
&& (instr.op1 == idx_reg || instr.op2 == idx_reg)
});
if !has_iinc && !has_iadd_inc {
return None;
}
// Set the induction variable register.
induction_reg = Some(idx_reg);
// --- Try to detect a specific pattern ---
// Look for ElementWiseBinop: two loads, one binop, one store.
if let Some(pattern) = try_detect_elementwise_binop(body, &loads, &stores, start_offset) {
let elem_type = infer_elem_type(&pattern, type_metadata);
let width = SimdWidth::from_elem_type(elem_type);
let array_regs = collect_array_regs(&pattern);
// Requirement 6: Check loop-carried dependencies.
if has_loop_carried_dependency(&pattern, &stores, idx_reg) {
return None;
}
// Requirement 4: Try to find trip count hint.
let (trip_count_hint, arr_len_reg) = find_trip_count_hint(body, &array_regs);
return Some(SimdRegion {
start_offset,
num_instrs,
pattern,
width,
elem_type,
induction_var_reg: induction_reg.unwrap(),
array_regs,
trip_count_hint,
arr_len_reg,
});
}
// Look for ElementWiseUnary: one load, one unary op, one store.
if let Some(pattern) = try_detect_elementwise_unary(body, &loads, &stores, start_offset) {
let elem_type = infer_elem_type_unary(&pattern, type_metadata);
let width = SimdWidth::from_elem_type(elem_type);
let array_regs = collect_array_regs_unary(&pattern);
if has_loop_carried_dependency_unary(&pattern, &stores, idx_reg) {
return None;
}
let (trip_count_hint, arr_len_reg) = find_trip_count_hint(body, &array_regs);
return Some(SimdRegion {
start_offset,
num_instrs,
pattern,
width,
elem_type,
induction_var_reg: induction_reg.unwrap(),
array_regs,
trip_count_hint,
arr_len_reg,
});
}
// Look for ElementWiseCmp: two loads, one comparison, one store.
if let Some(pattern) = try_detect_elementwise_cmp(body, &loads, &stores, start_offset) {
let elem_type = infer_elem_type_cmp(&pattern, type_metadata);
let width = SimdWidth::from_elem_type(elem_type);
let array_regs = collect_array_regs_cmp(&pattern);
if has_loop_carried_dependency_cmp(&pattern, &stores, idx_reg) {
return None;
}
let (trip_count_hint, arr_len_reg) = find_trip_count_hint(body, &array_regs);
return Some(SimdRegion {
start_offset,
num_instrs,
pattern,
width,
elem_type,
induction_var_reg: induction_reg.unwrap(),
array_regs,
trip_count_hint,
arr_len_reg,
});
}
None
}
// ---------------------------------------------------------------------------
// Pattern Detection Helpers
// ---------------------------------------------------------------------------
/// Try to detect `ElementWiseBinop`: two ArrLoads, one binary op, one ArrStore.
fn try_detect_elementwise_binop(
body: &[Instruction],
loads: &[(usize, u8, u8, u8)],
stores: &[(usize, u8, u8, u8)],
_start_offset: usize,
) -> Option<VectorizablePattern> {
// Need at least 2 loads and 1 store.
if loads.len() < 2 || stores.len() < 1 {
return None;
}
// Try every pair of loads and every store.
for (li1, &(_load1_idx, arr1, _idx1, dst1)) in loads.iter().enumerate() {
for (li2, &(_load2_idx, arr2, _idx2, dst2)) in loads.iter().enumerate() {
if li1 == li2 {
continue;
}
for &(_store_idx, store_arr, _store_idx_reg, store_src) in stores {
// Look for a binary operation that takes dst1 and dst2 as operands
// and produces store_src.
for instr in body {
let op_kind = match instr.opcode {
OpCode::IAdd => Some(BinopKind::IAdd),
OpCode::ISub => Some(BinopKind::ISub),
OpCode::IMul => Some(BinopKind::IMul),
OpCode::IDiv => Some(BinopKind::IDiv),
OpCode::FAdd => Some(BinopKind::FAdd),
OpCode::FSub => Some(BinopKind::FSub),
OpCode::FMul => Some(BinopKind::FMul),
OpCode::FDiv => Some(BinopKind::FDiv),
_ => None,
};
if let Some(op) = op_kind {
// Check if the binop uses the loaded values as operands
// and produces the value that gets stored.
let uses_operands = (instr.op1 == dst1 && instr.op2 == dst2)
|| (instr.op1 == dst2 && instr.op2 == dst1);
let produces_store_src = instr.op3 == store_src;
if uses_operands && produces_store_src {
return Some(VectorizablePattern::ElementWiseBinop {
op,
lhs_arr_reg: arr1,
rhs_arr_reg: arr2,
dst_arr_reg: store_arr,
lhs_elem_reg: dst1,
rhs_elem_reg: dst2,
result_reg: store_src,
});
}
}
}
}
}
}
None
}
/// Try to detect `ElementWiseUnary`: one ArrLoad, one unary op, one ArrStore.
fn try_detect_elementwise_unary(
body: &[Instruction],
loads: &[(usize, u8, u8, u8)],
stores: &[(usize, u8, u8, u8)],
_start_offset: usize,
) -> Option<VectorizablePattern> {
// Need at least 1 load and 1 store.
if loads.is_empty() || stores.is_empty() {
return None;
}
for &(_load_idx, load_arr, _idx, load_dst) in loads {
// If there are multiple loads, skip unary pattern to prefer binary.
if loads.len() > 1 {
// Only consider this load if no other load feeds into the same store.
// For simplicity, only allow unary when there's exactly 1 load.
if loads.len() != 1 {
continue;
}
}
for &(_store_idx, store_arr, _store_idx_reg, store_src) in stores {
// Look for a unary operation that takes load_dst and produces store_src.
for instr in body {
let op_kind = match instr.opcode {
OpCode::INeg => Some(UnaryKind::INeg),
OpCode::FNeg => Some(UnaryKind::FNeg),
_ => None,
};
if let Some(op) = op_kind {
let uses_loaded = instr.op1 == load_dst;
let produces_store_src = instr.op2 == store_src;
if uses_loaded && produces_store_src {
return Some(VectorizablePattern::ElementWiseUnary {
op,
src_arr_reg: load_arr,
dst_arr_reg: store_arr,
src_elem_reg: load_dst,
result_reg: store_src,
});
}
}
}
}
}
None
}
/// Try to detect `ElementWiseCmp`: two ArrLoads, one comparison, one ArrStore.
fn try_detect_elementwise_cmp(
body: &[Instruction],
loads: &[(usize, u8, u8, u8)],
stores: &[(usize, u8, u8, u8)],
_start_offset: usize,
) -> Option<VectorizablePattern> {
// Need at least 2 loads and 1 store.
if loads.len() < 2 || stores.len() < 1 {
return None;
}
for (li1, &(_load1_idx, arr1, _idx1, dst1)) in loads.iter().enumerate() {
for (li2, &(_load2_idx, arr2, _idx2, dst2)) in loads.iter().enumerate() {
if li1 == li2 {
continue;
}
for &(_store_idx, store_arr, _store_idx_reg, store_src) in stores {
for instr in body {
let op_kind = match instr.opcode {
OpCode::ICmpEq => Some(CmpKind::ICmpEq),
OpCode::ICmpLt => Some(CmpKind::ICmpLt),
OpCode::ICmpGt => Some(CmpKind::ICmpGt),
OpCode::ICmpLe => Some(CmpKind::ICmpLe),
OpCode::ICmpGe => Some(CmpKind::ICmpGe),
OpCode::FCmpEq => Some(CmpKind::FCmpEq),
OpCode::FCmpLt => Some(CmpKind::FCmpLt),
OpCode::FCmpGt => Some(CmpKind::FCmpGt),
_ => None,
};
if let Some(op) = op_kind {
let uses_operands = (instr.op1 == dst1 && instr.op2 == dst2)
|| (instr.op1 == dst2 && instr.op2 == dst1);
let produces_store_src = instr.op3 == store_src;
if uses_operands && produces_store_src {
return Some(VectorizablePattern::ElementWiseCmp {
op,
lhs_arr_reg: arr1,
rhs_arr_reg: arr2,
dst_arr_reg: store_arr,
lhs_elem_reg: dst1,
rhs_elem_reg: dst2,
result_reg: store_src,
});
}
}
}
}
}
}
None
}
// ---------------------------------------------------------------------------
// Loop-Carried Dependency Check
// ---------------------------------------------------------------------------
/// Check for loop-carried dependencies in a binary pattern.
///
/// Returns `true` if the pattern has a loop-carried dependency that would
/// prevent safe SIMD vectorization.
///
/// We conservatively reject in-place operations (where the destination array
/// is also a source array) because, even though element-wise in-place ops
/// with the same induction variable are technically safe, they may indicate
/// an accumulator or reduction pattern that is not vectorizable as a simple
/// SIMD lane operation.
fn has_loop_carried_dependency(
pattern: &VectorizablePattern,
_stores: &[(usize, u8, u8, u8)],
_idx_reg: u8,
) -> bool {
match pattern {
VectorizablePattern::ElementWiseBinop {
lhs_arr_reg,
rhs_arr_reg,
dst_arr_reg,
..
} => {
// Reject in-place element-wise operations conservatively.
// E.g. a[i] = a[i] + b[i] — while safe for SIMD, this may
// also catch accumulator-style patterns that are not vectorizable.
dst_arr_reg == lhs_arr_reg || dst_arr_reg == rhs_arr_reg
}
_ => false,
}
}
fn has_loop_carried_dependency_unary(
pattern: &VectorizablePattern,
_stores: &[(usize, u8, u8, u8)],
_idx_reg: u8,
) -> bool {
match pattern {
VectorizablePattern::ElementWiseUnary {
src_arr_reg,
dst_arr_reg,
..
} => {
// Conservatively reject in-place unary operations.
src_arr_reg == dst_arr_reg
}
_ => false,
}
}
fn has_loop_carried_dependency_cmp(
pattern: &VectorizablePattern,
_stores: &[(usize, u8, u8, u8)],
_idx_reg: u8,
) -> bool {
match pattern {
VectorizablePattern::ElementWiseCmp {
lhs_arr_reg,
rhs_arr_reg,
dst_arr_reg,
..
} => {
// Conservatively reject in-place comparison operations.
dst_arr_reg == lhs_arr_reg || dst_arr_reg == rhs_arr_reg
}
_ => false,
}
}
// ---------------------------------------------------------------------------
// Element Type Inference
// ---------------------------------------------------------------------------
/// Infer the element type from a binary pattern, using type metadata if available.
fn infer_elem_type(
pattern: &VectorizablePattern,
type_metadata: Option<&TypeMetadata>,
) -> SimdElemType {
match pattern {
VectorizablePattern::ElementWiseBinop { op, result_reg, .. } => {
// Use the operation kind to determine type category.
if op.is_float() {
// Check metadata for more precise type.
if let Some(meta) = type_metadata {
let ty = meta.get_type(*result_reg as usize);
if ty == KnownType::Float {
// Could be Float64 or Float32 — default to Float64 for now.
return SimdElemType::Float64;
}
}
SimdElemType::Float64
} else {
if let Some(meta) = type_metadata {
let ty = meta.get_type(*result_reg as usize);
if ty == KnownType::Int {
// Default to Int64 for integer operations.
return SimdElemType::Int64;
}
}
SimdElemType::Int64
}
}
_ => SimdElemType::Int64, // fallback
}
}
fn infer_elem_type_unary(
pattern: &VectorizablePattern,
type_metadata: Option<&TypeMetadata>,
) -> SimdElemType {
match pattern {
VectorizablePattern::ElementWiseUnary { op, result_reg, .. } => match op {
UnaryKind::FNeg => {
if let Some(meta) = type_metadata {
let ty = meta.get_type(*result_reg as usize);
if ty == KnownType::Float {
return SimdElemType::Float64;
}
}
SimdElemType::Float64
}
UnaryKind::INeg => {
if let Some(meta) = type_metadata {
let ty = meta.get_type(*result_reg as usize);
if ty == KnownType::Int {
return SimdElemType::Int64;
}
}
SimdElemType::Int64
}
},
_ => SimdElemType::Int64,
}
}
fn infer_elem_type_cmp(
pattern: &VectorizablePattern,
type_metadata: Option<&TypeMetadata>,
) -> SimdElemType {
match pattern {
VectorizablePattern::ElementWiseCmp {
op, lhs_elem_reg, ..
} => {
if op.is_float() {
if let Some(meta) = type_metadata {
let ty = meta.get_type(*lhs_elem_reg as usize);
if ty == KnownType::Float {
return SimdElemType::Float64;
}
}