[RFC][IR] Ability to shuffle vectors with dynamic mask

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.dynamicshuffle PR #208537
  • Generalize shufflevector to 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_EXPR uses 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, V2 of the same type <N x ty> (or
<vscale x N x ty>), and an integer index vector Mask of length M, produce
<M x ty> where result lane i is element Mask[i] of the concatenation
V1 ++ V2 (indices 0..N-1 select V1, N..2N-1 select V2), and any lane
whose zero-extended index is >= 2N or poison is poison.

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 call getShuffleMask() are untouched.
  • Constant masks are canonicalized to shufflevector in InstCombine (OOB → poison) and to ISD::VECTOR_SHUFFLE in 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 via isConstantMask() 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 poison rather 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, one mla), then tbl1/tbl2. A v16i8 two-source shuffle is a single tbl2.
  • x86 three tiers: AVX-512 vpermt2*/vperm* (VPERMV3’s index-mod-2N is exactly our semantics); AVX2 vpermd/vpermps per source plus a compare/blend; SSSE3 two pshufbs on byte indices with a saturating +0x70 bias so bit-7 zeroing deselects the wrong source.
  • RISC-V (vrgather/vrgatherei16) — gather from V1, masked gather from V2 (indices biased by -N) merged on index < N. Indices use data SEW, or i16 via vrgatherei16 when an SEW=8 vector can exceed 256 elements (or SEW > XLEN on RV32); an i16 mask feeds vrgatherei16 with 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

  1. 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 floated llvm.vector.shuffle).
  2. Name/mask-type conventions if A is chosen (mask width polymorphism, operand order).
  3. Should the generic default cost ever return a finite scalable cost, or stay Invalid until a target opts in?
  4. 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 TBL lowering miscompiles (byte-offset construction assumes little-endian); minimal fix bails to generic expansion on aarch64_be.
  • Scalable types on targets/paths without lowering hit report_fatal_error instead 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 createVariablePermute for 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)

  1. IR surface (A: add intrinsic + verifier + canonicalization; or B: generalize ShuffleVectorInst + verifier + the pass audit).
  2. ISD::VECTOR_SHUFFLE_VAR + default stack expansion + type legalization.
  3. AArch64 TBL lowering.
  4. x86 PSHUFB/VPERMD/VPERMV3 lowering.
  5. RISC-V vrgather lowering (incl. scalable).
  6. TTI getVariableShuffleCost.
4 Likes

Thanks for the write up, I’m aware LLMs were used for the PRs, so I just want to check was an LLM used to write this RFC?

The decision this RFC seeks is which surface to standardize on which approach is favored.

We need to seek consensus on whether a dynamic shuffle instruction/intrinsic is needed first.

I would be interested in hearing from the AArch64 side who have expressed a need for it from the loop vectorizer. Having it used in tree rather than just consumed by out of tree SIMD libraries justifies the complexity a lot more.

I used an llm for some of the rfc (names and semantics for the back ends I’m unfamiliar with, and the semantics of the intrinsic taken from the langref), but writing of the rfc otherwise is my words.

Thank you for working on this, a dynamic vector shuffle is something I do miss in LLVM IR.

How much of the existing shufflevector code paths would be shared across static vs dynamic mask?

Just because something is somewhat similar in semantics doesn’t mean it’s good to have the same instruction. If the majority of code paths only applies to static shufflevector and now requires an extra check, extending the instruction is probably not the way to go. Similar cases include the old br inst, where most users had to check whether the branch is conditional (now fixed), or load volatile where we have several bugs due to the flag not being checked.

I also see some other disadvantages of extending the instruction:

  • Completely different cost: I don’t think it’s good to have two very similar spellings where one is likely much more expensive – most targets, including x86-64-v1, won’t have good support for dynamic shufflevector and will fall back to the expensive in-memory table implementation. (This is similar to dynamic insertelement/extractelement, but there the cost is lower.) I fear that this ends up as yet another footgun where front-ends inadvertently generate bad IR.
  • Somewhat large amount of breakage, in-tree and out-of-tree (~every tool that does some analysis on vector instructions will break).
2 Likes

If we go down the route of a dynamic shuffle intrinsic, I’d like to see it only accept one source vector argument instead of two like shufflevector. Most the hardware shuffle instructions only accept one. Having two source vectors really complicates the lowering in RISCVISelLowering.cpp since we need to try and match shuffle patterns twice across both input sources.

Instructions that do accept two sources like VPERMV3 could just match on something like vector.shuffle(concat(v1, v2), %mask).

3 Likes

I’d be fine accepting 1 source. That seems relatively reasonable. Generally the dual pshufb trick from x86 works to turn a shuffle of 2 into 2 shuffles of 1 pretty cleanly, but I don’t have strong opinions here (I care way less about spelling than capability)

How much of the existing shufflevector code paths would be shared across static vs dynamic mask?

Not much. If you look at the PR for B, it splits out all the codegen. The biggest advantage of it is probably that it makes constant folding a dynamic shuffle into a constant shuffle free. All the codegen paths are different.

Please also specify the behavior when Mask[i] is poison: pass the poison through, or immediate UB? (Pass the poison through to result[i].)

Also needs to make it into the top-level specification

1 Like

I can confirm that we’d really like this in Rust, thanks a lot. :slight_smile:

Please mark those semantics as uncomfirmed then. I wouldn’t want to trust an LLM with such delicate matters, this needs more reliable validation.

Please also specify the behavior when Mask[i] is poison: pass the poison through, or immediate UB? (Pass the poison through to result[i].)

