Authos: Oscar Smith (@oscardssmith)
Summary
LLVM shufflevector can express a permutation of vector elements only when the permutation is constant. Every major target, however, has a data-driven permute that takes its index vector from a register.
- AArch64
TBL,TBX - x86
PSHUFB/VPERMD/VPERMV/VPERMV3, - RISC-V
vrgather/vrgatherei16 - PowerPC
vperm,xxperm
Today front ends and passes that want one must either emit target intrinsics directly or lower to a serialized store/gather, losing the permute on the targets that have it.
This RFC proposes a single target-independent way to express “shuffle two
vectors by a run-time index vector,” with poison-on-out-of-range semantics, a
polymorphic index element type, optional length change, and scalable-vector
support.
This RFC is deliberately agnostic about the surface syntax. Two implementations have been prototyped:
- New intrinsic
llvm.dynamicshufflePR #208537 - Generalize
shufflevectorto accept a non-constant mask PR #208872
These PRs differ only in how the operation is spelled in IR level, but otherwise have similar backend code (SelcectionDag and backend lowering). Feedback so far has pointed in both directions, so the two options are presented side by side and the trade-offs laid out explicitly. The decision this RFC seeks is which surface to standardize on which approach is favored.
Motivation
- Portable data-driven permutes. Table lookups, dynamic gathers within a register, byte-shuffle-based algorithms (base64, UTF-8 validation, sorting networks with data-dependent routing), and the interpreter/JIT patterns that today hand-roll target intrinsics.
- A lowering target for higher-level IR. Julia, Rust, WASM, want to have this as a target for users ( https://discourse.llvm.org/t/should-there-be-an-architecture-agnostic-variable-vector-shuffle-operation/88936/23?u=oscardssmith ). MLIR
vector, and autovectorization can emit one canonical operation instead of target-specific intrinsics, and get a single instruction on targets that have one (and a correct stack expansion for the other cases) - Cost visibility. A first-class operation gives the cost model something to reason about, instead of a store/reload sequence the vectorizer cannot see through.
Background: prior discussion
This picks up the Discourse thread Should there be an architecture-agnostic variable vector shuffle operation? (valadaptive, Nov 2025). That thread proposed llvm.vector.shuffle.XXX(lhs, rhs, <N_OUT x i64> idx, passthrough) with passthrough-on-OOB, and left several questions open:
- Index element type — lukel wanted flexibility to feed
vrgatherei16(i16 indices) and i64 indices directly, rather than forcing one width. - Scalable support — mshockwave doubted it was possible.
- Out-of-range behavior — GCC’s
VEC_PERM_EXPRuses modulo; the thread leaned toward passthrough. - Motivation and emulation cost (lukel, topperc) — is it worth a core op if most targets emulate it?
No patches were posted there. This RFC answers those questions concretely with a
working implementation and proposes to resolve the naming/surface syntax.
The operation
Independent of spelling, the operation is:
Given two input vectors
V1,V2of the same type<N x ty>(or
<vscale x N x ty>), and an integer index vectorMaskof lengthM, produce
<M x ty>where result laneiis elementMask[i]of the concatenation
V1 ++ V2(indices0..N-1selectV1,N..2N-1selectV2), and any lane
whose zero-extended index is>= 2Norpoisonispoison.
Key properties, and the rationale for each:
Poison on out-of-range
poison (not zero, not passthrough, not modulo) is the semantics that all three hardware permutes implement with no fixup code:
| Target / ext | Instruction | Native OOB behavior |
|---|---|---|
| x86 SSSE3 | PSHUFB |
index bit 7 set → 0, else index mod 16 within lane |
| x86 AVX | VPERMILPS/VPERMILPD (var) |
index mod (elts per 128-bit lane) |
| x86 AVX2 | VPERMD/VPERMPS |
index mod 8 |
| x86 AVX-512 | VPERMV (VPERMB/W/D/Q/PS/PD) |
index mod N |
| x86 AVX-512 | VPERMV3 / VPERMT2*/VPERMI2* |
index mod 2N |
| x86 XOP | VPPERM |
selectable per-byte zero/fill controls |
| AArch64 NEON/SVE/SVE2 | TBL |
0 |
| AArch64 NEON/SVE2 | TBX |
passthrough |
| RISC-V V | vrgather.vv |
0 |
| RISC-V V | vrgatherei16.vv |
0 |
| PowerPC AltiVec | vperm |
index mod 32 (low 5 bits) |
| PowerPC VSX (P9) | xxperm/xxpermr |
index mod 32 (low 5 bits) |
Because the result on an OOB lane is poison, any of these hardware behaviors is a valid refinement, so no target has to emit extra instructions to fix the mask. It also keeps the operation speculatable. Passthrough (the discourse thread’s leaning) would force a blend against the passthrough vector on every target. A passthrough result is still expressible as select(inbounds_mask, shuffle, passthrough) at the IR level when wanted, and targets that have that as native behavior can fuse the instructions if desired.
Polymorphic index element type
The index element type is any integer width, answering lukel’s request. Targets
consume the native width directly: i8 for TBL, i16 for vrgatherei16,
i32/i64 for VPERMV. Narrower-than-native indices are zero-extended (indices
are unsigned); the promotion is a plain zext.
Length change
M (the mask/result length) may differ from N (the input length), exactly as constant shufflevector already allows — the shuffle can widen or narrow. Result splitting splits only the mask, since each index spans the whole concatenated input.
Scalable vectors
Supported, contradicting the thread’s pessimism: RISC-V lowers scalable vrgather directly, and this is the first working scalable variable-shuffle lowering. For scalable types N is the run-time element count. The one restriction is that a scalable run-time mask must preserve the element count (codegen cannot expand a length-changing scalable shuffle); length change remains
available for fixed vectors and for scalable constant masks.
Two surfaces
Approach A — new intrinsic llvm.dynamicshuffle
<M x ty> @llvm.dynamicshuffle(<N x ty> %v1, <N x ty> %v2, <M x iK> %mask)
- Additive:
shufflevector, its verifier, and the ~dozens of passes that callgetShuffleMask()are untouched. - Constant masks are canonicalized to
shufflevectorin InstCombine (OOB → poison) and toISD::VECTOR_SHUFFLEin DAGCombine, so the intrinsic only ever carries genuinely dynamic masks. - Cost: a new intrinsic that every mask-aware analysis must learn about to see through, and a second first-class “shuffle” concept in the IR.
Approach B — generalize shufflevector
Make the mask operand 2 of ShuffleVectorInst, allowed to be any integer vector value (constant or run-time). Canonical constant masks stay byte-identical to today (<M x i32>, in-bounds or poison), with the int-mask form kept as a lazily validated cache so getShuffleMask() stays cheap. getShuffleMask() / getMaskValue() and friends now require isConstantMask().
- One concept: everything that already reasons about shuffles has the run-time case in scope automatically.
- Blast radius: every
getShuffleMask()/getMaskValue()call site must be audited to bail viaisConstantMask()or be shown unreachable for run-time masks. This audit is done on the branch (PatternMatch, ValueTracking, VectorUtils, InstructionSimplify, ConstantFolding, InstCombine, SLPVectorizer, VectorCombine, GVN/GVNSink, Scalarizer, InterleavedAccess, MSan/NSan, SandboxIR, the interpreter, and the AArch64/X86/AMDGPU TTI helpers). - Cost: OOB constant indices become
poisonrather than invalid IR, because constant propagation can RAUW a dynamic mask into an arbitrary constant and RAUW cannot re-verify.
Shared features between both PRs
Both lower dynamic masks to a new ISD::VECTOR_SHUFFLE_VAR SelectionDAG node
(V1, V2, Mask) and reuse identical backend code. The branch B commits are literally ported from the branch A prototype commit-for-commit (AArch64/X86/RISC-V lowering, the stack expansion, the cost hook). So choosing a surface does not re-litigate any of the codegen work.
SelectionDAG
ISD::VECTOR_SHUFFLE_VAR with three value operands. Default lowering (TargetLowering::expandVECTOR_SHUFFLE_VAR) spills both sources to stack temporary and loads each result element through a clamped variable index (clamped to handle OOB indeces). Type legalization: the mask is zero-extend promoted; result splitting splits the mask only; input splitting/widening falls back to the stack expansion (changing the input element count would renumber V2’s half of the index space).
Backend lowering
- AArch64 little endian (
TBL) element indices are converted to byte indices in-register (multiply by element byte width replicated into each byte, add an ascending byte ramp, onemla), thentbl1/tbl2. Av16i8two-source shuffle is a singletbl2. - x86 three tiers: AVX-512
vpermt2*/vperm*(VPERMV3’s index-mod-2N is exactly our semantics); AVX2vpermd/vpermpsper source plus a compare/blend; SSSE3 twopshufbs on byte indices with a saturating+0x70bias so bit-7 zeroing deselects the wrong source. - RISC-V (
vrgather/vrgatherei16) — gather from V1, masked gather from V2 (indices biased by-N) merged onindex < N. Indices use data SEW, or i16 viavrgatherei16when an SEW=8 vector can exceed 256 elements (or SEW > XLEN on RV32); an i16 mask feedsvrgatherei16with no conversion. Handles fixed and scalable.
Cost model
An overridable getVariableShuffleCost TTI hook. The generic default keeps the conservative stack-expansion estimate (2 + 4 per result lane; Invalid for scalable). BasicTTIImplBase refines it: when the target lowersVECTOR_SHUFFLE_VAR natively (Legal/Custom) for the legalized result type, model it as ~2 instructions per legal part — giving realistic AArch64/x86/RISC-V costs with no per-target code, addressing topperc’s emulation-cost concern from the thread.
Alternatives considered
- Passthrough- or zero-on-OOB (the thread’s leaning): rejected because it forces fixup code on x86. Modulo (GCC
VEC_PERM_EXPR): rejected because AArch64/RISC-V would need a fixup. - A masked/predicated form (VP-style
evl/mask operands): out of scope here. Can be layered later as a separate op if demanded. - Do nothing / keep using target intrinsics: leaves every front end and MLIR lowering to special-case targets and forfeits cost modeling.
Open questions
- Surface: intrinsic (A) vs generalized
shufflevector(B)? The core question. B is more “LLVM-native” and gives every shuffle-aware pass the dynamic case for free, but forces the constant-OOB-becomes-poison relaxation and a wide (completed) audit. A is strictly additive but adds a parallel shuffle concept and needs canonicalization to keep constant masks on the existing path. Naming under B may also bikeshed (the thread floatedllvm.vector.shuffle). - Name/mask-type conventions if A is chosen (mask width polymorphism, operand order).
- Should the generic default cost ever return a finite scalable cost, or stay
Invaliduntil a target opts in? - GlobalISel: both currently fall back to SelectionDAG for run-time masks — is a native GISel path required before this lands?
Status of the prototypes
Both branches build and pass targeted tests. The following issues are not yet done
- Missing scalarize type-legalization handler (
v1-legalized results, e.g.<4 x half>on RISC-V without zvfh) → crash. - AArch64 big-endian
TBLlowering miscompiles (byte-offset construction assumes little-endian); minimal fix bails to generic expansion onaarch64_be. - Scalable types on targets/paths without lowering hit
report_fatal_errorinstead of a clean diagnostic; the RISC-V M≠N case is not yet handled. - Minor: over-claimed alignment on the second stack store; x86 single-source could delegate to
createVariablePermutefor wider subtarget coverage; dead Custom registrations for 256-bit BWI/VBMI-without-VLX; the duplicated byte-index math.
None of these are surface-dependent — they live in the shared SelectionDAG / backend code that both approaches use.
Proposed patch series (surface-independent core)
- IR surface (A: add intrinsic + verifier + canonicalization; or B: generalize
ShuffleVectorInst+ verifier + the pass audit). ISD::VECTOR_SHUFFLE_VAR+ default stack expansion + type legalization.- AArch64
TBLlowering. - x86
PSHUFB/VPERMD/VPERMV3lowering. - RISC-V
vrgatherlowering (incl. scalable). - TTI
getVariableShuffleCost.