Author: Timm Baeder
Date: 2025-04-26T05:03:28+02:00
New Revision: 58d60a4df92d57941f6d47d46bd5025fe6298c93

URL: 
https://github.com/llvm/llvm-project/commit/58d60a4df92d57941f6d47d46bd5025fe6298c93
DIFF: 
https://github.com/llvm/llvm-project/commit/58d60a4df92d57941f6d47d46bd5025fe6298c93.diff

LOG: [clang][bytecode] Diagnose destroying already dead locals (#137357)

Added: 
    

Modified: 
    clang/lib/AST/ByteCode/Interp.h
    clang/test/AST/ByteCode/lifetimes.cpp

Removed: 
    


################################################################################
diff  --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index ac5e095ffa1f1..c1970f064cef5 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -2197,6 +2197,21 @@ inline bool SubPtr(InterpState &S, CodePtr OpPC) {
 
//===----------------------------------------------------------------------===//
 
 inline bool Destroy(InterpState &S, CodePtr OpPC, uint32_t I) {
+  assert(S.Current->getFunction());
+
+  // FIXME: We iterate the scope once here and then again in the destroy() call
+  // below.
+  for (auto &Local : S.Current->getFunction()->getScope(I).locals_reverse()) {
+    const Pointer &Ptr = S.Current->getLocalPointer(Local.Offset);
+
+    if (Ptr.getLifetime() == Lifetime::Ended) {
+      auto *D = cast<NamedDecl>(Ptr.getFieldDesc()->asDecl());
+      S.FFDiag(D->getLocation(), diag::note_constexpr_destroy_out_of_lifetime)
+          << D->getNameAsString();
+      return false;
+    }
+  }
+
   S.Current->destroy(I);
   return true;
 }

diff  --git a/clang/test/AST/ByteCode/lifetimes.cpp 
b/clang/test/AST/ByteCode/lifetimes.cpp
index 43039d0c766e9..17f8d4e24bd85 100644
--- a/clang/test/AST/ByteCode/lifetimes.cpp
+++ b/clang/test/AST/ByteCode/lifetimes.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -fexperimental-new-constant-interpreter 
-verify=expected,both %s
-// RUN: %clang_cc1 -verify=ref,both %s
+// RUN: %clang_cc1 -verify=expected,both -std=c++20 %s 
-fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 -verify=ref,both      -std=c++20 %s
 
 /// FIXME: Slight 
diff erence in diagnostic output here.
 
@@ -68,3 +68,17 @@ namespace PrimitiveMoveFn {
     const float &x = y;
   }
 }
+
+/// FIXME:
+///  1) This doesn't work for parameters
+///  2) We need to do this for all fields in composite scenarios
+namespace PseudoDtor {
+  typedef int I;
+  constexpr bool foo() { // both-error {{never produces a constant expression}}
+    {
+      int a; // both-note {{destroying object 'a' whose lifetime has already 
ended}}
+      a.~I();
+    }
+    return true;
+  }
+}


        
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to