https://github.com/steakhal created 
https://github.com/llvm/llvm-project/pull/191697

While the ASTContext has more things inside, I think we should at least clear 
the TUDecl so that when traversing the (dangling) AST would immediately step on 
the null-dereference instead of chasing dangling pointers and crash later.

I was bitten by this in #191058.

This commit should be NFC - assuming that people didn't traverse already 
dangling ASTs.

From 2a67e7213aea6e672467f3acb3a6108d1c848550 Mon Sep 17 00:00:00 2001
From: Balazs Benics <[email protected]>
Date: Sun, 12 Apr 2026 11:33:37 +0100
Subject: [PATCH] [clang] Clear ASTContext::TUDecl in 'cleanup' for easier
 debugging

While the ASTContext has more things inside, I think we should at least
clear the TUDecl so that when traversing the (dangling) AST would
immediately step on the null-dereference instead of chasing dangling
pointers and crash later.

I was bitten by this in #191058.

This commit should be NFC - assuming that people didn't traverse already
dangling ASTs.
---
 clang/include/clang/AST/ASTContext.h | 2 ++
 clang/lib/AST/ASTContext.cpp         | 1 +
 2 files changed, 3 insertions(+)

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index ba1b58489c327..fc39f6af0cd9a 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -1268,6 +1268,8 @@ class ASTContext : public RefCountedBase<ASTContext> {
   bool isInSameModule(const Module *M1, const Module *M2) const;
 
   TranslationUnitDecl *getTranslationUnitDecl() const {
+    assert(TUDecl && "TUDecl might have been reset by 'cleanup' likely because 
"
+                     "'CodeGenOpts.ClearASTBeforeBackend' was set.");
     assert(TUDecl->getMostRecentDecl() == TUDecl &&
            "The active TU is not current one!");
     return TUDecl->getMostRecentDecl();
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index ee7f823b014b2..24a9295c4a2e6 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -943,6 +943,7 @@ void ASTContext::cleanup() {
     Value.second->~PerModuleInitializers();
   ModuleInitializers.clear();
 
+  TUDecl = nullptr;
   XRayFilter.reset();
   NoSanitizeL.reset();
 }

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

Reply via email to