I think the mask[i] being poison passing the poison to result[i] is the sensible answer. Will update the RFC.

I have since confirmed these manually (the use of the LLM was to get the names since looking up an instruction is much easier when you know what the name is).

1 Like

I think we have at least rough consensus that we do want this feature (Between the PRs and RFCs I count 4 in favor vs one opposed).

We have much less consensus so far on the question of unified vs separate intrinsics. @arsenm and @RKSimon commented (on the PR) in favor of unified. @nikic (on the PR) and @aengelke have commented in favor of a separate intrinsic. I’d appreciate if we can focus on optimal design here.

@lukel’s suggestion to make dynamicshuffle only take a single argument is also interesting. It does help justify why it’s a separate intrinsic, and I agree that the double version should be matchable by targets that support it (and emulatable by targets that don’t).

Single arg dynamicshuffle does have a notable downsides for users desiring to express the shuffle of 2 args which x86 and arm both support. Matching dynamicshuffle(concat_vectors(a, b), m) needs to happen before type legalization which would require some special handling per backend. (Also worth noting that backends that only have single arg shuffle can fairly cheaply emulate 2 arg shuffle, and can have fast paths for when the 2nd arg is poison or indices are known <n to avoid the emulation).

You can have a separate ISel node for two source shuffles and legalize to it during type legalisation. That way backends can just mark which types of shuffle they have as legal separately, and ideally not have to do any custom lowering.

NEON also has a TBL4 instruction I think, so it would be good to not encode a fixed number of sources at the IR level.

To emulate the 2 arg shuffle you need to implicitly concatenate two vectors which isn’t always cheap. On RISC-V that will involve a vslideup or vslidedown for any fixed length vector or vector sized smaller than a vector register.

To emulate the 2 arg shuffle you need to implicitly concatenate two vectors which isn’t always cheap. On RISC-V that will involve a vslideup or vslidedown for any fixed length vector or vector sized smaller than a vector register.

The other option is to vpgather the first vector, subtract vlen from the mask, vpgather the 2nd vector, compare the mask to 0 and vcompress the results (4 instructions).

That works too, by vcompress I think you mean vmerge.vvm?

But in any case having two separate fast and slow paths for the lowering is the type of complexity I would like to avoid. It’s very difficult to cost model instructions with multiple lowerings that depend on the value (the second source being poison), because in places like LoopVectorize or VectorCombine the value doesn’t yet exist.

I’m happy now that there’s enough demand for some sort of dynamic vector shuffle intrinsic. Some thoughts on the design though:

  1. There should only be one source operand, for the reasons mentioned above and it being the common denominator across the various target instructions.
  2. We shouldn’t allow length changing shuffles. I’m assuming the length changing shuffle mask as described in the RFC comes from shufflevector. IIUC shufflevector was added at a time before llvm.vector.insert/llvm.vector.extract existed, and allowing a variable mask allowed for doing these types of extractions. Target shuffle instructions don’t change the length, and having the same input and output type dramatically simplifies things. (E.g. see how many lines of code SelectionDAGBuilder::visitShuffleVector is, and case Instruction::ShuffleVector in TargetTransformInfoImplCRTPBase::getInstructionCost). So the intrinsic I’m imagining is something like:
    <N x ty> @llvm.vector.shuffle(<N x ty> %v, <N x iK> %mask)
    
  3. I’m not sure how TLI should determine what type to legalize the mask operand to during op legalization. We might need another TLI->getShuffleMaskAction that’s separate from getOperationAction.
  4. It’s worth noting that scalable vector.reverse and vector.splice.* would now be expressible with a dynamic shuffle mask. But vector.splice is usually just lowered to one specific instruction on RVV + SVE, and vector.reverse has a dedicated instruction on SVE. So it’s probably worth keeping them to simplify costing and lowering.

that prevents using the shuffles where the input is two (or more) N-element vectors concatenated together and the output is an N-element vector.

1 Like

That still would be expressible by having fused recognition for concat->shuffle->extract, but IMO that’s putting a lot of work on the backends for very little benefit.

AVX512 and AArch64 can just add a single DAGCombine on ISD::EXTRACT_SUBVECTOR if they want to match VPERMV3 or TBL2. Or we can have a dedicated ISD node too as mentioned earlier.

It’s the other way around, it’s a lot less work in the backend to just disallow length changing shuffles. The backend has to legalize every length-changing shuffle to a fixed-length shuffle otherwise, which is not trivial.

Yes. Quoting from https://developer.arm.com/documentation/102159/0400/Permutation---Neon-instructions?lang=en#md492-permutation---neon-instructions__lookup-table-instructions

The TBL and TBX instructions take two inputs:

  • An index input, consisting of one vector register containing a series of lookup values
  • A lookup table, consisting of a group of up to four vector registers containing data

That’s not the Arm ARM but that reference is… less conversational.

As far as the vector size question goes, I expect that the only “length-changing shuffle” people might realistically want is [<N x T>; I] to <N x T>, because that’s the only natural option in any hardware, and that remains true whether the hardware naturally supports up to 1 or 4 for I. Maybe something like that would be fine to accept, and reduce the work a backend must do to pattern-match to the desired instructions when the machine backend has direct support for I greater than 1?

I do agree with prohibiting arbitrary length-changing, however. That seems pointless, to me, as there’s no apparent codegen benefit.

I don’t think we have enough support here to justify this at the moment.

@sdesmalen-arm @paulwalker-arm Any thoughts on this for SVE?