[llvm] [SelectionDAG] Convert to or mask if all insertions are -1 (PR #138213)

Matt Arsenault via llvm-commits llvm-commits at lists.llvm.org
Mon May 5 12:26:14 PDT 2025


================
@@ -22973,18 +22973,31 @@ SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
             return NewShuffle;
       }
 
-      // If all insertions are zero value, try to convert to AND mask.
-      // TODO: Do this for -1 with OR mask?
-      if (!LegalOperations && llvm::isNullConstant(InVal) &&
+      // We can convert to AND/OR mask if all insertions are zero or -1
+      // respectively.
+      if (!LegalOperations &&
+          (llvm::isNullConstant(InVal) || llvm::isAllOnesConstant(InVal)) &&
           all_of(Ops, [InVal](SDValue Op) { return !Op || Op == InVal; }) &&
           count_if(Ops, [InVal](SDValue Op) { return Op == InVal; }) >= 2) {
         SDValue Zero = DAG.getConstant(0, DL, MaxEltVT);
         SDValue AllOnes = DAG.getAllOnesConstant(DL, MaxEltVT);
         SmallVector<SDValue, 8> Mask(NumElts);
-        for (unsigned I = 0; I != NumElts; ++I)
-          Mask[I] = Ops[I] ? Zero : AllOnes;
-        return DAG.getNode(ISD::AND, DL, VT, CurVec,
-                           DAG.getBuildVector(VT, DL, Mask));
+
+        // Build the mask and return the corresponding DAG node.
+        auto buildMaskAndNode = [&](SDValue trueVal, SDValue falseVal,
+                                    unsigned nodeOpcode) -> SDValue {
+          for (unsigned I = 0; I < NumElts; ++I)
+            Mask[I] = Ops[I] ? trueVal : falseVal;
+          return DAG.getNode(nodeOpcode, DL, VT, CurVec,
+                             DAG.getBuildVector(VT, DL, Mask));
+        };
+
+        // If all elements are zero, we can use AND with all ones.
+        if (llvm::isNullConstant(InVal))
----------------
arsenm wrote:

Replacing it with isAllOnesConstant isn't any better, avoid repeating the nontrivial check twice 

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


More information about the llvm-commits mailing list