Skip to content

Commit 2e38c50

Browse files
[clang-repl] Fix remove invalidates iterators in CleanUpPTU() (#85378)
Using remove() on DeclContext::lookup_result list invalidates iterators. This assertion failure was one (fortunate) symptom: ``` clang/include/clang/AST/DeclBase.h:1337: reference clang::DeclListNode::iterator::operator*() const: Assertion `Ptr && "dereferencing end() iterator"' failed. ```
1 parent 89ef313 commit 2e38c50

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

clang/include/clang/AST/DeclContextInternals.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ class StoredDeclsList {
205205
Data.setPointer(Head);
206206
}
207207

208-
/// Return an array of all the decls that this list represents.
208+
/// Return the list of all the decls.
209209
DeclContext::lookup_result getLookupResult() const {
210210
return DeclContext::lookup_result(Data.getPointer());
211211
}

clang/lib/Interpreter/IncrementalParser.cpp

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -375,16 +375,22 @@ void IncrementalParser::CleanUpPTU(PartialTranslationUnit &PTU) {
375375
TranslationUnitDecl *MostRecentTU = PTU.TUPart;
376376
TranslationUnitDecl *FirstTU = MostRecentTU->getFirstDecl();
377377
if (StoredDeclsMap *Map = FirstTU->getPrimaryContext()->getLookupPtr()) {
378-
for (auto I = Map->begin(); I != Map->end(); ++I) {
379-
StoredDeclsList &List = I->second;
378+
for (auto &&[Key, List] : *Map) {
380379
DeclContextLookupResult R = List.getLookupResult();
380+
std::vector<NamedDecl *> NamedDeclsToRemove;
381+
bool RemoveAll = true;
381382
for (NamedDecl *D : R) {
382-
if (D->getTranslationUnitDecl() == MostRecentTU) {
383+
if (D->getTranslationUnitDecl() == MostRecentTU)
384+
NamedDeclsToRemove.push_back(D);
385+
else
386+
RemoveAll = false;
387+
}
388+
if (LLVM_LIKELY(RemoveAll)) {
389+
Map->erase(Key);
390+
} else {
391+
for (NamedDecl *D : NamedDeclsToRemove)
383392
List.remove(D);
384-
}
385393
}
386-
if (List.isNull())
387-
Map->erase(I);
388394
}
389395
}
390396
}

0 commit comments

Comments
 (0)