Skip to content

Commit

Permalink
[InstSimplify] Fold LoadInst for uniform constant global variables
Browse files Browse the repository at this point in the history
Fold LoadInst for uniformly initialized constants, even if there
are non-constant GEP indices.

Goal proof: https://alive2.llvm.org/ce/z/oZtVby

Motivated by rust-lang/rust#107208

Differential Revision: https://reviews.llvm.org/D144184
  • Loading branch information
khei4 authored and CarlosAlbertoEnciso committed Feb 21, 2023
1 parent 354295c commit a0de7b7
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
6 changes: 6 additions & 0 deletions llvm/lib/Analysis/InstructionSimplify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6586,6 +6586,12 @@ static Value *simplifyLoadInst(LoadInst *LI, Value *PtrOp,
if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
return nullptr;

// If GlobalVariable's initializer is uniform, then return the constant
// regardless of its offset.
if (Constant *C =
ConstantFoldLoadFromUniformValue(GV->getInitializer(), LI->getType()))
return C;

// Try to convert operand into a constant by stripping offsets while looking
// through invariant.group intrinsics.
APInt Offset(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()), 0);
Expand Down
9 changes: 2 additions & 7 deletions llvm/test/Transforms/InstSimplify/load.ll
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,7 @@ define <3 x float> @load_vec3() {

define i32 @load_gep_const_zero_array(i64 %idx) {
; CHECK-LABEL: @load_gep_const_zero_array(
; CHECK-NEXT: [[GEP:%.*]] = getelementptr inbounds [4 x i32], ptr @constzeroarray, i64 0, i64 [[IDX:%.*]]
; CHECK-NEXT: [[LOAD:%.*]] = load i32, ptr [[GEP]], align 4
; CHECK-NEXT: ret i32 [[LOAD]]
; CHECK-NEXT: ret i32 0
;
%gep = getelementptr inbounds [4 x i32], ptr @constzeroarray, i64 0, i64 %idx
%load = load i32, ptr %gep
Expand All @@ -59,10 +57,7 @@ define i32 @load_gep_const_zero_array(i64 %idx) {

define i8 @load_i8_multi_gep_const_zero_array(i64 %idx1, i64 %idx2) {
; CHECK-LABEL: @load_i8_multi_gep_const_zero_array(
; CHECK-NEXT: [[GEP1:%.*]] = getelementptr inbounds i8, ptr @constzeroarray, i64 [[IDX1:%.*]]
; CHECK-NEXT: [[GEP:%.*]] = getelementptr inbounds i8, ptr [[GEP1]], i64 [[IDX2:%.*]]
; CHECK-NEXT: [[LOAD:%.*]] = load i8, ptr [[GEP]], align 1
; CHECK-NEXT: ret i8 [[LOAD]]
; CHECK-NEXT: ret i8 0
;
%gep1 = getelementptr inbounds i8, ptr @constzeroarray, i64 %idx1
%gep = getelementptr inbounds i8, ptr %gep1, i64 %idx2
Expand Down

0 comments on commit a0de7b7

Please sign in to comment.