[llvm] 87f7884 - [NaryReassociate] Fix divide by zero crash in NaryReassociatePass (#202377)
via llvm-commits
llvm-commits at lists.llvm.org
Thu Jun 25 06:07:31 PDT 2026
Author: t-demchuk
Date: 2026-06-25T15:07:25+02:00
New Revision: 87f7884cb69912ca812d3a0543c94e0362d395a9
URL: https://github.com/llvm/llvm-project/commit/87f7884cb69912ca812d3a0543c94e0362d395a9
DIFF: https://github.com/llvm/llvm-project/commit/87f7884cb69912ca812d3a0543c94e0362d395a9.diff
LOG: [NaryReassociate] Fix divide by zero crash in NaryReassociatePass (#202377)
Updates NaryReassociatePass with a safety check to guard against GEPs
into arrays with zero sized element types (eg. [0 x ptr]) to prevent
division by zero.
Added:
llvm/test/Transforms/NaryReassociate/nary-gep-zero-sized-element.ll
Modified:
llvm/lib/Transforms/Scalar/NaryReassociate.cpp
Removed:
################################################################################
diff --git a/llvm/lib/Transforms/Scalar/NaryReassociate.cpp b/llvm/lib/Transforms/Scalar/NaryReassociate.cpp
index cf0d77dc11116..5bdbd3e8b47cb 100644
--- a/llvm/lib/Transforms/Scalar/NaryReassociate.cpp
+++ b/llvm/lib/Transforms/Scalar/NaryReassociate.cpp
@@ -442,7 +442,7 @@ NaryReassociatePass::tryReassociateGEPAtIndex(GetElementPtrInst *GEP,
// sizeof(S) = 100 is indivisible by sizeof(int64) = 8.
//
// TODO: bail out on this case for now. We could emit uglygep.
- if (IndexedSize % ElementSize != 0)
+ if (ElementSize == 0 || IndexedSize % ElementSize != 0)
return nullptr;
// NewGEP = &Candidate[RHS * (sizeof(IndexedType) / sizeof(Candidate[0])));
diff --git a/llvm/test/Transforms/NaryReassociate/nary-gep-zero-sized-element.ll b/llvm/test/Transforms/NaryReassociate/nary-gep-zero-sized-element.ll
new file mode 100644
index 0000000000000..f78023684d11f
--- /dev/null
+++ b/llvm/test/Transforms/NaryReassociate/nary-gep-zero-sized-element.ll
@@ -0,0 +1,22 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py UTC_ARGS: --version 6
+; RUN: opt < %s -passes=nary-reassociate -S | FileCheck %s
+
+; This test checks that NaryReassociate does not crash when a GEP's result
+; element type has a size of zero (eg. [0 x ptr] such as `%T` below).
+
+; Struct with a zero-sized field: sizeof(field 1) == 0.
+%T = type { [1 x ptr], [0 x ptr] }
+
+define ptr @foo(ptr %base, i64 %x, i64 %y) {
+; CHECK-LABEL: define ptr @foo(
+; CHECK-SAME: ptr [[BASE:%.*]], i64 [[X:%.*]], i64 [[Y:%.*]]) {
+; CHECK-NEXT: [[Z:%.*]] = add i64 [[X]], [[Y]]
+; CHECK-NEXT: [[GEP1:%.*]] = getelementptr [[T:%.*]], ptr [[BASE]], i64 [[X]], i32 1
+; CHECK-NEXT: [[GEP2:%.*]] = getelementptr inbounds [[T]], ptr [[BASE]], i64 [[Z]], i32 1
+; CHECK-NEXT: ret ptr [[GEP2]]
+;
+ %z = add i64 %x, %y
+ %gep1 = getelementptr inbounds %T, ptr %base, i64 %x, i32 1
+ %gep2 = getelementptr inbounds %T, ptr %base, i64 %z, i32 1
+ ret ptr %gep2
+}
More information about the llvm-commits
mailing list