[llvm] [DAGCombiner] Fold insert_vector_elt into a shared BUILD_VECTOR with undef lanes (PR #210905)

Yuyang Zhang via llvm-commits llvm-commits at lists.llvm.org
Tue Jul 21 02:14:33 PDT 2026


================
@@ -25179,7 +25179,14 @@ SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
         return CanonicalizeBuildVector(Ops, /*FreezeUndef=*/true);
 
       // BUILD_VECTOR - insert unused operands and build new BUILD_VECTOR.
-      if (CurVec.getOpcode() == ISD::BUILD_VECTOR && CurVec.hasOneUse()) {
+      // A multi-use base is allowed if it has an undef operand and the target
+      // opts in: rebuilding only re-references its scalars, so it cannot
+      // duplicate real work, and it un-shares a poison-padded base.
+      if (CurVec.getOpcode() == ISD::BUILD_VECTOR &&
+          (CurVec.hasOneUse() ||
+           (TLI.shouldUnshareBuildVectorForInsertElt(N->getValueType(0)) &&
+            any_of(CurVec->op_values(),
+                   [](SDValue Op) { return Op.isUndef(); })))) {
----------------
yuyzhang512 wrote:

Removed the `undef` check. I had originally assumed the rebuild was only "free" when there were `undef` lanes, but that isn't actually the case. `BUILD_VECTOR` is just `REG_SEQUENCE` glue, so rebuilding simply re-references the same scalar operands without introducing extra instructions, regardless of whether the base has `undef` lanes. The condition is now just `hasOneUse() || TLI.aggressivelyPreferBuildVectorSources(VT)`, matching the existing `extract_vector_elt` fold.

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


More information about the llvm-commits mailing list