SIMD Operations
Array and tensor operations express work over multiple elements. LLVM and SIR then choose supported scalar, vector or device paths. Keep three questions separate: what the source expression means, what IR was produced, and which machine instructions execute on the selected target.
SIMD Model
Auto-Vectorization Threshold
The inline-SIMD eligibility rule requires a nonzero power-of-two lane count, at most 64 lanes and at most 64 bytes in total. Eligible operations can use LLVM vectors; other shapes use different lowering paths. The rule is an implementation threshold, not a language limit or an instruction-count promise. A 64-byte value spans four 128-bit registers on a target using that register width.
An expression such as addition on [f32; 8] can appear as an LLVM fadd <8 x float>. LLVM may split it, scalarize it or use a native vector instruction according to target capabilities. Loading and storing values add work beyond the arithmetic itself.
Element-Wise Arithmetic and Masks
This complete example adds four lanes and counts the lanes above a threshold:
fn main(): i32 {
let a: [i32; 4] = [1, 2, 3, 4];
let b: [i32; 4] = [4, 3, 2, 1];
let sum = a + b;
let selected = a > 2;
if sum[0] != 5 || sum[3] != 5 { return 1; }
if selected.countBits() != 2 { return 2; }
$println(sum[0]);
$println(selected.countBits());
return 0;
}Save as simd-lanes.vx and run VEX_NO_GPU=1 vex run simd-lanes.vx. Expected stdout is 5 then 2, each on its own line, with exit status 0. The test establishes values for these lanes; it does not assert a particular SIMD instruction or GPU route.
Scalar Broadcast
A supported scalar/sequence operation applies the scalar to each lane. Keep the element type explicit when its width or precision matters:
let values: [f32; 4] = [1.0, 2.0, 3.0, 4.0];
let doubled = values * 2.0f32;Broadcasting one scalar is distinct from combining sequences of different lengths. State the required shape relationship in reusable APIs instead of assuming that an arbitrary tensor library's broadcasting rules apply.
SIMD Comparison and Masks
Comparisons produce lane decisions. Combine compatible masks with &, | and !, then use any(), all() or countBits() to obtain a scalar result. mask.select(left, right) chooses by lane; it does not make invalid arguments safe by suppressing their earlier evaluation.
Mask-to-Bitmask Conversion
Packed integers are useful at a narrow boundary, but their bit width is finite. A runtime mask can contain more lanes than one integer word. Use the documented windowed operation when necessary and preserve the logical length. See Tensor and Mask Types for the distinction between static masks, packed host masks and GPU lane transport.
Saturating Arithmetic
+|, -| and *| express saturating operations for supported integer operands. For example, adding 200 and 100 in u8 saturates at 255; normal wrapping arithmetic would instead yield 44. Pick saturation because clipping is part of the data contract, such as bounded channel intensity. It can hide an error when overflow should instead reject a calculation.
Min/Max Operations
a <? b and a >? b express element-wise minimum and maximum. Integer order and floating-point exceptional-value rules are different concerns. If NaN or signed zero is possible, test the relevant dtype/backend behavior rather than assuming a mathematical total order.
Fused Multiply-Add (FMA)
A mathematical fused multiply-add computes a product and sum with one final rounding. The expression a * b + c does not alone prove that the generated program uses that numerical rule or one hardware instruction. SIR has a ternary FMA operation, while source parsing and optimization decide how an expression reaches it. In particular, the two-operand spelling a *+ b is not evidence that a following + c is fused.
When the rounding distinction matters, inspect the generated operation and compare inputs chosen to distinguish fused from separate evaluation. Measure performance on the actual target; fused operations are not universally faster for every workload or available for every dtype.
Carry-less Multiply (CLMUL)
Carry-less multiplication combines bit-polynomials using XOR rather than integer carry propagation. It is a building block in some CRC and finite-field algorithms. A product alone is not a CRC: a CRC definition also specifies the reduction polynomial, bit order, initial state and final transformation. Use a maintained checksum or cryptographic API when that complete operation is required. The crypto guide describes those higher-level boundaries.
Bit Rotation
Rotation moves bits cyclically within the operand width:
let x: u8 = 0b1000_0001;
let left = x <<< 1; // 0b0000_0011
let right = x >>> 1; // 0b1100_0000State the width explicitly in bit-level protocols. A rotation of u8 and one of u32 operate on different rings of bits even for the same numeric input.
Horizontal Reductions
Reductions combine lanes into a scalar. For example, the source spelling <+ values sums a fixed array in the inline path:
fn sum4(values: [i32; 4]): i32 {
return <+ values;
}A floating-point reduction is sensitive to accumulation order. Define empty input behavior and, for averages, reject or separately handle zero length before dividing by the count. Use a reference implementation to establish correctness before comparing CPU and GPU timing.
Matrix Operations
Matrix multiplication needs an explicit relationship between dimensions: M × K multiplied by K × N produces M × N. A flat array of four elements does not by itself establish that it represents a 2 × 2 matrix.
The compiler has shape-aware paths for supported fixed rank-two operations and SIR matrix nodes, but element type and backend support vary. Do not infer that recognizing <*>, <^> or <\> means every matrix product, power or solve can execute on every backend. A linear solve also needs a policy for singular or ill-conditioned input.
For a complete algorithm reference with rectangular dimensions and tail handling, see Graph Functions and GPU Execution. That sequential reference is useful for checking a device implementation; it is not a manually launched Vex kernel.
SIMD Math Intrinsics
The Math namespace provides math operations with supported lifted forms. Math intrinsics are IR-level operations, not cycle-count guarantees. A transcendental operation can become a library call or a sequence of instructions. Decimal approximations to π also do not yield exact zeros from trigonometric functions. Specify a tolerance when checking results.
Gather and Scatter
gather(indices) produces a sequence in the requested index order. scatter(indices, updates) returns a new result and leaves its source unchanged. Ignoring that result does not update the source tensor.
The complete indexed tensor example checks both the result and the unchanged source. Use integer indices within bounds and matching update extents. The combining operations are spelled scatter_add, scatter_mul, scatter_min and scatter_max; duplicate-index and floating-point ordering behavior need operation-specific validation. These operations do not authorize unsynchronized application-level sharing.
SIMD Backend Configuration
SIMD width and target-feature selection belong to compiler/backend configuration. An internal SimdBackend struct is not a Vex source-level configuration object. Wider vectors can increase register pressure and do not automatically improve throughput. Use the CLI options documented by the selected compiler and inspect the result for the deployment target.
Practical Workflow
- Define element type, shape, empty input and error behavior.
- Keep an independently understandable scalar reference.
- Check exact integer results and meaningful floating-point edge cases.
- Inspect IR or machine code only when a specific lowering matters.
- Measure the complete workload, including allocation and data movement.