https://github.com/dingcyrus created 
https://github.com/llvm/llvm-project/pull/246597

Fixes #246281

EvalInfo::CheckArraySize does two checks. It returns one bool for both. The 
first asks whether the array bound can be represented at all. The second asks 
whether the array has more elements than -fconstexpr-steps allows, which is the
GH63562 stand-in for one APValue per element. Only the first is the "erroneous 
array bound" case, and only for that case does [expr.new] give a non-throwing 
allocation a null pointer. VisitCXXNewExpr applies the rule to both.

    const int n = 1048577;
    unsigned char *const p = new (std::nothrow) unsigned char[n];

This evaluates "successfully" to nullptr. CodeGen still emits the call to 
operator new[], then throws the result away. Every later read of p sees null, 
and delete[] p gets a constant null, so the block leaks too. It reproduces at 
-O0, so LLVM optimization is not involved.

CheckArraySize now says which check failed. Only a bound that is not 
representable takes the null path. Past the resource limit the evaluation 
fails, which leaves the allocation to run time, where it succeeds. The step 
limit belongs to the compile-time evaluator; the running program does not have 
it, and the code Clang emits for this expression does not treat the bound as 
erroneous either. HandleOperatorNewCall reaches the same check through 
std::allocator<T>::allocate, so it changes the same way.

tooBig in the new tests still folds to a null pointer. A bound that no address 
space can hold really is erroneous, and that half of [expr.new] is unchanged.

In a constant expression this was a silent null pointer before. I checked that 
against the parent commit: the file below compiles with no diagnostic at all.

    constexpr auto overLimit = new (std::nothrow) unsigned char[1025];
    static_assert(overLimit == nullptr);   // accepted

Now it is an error with a note that explains it. The resource-limit note is no 
longer gated on the diagnostic flag, because unlike the check above it says 
nothing about the expression. In a non-constant-evaluated fold nothing prints 
either way, since State::diag has no sink there. The traditional evaluator and 
the bytecode interpreter now report the same error and the same two notes.

AI assistance was used for code review analysis and local build verification.

>From 8c5dcedb2d751d50088f8f12985d9342e6f59b55 Mon Sep 17 00:00:00 2001
From: Cyrus Ding <[email protected]>
Date: Fri, 27 Nov 2026 16:57:14 +0800
Subject: [PATCH] [ExprConstant] Do not fold a nothrow new to null at the step
 limit

A runtime

  const int n = 1048577;
  unsigned char *const p = new (std::nothrow) unsigned char[n];

folds to a null pointer, because the array bound has more elements than
-fconstexpr-steps allows and EvalInfo::CheckArraySize reports that the same way
it reports an erroneous array bound. [expr.new] grants the null result only to a
new-expression whose array bound *is* erroneous; reaching the evaluator's own
resource limit says nothing about the expression. So the evaluation claimed
success with a null value, CodeGen emitted the call to operator new[] and threw
its result away, every later read of the pointer saw nullptr, and delete[] was
handed a constant null, leaking the block. This is a miscompilation rather than
a missed optimization: the issue reports plzip 1.13 failing every -d run with
"Not enough memory" because of it.

CheckArraySize has always made two distinct checks but collapsed them into one
bool. Say which one failed, and take the null result only for a bound that
genuinely is not representable; past the resource limit, fail the evaluation and
leave the allocation to run time. HandleOperatorNewCall, which reaches the same
check through std::allocator<T>::allocate, is adjusted the same way.

The resource-limit note is no longer gated on the diagnostic flag. A
non-constant-evaluated fold has no diagnostic sink, so nothing is printed there;
in a constant expression, where a bound this large used to yield a silent null
pointer, the traditional evaluator now reports the same error and notes as the
bytecode interpreter already did.

Fixes https://github.com/llvm/llvm-project/issues/246281

