Skip to content

Commit 899faa5

Browse files
committed
[InstCombine] Check inbounds in load/store of gep null transform (PR48577)
If the GEP isn't inbounds, then accessing a GEP of null location is generally not UB. While this is a minimal fix, the GEP of null handling should probably be its own fold.
1 parent de127d8 commit 899faa5

File tree

3 files changed

+7
-5
lines changed

3 files changed

+7
-5
lines changed

llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp

+3-2
Original file line numberDiff line numberDiff line change
@@ -908,15 +908,16 @@ static bool canSimplifyNullStoreOrGEP(StoreInst &SI) {
908908

909909
auto *Ptr = SI.getPointerOperand();
910910
if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
911-
Ptr = GEPI->getOperand(0);
911+
if (GEPI->isInBounds())
912+
Ptr = GEPI->getOperand(0);
912913
return (isa<ConstantPointerNull>(Ptr) &&
913914
!NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()));
914915
}
915916

916917
static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op) {
917918
if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
918919
const Value *GEPI0 = GEPI->getOperand(0);
919-
if (isa<ConstantPointerNull>(GEPI0) &&
920+
if (isa<ConstantPointerNull>(GEPI0) && GEPI->isInBounds() &&
920921
!NullPointerIsDefined(LI.getFunction(), GEPI->getPointerAddressSpace()))
921922
return true;
922923
}

llvm/test/Transforms/InstCombine/load.ll

+3-2
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,9 @@ define i32 @load_gep_null_inbounds(i64 %X) {
6969

7070
define i32 @load_gep_null_not_inbounds(i64 %X) {
7171
; CHECK-LABEL: @load_gep_null_not_inbounds(
72-
; CHECK-NEXT: store i32 undef, i32* null, align 536870912
73-
; CHECK-NEXT: ret i32 undef
72+
; CHECK-NEXT: [[V:%.*]] = getelementptr i32, i32* null, i64 [[X:%.*]]
73+
; CHECK-NEXT: [[R:%.*]] = load i32, i32* [[V]], align 4
74+
; CHECK-NEXT: ret i32 [[R]]
7475
;
7576
%V = getelementptr i32, i32* null, i64 %X
7677
%R = load i32, i32* %V

llvm/test/Transforms/InstCombine/store.ll

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ define void @store_at_gep_off_null_inbounds(i64 %offset) {
3737
define void @store_at_gep_off_null_not_inbounds(i64 %offset) {
3838
; CHECK-LABEL: @store_at_gep_off_null_not_inbounds(
3939
; CHECK-NEXT: [[PTR:%.*]] = getelementptr i32, i32* null, i64 [[OFFSET:%.*]]
40-
; CHECK-NEXT: store i32 undef, i32* [[PTR]], align 4
40+
; CHECK-NEXT: store i32 24, i32* [[PTR]], align 4
4141
; CHECK-NEXT: ret void
4242
;
4343
%ptr = getelementptr i32, i32 *null, i64 %offset

0 commit comments

Comments
 (0)