Index: include/llvm/Analysis/InstructionSimplify.h =================================================================== --- include/llvm/Analysis/InstructionSimplify.h +++ include/llvm/Analysis/InstructionSimplify.h @@ -161,6 +161,10 @@ Value *SimplifyInsertValueInst(Value *Agg, Value *Val, ArrayRef Idxs, const SimplifyQuery &Q); +/// Given operands for an InsertElement, fold the result or return null. +Value *SimplifyInsertElementInst(Value *Vec, Value *Elt, Value *Idx, + const SimplifyQuery &Q); + /// Given operands for an ExtractValueInst, fold the result or return null. Value *SimplifyExtractValueInst(Value *Agg, ArrayRef Idxs, const SimplifyQuery &Q); Index: lib/Analysis/InstructionSimplify.cpp =================================================================== --- lib/Analysis/InstructionSimplify.cpp +++ lib/Analysis/InstructionSimplify.cpp @@ -3769,6 +3769,20 @@ return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit); } +Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *, Value *Idx, + const SimplifyQuery &) { + // Fold into undef if index is out of bounds + if (auto *CI = dyn_cast(Idx)) { + uint64_t IdxVal = CI->getZExtValue(); + uint64_t NumElements = cast(Vec->getType())->getNumElements(); + + if (IdxVal >= NumElements) + return UndefValue::get(Vec->getType()); + } + + return nullptr; +} + /// Given operands for an ExtractValueInst, see if we can fold the result. /// If not, this returns null. static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef Idxs, @@ -4637,6 +4651,12 @@ IV->getIndices(), Q); break; } + case Instruction::InsertElement: { + auto *IE = cast(I); + Result = SimplifyInsertElementInst(IE->getOperand(0), IE->getOperand(1), + IE->getOperand(2), Q); + break; + } case Instruction::ExtractValue: { auto *EVI = cast(I); Result = SimplifyExtractValueInst(EVI->getAggregateOperand(), Index: test/Transforms/InstSimplify/insertelement.ll =================================================================== --- /dev/null +++ test/Transforms/InstSimplify/insertelement.ll @@ -0,0 +1,19 @@ +; RUN: opt -S -instsimplify < %s | FileCheck %s + +define <4 x i32> @test(<4 x i32> %A) { + %I = insertelement <4 x i32> %A, i32 5, i64 4294967296 + ; CHECK: ret <4 x i32> undef + ret <4 x i32> %I +} + +define <4 x i32> @test1(<4 x i32> %A) { + %I = insertelement <4 x i32> %A, i32 5, i64 4 + ; CHECK: ret <4 x i32> undef + ret <4 x i32> %I +} + +define <4 x i32> @test2(<4 x i32> %A) { + %I = insertelement <4 x i32> %A, i32 5, i64 1 + ; CHECK: ret <4 x i32> %I + ret <4 x i32> %I +}