[clang] [clang][DebugInfo] Fix iterator invalidation during EmitGlobalVariable (PR #72415)

Michael Buch via cfe-commits cfe-commits at lists.llvm.org
Wed Nov 15 09:18:09 PST 2023


https://github.com/Michael137 created https://github.com/llvm/llvm-project/pull/72415

This patch fixes an issue introduced in https://github.com/llvm/llvm-project/pull/71780 where, if `EmitGlobalVariable` triggered a call to `CreateRecordStaticField` it would invalidate the `StaticDataMemberDefinitionsToEmit` iterator that
is currently in-use.

This fixes a crash reported in https://github.com/llvm/llvm-project/pull/71780#issuecomment-1812589911

>From 5aeb017edb3b2b9c4a427b4479fc9498f175c608 Mon Sep 17 00:00:00 2001
From: Michael Buch <michaelbuch12 at gmail.com>
Date: Wed, 15 Nov 2023 16:55:24 +0000
Subject: [PATCH] [clang][DebugInfo] Fix iterator invalidation during
 EmitGlobalVariable

This patch fixes an issue introduced in
https://github.com/llvm/llvm-project/pull/71780 where,
if `EmitGlobalVariable` triggered a call to
`CreateRecordStaticField` it would invalidate the
`StaticDataMemberDefinitionsToEmit` iterator that
is currently in-use.

This fixes a crash reported in
https://github.com/llvm/llvm-project/pull/71780#issuecomment-1812589911
---
 clang/lib/CodeGen/CGDebugInfo.cpp | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp b/clang/lib/CodeGen/CGDebugInfo.cpp
index a201cf03c22f711..d19e23e1392f4b4 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -5830,8 +5830,13 @@ void CGDebugInfo::setDwoId(uint64_t Signature) {
 }
 
 void CGDebugInfo::finalize() {
-  for (auto const *VD : StaticDataMemberDefinitionsToEmit) {
-    assert(VD->isStaticDataMember());
+  // We can't use a for-each here because `EmitGlobalVariable`
+  // may push new decls into `StaticDataMemberDefinitionsToEmit`,
+  // which would invalidate any iterator.
+  for (size_t i = 0; i < StaticDataMemberDefinitionsToEmit.size(); ++i) {
+    auto const *VD = StaticDataMemberDefinitionsToEmit[i];
+
+    assert(VD && VD->isStaticDataMember());
 
     if (DeclCache.contains(VD))
       continue;



More information about the cfe-commits mailing list