[llvm] [VPlan] Implement VPlan-based unit-strideness speculation (PR #182595)
Luke Lau via llvm-commits
llvm-commits at lists.llvm.org
Tue Aug 4 21:23:17 PDT 2026
================
@@ -5543,6 +5552,170 @@ void VPlanTransforms::makeMemOpWideningDecisions(VPlan &Plan, VFRange &Range,
});
}
+void VPlanTransforms::multiversionForUnitStridedMemOps(
+ VPlan &Plan, VPCostContext &CostCtx, VFRange &Range,
+ ArrayRef<VPInstruction *> MemOps) {
+ ScalarEvolution *SE = CostCtx.PSE.getSE();
+ SCEVUnionPredicate StridePredicates({}, *SE);
+
+ for (VPInstruction *VPI : MemOps) {
+ VPValue *PtrOp = VPI->getOpcode() == Instruction::Load ? VPI->getOperand(0)
+ : VPI->getOperand(1);
+
+ const SCEV *PtrSCEV =
+ vputils::getSCEVExprForVPValue(PtrOp, CostCtx.PSE, CostCtx.L);
+ const SCEV *Start, *Stride;
+
+ if (!match(PtrSCEV, m_scev_AffineAddRec(m_SCEV(Start), m_SCEV(Stride),
+ m_SpecificLoop(CostCtx.L))))
+ continue;
+
+ Type *ScalarTy = VPI->getOpcode() == Instruction::Load
+ ? VPI->getScalarType()
+ : VPI->getOperand(0)->getScalarType();
+
+ if (VPI->getMask()) {
+ Instruction *I = VPI->getUnderlyingInstr();
+ bool IsLoad = VPI->getOpcode() == Instruction::Load;
+ // Don't speculate unit-strideness if it won't result in any unit-strided
+ // loads, as we'd pay the price of not taking vector loop if the runtime
+ // condition is false for no benefits.
+ if (!CostCtx.Config.isLegalMaskedLoadOrStore(IsLoad, ScalarTy,
+ getLoadStoreAlignment(I),
+ getLoadStoreAddressSpace(I)))
+ continue;
+ }
+
+ if (isa<SCEVConstant>(Stride))
+ continue;
+
+ const auto *TypeSize = cast<SCEVConstant>(SE->getSizeOfExpr(
+ Stride->getType(), SE->getDataLayout().getTypeAllocSize(ScalarTy)));
+
+ const SCEVConstant *StrideConstantMultiplier;
+ const SCEV *StrideNonConstantMultiplier;
+
+ const SCEV *ToMultiVersion = Stride;
+ const SCEV *MVConst = TypeSize;
+ if (match(Stride, m_scev_c_Mul(m_SCEVConstant(StrideConstantMultiplier),
+ m_SCEV(StrideNonConstantMultiplier)))) {
+ if (TypeSize != StrideConstantMultiplier) {
+ // TODO: Support `TypeSize = N * StrideConstantMultiplier`,
+ // including negative `N`. For now, only process when they're equal,
+ // which matches the useful part of the legacy behavior that
+ // multiversiones GEP index for stride one.
+ continue;
+ }
+ ToMultiVersion = StrideNonConstantMultiplier;
+ MVConst = SE->getOne(ToMultiVersion->getType());
+ } else if (!TypeSize->isOne()) {
+ // Likewise - try to match legacy behavior.
+ continue;
+ }
+
+ while (auto *C = dyn_cast<SCEVIntegralCastExpr>(ToMultiVersion)) {
+ ToMultiVersion = C->getOperand();
+ MVConst = SE->getTruncateOrSignExtend(MVConst, ToMultiVersion->getType());
+ }
+
+ if (match(ToMultiVersion, m_scev_UndefOrPoison()))
+ continue;
+
+ if (!isa<SCEVUnknown>(ToMultiVersion)) {
+ // Match legacy behavior.
+ // If/when changed, make sure that explicit poison/undef in the defining
+ // expression doesn't cause any issues.
+ continue;
+ }
+
+ Value *StrideVal = cast<SCEVUnknown>(ToMultiVersion)->getValue();
+
+ const SCEVPredicate *NewPred =
+ SE->getComparePredicate(CmpInst::ICMP_EQ, ToMultiVersion, MVConst);
+
+ // Check if new predicate implies that vectorizing a loop of such trip count
+ // is meaningless. The heuristic here could probably be improved.
+ auto *PredicatedMaxBTC = SE->rewriteUsingPredicate(
+ SE->getSymbolicMaxBackedgeTakenCount(CostCtx.L), CostCtx.L,
+ StridePredicates.getUnionWith(NewPred, *SE)
+ .getUnionWith(&CostCtx.PSE.getPredicate(), *SE));
+
+ if (LoopVectorizationPlanner::getDecisionAndClampRange(
+ [&](ElementCount VF) {
+ return SE->isKnownPredicate(
+ ICmpInst::ICMP_ULT, PredicatedMaxBTC,
+ SE->getConstant(PredicatedMaxBTC->getType(),
+ Plan.hasTailFolded() || VF.isScalable()
+ ? 1
+ : VF.getFixedValue() - 1));
+ },
+ Range))
+ continue;
+
+ StridePredicates = StridePredicates.getUnionWith(NewPred, *SE);
+
+ auto ReplaceMVUses = [&](Value *V) {
+ VPValue *From = Plan.getLiveIn(V);
+ if (!From)
+ return;
+ VPValue *To = Plan.getConstantInt(
+ From->getScalarType(),
+ cast<SCEVConstant>(MVConst)->getAPInt().getLimitedValue());
+
+ // Original scalar loop can still use `From`, make sure to only rewrite
+ // uses inside the vector loop that we guard with the checks.
+ From->replaceUsesWithIf(To, [&](VPUser &U, unsigned) {
+ auto *R = cast<VPRecipeBase>(&U);
+ return R->getRegion() ||
+ R->getParent() ==
+ Plan.getVectorLoopRegion()->getSinglePredecessor();
+ });
+ };
+
+ ReplaceMVUses(StrideVal);
+ for (auto *U : StrideVal->users())
+ if (isa<SExtInst, ZExtInst, TruncInst>(U))
+ ReplaceMVUses(U);
----------------
lukel97 wrote:
This is an edge case, but I don't think it's correct to RAUW a sext of i1 with 1, e.g. this test case:
```llvm
define void @i1_stride_with_sext_use(ptr noalias %p.out, ptr %p, i1 %b) {
entry:
%stride = zext i1 %b to i64
%e = sext i1 %b to i32
br label %loop
loop:
%iv = phi i64 [ 0, %entry ], [ %iv.next, %loop ]
%mul = mul i64 %iv, %stride
%gep = getelementptr i32, ptr %p, i64 %mul
%v = load i32, ptr %gep, align 4
%add = add i32 %v, %e ; GETS RAUW'd TO i32 1, SHOULD TO BE i32 -1
%gep.out = getelementptr i32, ptr %p.out, i64 %iv
store i32 %add, ptr %gep.out, align 4
%iv.next = add i64 %iv, 1
%ec = icmp eq i64 %iv.next, 128
br i1 %ec, label %exit, label %loop
exit:
ret void
}
```
I think we need to adjust the lambda to be something like
```c++
auto ReplaceUsesInVectorLoop = [&](Value *From, VPValue *To) { ... }
```
And then in the users() loop construct the appropriate sext/zext/trunc VPValue based off of MVConst.
https://github.com/llvm/llvm-project/pull/182595
More information about the llvm-commits
mailing list