[clang] [clang][bytecode] Diagnose negative AllocCN element counts (PR #202108)

via cfe-commits cfe-commits at lists.llvm.org
Sun Jun 7 00:21:07 PDT 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)

<details>
<summary>Changes</summary>

Just like we do in AllocN.

---
Full diff: https://github.com/llvm/llvm-project/pull/202108.diff


2 Files Affected:

- (modified) clang/lib/AST/ByteCode/Interp.h (+9-1) 
- (modified) clang/test/AST/ByteCode/new-delete.cpp (+9-3) 


``````````diff
diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index fa77e19afce66..d2ca122d0e805 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -3894,7 +3894,15 @@ inline bool AllocCN(InterpState &S, CodePtr OpPC, const Descriptor *ElementDesc,
     S.Stk.push<Pointer>(0, ElementDesc);
     return true;
   }
-  assert(NumElements.isPositive());
+  if (NumElements.isNegative()) {
+    if (!IsNoThrow) {
+      S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_new_negative)
+          << NumElements.toDiagnosticString(S.getASTContext());
+      return false;
+    }
+    S.Stk.push<Pointer>(0, nullptr);
+    return true;
+  }
 
   if (!CheckArraySize(S, OpPC, static_cast<uint64_t>(NumElements)))
     return false;
diff --git a/clang/test/AST/ByteCode/new-delete.cpp b/clang/test/AST/ByteCode/new-delete.cpp
index f31851c98213c..7481eccd2c03a 100644
--- a/clang/test/AST/ByteCode/new-delete.cpp
+++ b/clang/test/AST/ByteCode/new-delete.cpp
@@ -1101,12 +1101,18 @@ namespace BaseCompare {
 }
 
 
-namespace NegativeArraySize { 
+namespace NegativeArraySize {
   constexpr void f() { // both-error {{constexpr function never produces a constant expression}}
     int x = -1;
-    int *p = new int[x]; //both-note {{cannot allocate array; evaluated array bound -1 is negative}} 
+    int *p = new int[x]; //both-note {{cannot allocate array; evaluated array bound -1 is negative}}
   }
-} // namespace NegativeArraySize
+
+  struct S {};
+  constexpr void f1() { // both-error {{constexpr function never produces a constant expression}}
+    int x = -1;
+    int *p = new int[x]; //both-note {{cannot allocate array; evaluated array bound -1 is negative}}
+  }
+}
 
 namespace NewNegSizeNothrow {
   constexpr int get_neg_size() {

``````````

</details>


https://github.com/llvm/llvm-project/pull/202108


More information about the cfe-commits mailing list