forked from anthropics/claudes-c-compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvectorize.rs
More file actions
3943 lines (3610 loc) · 148 KB
/
vectorize.rs
File metadata and controls
3943 lines (3610 loc) · 148 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
//! AVX2/SSE2 vectorization pass for matmul-style loops.
//!
//! Recognizes innermost loops with stride-1 double-precision accumulation patterns
//! and transforms them into FmaF64x4 (AVX2, default) or FmaF64x2 (SSE2) intrinsics.
//!
//! Target pattern (matmul j-loop):
//! ```c
//! for (int j = 0; j < N; j++)
//! C[i][j] += A[i][k] * B[k][j];
//! ```
//!
//! ## AVX2 Transformation (default, 4-wide):
//! ```c
//! for (int j = 0; j < N/4; j++) // Loop N/4 times
//! FmaF64x4(&C[i][j*4], &A[i][k], &B[k][j*4]); // Process 4 elements per iteration
//! ```
//!
//! ## SSE2 Transformation (with LCCC_FORCE_SSE2=1, 2-wide):
//! ```c
//! for (int j = 0; j < N/2; j++) // Loop N/2 times
//! FmaF64x2(&C[i][j*2], &A[i][k], &B[k][j*2]); // Process 2 elements per iteration
//! ```
//!
//! ## Transformation Details
//!
//! ### AVX2 (4-wide, default):
//! 1. **Loop Bound**: Modified from `j < N` to `j < N/4`
//! - For constant N: divide by 4 at compile time
//! - For dynamic N: insert `udiv` instruction to compute N/4
//! - Modifies ALL comparisons involving IV-derived values in the loop
//!
//! 2. **Array Indexing**: Changed from `j` to `j*4`
//! - Inserts multiply instructions before GEPs: `offset' = offset * 4`
//! - Ensures iteration j accesses elements [j*4..j*7] instead of [j, j+1]
//! - Backend generates stride-32 addressing (4 doubles × 8 bytes)
//!
//! 3. **Induction Variable**: Keeps incrementing by 1
//! - Backend-friendly: `j++` instead of `j += 4`
//! - Combined with 4× offset, produces correct element access
//!
//! 4. **AVX2 Code Generation**:
//! - `vbroadcastsd`: broadcast A[i][k] scalar to 4 lanes
//! - `vmovupd`: load 4 doubles from B[k][j*4]
//! - `vmulpd`: packed multiply (4 doubles)
//! - `vaddpd`: packed add with C[i][j*4]
//! - `vmovupd`: store 4 results back
//!
//! ### SSE2 (2-wide, with LCCC_FORCE_SSE2=1):
//! 1. **Loop Bound**: Modified from `j < N` to `j < N/2`
//! 2. **Array Indexing**: Changed from `j` to `j*2` (stride-16)
//! 3. **SSE2 Code Generation**:
//! - `movsd` + `unpcklpd`: broadcast A[i][k] scalar
//! - `movupd`: load 2 doubles from B[k][j*2]
//! - `mulpd`: packed multiply (2 doubles)
//! - `addpd`: packed add with C[i][j*2]
//! - `movupd`: store 2 results back
//!
//! ## Remainder Loops
//!
//! Remainder loops are automatically inserted to handle cases where N is not divisible by the vector width:
//! - AVX2 (4-wide): Handles N % 4 ∈ {1, 2, 3} with scalar remainder loop
//! - SSE2 (2-wide): Handles N % 2 = 1 with scalar remainder loop
//!
//! Example for N=255 with AVX2:
//! - Vectorized loop: 63 iterations processing indices [0..251] (4 elements each)
//! - Remainder loop: 3 iterations processing indices [252, 253, 254] (scalar)
//!
//! ## Limitations
//!
//! - Only handles matmul-style patterns (load, multiply, add, store)
//! - Requires innermost loop with IV-based indexing
//!
//! ## Environment Variables
//!
//! - `LCCC_FORCE_SSE2=1`: Force SSE2 2-wide vectorization instead of AVX2 4-wide
//! - `LCCC_FORCE_AVX2=1`: Explicitly enable AVX2 (default behavior, provided for clarity)
//! - `LCCC_DEBUG_VECTORIZE=1`: Enable debug output for vectorization pass
use crate::common::fx_hash::{FxHashMap, FxHashSet};
use crate::common::types::{AddressSpace, IrType};
use crate::ir::analysis::CfgAnalysis;
use crate::ir::instruction::{BasicBlock, BlockId, Instruction, Operand, Terminator, Value};
use crate::ir::intrinsics::IntrinsicOp;
use crate::ir::ops::{IrBinOp, IrCmpOp};
use crate::ir::reexports::{IrConst, IrFunction};
use crate::passes::loop_analysis;
/// Run SSE2 vectorization on a function with precomputed CFG analysis.
pub(crate) fn vectorize_with_analysis(func: &mut IrFunction, cfg: &CfgAnalysis) -> usize {
let num_blocks = func.blocks.len();
let loops = loop_analysis::find_natural_loops(
num_blocks,
&cfg.preds,
&cfg.succs,
&cfg.idom,
);
let debug = std::env::var("LCCC_DEBUG_VECTORIZE").is_ok();
if debug {
eprintln!("[VEC] Function: {}, blocks: {}, loops: {}", func.name, num_blocks, loops.len());
}
if loops.is_empty() {
return 0;
}
let mut total_changes = 0;
// Process innermost loops (loops that don't contain other loops).
for (idx, loop_info) in loops.iter().enumerate() {
// Check if this is an innermost loop (no other loop nests strictly inside it).
let is_innermost = !loops.iter().enumerate().any(|(other_idx, other)| {
idx != other_idx
&& other.body.len() < loop_info.body.len()
&& other.body.iter().all(|b| loop_info.body.contains(b))
});
if debug {
eprintln!("[VEC] Loop {} at header={}, body_size={}, innermost={}",
idx, loop_info.header, loop_info.body.len(), is_innermost);
}
if !is_innermost {
continue;
}
// Try to vectorize this loop - first try matmul, then try reduction patterns.
if let Some(pattern) = analyze_loop_pattern(func, loop_info, cfg) {
// Select vector width: default to AVX2 (4-wide) unless explicitly disabled
let use_sse2 = std::env::var("LCCC_FORCE_SSE2").is_ok();
let vec_width: i64 = if use_sse2 { 2 } else { 4 };
// Check: if the loop limit is a known constant smaller than the vector width,
// skip vectorization — the vectorized loop would never execute, and the
// remainder loop may not correctly handle the full trip count.
let skip_small = match &pattern.limit {
Operand::Const(c) => c.to_i64().map_or(false, |n| n <= vec_width),
_ => false,
};
if skip_small {
if debug { eprintln!("[VEC] Skip: loop limit < vector width ({})", vec_width); }
} else
if use_sse2 {
if debug {
eprintln!("[VEC] Matmul pattern matched! Transforming to FmaF64x2 (SSE2, 2-wide)");
}
total_changes += transform_to_fma_f64x2(func, &pattern);
} else {
// Use AVX2 by default (or if LCCC_FORCE_AVX2 is set)
if debug {
eprintln!("[VEC] Matmul pattern matched! Transforming to FmaF64x4 (AVX2, 4-wide)");
}
total_changes += transform_to_fma_f64x4(func, &pattern);
}
} else if let Some(red_pattern) = analyze_reduction_pattern(func, loop_info, cfg) {
// Try reduction pattern vectorization (sum += arr[i], sum += a[i] * b[i], etc.)
let use_sse2 = std::env::var("LCCC_FORCE_SSE2").is_ok();
if use_sse2 {
if debug {
eprintln!("[VEC] Reduction pattern matched! Transforming to SSE2 2-wide");
}
total_changes += transform_reduction_sse2(func, &red_pattern);
} else {
if debug {
eprintln!("[VEC] Reduction pattern matched! Transforming to AVX2 4-wide");
}
total_changes += transform_reduction_avx2(func, &red_pattern);
}
} else if debug {
eprintln!("[VEC] No vectorizable pattern found for loop {}", idx);
}
}
total_changes
}
/// Pattern matching result for a vectorizable loop.
#[derive(Debug)]
struct VectorizablePattern {
/// Loop header block index
header_idx: usize,
/// Loop body block (where the accumulation happens)
body_idx: usize,
/// Loop latch block index (contains the increment and backedge)
latch_idx: usize,
/// Exit block index
exit_idx: usize,
/// Induction variable (loop counter)
iv: Value,
/// Induction variable increment instruction index in latch block
iv_inc_idx: usize,
/// GEP for C array (result pointer)
c_gep: Value,
/// GEP for B array (source vector pointer)
b_gep: Value,
/// A scalar pointer (broadcasted value, loop-invariant)
a_ptr: Value,
/// Store instruction index in body (will be replaced)
store_idx: usize,
/// Loop limit value (N in `j < N`)
limit: Operand,
/// Comparison instruction index that tests loop exit condition
exit_cmp_inst_idx: usize,
/// Comparison destination value
exit_cmp_dest: Value,
/// All block indices in the loop body
loop_blocks: FxHashSet<usize>,
}
/// Reduction pattern types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ReductionKind {
/// Simple sum: sum += arr[i]
Sum,
/// Dot product: sum += a[i] * b[i]
DotProduct,
}
/// Pattern matching result for a vectorizable reduction loop.
#[derive(Debug)]
struct ReductionPattern {
/// Type of reduction
kind: ReductionKind,
/// Element type being reduced (F64, F32, I32, I64)
element_type: IrType,
/// Loop header block index
header_idx: usize,
/// Loop body block (where the accumulation happens)
body_idx: usize,
/// Loop latch block index (contains the increment and backedge)
latch_idx: usize,
/// Exit block index
exit_idx: usize,
/// Induction variable (loop counter)
iv: Value,
/// Induction variable increment instruction index in latch block
iv_inc_idx: usize,
/// Scalar accumulator phi node destination value in header
accumulator_phi: Value,
/// GEP for first array (arr for sum, a for dot product)
array_a_gep: Value,
/// GEP for second array (only for dot product)
array_b_gep: Option<Value>,
/// Index of the add instruction that updates the accumulator
accumulator_add_idx: usize,
/// Loop limit value (N in `i < N`)
limit: Operand,
/// Comparison instruction index that tests loop exit condition
exit_cmp_inst_idx: usize,
/// Comparison destination value
exit_cmp_dest: Value,
/// All block indices in the loop body
loop_blocks: FxHashSet<usize>,
}
/// Analyze a loop to detect the vectorizable matmul pattern.
fn analyze_loop_pattern(
func: &IrFunction,
loop_info: &loop_analysis::NaturalLoop,
_cfg: &CfgAnalysis,
) -> Option<VectorizablePattern> {
let debug = std::env::var("LCCC_DEBUG_VECTORIZE").is_ok();
// Build label→index map so we can convert BlockId labels to array indices.
let label_to_idx: FxHashMap<BlockId, usize> = func.blocks.iter()
.enumerate()
.map(|(i, b)| (b.label, i))
.collect();
let header_idx = loop_info.header;
let header = &func.blocks[header_idx];
// Find the induction variable phi in header.
let mut iv = None;
for inst in &header.instructions {
if let Instruction::Phi { dest, incoming, .. } = inst {
if incoming.len() == 2 {
iv = Some(dest);
break;
}
}
}
if iv.is_none() && debug {
eprintln!("[VEC] No IV phi found in header");
return None;
}
let iv = *iv?;
// Build a map of values that are derived from the IV (casts, copies, etc.)
let mut iv_derived = FxHashSet::default();
iv_derived.insert(iv);
for inst in &header.instructions {
match inst {
Instruction::Cast { dest, src, .. } | Instruction::Copy { dest, src } => {
if let Operand::Value(src_val) = src {
if iv_derived.contains(src_val) {
iv_derived.insert(*dest);
}
}
}
_ => {}
}
}
// Find the comparison instruction for loop exit in header
let mut exit_cmp_info = None;
for (idx, inst) in header.instructions.iter().enumerate() {
if let Instruction::Cmp { dest, op: _, lhs, rhs, ty: _ } = inst {
// Check if comparing IV (or derived value) to a limit
if let Operand::Value(lhs_val) = lhs {
if iv_derived.contains(lhs_val) {
exit_cmp_info = Some((idx, *dest, rhs.clone()));
if debug {
eprintln!("[VEC] Found comparison with IV-derived on left: {:?} < {:?}", lhs, rhs);
}
break;
}
} else if let Operand::Value(rhs_val) = rhs {
if iv_derived.contains(rhs_val) {
// IV is on the right, use lhs as the limit
exit_cmp_info = Some((idx, *dest, lhs.clone()));
if debug {
eprintln!("[VEC] Found comparison with IV-derived on right: {:?} > {:?}", lhs, rhs);
}
break;
}
}
}
}
if exit_cmp_info.is_none() {
if debug {
eprintln!("[VEC] No comparison instruction found for IV");
eprintln!("[VEC] Header block has {} instructions:", header.instructions.len());
for (idx, inst) in header.instructions.iter().enumerate() {
eprintln!("[VEC] {}: {:?}", idx, inst);
}
}
return None;
}
let (exit_cmp_inst_idx, exit_cmp_dest, limit) = exit_cmp_info?;
// Search all blocks in the loop to find the one with the store instruction.
// This is the actual computation block we want to vectorize.
let mut body_idx = None;
for &block_idx in &loop_info.body {
if block_idx == header_idx {
continue;
}
let block = &func.blocks[block_idx];
for inst in &block.instructions {
if matches!(inst, Instruction::Store { .. }) {
body_idx = Some(block_idx);
break;
}
}
if body_idx.is_some() {
break;
}
}
if body_idx.is_none() {
if debug {
eprintln!("[VEC] No store instruction found in any loop body block");
}
return None;
}
let body_idx = body_idx?;
// Find exit by looking at loop successors that are outside the loop.
// Use label_to_idx to convert BlockId labels to block array indices for body.contains().
let mut exit_label = None;
for &block_idx in &loop_info.body {
let block = &func.blocks[block_idx];
match &block.terminator {
Terminator::CondBranch { true_label, false_label, .. } => {
let then_idx = label_to_idx.get(true_label).copied();
let else_idx = label_to_idx.get(false_label).copied();
let then_in_loop = then_idx.map_or(false, |i| loop_info.body.contains(&i));
let else_in_loop = else_idx.map_or(false, |i| loop_info.body.contains(&i));
if !then_in_loop {
exit_label = Some(*true_label);
break;
} else if !else_in_loop {
exit_label = Some(*false_label);
break;
}
}
Terminator::Branch(target) => {
let target_idx = label_to_idx.get(target).copied();
if !target_idx.map_or(false, |i| loop_info.body.contains(&i)) {
exit_label = Some(*target);
break;
}
}
_ => {}
}
}
if exit_label.is_none() {
if debug {
eprintln!("[VEC] No exit block found");
}
return None;
}
let exit_label = exit_label?;
let exit_idx = *label_to_idx.get(&exit_label)?;
// Find the latch block (backedges to header).
let latch_idx = find_latch(func, loop_info);
if latch_idx.is_none() {
if debug {
eprintln!("[VEC] No latch block found");
}
return None;
}
let latch_idx = latch_idx?;
let latch = &func.blocks[latch_idx];
// Find IV increment in latch: %next = add %iv, 1
let mut iv_inc_idx = None;
for (idx, inst) in latch.instructions.iter().enumerate() {
if let Instruction::BinOp {
op: IrBinOp::Add,
lhs,
rhs,
..
} = inst
{
if let Operand::Value(lhs_val) = lhs {
if *lhs_val == iv {
if let Operand::Const(c) = rhs {
if c.to_i64() == Some(1) {
iv_inc_idx = Some(idx);
break;
}
}
}
}
}
}
if iv_inc_idx.is_none() {
if debug {
eprintln!("[VEC] No IV increment by 1 found in latch");
}
return None;
}
let iv_inc_idx = iv_inc_idx?;
// Analyze the body block for accumulation pattern.
let body = &func.blocks[body_idx];
// Find the store instruction.
let mut store_info = None;
for (idx, inst) in body.instructions.iter().enumerate() {
if let Instruction::Store { ptr, val, .. } = inst {
if let Operand::Value(store_val) = val {
store_info = Some((idx, *ptr, *store_val));
break;
}
}
}
if store_info.is_none() {
if debug {
eprintln!("[VEC] No store instruction found in body block {}", body_idx);
}
return None;
}
let (store_idx, store_addr, store_value) = store_info?;
if debug {
eprintln!("[VEC] Found store in block {}, tracing backward...", body_idx);
}
// Trace backwards: store_value should be result of fadd.
let fadd_inst = find_inst_by_dest(body, store_value);
if fadd_inst.is_none() {
if debug {
eprintln!("[VEC] Store value not produced in body block");
}
return None;
}
let fadd_inst = fadd_inst?;
let (c_load_val, mul_val) = match fadd_inst {
Instruction::BinOp {
op: IrBinOp::Add,
lhs,
rhs,
..
} => Some((lhs, rhs)),
_ => {
if debug {
eprintln!("[VEC] Store value not from Add instruction");
}
None
}
}?;
// Find the multiply.
let mul_dest = match mul_val {
Operand::Value(v) => v,
_ => {
if debug {
eprintln!("[VEC] Multiply operand is not a Value");
}
return None;
}
};
let fmul_inst = find_inst_by_dest(body, *mul_dest);
if fmul_inst.is_none() {
if debug {
eprintln!("[VEC] Multiply value not produced in body block");
}
return None;
}
let fmul_inst = fmul_inst?;
let (a_val, b_val) = match fmul_inst {
Instruction::BinOp {
op: IrBinOp::Mul,
lhs,
rhs,
..
} => Some((lhs, rhs)),
_ => {
if debug {
eprintln!("[VEC] Add operand not from Mul instruction");
}
None
}
}?;
// Verify C load.
let c_load_dest = match c_load_val {
Operand::Value(v) => v,
_ => {
if debug {
eprintln!("[VEC] C load operand is not a Value");
}
return None;
}
};
let c_load_inst = find_inst_by_dest(body, *c_load_dest);
if c_load_inst.is_none() {
if debug {
eprintln!("[VEC] C load value not produced in body block");
}
return None;
}
let c_load_inst = c_load_inst?;
let c_load_addr = match c_load_inst {
Instruction::Load { ptr, .. } => *ptr,
_ => {
if debug {
eprintln!("[VEC] C load not from Load instruction");
}
return None;
}
};
// Store and load must use the same GEP.
if c_load_addr != store_addr {
if debug {
eprintln!("[VEC] C load and store use different addresses");
}
return None;
}
// Extract GEPs for C and B.
let c_gep = store_addr;
// Verify C GEP exists somewhere in the loop (may have been hoisted by LICM)
if find_inst_in_loop(func, &loop_info.body, c_gep).is_none() {
if debug {
eprintln!("[VEC] C GEP not found in loop");
}
return None;
}
// Find B load and GEP.
let b_load_dest = match b_val {
Operand::Value(v) => v,
_ => {
if debug {
eprintln!("[VEC] B value operand is not a Value");
}
return None;
}
};
// Search for B load in the entire loop (may have been moved by optimizations)
let b_load_result = find_inst_in_loop(func, &loop_info.body, *b_load_dest);
if b_load_result.is_none() {
if debug {
eprintln!("[VEC] B load not found in loop");
}
return None;
}
let (_b_load_block, b_load_inst) = b_load_result?;
let b_load_addr = match b_load_inst {
Instruction::Load { ptr, .. } => ptr,
_ => {
if debug {
eprintln!("[VEC] B load not from Load instruction");
}
return None;
}
};
let b_gep = *b_load_addr;
// Verify B GEP exists somewhere in the loop
if find_inst_in_loop(func, &loop_info.body, b_gep).is_none() {
if debug {
eprintln!("[VEC] B GEP not found in loop");
}
return None;
}
// Find A load (should be loop-invariant, may have been hoisted by LICM).
let a_load_dest = match a_val {
Operand::Value(v) => v,
_ => {
if debug {
eprintln!("[VEC] A value operand is not a Value");
}
return None;
}
};
// Search for A load in the entire loop
let a_load_result = find_inst_in_loop(func, &loop_info.body, *a_load_dest);
if a_load_result.is_none() {
if debug {
eprintln!("[VEC] A load not found in loop");
}
return None;
}
let (_a_load_block, a_load_inst) = a_load_result?;
let a_ptr = match a_load_inst {
Instruction::Load { ptr, .. } => *ptr,
_ => {
if debug {
eprintln!("[VEC] A load not from Load instruction");
}
return None;
}
};
Some(VectorizablePattern {
header_idx,
body_idx,
latch_idx,
exit_idx,
iv,
iv_inc_idx,
c_gep,
b_gep,
a_ptr,
store_idx,
limit,
exit_cmp_inst_idx,
exit_cmp_dest,
loop_blocks: loop_info.body.clone(),
})
}
/// Analyze a loop to detect vectorizable reduction patterns (sum += arr[i], sum += a[i] * b[i]).
fn analyze_reduction_pattern(
func: &IrFunction,
loop_info: &loop_analysis::NaturalLoop,
_cfg: &CfgAnalysis,
) -> Option<ReductionPattern> {
let debug = std::env::var("LCCC_DEBUG_VECTORIZE").is_ok();
let header_idx = loop_info.header;
let header = &func.blocks[header_idx];
if debug {
eprintln!("[VEC-RED] Analyzing reduction pattern for loop at header {}", header_idx);
}
// Find exit and latch blocks first
let exit_idx = find_exit(func, loop_info);
if exit_idx.is_none() {
if debug {
eprintln!("[VEC-RED] Could not find exit block");
}
return None;
}
let exit_idx = exit_idx?;
let latch_idx = find_latch(func, loop_info);
if latch_idx.is_none() {
if debug {
eprintln!("[VEC-RED] Could not find latch block");
}
return None;
}
let latch_idx = latch_idx?;
let latch = &func.blocks[latch_idx];
// Find the induction variable by looking for increments in latch
let mut iv = None;
for inst in &latch.instructions {
if let Instruction::BinOp {
dest,
op: IrBinOp::Add,
lhs,
rhs,
..
} = inst
{
// Check if incrementing by 1
if let Operand::Const(c) = rhs {
if c.to_i64() == Some(1) {
// lhs should be the IV phi
if let Operand::Value(lhs_val) = lhs {
iv = Some(*lhs_val);
break;
}
}
}
}
}
if iv.is_none() && debug {
eprintln!("[VEC-RED] No IV increment found in latch");
return None;
}
let iv = iv?;
// Build IV-derived values using fixed-point iteration (like matmul pattern)
// This captures casts/copies of the IV across ALL loop blocks, not just the header
let mut iv_derived = FxHashSet::default();
iv_derived.insert(iv);
let mut changed = true;
while changed {
changed = false;
for &block_idx in &loop_info.body {
let block = &func.blocks[block_idx];
for inst in &block.instructions {
match inst {
Instruction::Cast { dest, src, .. } | Instruction::Copy { dest, src } => {
if let Operand::Value(src_val) = src {
if iv_derived.contains(src_val) && iv_derived.insert(*dest) {
changed = true;
}
}
}
_ => {}
}
}
}
}
if debug {
eprintln!("[VEC-RED] IV-derived values: {:?}", iv_derived);
}
// Find comparison for loop exit
let mut exit_cmp_info = None;
for (idx, inst) in header.instructions.iter().enumerate() {
if let Instruction::Cmp { dest, op: _, lhs, rhs, ty: _ } = inst {
if let Operand::Value(lhs_val) = lhs {
if iv_derived.contains(lhs_val) {
exit_cmp_info = Some((idx, *dest, rhs.clone()));
break;
}
} else if let Operand::Value(rhs_val) = rhs {
if iv_derived.contains(rhs_val) {
exit_cmp_info = Some((idx, *dest, lhs.clone()));
break;
}
}
}
}
let (exit_cmp_inst_idx, exit_cmp_dest, limit) = exit_cmp_info?;
// Find IV increment in latch: %next = add %iv, 1
let mut iv_inc_idx = None;
for (idx, inst) in latch.instructions.iter().enumerate() {
if let Instruction::BinOp {
op: IrBinOp::Add,
lhs,
rhs,
..
} = inst
{
if let Operand::Value(lhs_val) = lhs {
if *lhs_val == iv {
if let Operand::Const(c) = rhs {
if c.to_i64() == Some(1) {
iv_inc_idx = Some(idx);
break;
}
}
}
}
}
}
let iv_inc_idx = iv_inc_idx?;
// Find the accumulator phi (scalar sum variable)
let mut accumulator_phi = None;
let mut accumulator_init_is_zero = false;
for inst in &header.instructions {
if let Instruction::Phi { dest, incoming, .. } = inst {
if incoming.len() == 2 && *dest != iv {
// Check if initialized to zero (common for reductions)
for (val, _block) in incoming {
if let Operand::Const(c) = val {
if c.to_i64() == Some(0) {
accumulator_init_is_zero = true;
} else if c.to_f64().map(|f| f == 0.0).unwrap_or(false) {
accumulator_init_is_zero = true;
}
}
}
if accumulator_init_is_zero {
accumulator_phi = Some(*dest);
break;
}
}
}
}
if accumulator_phi.is_none() {
if debug {
eprintln!("[VEC-RED] No accumulator phi found (initialized to zero)");
}
return None;
}
let accumulator_phi = accumulator_phi?;
// Reject loops with multiple reduction phis (e.g., `vBv += ... ; vv += ...`).
// The vectorizer only handles one reduction; transforming the loop structure
// (splitting into vector + remainder) corrupts any additional reductions.
let other_zero_phis = header.instructions.iter().filter(|inst| {
if let Instruction::Phi { dest, incoming, .. } = inst {
if *dest != iv && *dest != accumulator_phi && incoming.len() == 2 {
return incoming.iter().any(|(val, _)| {
if let Operand::Const(c) = val {
c.to_i64() == Some(0) || c.to_f64().map(|f| f == 0.0).unwrap_or(false)
} else {
false
}
});
}
}
false
}).count();
if other_zero_phis > 0 {
if debug {
eprintln!("[VEC-RED] Rejecting: {} other zero-init phis in header (multi-reduction)", other_zero_phis);
}
return None;
}
// Build a set of accumulator-derived values (accumulator + casts of accumulator)
let mut accumulator_derived = FxHashSet::default();
accumulator_derived.insert(accumulator_phi);
// Find all casts/copies of the accumulator
let mut changed = true;
while changed {
changed = false;
for &block_idx in &loop_info.body {
let block = &func.blocks[block_idx];
for inst in &block.instructions {
match inst {
Instruction::Cast { dest, src, .. } | Instruction::Copy { dest, src } => {
if let Operand::Value(src_val) = src {
if accumulator_derived.contains(src_val) && !accumulator_derived.contains(dest) {
accumulator_derived.insert(*dest);
changed = true;
}
}
}
_ => {}
}
}
}
}
// Find the body block that updates the accumulator
let mut body_idx = None;
let mut accumulator_add_idx = None;
let mut add_result = None;
for &block_idx in &loop_info.body {
if block_idx == header_idx {
continue;
}
let block = &func.blocks[block_idx];
if debug {
eprintln!("[VEC-RED] Searching block {} for accumulator update (accumulator_phi = {})", block_idx, accumulator_phi.0);
eprintln!("[VEC-RED] Accumulator-derived values: {:?}", accumulator_derived);
for (idx, inst) in block.instructions.iter().enumerate() {
eprintln!("[VEC-RED] {}: {:?}", idx, inst);
}
}
for (idx, inst) in block.instructions.iter().enumerate() {
if let Instruction::BinOp {
dest,
op: IrBinOp::Add,
lhs,
rhs,
..
} = inst
{
// Check if this is accumulator += something (allowing casts)
let lhs_is_acc = if let Operand::Value(v) = lhs { accumulator_derived.contains(v) } else { false };
let rhs_is_acc = if let Operand::Value(v) = rhs { accumulator_derived.contains(v) } else { false };
if lhs_is_acc || rhs_is_acc {
body_idx = Some(block_idx);
accumulator_add_idx = Some(idx);
add_result = Some(*dest);
break;
}
}
}
if body_idx.is_some() {
break;
}
}
if body_idx.is_none() {
if debug {
eprintln!("[VEC-RED] No accumulator update found");
}
return None;
}
let body_idx = body_idx?;
let accumulator_add_idx = accumulator_add_idx?;
let add_result = add_result?;
let body = &func.blocks[body_idx];
let add_inst = &body.instructions[accumulator_add_idx];
// Get the element type from the add instruction
let element_type = match add_inst {
Instruction::BinOp { ty, .. } => *ty,
_ => return None,
};
// Verify element type is vectorizable (F64, F32, I32, I64)
if !matches!(element_type, IrType::F64 | IrType::F32 | IrType::I32 | IrType::I64) {
if debug {
eprintln!("[VEC-RED] Unsupported element type: {:?}", element_type);
}
return None;
}
// Determine what is being added to the accumulator
let (lhs_val, rhs_val) = match add_inst {
Instruction::BinOp { lhs, rhs, .. } => {
let lhs_v = if let Operand::Value(v) = lhs { Some(*v) } else { None };
let rhs_v = if let Operand::Value(v) = rhs { Some(*v) } else { None };
(lhs_v, rhs_v)
}
_ => (None, None),
};
// The non-accumulator operand is what we're adding (check accumulator_derived set)
let added_value = if lhs_val.is_some() && accumulator_derived.contains(&lhs_val.unwrap()) {
rhs_val?
} else if rhs_val.is_some() && accumulator_derived.contains(&rhs_val.unwrap()) {
lhs_val?
} else {
if debug {
eprintln!("[VEC-RED] Add instruction doesn't use accumulator or derived value");
}
return None;
};
// Check if added_value is a load (simple sum) or multiply (dot product)
let added_inst = find_inst_by_dest(body, added_value)?;
if debug {
eprintln!("[VEC-RED] Added value {} is produced by: {:?}", added_value.0, added_inst);
}
match added_inst {
// Simple sum pattern: sum += arr[i]
Instruction::Load { ptr, .. } => {
let array_gep = *ptr;
// Verify GEP uses IV
if !gep_uses_iv(func, &loop_info.body, array_gep, iv, &iv_derived) {
if debug {
eprintln!("[VEC-RED] Array GEP doesn't use IV");
}
return None;
}
if debug {
eprintln!("[VEC-RED] Simple sum pattern detected: {:?} += load(arr[iv])", element_type);
}
Some(ReductionPattern {
kind: ReductionKind::Sum,
element_type,
header_idx,
body_idx,
latch_idx,
exit_idx,
iv,
iv_inc_idx,
accumulator_phi,
array_a_gep: array_gep,