[llvm] [VectorCombine] Fold binop(shuffle(V1, Mask), shuffle(V2, Mask)) -> shuffle(binop(V1, V2), Mask) (PR #211530)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Thu Jul 23 07:32:29 PDT 2026


================
@@ -2443,6 +2444,70 @@ bool VectorCombine::foldConcatOfBoolMasks(Instruction &I) {
   return true;
 }
 
+// Fold binop(shuffle(V0, Mask), shuffle(V1, Mask))
+// --> shuffle(binop(V0, V1), Mask)
+bool VectorCombine::foldBinopOfShuffles(Instruction &I) {
+  // It is not safe to transform things like div, urem, etc. because we may
+  // create undefined behavior when executing those on unknown vector elements.
+  if (!isSafeToSpeculativelyExecute(&I))
+    return false;
+
+  // If both arguments of the binary operation are shuffles that use the same
+  // mask and shuffle within a single vector, move the shuffle after the binop.
+  ArrayRef<int> Mask;
+  Value *LHS, *RHS, *V0, *V1;
+  if (!match(&I, m_BinOp(m_Value(LHS), m_Value(RHS))) ||
+      !match(LHS, m_Shuffle(m_Value(V0), m_Poison(), m_Mask(Mask))) ||
+      !match(RHS, m_Shuffle(m_Value(V1), m_Poison(), m_SpecificMask(Mask))))
+    return false;
+
+  if (V0->getType() != V1->getType())
+    return false;
+
+  auto *BO = cast<BinaryOperator>(&I);
+  auto *OpTy = cast<VectorType>(V0->getType());
+  auto *DstTy = cast<VectorType>(I.getType());
+  Instruction::BinaryOps Opcode = BO->getOpcode();
+
+  InstructionCost OldCost;
+  OldCost += TTI.getInstructionCost(&I, CostKind);
+  OldCost += TTI.getInstructionCost(cast<Instruction>(LHS), CostKind);
+  if (LHS != RHS)
+    OldCost += TTI.getInstructionCost(cast<Instruction>(RHS), CostKind);
----------------
dtcxzyw wrote:

Is it covered by any test cases?


https://github.com/llvm/llvm-project/pull/211530


More information about the llvm-commits mailing list