From 9e6625d6a25bf5849d381fa8774adfd29ed823fb Mon Sep 17 00:00:00 2001 From: Nikita Popov Date: Wed, 19 Jun 2024 12:18:01 +0200 Subject: [InstCombine] Preserve all gep flags in another select of gep fold --- .../Transforms/InstCombine/InstCombineSelect.cpp | 5 ++--- llvm/test/Transforms/InstCombine/select-gep.ll | 26 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp b/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp index 66b7aa4..fbac209 100644 --- a/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp +++ b/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp @@ -3712,9 +3712,8 @@ Instruction *InstCombinerImpl::visitSelectInst(SelectInst &SI) { std::swap(NewT, NewF); Value *NewSI = Builder.CreateSelect(CondVal, NewT, NewF, SI.getName() + ".idx", &SI); - if (Gep->isInBounds()) - return GetElementPtrInst::CreateInBounds(ElementType, Ptr, {NewSI}); - return GetElementPtrInst::Create(ElementType, Ptr, {NewSI}); + return GetElementPtrInst::Create(ElementType, Ptr, NewSI, + Gep->getNoWrapFlags()); }; if (auto *TrueGep = dyn_cast(TrueVal)) if (auto *NewGep = SelectGepWithBase(TrueGep, FalseVal, false)) diff --git a/llvm/test/Transforms/InstCombine/select-gep.ll b/llvm/test/Transforms/InstCombine/select-gep.ll index 53bbcda..1730480 100644 --- a/llvm/test/Transforms/InstCombine/select-gep.ll +++ b/llvm/test/Transforms/InstCombine/select-gep.ll @@ -84,6 +84,32 @@ define ptr @test2a(ptr %p, i64 %x, i64 %y) { ret ptr %select } +define ptr @test2a_nusw(ptr %p, i64 %x, i64 %y) { +; CHECK-LABEL: @test2a_nusw( +; CHECK-NEXT: [[CMP:%.*]] = icmp ugt i64 [[X:%.*]], [[Y:%.*]] +; CHECK-NEXT: [[SELECT_IDX:%.*]] = select i1 [[CMP]], i64 [[X]], i64 0 +; CHECK-NEXT: [[SELECT:%.*]] = getelementptr nusw i32, ptr [[P:%.*]], i64 [[SELECT_IDX]] +; CHECK-NEXT: ret ptr [[SELECT]] +; + %gep = getelementptr nusw i32, ptr %p, i64 %x + %cmp = icmp ugt i64 %x, %y + %select = select i1 %cmp, ptr %gep, ptr %p + ret ptr %select +} + +define ptr @test2a_nuw(ptr %p, i64 %x, i64 %y) { +; CHECK-LABEL: @test2a_nuw( +; CHECK-NEXT: [[CMP:%.*]] = icmp ugt i64 [[X:%.*]], [[Y:%.*]] +; CHECK-NEXT: [[SELECT_IDX:%.*]] = select i1 [[CMP]], i64 [[X]], i64 0 +; CHECK-NEXT: [[SELECT:%.*]] = getelementptr nuw i32, ptr [[P:%.*]], i64 [[SELECT_IDX]] +; CHECK-NEXT: ret ptr [[SELECT]] +; + %gep = getelementptr nuw i32, ptr %p, i64 %x + %cmp = icmp ugt i64 %x, %y + %select = select i1 %cmp, ptr %gep, ptr %p + ret ptr %select +} + ; PR50183 define ptr @test2b(ptr %p, i64 %x, i64 %y) { ; CHECK-LABEL: @test2b( -- cgit v1.1