[llvm] [LAA] Fix off-by-EltSize in negative-step deref bounds check (PR #211964)

Aleksandr Popov via llvm-commits llvm-commits at lists.llvm.org
Sat Jul 25 12:37:12 PDT 2026


https://github.com/aleks-tmb updated https://github.com/llvm/llvm-project/pull/211964

>From dcb2f7e6597f64d880289132e9d0f03941f04161 Mon Sep 17 00:00:00 2001
From: Aleksandr Popov <apopov at azul.com>
Date: Fri, 24 Jul 2026 22:37:09 +0000
Subject: [PATCH 1/2] [LAA][NFC] Refactor deref no-wrap check; expose broken
 reverse-loop bounds

evaluatePtrAddRecAtMaxBTCWillNotWrap gets both sides of the deref
check wrong on the negative-step branch:

  * Lower bound is over-strict.  It requires
      FirstIterOffset >= MaxBTC*|Step| + EltSize
    but the correct condition is
      FirstIterOffset >= MaxBTC*|Step|.
    The extra EltSize slack is unnecessary: the lowest accessed byte
    is itself the start of an EltSize-sized access.  Reverse loops
    whose last iteration reaches the base pointer are wrongly
    rejected.

  * Upper bound is over-lenient.  It compares FirstIterOffset (the
    address of the top element) against DerefBytes, missing the size
    of the top access.  The correct condition is
      FirstIterOffset + EltSize <= DerefBytes.
    A loop whose top pointer sits exactly at DerefBytes is accepted
    as safe even though its top read spills past the deref region.
---
 llvm/lib/Analysis/LoopAccessAnalysis.cpp      | 56 +++++------
 .../negative-step-deref-off-by-eltsize.ll     | 93 +++++++++++++++++++
 2 files changed, 123 insertions(+), 26 deletions(-)
 create mode 100644 llvm/test/Analysis/LoopAccessAnalysis/negative-step-deref-off-by-eltsize.ll

diff --git a/llvm/lib/Analysis/LoopAccessAnalysis.cpp b/llvm/lib/Analysis/LoopAccessAnalysis.cpp
index 1f13106214ea9..e0782ddb6fe85 100644
--- a/llvm/lib/Analysis/LoopAccessAnalysis.cpp
+++ b/llvm/lib/Analysis/LoopAccessAnalysis.cpp
@@ -266,56 +266,60 @@ static bool evaluatePtrAddRecAtMaxBTCWillNotWrap(
 
   Step = SE.getNoopOrSignExtend(Step, WiderTy);
   MaxBTC = SE.getNoopOrZeroExtend(MaxBTC, WiderTy);
+  EltSize = SE.getNoopOrZeroExtend(EltSize, WiderTy);
 
   // For the computations below, make sure they don't unsigned wrap.
   if (!SE.isKnownPredicate(CmpInst::ICMP_UGE, AR->getStart(), StartPtr))
     return false;
-  const SCEV *StartOffset = SE.getNoopOrZeroExtend(
+  // Byte offset of the pointer at iteration 0 from the base pointer.
+  const SCEV *FirstIterOffset = SE.getNoopOrZeroExtend(
       SE.getMinusSCEV(AR->getStart(), StartPtr), WiderTy);
 
   if (!LoopGuards)
     LoopGuards.emplace(ScalarEvolution::LoopGuards::collect(AR->getLoop(), SE));
   MaxBTC = SE.applyLoopGuards(MaxBTC, *LoopGuards);
 
-  const SCEV *OffsetAtLastIter =
-      mulSCEVNoOverflow(MaxBTC, SE.getAbsExpr(Step, /*IsNSW=*/false), SE);
-  if (!OffsetAtLastIter) {
+  const SCEV *AbsStep = SE.getAbsExpr(Step, /*IsNSW=*/false);
+  // Total distance (in bytes) walked between the first and the last
+  // accessed pointer; MaxBTC * |Step|.
+  const SCEV *WalkBytes = mulSCEVNoOverflow(MaxBTC, AbsStep, SE);
+  if (!WalkBytes) {
     // Re-try with constant max backedge-taken count if using the symbolic one
     // failed.
     MaxBTC = SE.getConstantMaxBackedgeTakenCount(AR->getLoop());
     if (isa<SCEVCouldNotCompute>(MaxBTC))
       return false;
-    MaxBTC = SE.getNoopOrZeroExtend(
-        MaxBTC, WiderTy);
-    OffsetAtLastIter =
-        mulSCEVNoOverflow(MaxBTC, SE.getAbsExpr(Step, /*IsNSW=*/false), SE);
-    if (!OffsetAtLastIter)
+    MaxBTC = SE.getNoopOrZeroExtend(MaxBTC, WiderTy);
+    WalkBytes = mulSCEVNoOverflow(MaxBTC, AbsStep, SE);
+    if (!WalkBytes)
       return false;
   }
 
-  const SCEV *OffsetEndBytes = addSCEVNoOverflow(
-      OffsetAtLastIter, SE.getNoopOrZeroExtend(EltSize, WiderTy), SE);
-  if (!OffsetEndBytes)
+  // Total length in bytes of the accessed range (from the first accessed
+  // byte through the end of the last access); WalkBytes + EltSize.
+  const SCEV *SpanBytes = addSCEVNoOverflow(WalkBytes, EltSize, SE);
+  if (!SpanBytes)
     return false;
 
+  // Compute MaxOffset per direction: exclusive upper offset of the
+  // accessed range.
+  const SCEV *MaxOffset;
   if (IsKnownNonNegative) {
-    // For positive steps, check if
-    //  (AR->getStart() - StartPtr) + (MaxBTC  * Step) + EltSize <= DerefBytes,
-    // while making sure none of the computations unsigned wrap themselves.
-    const SCEV *EndBytes = addSCEVNoOverflow(StartOffset, OffsetEndBytes, SE);
-    if (!EndBytes)
+    // Range = [FirstIterOffset, FirstIterOffset + SpanBytes).
+    MaxOffset = addSCEVNoOverflow(FirstIterOffset, SpanBytes, SE);
+    if (!MaxOffset)
       return false;
-
     DerefBytesSCEV = SE.applyLoopGuards(DerefBytesSCEV, *LoopGuards);
-    return SE.isKnownPredicate(CmpInst::ICMP_ULE, EndBytes, DerefBytesSCEV);
+  } else {
+    // Range = [FirstIterOffset - WalkBytes, FirstIterOffset + EltSize).
+    // Lower end must not underflow past StartPtr.
+    assert(SE.isKnownNegative(Step) && "must be known negative");
+    if (!SE.isKnownPredicate(CmpInst::ICMP_SGE, FirstIterOffset, SpanBytes))
+      return false;
+    MaxOffset = FirstIterOffset;
   }
-
-  // For negative steps check if
-  //  * StartOffset >= (MaxBTC * Step + EltSize)
-  //  * StartOffset <= DerefBytes.
-  assert(SE.isKnownNegative(Step) && "must be known negative");
-  return SE.isKnownPredicate(CmpInst::ICMP_SGE, StartOffset, OffsetEndBytes) &&
-         SE.isKnownPredicate(CmpInst::ICMP_ULE, StartOffset, DerefBytesSCEV);
+  // MaxOffset must not exceed the deref-region end.
+  return SE.isKnownPredicate(CmpInst::ICMP_ULE, MaxOffset, DerefBytesSCEV);
 }
 
 std::pair<const SCEV *, const SCEV *> llvm::getStartAndEndForAccess(
diff --git a/llvm/test/Analysis/LoopAccessAnalysis/negative-step-deref-off-by-eltsize.ll b/llvm/test/Analysis/LoopAccessAnalysis/negative-step-deref-off-by-eltsize.ll
new file mode 100644
index 0000000000000..f0f351e88c985
--- /dev/null
+++ b/llvm/test/Analysis/LoopAccessAnalysis/negative-step-deref-off-by-eltsize.ll
@@ -0,0 +1,93 @@
+; RUN: opt -passes='print<access-info>' -disable-output %s 2>&1 | FileCheck %s
+
+; Reverse i32 loop over 4 elements whose access range exactly fills the
+; dereferenceable region (deref(16), reads bytes [0, 16)).
+;
+; TODO: LAA should recognise that this AR fits within the deref
+; region and produce tight bounds (Low: %A, High: %A + 16).
+;
+; Pseudocode:
+;   // A, B: at least 4 i32s dereferenceable each
+;   for (i64 i = 3; i >= 0; --i) {
+;     i32 l = A[i];       // A[3], A[2], A[1], A[0]
+;     B[i] = 0;
+;     if (l == 0) break;
+;   }
+
+define void @reverse_reaches_base(ptr dereferenceable(16) %A, ptr dereferenceable(16) %B) {
+; CHECK-LABEL: 'reverse_reaches_base'
+; CHECK:      Group GRP0:
+; CHECK-NEXT:   (Low: (-4 + inttoptr (i64 -1 to ptr))<nsw> High: (16 + %B)<nuw>)
+; CHECK-NEXT:     Member: {(12 + %B)<nuw>,+,-4}<nw><%loop>
+; CHECK:      Group GRP1:
+; CHECK-NEXT:   (Low: (-4 + inttoptr (i64 -1 to ptr))<nsw> High: (16 + %A)<nuw>)
+; CHECK-NEXT:     Member: {(12 + %A)<nuw>,+,-4}<nw><%loop>
+entry:
+  br label %loop
+
+loop:
+  %iv = phi i64 [ 3, %entry ], [ %iv.dec, %latch ]
+  %gep.A = getelementptr inbounds i32, ptr %A, i64 %iv
+  %gep.B = getelementptr inbounds i32, ptr %B, i64 %iv
+  %l = load i32, ptr %gep.A, align 4
+  store i32 0, ptr %gep.B, align 4
+  %uncntable = icmp eq i32 %l, 0
+  br i1 %uncntable, label %exit.early, label %latch
+
+latch:
+  %iv.dec = add nsw i64 %iv, -1
+  %ec = icmp eq i64 %iv, 0
+  br i1 %ec, label %exit.done, label %loop
+
+exit.early:
+  ret void
+
+exit.done:
+  ret void
+}
+
+; Reverse i32 loop whose top read spills one byte past the deref end.
+; The IR is UB by construction: top i32 read at byte 13 covers [13, 17),
+; but deref(16) only guarantees [0, 16).
+;
+; TODO: LAA should reject this AR (top access exits the deref region)
+; and fall back to the wide low bound.
+;
+; Pseudocode:
+;   for (i64 i = 13; i > 1; i -= 4) {
+;     i32 l = *(i32*)((char*)A + i);   // reads [i, i+4)
+;     *(i32*)((char*)B + i) = 0;
+;     if (l == 0) break;
+;   }
+
+define void @reverse_top_spills(ptr dereferenceable(16) %A, ptr dereferenceable(16) %B) {
+; CHECK-LABEL: 'reverse_top_spills'
+; CHECK:      Group GRP0:
+; CHECK-NEXT:   (Low: (5 + %B)<nuw> High: (17 + %B))
+; CHECK-NEXT:     Member: {(13 + %B)<nuw>,+,-4}<nw><%loop2>
+; CHECK:      Group GRP1:
+; CHECK-NEXT:   (Low: (5 + %A)<nuw> High: (17 + %A))
+; CHECK-NEXT:     Member: {(13 + %A)<nuw>,+,-4}<nw><%loop2>
+entry:
+  br label %loop2
+
+loop2:
+  %iv = phi i64 [ 13, %entry ], [ %iv.dec, %latch ]
+  %gep.A = getelementptr inbounds i8, ptr %A, i64 %iv
+  %gep.B = getelementptr inbounds i8, ptr %B, i64 %iv
+  %l = load i32, ptr %gep.A, align 1
+  store i32 0, ptr %gep.B, align 1
+  %uncntable = icmp eq i32 %l, 0
+  br i1 %uncntable, label %exit.early, label %latch
+
+latch:
+  %iv.dec = add nsw i64 %iv, -4
+  %ec = icmp eq i64 %iv, 5
+  br i1 %ec, label %exit.done, label %loop2
+
+exit.early:
+  ret void
+
+exit.done:
+  ret void
+}

>From f394cacf664486f30efa9781754e3253e5192b49 Mon Sep 17 00:00:00 2001
From: Aleksandr Popov <apopov at azul.com>
Date: Fri, 24 Jul 2026 23:35:51 +0000
Subject: [PATCH 2/2] [LAA] Fix off-by-EltSize in negative-step deref bounds
 check

Negative-step branch of evaluatePtrAddRecAtMaxBTCWillNotWrap fixes:

  * Lower bound: compare FirstIterOffset against WalkBytes instead of
    SpanBytes (= WalkBytes + EltSize).  The lowest accessed byte is
    itself the start of an EltSize-sized access, so no extra slack is
    needed.

  * Upper bound: MaxOffset is the exclusive upper offset of the
    accessed range, so it must be FirstIterOffset + EltSize, not
    FirstIterOffset alone.  This closes the gap that let the top
    access spill past DerefBytes without being noticed.

Apply loop guards for FirstIterOffset and DerefBytes SCEVs for both
directions.

Fixes llvm/llvm-project#211962
---
 llvm/lib/Analysis/LoopAccessAnalysis.cpp      |  9 ++++++---
 .../negative-step-deref-off-by-eltsize.ll     | 20 ++++++++-----------
 2 files changed, 14 insertions(+), 15 deletions(-)

diff --git a/llvm/lib/Analysis/LoopAccessAnalysis.cpp b/llvm/lib/Analysis/LoopAccessAnalysis.cpp
index e0782ddb6fe85..547c9e8016839 100644
--- a/llvm/lib/Analysis/LoopAccessAnalysis.cpp
+++ b/llvm/lib/Analysis/LoopAccessAnalysis.cpp
@@ -304,21 +304,24 @@ static bool evaluatePtrAddRecAtMaxBTCWillNotWrap(
   // Compute MaxOffset per direction: exclusive upper offset of the
   // accessed range.
   const SCEV *MaxOffset;
+  FirstIterOffset = SE.applyLoopGuards(FirstIterOffset, *LoopGuards);
   if (IsKnownNonNegative) {
     // Range = [FirstIterOffset, FirstIterOffset + SpanBytes).
     MaxOffset = addSCEVNoOverflow(FirstIterOffset, SpanBytes, SE);
     if (!MaxOffset)
       return false;
-    DerefBytesSCEV = SE.applyLoopGuards(DerefBytesSCEV, *LoopGuards);
   } else {
     // Range = [FirstIterOffset - WalkBytes, FirstIterOffset + EltSize).
     // Lower end must not underflow past StartPtr.
     assert(SE.isKnownNegative(Step) && "must be known negative");
-    if (!SE.isKnownPredicate(CmpInst::ICMP_SGE, FirstIterOffset, SpanBytes))
+    if (!SE.isKnownPredicate(CmpInst::ICMP_SGE, FirstIterOffset, WalkBytes))
+      return false;
+    MaxOffset = addSCEVNoOverflow(FirstIterOffset, EltSize, SE);
+    if (!MaxOffset)
       return false;
-    MaxOffset = FirstIterOffset;
   }
   // MaxOffset must not exceed the deref-region end.
+  DerefBytesSCEV = SE.applyLoopGuards(DerefBytesSCEV, *LoopGuards);
   return SE.isKnownPredicate(CmpInst::ICMP_ULE, MaxOffset, DerefBytesSCEV);
 }
 
diff --git a/llvm/test/Analysis/LoopAccessAnalysis/negative-step-deref-off-by-eltsize.ll b/llvm/test/Analysis/LoopAccessAnalysis/negative-step-deref-off-by-eltsize.ll
index f0f351e88c985..db8670bf896b0 100644
--- a/llvm/test/Analysis/LoopAccessAnalysis/negative-step-deref-off-by-eltsize.ll
+++ b/llvm/test/Analysis/LoopAccessAnalysis/negative-step-deref-off-by-eltsize.ll
@@ -1,10 +1,8 @@
 ; RUN: opt -passes='print<access-info>' -disable-output %s 2>&1 | FileCheck %s
 
 ; Reverse i32 loop over 4 elements whose access range exactly fills the
-; dereferenceable region (deref(16), reads bytes [0, 16)).
-;
-; TODO: LAA should recognise that this AR fits within the deref
-; region and produce tight bounds (Low: %A, High: %A + 16).
+; dereferenceable region (deref(16), reads bytes [0, 16)).  LAA proves
+; no-wrap and produces the tight (%A .. %A + 16) bound.
 ;
 ; Pseudocode:
 ;   // A, B: at least 4 i32s dereferenceable each
@@ -17,10 +15,10 @@
 define void @reverse_reaches_base(ptr dereferenceable(16) %A, ptr dereferenceable(16) %B) {
 ; CHECK-LABEL: 'reverse_reaches_base'
 ; CHECK:      Group GRP0:
-; CHECK-NEXT:   (Low: (-4 + inttoptr (i64 -1 to ptr))<nsw> High: (16 + %B)<nuw>)
+; CHECK-NEXT:   (Low: %B High: (16 + %B)<nuw>)
 ; CHECK-NEXT:     Member: {(12 + %B)<nuw>,+,-4}<nw><%loop>
 ; CHECK:      Group GRP1:
-; CHECK-NEXT:   (Low: (-4 + inttoptr (i64 -1 to ptr))<nsw> High: (16 + %A)<nuw>)
+; CHECK-NEXT:   (Low: %A High: (16 + %A)<nuw>)
 ; CHECK-NEXT:     Member: {(12 + %A)<nuw>,+,-4}<nw><%loop>
 entry:
   br label %loop
@@ -48,10 +46,8 @@ exit.done:
 
 ; Reverse i32 loop whose top read spills one byte past the deref end.
 ; The IR is UB by construction: top i32 read at byte 13 covers [13, 17),
-; but deref(16) only guarantees [0, 16).
-;
-; TODO: LAA should reject this AR (top access exits the deref region)
-; and fall back to the wide low bound.
+; but deref(16) only guarantees [0, 16).  LAA rejects the AR and
+; falls back to the wide low bound.
 ;
 ; Pseudocode:
 ;   for (i64 i = 13; i > 1; i -= 4) {
@@ -63,10 +59,10 @@ exit.done:
 define void @reverse_top_spills(ptr dereferenceable(16) %A, ptr dereferenceable(16) %B) {
 ; CHECK-LABEL: 'reverse_top_spills'
 ; CHECK:      Group GRP0:
-; CHECK-NEXT:   (Low: (5 + %B)<nuw> High: (17 + %B))
+; CHECK-NEXT:   (Low: (-4 + inttoptr (i64 -1 to ptr))<nsw> High: (17 + %B))
 ; CHECK-NEXT:     Member: {(13 + %B)<nuw>,+,-4}<nw><%loop2>
 ; CHECK:      Group GRP1:
-; CHECK-NEXT:   (Low: (5 + %A)<nuw> High: (17 + %A))
+; CHECK-NEXT:   (Low: (-4 + inttoptr (i64 -1 to ptr))<nsw> High: (17 + %A))
 ; CHECK-NEXT:     Member: {(13 + %A)<nuw>,+,-4}<nw><%loop2>
 entry:
   br label %loop2



More information about the llvm-commits mailing list