if (auto *I = dyn_cast<Instruction>(SrcVec)) {
if (auto *IE = dyn_cast<InsertElementInst>(I)) {
+ // If the possibly-variable indices are trivially known to be equal
+ // (because they are the same operand) then use the value that was
+ // inserted directly.
+ if (IE->getOperand(2) == Index)
+ return replaceInstUsesWith(EI, IE->getOperand(1));
// instsimplify already handled the case where the indices are constants
// and equal by value, if both are constants, they must not be the same
// value, extract from the pre-inserted value instead.
--- /dev/null
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
+; RUN: opt < %s -passes=instcombine -S | FileCheck %s
+
+; extracting a just-inserted element should yield the original value
+define float @constant_index(<4 x float> %x, float %val) {
+; CHECK-LABEL: @constant_index(
+; CHECK-NEXT: ret float [[VAL:%.*]]
+;
+ %ins = insertelement <4 x float> %x, float %val, i32 1
+ %ext = extractelement <4 x float> %ins, i32 1
+ ret float %ext
+}
+
+; extracting a just-inserted element should yield the original value even if
+; the index is dynamic
+define float @dynamic_index(<4 x float> %x, float %val, i32 %idx) {
+; CHECK-LABEL: @dynamic_index(
+; CHECK-NEXT: ret float [[VAL:%.*]]
+;
+ %ins = insertelement <4 x float> %x, float %val, i32 %idx
+ %ext = extractelement <4 x float> %ins, i32 %idx
+ ret float %ext
+}