[llvm] [ConstantFolding] Add folding for [de]interleave2, insert and extract (PR #141301)

Craig Topper via llvm-commits llvm-commits at lists.llvm.org
Wed Jun 11 09:20:05 PDT 2025


================
@@ -3750,6 +3754,84 @@ static Constant *ConstantFoldFixedVectorCall(
     }
     return nullptr;
   }
+  case Intrinsic::vector_extract: {
+    auto *Idx = dyn_cast<ConstantInt>(Operands[1]);
+    Constant *Vec = Operands[0];
+    if (!Idx || !isa<FixedVectorType>(Vec->getType()))
+      return nullptr;
+
+    unsigned NumElements = FVTy->getNumElements();
+    unsigned VecNumElements =
+        cast<FixedVectorType>(Vec->getType())->getNumElements();
+    unsigned StartingIndex = Idx->getZExtValue();
+
+    // Extracting entire vector is nop
+    if (NumElements == VecNumElements && StartingIndex == 0)
+      return Vec;
+
+    const unsigned NonPoisonNumElements =
+        std::min(StartingIndex + NumElements, VecNumElements);
+    for (unsigned I = StartingIndex; I < NonPoisonNumElements; ++I) {
+      Constant *Elt = Vec->getAggregateElement(I);
+      if (!Elt)
+        return nullptr;
+      Result[I - StartingIndex] = Elt;
+    }
+
+    // Remaining elements are poison since they are out of bounds.
----------------
topperc wrote:

According to LangRef, out of bounds poisons the entire result vector not just the out of bounds elements.

```
Elements idx through (idx + num_elements(result_type) - 1) must be valid vector indices. If this condition cannot be determined statically but is false at runtime, then the result vector is a [poison value](https://llvm.org/docs/LangRef.html#poisonvalues).
```

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


More information about the llvm-commits mailing list