Skip to content

Commit 3764f5e

Browse files
rikhuijzergysit
andauthored
[mlir][llvm] Fix negative GEP crash in type consistency (#74859)
Fixes #74453. The `gepToByteOffset` was implicitly casting an signed integer to an unsigned integer even though negative dimensions are valid for `llvm.getelementptr`. --------- Co-authored-by: Tobias Gysi <[email protected]>
1 parent 01ac530 commit 3764f5e

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

mlir/lib/Dialect/LLVMIR/Transforms/TypeConsistency.cpp

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,10 @@ static std::optional<uint64_t> gepToByteOffset(DataLayout &layout, GEPOp gep) {
161161
IntegerAttr indexInt = llvm::dyn_cast_if_present<IntegerAttr>(index);
162162
if (!indexInt)
163163
return std::nullopt;
164-
indices.push_back(indexInt.getInt());
164+
int32_t gepIndex = indexInt.getInt();
165+
if (gepIndex < 0)
166+
return std::nullopt;
167+
indices.push_back(static_cast<uint32_t>(gepIndex));
165168
}
166169

167170
uint64_t offset = indices[0] * layout.getTypeSize(gep.getElemType());

mlir/test/Dialect/LLVMIR/type-consistency.mlir

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,20 @@ llvm.func @index_to_struct(%arg: i32) {
151151

152152
// -----
153153

154+
// CHECK-LABEL: llvm.func @no_crash_on_negative_gep_index
155+
llvm.func @no_crash_on_negative_gep_index() {
156+
%0 = llvm.mlir.constant(1.000000e+00 : f16) : f16
157+
%1 = llvm.mlir.constant(1 : i32) : i32
158+
// CHECK: %[[ALLOCA:.*]] = llvm.alloca %{{.*}} x !llvm.struct<"foo", (i32, i32, i32)>
159+
%2 = llvm.alloca %1 x !llvm.struct<"foo", (i32, i32, i32)> : (i32) -> !llvm.ptr
160+
// CHECK: llvm.getelementptr %[[ALLOCA]][-1] : (!llvm.ptr) -> !llvm.ptr, f32
161+
%3 = llvm.getelementptr %2[-1] : (!llvm.ptr) -> !llvm.ptr, f32
162+
llvm.store %0, %3 : f16, !llvm.ptr
163+
llvm.return
164+
}
165+
166+
// -----
167+
154168
// CHECK-LABEL: llvm.func @coalesced_store_ints
155169
// CHECK-SAME: %[[ARG:.*]]: i64
156170
llvm.func @coalesced_store_ints(%arg: i64) {

0 commit comments

Comments
 (0)