Assisted-by: Claude Code
Co-Authored-By: Claude Code <[email protected]>
---
 clang/docs/ReleaseNotes.md                    |  9 +++
 clang/lib/AST/ExprConstant.cpp                | 73 +++++++++++++------
 .../new-nothrow-constexpr-steps.cpp           | 54 ++++++++++++++
 .../SemaCXX/constexpr-new-nothrow-limit.cpp   | 33 +++++++++
 4 files changed, 148 insertions(+), 21 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/new-nothrow-constexpr-steps.cpp
 create mode 100644 clang/test/SemaCXX/constexpr-new-nothrow-limit.cpp

diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index f8115a8aff6afa..f71ca8ec364527 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -1090,6 +1090,15 @@ documentation](CIR/index.md) for more information 
regarding ClangIR's status and
 
 - Instantiate constexpr functions as needed before they are evaluated. 
(#GH73232) (#GH35052) (#GH100897)
 
+- Fixed a miscompilation where a runtime `new (std::nothrow) T[N]` with a 
constant
+  `N` larger than `-fconstexpr-steps` was folded to a null pointer: the 
allocation
+  function was still called, but its result was thrown away, so every later 
read
+  of the pointer saw `nullptr` and the block leaked. Reaching the step limit 
only
+  means the evaluator could not evaluate the bound, which is not the same 
thing as
+  an erroneous array bound under [expr.new]. Such an allocation in a constant
+  expression is now diagnosed instead of silently evaluating to a null pointer.
+  (#GH246281)
+
 - Fixed lambdas with specifiers or attributes after the capture list being
   misparsed as function declarations in direct-initialization contexts under
   `-fms-extensions` or in HLSL mode.
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 3ead1325191ea1..2bdf2296fcf738 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -922,8 +922,25 @@ namespace {
       return false;
     }
 
-    bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
-                        uint64_t ElemCount, bool Diag) {
+    /// How an array size check turned out. The two failures have to stay
+    /// distinct: only the first one is a property of the expression.
+    enum class ArraySizeResult {
+      /// The array can be built.
+      OK,
+      /// The bound is not representable. [expr.new] calls such a 
new-expression
+      /// erroneous, which is what lets a non-throwing allocation evaluate to a
+      /// null pointer without calling the allocation function.
+      ErroneousBound,
+      /// The bound is representable, but giving every element an APValue would
+      /// use more memory than we allow (GH63562). This is a limit of the
+      /// evaluator, not a property of the expression, so the evaluation has to
+      /// fail instead of producing a value -- otherwise a new-expression that
+      /// we merely could not fold turns into a null pointer at run time.
+      OverResourceLimit,
+    };
+
+    ArraySizeResult CheckArraySize(SourceLocation Loc, unsigned BitWidth,
+                                   uint64_t ElemCount, bool Diag) {
       // FIXME: GH63562
       // APValue stores array extents as unsigned,
       // so anything that is greater that unsigned would overflow when
@@ -932,7 +949,7 @@ namespace {
           ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
         if (Diag)
           FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
-        return false;
+        return ArraySizeResult::ErroneousBound;
       }
 
       // FIXME: GH63562
@@ -942,14 +959,16 @@ namespace {
       // of each element is likely to take some number of steps anyway.
       uint64_t Limit = getLangOpts().ConstexprStepLimit;
       if (Limit != 0 && ElemCount > Limit) {
-        if (Diag) {
-          FFDiag(Loc, diag::note_constexpr_new_exceeds_limits, 1)
-              << ElemCount << Limit;
-          Note(Loc, diag::note_constexpr_steps);
-        }
-        return false;
+        // Unlike the check above, this one says nothing about the expression,
+        // so even a non-throwing allocation gets to be told why it did not
+        // evaluate. Diagnostics are dropped unless this is a real constant
+        // evaluation, so this stays quiet where we only failed to fold.
+        FFDiag(Loc, diag::note_constexpr_new_exceeds_limits, 1)
+            << ElemCount << Limit;
+        Note(Loc, diag::note_constexpr_steps);
+        return ArraySizeResult::OverResourceLimit;
       }
-      return true;
+      return ArraySizeResult::OK;
     }
 
     std::pair<CallStackFrame *, unsigned>
@@ -3875,9 +3894,9 @@ static bool lifetimeStartedInEvaluation(EvalInfo &Info,
 static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
                            SourceLocation CallLoc = {}) {
   return Info.CheckArraySize(
-      CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
-      CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
-      /*Diag=*/true);
+             CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
+             CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
+             /*Diag=*/true) == EvalInfo::ArraySizeResult::OK;
 }
 
 static bool handleScalarCast(EvalInfo &Info, const FPOptions FPO, const Expr 
*E,
@@ -7902,9 +7921,13 @@ static bool HandleOperatorNewCall(EvalInfo &Info, const 
CallExpr *E,
     return false;
   }
 
-  if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
-                           Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
-    if (IsNothrow) {
+  auto SizeCheck =
+      Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
+                          Size.getZExtValue(), /*Diag=*/!IsNothrow);
+  if (SizeCheck != EvalInfo::ArraySizeResult::OK) {
+    // A null result stands for an erroneous array bound only; past the
+    // evaluator's own limits we simply do not know what this allocates.
+    if (IsNothrow && SizeCheck == EvalInfo::ArraySizeResult::ErroneousBound) {
       Result.setNull(Info.Ctx, E->getType());
       return true;
     }
@@ -11253,11 +11276,19 @@ bool PointerExprEvaluator::VisitCXXNewExpr(const 
CXXNewExpr *E) {
 
     //   -- its value is such that the size of the allocated object would
     //      exceed the implementation-defined limit
-    if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
-                             ConstantArrayType::getNumAddressingBits(
-                                 Info.Ctx, AllocType, ArrayBound),
-                             ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
-      if (IsNothrow)
+    auto SizeCheck =
+        Info.CheckArraySize(ArraySize.value()->getExprLoc(),
+                            ConstantArrayType::getNumAddressingBits(
+                                Info.Ctx, AllocType, ArrayBound),
+                            ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow);
+    if (SizeCheck != EvalInfo::ArraySizeResult::OK) {
+      // This is where the null result of a non-throwing allocation comes from,
+      // and it is only justified for a bound that really is erroneous. A size
+      // that we refuse to build APValues for says nothing about the
+      // new-expression: failing here leaves the allocation to run time, where
+      // it succeeds, rather than folding it to a null pointer that CodeGen
+      // would then use for every later read of the pointer.
+      if (IsNothrow && SizeCheck == EvalInfo::ArraySizeResult::ErroneousBound)
         return ZeroInitialization(E);
       return false;
     }
diff --git a/clang/test/CodeGenCXX/new-nothrow-constexpr-steps.cpp 
b/clang/test/CodeGenCXX/new-nothrow-constexpr-steps.cpp
new file mode 100644
index 00000000000000..99752ccb90eb2b
--- /dev/null
+++ b/clang/test/CodeGenCXX/new-nothrow-constexpr-steps.cpp
@@ -0,0 +1,54 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -std=c++17 
-fconstexpr-steps=1024 -emit-llvm -o - %s | FileCheck %s
+
+// Reaching -fconstexpr-steps says the evaluator gave up on the array bound, 
not
+// that the bound is erroneous. [expr.new] only lets a *new-expression* whose
+// array bound is erroneous evaluate to a null pointer, so an allocation whose
+// bound we merely could not evaluate has to happen at run time and its result
+// has to be used. Clang used to fold the pointer to null while still emitting
+// the call, so every later read saw nullptr and the block leaked.
+// https://github.com/llvm/llvm-project/issues/246281
+
+namespace std {
+using size_t = decltype(sizeof(0));
+struct nothrow_t {};
+inline constexpr nothrow_t nothrow{};
+} // namespace std
+
+void *operator new[](std::size_t, const std::nothrow_t &) noexcept;
+void operator delete[](void *) noexcept;
+
+// One element more than -fconstexpr-steps allows: representable, so not
+// erroneous, so not a constant either.
+int overLimit() {
+  const int n = 1025;
+  unsigned char *const p = new (std::nothrow) unsigned char[n];
+  if (p) {
+    operator delete[](p);
+    return 1;
+  }
+  return 0;
+}
+
+// The condition is compared against the value the call returned, rather than
+// folded, and the block that is freed is the one that was loaded back.
+// CHECK-LABEL: define{{.*}} @_Z9overLimitv
+// CHECK:      %[[ALLOC:.+]] = call{{.*}} ptr @_ZnamRKSt9nothrow_t
+// CHECK:      store ptr %[[ALLOC]]
+// CHECK:      icmp ne ptr
+// CHECK:      %[[FREED:.+]] = load ptr, ptr
+// CHECK:      call void @_ZdaPv(ptr {{.*}}%[[FREED]])
+
+// A bound no address space can hold is an erroneous new-expression, so the
+// non-throwing allocation still evaluates to a null pointer.
+int tooBig() {
+  unsigned char *const p = new (std::nothrow) unsigned char[4294967296ULL];
+  if (p) {
+    operator delete[](p);
+    return 1;
+  }
+  return 0;
+}
+
+// CHECK-LABEL: define{{.*}} @_Z6tooBigv
+// CHECK-NOT:   icmp
+// CHECK:       ret i32 0
diff --git a/clang/test/SemaCXX/constexpr-new-nothrow-limit.cpp 
b/clang/test/SemaCXX/constexpr-new-nothrow-limit.cpp
new file mode 100644
index 00000000000000..cfb3e2782539c5
--- /dev/null
+++ b/clang/test/SemaCXX/constexpr-new-nothrow-limit.cpp
@@ -0,0 +1,33 @@
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -fconstexpr-steps=1024 
-verify=both %s
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -fconstexpr-steps=1024 
-verify=both -fexperimental-new-constant-interpreter %s
+
+namespace std {
+using size_t = decltype(sizeof(0));
+struct nothrow_t {};
+inline constexpr nothrow_t nothrow{};
+} // namespace std
+
+void *operator new[](std::size_t, const std::nothrow_t &) noexcept;
+void operator delete[](void *) noexcept;
+
+// Past -fconstexpr-steps the evaluator has decided nothing about this
+// allocation, so it is not a constant. It used to come out as a null pointer:
+// the evaluator's own resource limit was reported like an erroneous array
+// bound, and [expr.new] turns an erroneous non-throwing new-expression into a
+// null pointer, which counted as a successful result with no diagnostic. Both
+// interpreters now agree.
+constexpr auto overLimit = new (std::nothrow) unsigned char[1025];
+// both-error@-1 {{constexpr variable 'overLimit' must be initialized by a 
constant expression}}
+// both-note@-2 {{cannot allocate array; evaluated array bound 1025 exceeds 
the limit (1024)}}
+// both-note@-3 {{use -fconstexpr-steps= to increase this limit (=0 will 
remove the limit)}}
+
+// A throwing allocation past the limit always failed and explained itself.
+constexpr auto throwingOverLimit = new unsigned char[1025];
+// both-error@-1 {{constexpr variable 'throwingOverLimit' must be initialized 
by a constant expression}}
+// both-note@-2 {{cannot allocate array; evaluated array bound 1025 exceeds 
the limit (1024)}}
+// both-note@-3 {{use -fconstexpr-steps= to increase this limit (=0 will 
remove the limit)}}
+
+// A bound that no address space can hold is an erroneous new-expression, so a
+// non-throwing allocation of it is a null pointer, without a diagnostic.
+constexpr auto tooBig = new (std::nothrow) unsigned char[4294967296ULL];
+static_assert(tooBig == nullptr);

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to