clang 24.0.0git
ErrorRecovery.cpp
Go to the documentation of this file.
1//===--------- ErrorRecovery.cpp - Declaration State Recovery -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception.
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements declaration state recovery for failed
10// partial translation units (PTUs), restoring declaration state to
11// the state of the previous PTU.
12//
13//===----------------------------------------------------------------------===//
14
15#include "ErrorRecovery.h"
16
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclCXX.h"
24#include "clang/Sema/Sema.h"
25
26#define DEBUG_TYPE "clang-repl"
27
28namespace clang {
29
30/// -----------------------------------------------------------------------
31//////////////////////// PTUMutationActions::Helpers ///////////////////////
32/// -----------------------------------------------------------------------
33
34/// ASTDeclUnmerger handles two cases based on whether a declaration should be
35/// discarded or belongs to a previous PTU: it unlinks discarded declarations
36/// from the compiler's shared state, or restores their previous state using
37/// the MutationRecord information.
38class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
39private:
40 PTUID ID;
42 [[maybe_unused]] PTUMutationActions &Actions;
43 Sema &SemaRef;
44 [[maybe_unused]] SemaCacheReverter &SemaCache;
45 MutationRecord *Rec = nullptr;
46
47 bool isFromThisPTU(const void *Ptr) const {
48 return Tracker.isFromThisPTU(Ptr, ID);
49 }
50
51 bool isDiscarded(const void *Ptr) const {
52 return Tracker.isFromThisPTU(Ptr, ID);
53 }
54
55 bool hasRecord() const { return Rec != nullptr; }
56
57 MutationRecord &Record() { return *Rec; }
58
59 bool hasNoPreviousDecl(const Decl *D) {
60 return D->getPreviousDecl() == nullptr;
61 }
62
63 template <typename DeclT> DeclT *findSurvivor(DeclT *D) const {
64 for (Decl *It = D->getMostRecentDecl(); It; It = It->getPreviousDecl())
65 if (!isFromThisPTU(It))
66 return dyn_cast<DeclT>(It);
67 return nullptr;
68 }
69
70 template <typename DeclT>
71 void resetRedeclLink(Redeclarable<DeclT> *DBase, DeclT *Survivor) {
72 auto *Latest = static_cast<DeclT *>(DBase);
73
74 // Rebuild First -> ... -> Survivor -> ... -> Latest as
75 // First -> ... -> Survivor.
76 Latest->getFirstDecl()->RedeclLink.setLatest(Survivor);
77
78 // The chain is circular: a withdrawn declaration still linked into it can
79 // never walk back around to itself, so redecls() on one would not
80 // terminate. Give each withdrawn declaration a chain of its own.
81 for (DeclT *Dead = Latest; Dead != Survivor;) {
82 DeclT *Next = Dead->getPreviousDecl();
83 Dead->First = Dead;
84 Dead->RedeclLink =
85 Redeclarable<DeclT>::LatestDeclLink(Tracker.getASTContext());
86 Dead = Next;
87 }
88 }
89
90 template <typename DeclT> void unlinkRedeclChain(DeclT *D) {
91 DeclT *Latest = D->getMostRecentDecl();
92 if (DeclT *Survivor = findSurvivor(D))
93 resetRedeclLink(Latest, Survivor);
94 }
95
96 /// Remove D from its DeclContext lookup map and restore the previous
97 /// declaration if it was replaced.
98 void removeFromDCLookup(NamedDecl *ND) {
99 // Find any declaration from the previous PTU in the redecl chain that may
100 // have been replaced by this declaration.
101 if (!ND->getDeclName())
102 return;
103
104 NamedDecl *Survivor = findSurvivor(ND);
105 DeclarationName Name = ND->getDeclName();
106
107 DeclContext *DC = ND->getDeclContext();
108 do {
109 DeclContext *Primary = DC->getPrimaryContext();
110 if (StoredDeclsMap *Map = Primary->getLookupPtr()) {
111 auto Pos = Map->find(Name);
112 if (Pos != Map->end()) {
113 StoredDeclsList &List = Pos->second;
114 List.remove(ND);
115
116 if (Survivor) {
117 List.addOrReplaceDecl(Survivor);
118 }
119 if (List.isNull())
120 Map->erase(Pos);
121 }
122 }
123 } while ((DC->isTransparentContext() || DC->isInlineNamespace()) &&
124 (DC = DC->getParent()));
125 }
126
127 /// Remove entry from "C"'s lookup tables
128 void removeFromLookups(NamedDecl *D) {
129 if (D->getDeclName().isEmpty())
130 return;
131
132 if (D->getDeclName().isIdentifier() && D->getDeclName().getFETokenInfo() &&
133 !D->getLangOpts().ObjC && !D->getLangOpts().CPlusPlus)
134 SemaRef.IdResolver.RemoveDecl(D);
135
137 if (StoredDeclsMap *Map = ECCD->getPrimaryContext()->getLookupPtr()) {
138 auto It = Map->find(D->getDeclName());
139 if (It != Map->end())
140 It->second.remove(D);
141 }
142 }
143
144 void detachDefData(CXXRecordDecl *RD) {
145 for (auto *I : RD->redecls())
146 cast<CXXRecordDecl>(I)->DefinitionData = nullptr;
147 }
148
149 void repairLexicalChain(DeclContext *DC) {
150 Decl *Prev = nullptr;
151 for (Decl *Cur = DC->FirstDecl; Cur; Cur = Cur->getNextDeclInContext()) {
152 if (isFromThisPTU(Cur)) {
153 if (Prev) {
154 DC->LastDecl = Prev;
155 Prev->NextInContextAndBits.setPointer(nullptr);
156 } else {
157 DC->FirstDecl = DC->LastDecl = nullptr; // nothing survives
158 }
159 return;
160 }
161 Prev = Cur;
162 }
163 }
164
165 class ScopedMutationRecord {
166 MutationRecord *&Rec;
167 MutationRecord *OldRec;
168
169 public:
170 ScopedMutationRecord(MutationRecord *&Rec, MutationRecord *R)
171 : Rec(Rec), OldRec(Rec) {
172 Rec = R;
173 }
174
175 ~ScopedMutationRecord() { Rec = OldRec; }
176
177 ScopedMutationRecord(const ScopedMutationRecord &) = delete;
178 ScopedMutationRecord &operator=(const ScopedMutationRecord &) = delete;
179 };
180
181 void VisitDeclContext(DeclContext *DC) {
182 ScopedMutationRecord Guard(Rec, nullptr);
183 for (Decl *D : llvm::SmallVector<Decl *, 8>(DC->decls()))
184 Visit(D);
185 repairLexicalChain(DC);
186 }
187
188 template <typename T>
189 void removeSpec(llvm::FoldingSetVector<T> &FSV,
190 llvm::function_ref<bool(const void *)> ShouldStop) {
191 SmallVector<T *, 8> Remaining;
192
193 for (T &Node : FSV) {
194 if (ShouldStop(&Node))
195 break;
196 Remaining.push_back(&Node);
197 }
198
199 FSV.clear();
200
201 for (T *Node : Remaining)
202 FSV.insert(Node);
203 }
204
205public:
206 friend class PTUMutationActions;
207
209 PTUMutationActions &Action, Sema &SemaRef,
210 SemaCacheReverter &SemaCache)
211 : ID(ID), Tracker(Tracker), Actions(Action), SemaRef(SemaRef),
212 SemaCache(SemaCache) {}
213
217 const auto &Live = RD.data();
218#define FIELD(Name, Width, Merge) FP.Name = Live.Name;
219#include "clang/AST/CXXRecordDeclDefinitionBits.def"
220 return FP;
221 }
222
224 CXXRecordDecl &RD) {
225 auto &Live = RD.data();
226#define FIELD(Name, Width, Merge) Live.Name = FP.Name;
227#include "clang/AST/CXXRecordDeclDefinitionBits.def"
228 }
229
230 // Generic across every other footprint type exclusing DefinitionDataFootprint
231 // -- ClassSpecializationFootprint, VarSpecializationFootprint,
232 // FunctionSpecializationFootprint, MemberSpecializationFootprint.
233 template <typename FootprintT, typename OwnerT>
234 static FootprintT createFootprint(const OwnerT &Owner) {
235 FootprintT FP;
236 FP.update(Owner);
237 return FP;
238 }
239 template <typename FootprintT, typename OwnerT>
240 static void restoreFootprint(const FootprintT &FP, OwnerT &Owner) {
241 FP.restore(Owner);
242 }
243
245 ScopedMutationRecord Guard(Rec, &R);
246 Visit(D);
247 }
248
249 void VisitDecl(Decl *D) {
250 if (!isDiscarded(D))
251 return;
252
253 if (auto *DC = dyn_cast<DeclContext>(D))
254 VisitDeclContext(DC);
255 }
256
257 /// Remove ND from its context and the lookup tables, and make the
258 /// declaration it redeclares visible again. Called by VisitRedeclarable()
259 /// before it restores the redeclaration chain, which hides that declaration.
261 if (!isDiscarded(ND))
262 return;
263 // The templated decl of a template is not a member of its context: the
264 // template is.
266 if (!DC->containsDecl(ND))
267 return;
268 removeFromDCLookup(ND);
269 removeFromLookups(ND);
270 }
271
272 /// Remove D like VisitNamedDecl() and restore its redeclaration chain to the
273 /// previous state.
274 template <typename DeclT> void VisitRedeclarable(Redeclarable<DeclT> *DBase) {
275 auto *D = static_cast<DeclT *>(DBase);
277 if (hasNoPreviousDecl(D) || isFromThisPTU(D->getCanonicalDecl()))
278 return;
279 unlinkRedeclChain(D);
280 }
281
283 void VisitTagDecl(TagDecl *TD);
286 void VisitVarDecl(VarDecl *VD);
287 void VisitEnumDecl(EnumDecl *ED);
294 void VisitTranslationUnitDecl(TranslationUnitDecl *D) { VisitDeclContext(D); }
295};
296
297static DeclShape classifyShape(const Decl *D) {
298 // Base shape -- most-derived first.
300 return DeclShape::Template;
301 else if (isa<EnumDecl>(D))
302 return DeclShape::Enum;
303 else if (isa<FunctionDecl>(D))
304 return DeclShape::Function;
305 else if (isa<VarDecl>(D))
306 return DeclShape::Var;
307 else if (isa<CXXRecordDecl>(D))
308 return DeclShape::Class;
310 return DeclShape::Typedef;
311 else
312 return DeclShape::None;
313}
314
315/// This is called when a decl is created or seen for the first time. It also
316/// checks whether the decl is still in a mutation-sensitive state, meaning that
317/// a later PTU can modify it. Because of this, we need to track its state. This
318/// function provides a single place to decide whether a decl needs to be
319/// committed or not. It is called from CommitDecl to determine whether a new
320/// decl needs to be tracked.
321///
322/// This requires Decl to determine which mutation kinds apply to the shape and
323/// whether they need to be tracked. In the future, if a new mutation site is
324/// found for a shape, it should be added here along with the logic to determine
325/// whether the decl is still in an open, modifiable state.
327 // TODO: Add logic to determine which mutation kinds require explicit
328 // tracking, similar to how MutationKind::DefinitionData is handled.
329 uint32_t Kinds = 0;
330 switch (S) {
331 case DeclShape::Class: {
332 const auto *RD = cast<CXXRecordDecl>(D);
333 if (RD->hasDefinition() && RD == RD->getDefinition()) {
334 // Do we really need to create a DefData chain here? Usually, an implicit
335 // decl can be mutated later after the definition. If it is already wired
336 // correctly, there is nothing to mutate or track here.
337 //
338 // Save the current DefinitionData because it may change later.
339 if (RD->needsImplicitDefaultConstructor() ||
340 RD->needsImplicitCopyConstructor() ||
341 RD->needsImplicitCopyAssignment() ||
342 RD->needsImplicitMoveConstructor() ||
343 RD->needsImplicitMoveAssignment() || RD->needsImplicitDestructor())
344 Kinds |= uint32_t(MutationKind::DefinitionData);
345 }
346 Kinds |= uint32_t(MutationKind::SpecInfo) |
347 uint32_t(MutationKind::MemberSpecInfo);
348 break;
349 }
350 case DeclShape::Function:
351 Kinds |= uint32_t(MutationKind::SpecInfo) |
352 uint32_t(MutationKind::MemberSpecInfo);
353 break;
354 case DeclShape::Var:
355 Kinds |= uint32_t(MutationKind::SpecInfo) |
356 uint32_t(MutationKind::MemberSpecInfo);
357 break;
358 case DeclShape::Enum:
359 Kinds |= uint32_t(MutationKind::MemberSpecInfo);
360 break;
361 case DeclShape::Template:
362 case DeclShape::Typedef:
363 case DeclShape::None:
364 break;
365 }
366 return Kinds;
367}
368
369template <typename T>
370static bool differsFromLast(IncrementalStateTracker &Tracker, const Decl *Owner,
371 MutationKind K, const T &LiveValue) {
372 const auto *Last = Tracker.getFootprints().mostRecent<T>(Owner, K);
373 assert(Last && "baseline missing at verify time");
374 return !Last || *Last != LiveValue;
375}
376
377template <typename FootprintT, typename OwnerT>
378static FootprintT Footprint(const OwnerT &Owner) {
379 FootprintT FP;
380 FP.update(Owner);
381 return FP;
382}
383
384/// The single place to check whether a kind has actually changed.
385///
386/// This handles both listener-less kinds and listener-unconfirmed mutations
387/// (currently SpecInfo and MemberSpecInfo). Mutations can be detected by
388/// both SweepTracker and the listener re-check. SweepTracker tracks hidden
389/// and listener-unconfirmed mutations in case the listener misses them. If the
390/// listener catches a mutation, it is removed from SweepTracker; see
391/// PTUStateInfo::verifyMutations. both use this functionality to verify
392/// mutation kind.
393///
394/// This check uses the decl shape and mutation kind to determine whether the
395/// decl has changed from its previous state.
396///
397/// Similarly, if a new hidden or listener-unconfirmed mutation is introduced
398/// in DeclNeedingTracking, and we need to determine whether it changed the
399/// previous state, the corresponding logic should be added here too
400/// when the kind is categorized as a hidden mutation from the listener.
402 uint32_t FlaggedKinds) {
403 uint32_t Verified = 0;
404 switch (S) {
405 case DeclShape::Class: {
406 const auto *RD = cast<CXXRecordDecl>(D);
407 if (FlaggedKinds & uint32_t(MutationKind::SpecInfo)) {
408 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RD))
409 if (differsFromLast(Tracker, Spec, MutationKind::SpecInfo,
411 Verified |= uint32_t(MutationKind::SpecInfo);
412 } else if (FlaggedKinds & uint32_t(MutationKind::MemberSpecInfo)) {
413 if (differsFromLast(Tracker, RD, MutationKind::MemberSpecInfo,
415 Verified |= uint32_t(MutationKind::MemberSpecInfo);
416 }
417 break;
418 }
419 case DeclShape::Function: {
420 const auto *FD = cast<FunctionDecl>(D);
421 if (FlaggedKinds & uint32_t(MutationKind::SpecInfo)) {
422 if (differsFromLast(Tracker, FD, MutationKind::SpecInfo,
424 Verified |= uint32_t(MutationKind::SpecInfo);
425 } else if (FlaggedKinds & uint32_t(MutationKind::MemberSpecInfo)) {
426 if (differsFromLast(Tracker, FD, MutationKind::MemberSpecInfo,
428 Verified |= uint32_t(MutationKind::MemberSpecInfo);
429 }
430 break;
431 }
432 case DeclShape::Var: {
433 const auto *VD = cast<VarDecl>(D);
434 if (FlaggedKinds & uint32_t(MutationKind::SpecInfo)) {
435 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
436 if (differsFromLast(Tracker, Spec, MutationKind::SpecInfo,
438 Verified |= uint32_t(MutationKind::SpecInfo);
439 } else if (FlaggedKinds & uint32_t(MutationKind::MemberSpecInfo)) {
440 if (differsFromLast(Tracker, VD, MutationKind::MemberSpecInfo,
442 Verified |= uint32_t(MutationKind::MemberSpecInfo);
443 }
444 break;
445 }
446 case DeclShape::Enum: {
447 const auto *ED = cast<EnumDecl>(D);
448 if (FlaggedKinds & uint32_t(MutationKind::MemberSpecInfo)) {
449 if (differsFromLast(Tracker, ED, MutationKind::MemberSpecInfo,
451 Verified |= uint32_t(MutationKind::MemberSpecInfo);
452 }
453 break;
454 }
455 case DeclShape::Template:
456 case DeclShape::Typedef:
457 case DeclShape::None:
458 break;
459 }
460 return Verified;
461}
462
463/// A single function called during commit and restore (when the PTU is
464/// uncommitted).
465///
466/// This is where we check for any hidden mutations previously registered with
467/// SweepTracker. If a mutation is confirmed, we record it in the
468/// PTUStateInfo mutation set via OnConfirmed.
469template <typename OnConfirmedFn>
470void SweepTracker::sweep(PTUMutationActions &Act, OnConfirmedFn OnConfirmed) {
471 for (auto &Entry : Active) {
472 const Decl *D = Entry.getFirst();
473 uint32_t StillOpen = Entry.getSecond();
475 if (uint32_t Newly = Act.confirmMutation(D, S, StillOpen)) {
476 OnConfirmed(D, S, Newly);
477 }
478 }
479}
480
481/// These kinds have listeners, but listeners alone cannot reliably detect
482/// real changes. Compare the current value with the last known value, as we
483/// do for kinds without listeners.
484///
485/// These kinds are also checked by the sweep to catch changes that listeners
486/// miss or report incorrectly.
487///
488/// Currently, SpecInfo/MemberSpecInfo are tracked from the listener side.
489/// This applies when the listener reports that a mutation may have happened
490/// but it has not been confirmed yet.
491///
492/// Not all hidden mutations are tracked here; they are tracked in
493/// SweepTracker. This logic applies only to listener-unconfirmed mutations.
495 uint32_t(MutationKind::SpecInfo) | uint32_t(MutationKind::MemberSpecInfo);
496
497/// Start tracking D for mutation kinds that need verification.
498/// Called when a new mutation is committed or an undone mutation is restored.
499/// we apply this for listener unconfirmed cases.
501 if (uint32_t Flag = Kinds & KindsNeedingVerification)
502 HiddenMutationTracker.track(D, Flag);
503}
504
505/// Stop tracking Decl D when it no longer needs verification.
506/// Re-check DeclNeedingTracking to see if a later PTU can still update D.
508 uint32_t Confirmed) {
509 uint32_t Flag = Confirmed & KindsNeedingVerification;
510 if (!Flag || !HiddenMutationTracker.isTrackedFor(D, Flag))
511 return;
512 uint32_t StillOpen = DeclNeedingTracking(S, D) & Flag;
513 uint32_t Closed = Flag & ~StillOpen;
514 if (Closed)
515 HiddenMutationTracker.untrack(D, Closed);
516}
517
518// Shared sweep-tracking logic(track/untrack) for
519// commitClass/commitFunction/commitVar/commitEnum.
521 uint32_t Kinds, bool IsNew) {
522 if (IsNew)
523 trackForSweep(D, Kinds);
524 else
525 untrackIfClosed(D, S, Kinds);
526}
527
528/// Verify recorded mutations and remove any false mutation ones. If none of a
529/// decl’s mutation kinds are confirmed, remove the record entirely so
530/// restore() does not pop chain entries that were never written.
532 Mutations.remove_if([&](auto &Entry) -> bool {
533 const Decl *D = Entry.first;
534 MutationRecord &Rec = Entry.second;
536 if (!Flagged)
537 return false;
538 uint32_t Confirmed = Actions.confirmMutation(D, Rec.S, Flagged);
539 /// untrack kind from SweepTracker if confirmed.
540 Actions.untrackIfClosed(D, Rec.S, Confirmed);
541 Rec.MutationFlags = (Rec.MutationFlags & ~Flagged) | Confirmed;
542 return Rec.MutationFlags == 0;
543 });
544}
545
546static bool isReachableFromThisTU(const Decl *D,
547 const TranslationUnitDecl *ThisTU) {
548 const DeclContext *DC = D->getLexicalDeclContext();
549
550 for (; DC; DC = DC->getLexicalParent()) {
551 if (DC->containsDecl(const_cast<Decl *>(D))) {
552 const DeclContext *Parent = DC;
553
554 while (Parent && !Parent->isTranslationUnit())
555 Parent = Parent->getLexicalParent();
556
557 return Parent == ThisTU;
558 }
559 }
560
561 return false;
562}
563
564/// -----------------------------------------------------------------------
565//////////////////////// PTUMutationActions::commit ///////////////////////
566/// -----------------------------------------------------------------------
567
568/// These are the places where the incremental state of a declaration is
569/// registered based on its DeclKind.
570///
571/// For a declaration created in the current PTU, its state is committed
572/// to the tracker. For an existing declaration modified in the current
573/// PTU, its previous state is recorded so it can be restored on undo.
574///
575/// The idea is to keep state tracking limited to a small set of known
576/// mutation sites for each DeclKind, instead of tracking changes
577/// everywhere in Clang.
578///
579/// Currently, this covers Class, Function, Enum, Template, etc. Each
580/// DeclKind is associated with the mutation kinds that need to be tracked.
581///
582/// When adding a new mutation site, it should be handled according to
583/// the corresponding DeclKind and mutation kind.
584
586 if (isa<NamespaceDecl>(D))
587 return true;
588 if (const auto *RD = dyn_cast<CXXRecordDecl>(D))
589 return RD->isCompleteDefinition();
590 return false;
591}
592
594 for (const Decl *D : DC->decls()) {
595 if (shouldRecurseInto(D))
597 CommitDecl(D, nullptr);
598 }
599}
600
603 return;
604
605 MutationRecord NewRec;
606 if (!R) {
608 if (S == DeclShape::None)
609 return;
610
611 // Handle cases where baseline info needs to be created, as well as cases
612 // where a declaration has already completed all required mutations. For
613 // example, member specs may already be fully populated, so we should avoid
614 // creating spec info blindly.
615 uint32_t Kinds = DeclNeedingTracking(S, D);
616 if (!Kinds)
617 return;
618
619 NewRec.add(Kinds);
620 R = &NewRec;
621 }
622
623 MutationRecord *OldRec = Rec;
624 Rec = R;
625 Visit(D);
626 Rec = OldRec;
627}
628
630 PTUStateInfo &Cur = Tracker.current();
631 assert(!Cur.Commited && "Current PTUState is already commited");
632 Cur.ThisPTU = ThisTU;
633
634 LLVM_DEBUG({ llvm::dbgs() << "Commit ThisTU\n"; });
635
636 // 1. Verify any unconfirmed mutation (see : KindsNeedingVerification)
637 // reported by the listener, whether true or false.
638 Cur.verifyMutations(*this);
639 // 2. Catch any mutation-sensitive state of Decl from previous PTUs that
640 // ASTMutationListener cannot catch if it was registered during a
641 // previous PTU commit.
642 Tracker.getHiddenMutationTracker().sweep(
643 *this, [&](const Decl *D, DeclShape S, uint32_t K) {
644 Cur.noteMutated(D, S, K);
645 });
646
647 // 3. Update the tracking state of declarations from the previous PTU using
648 // Cur.Mutations reported by ASTMutationListener and HiddenMutationTracker.
649 for (auto &[D, Rec] : Cur.Mutations)
650 CommitDecl(D, &Rec);
651
652 // 4. Cur.ImplicitlyGeneratedDecls: Declarations created by this PTU. Register
653 // them for
654 // tracking if they have mutation-sensitive state that can be modified by
655 // later PTUs.
656 //
657 // CommitDecl: Decides what to do with declarations created by the current
658 // PTU, such as whether a declaration needs to be tracked or not.
659 for (const Decl *D : Cur.ImplicitlyGeneratedDecls) {
660 if (isReachableFromThisTU(D, ThisTU))
661 continue;
662 if (shouldRecurseInto(D))
664 CommitDecl(D, nullptr);
665 }
666
667 // Iterate over all declarations in this TU and register them whether they
668 // need explicit tracking.
669 VisitDeclContext(ThisTU);
670
671 Cur.Commited = true;
672}
673
674/// -----------------------------------------------------------------------
675//////////////////////// PTUMutationActions::restore //////////////////////
676/// -----------------------------------------------------------------------
677
678/// These are the places where we restore or undo/unlink the incremental state
679/// of a decl based on its DeclShape.
680///
681/// The same DeclShape -> mutation kind relationship used during commit is
682/// followed here. For declarations created in the current PTU, unlinks them
683/// from the compiler shared state. For existing declarations that were
684/// modified, restore brings them back to their previous state.
685///
686/// When adding a new mutation site that requires restoring or unlinking
687/// state, it should be handled according to the corresponding DeclShape
688/// and mutation kind.
689
691 // we don't care about the decl which complete chain is part belong to
692 // current PTU.
693 if (!Tracker.isFromThisPTU(D->getCanonicalDecl(), ID) ||
695 VisitDeclContext(D);
697}
698
700 // Some members of a definition are visible outside of it: the enumerators
701 // of an unscoped enumeration, and in C the tags and enumerators declared
702 // in a structure or union.
704 VisitDeclContext(D);
705
707}
708
710 if (isDiscarded(RD)) {
711 CXXRecordDecl *Def = RD->getDefinition();
712 CXXRecordDecl *Canon = RD->getCanonicalDecl();
713 bool DetachDefData = (Def && isFromThisPTU(Def) && !isFromThisPTU(Canon));
715 unlinkRedeclChain<TagDecl>(RD);
716 else
717 VisitTagDecl(RD);
718 if (DetachDefData)
719 detachDefData(Canon);
720 return;
721 }
722
723 if (!hasRecord())
724 return;
725
726 // else perform restoration of decl state.
727}
728
730 // unlink Discarded decl.
731 if (isDiscarded(FD)) {
733 return;
734 }
735
736 if (!hasRecord())
737 return;
738
739 // Restore decl state.
740}
741
743 // Unlinking discared Decl.
744 if (isDiscarded(VD)) {
746 return;
747 }
748
749 if (!hasRecord())
750 return;
751
752 // Restore decl state.
753}
754
756 // Unlink Discarded Decl.
757 if (isDiscarded(ED)) {
758 VisitTagDecl(ED);
759 return;
760 }
761
762 if (!hasRecord())
763 return;
764
765 // Restore decl state.
766}
767
769 // Unlinking discared Decl.
770 if (isDiscarded(CT)) {
771 NamedDecl *Templated = CT->getTemplatedDecl();
772 if (auto *RD = dyn_cast<CXXRecordDecl>(Templated)) {
773 if (CXXRecordDecl *Def = RD->getDefinition(); Def && isFromThisPTU(Def))
774 detachDefData(RD);
776 }
778 }
779
780 if (!hasRecord())
781 return;
782
783 // Restore Decl.
784 if (Record().has(MutationKind::SpecializationAdded)) {
785 auto &Specs = CT->getSpecializations();
786 removeSpec(Specs, [&](const void *Ptr) -> bool {
787 return Tracker.isFromThisPTU(Ptr, ID);
788 });
789 }
790}
791
793 // Unlinking discared Decl.
794 if (isDiscarded(FTD)) {
795 if (!isFromThisPTU(FTD->getCanonicalDecl())) {
796 if (auto *FD = dyn_cast<FunctionDecl>(FTD->getTemplatedDecl()))
797 unlinkRedeclChain(FD);
798 }
800 }
801
802 if (!hasRecord())
803 return;
804
805 // Restore Decl.
806}
807
809 // Unlinking discared Decl.
810 if (isDiscarded(VTD)) {
811 if (!isFromThisPTU(VTD->getCanonicalDecl())) {
812 if (auto *VD = dyn_cast<VarDecl>(VTD->getTemplatedDecl()))
813 unlinkRedeclChain(VD);
814 }
816 }
817
818 if (!hasRecord())
819 return;
820
821 // Restore Decl.
822}
823
825 if (!isDiscarded(D))
826 return;
827
829}
830
832 if (!isDiscarded(D))
833 return;
834
836}
837
839 if (!isDiscarded(D))
840 return;
841
843}
844
846 PTUStateInfo &Cur = Tracker.current();
847 if (!Cur.HadImplicitCXXMember)
848 return;
849
851 for (auto &Entry : SemaRef.SpecialMemberCache) {
852 CXXMethodDecl *MD = Entry.second.getMethod();
853 if (MD && (Tracker.isFromThisPTU(MD, ID) ||
854 Cur.ImplicitlyGeneratedDecls.contains(MD)))
855 ToRemove.push_back(Entry.first);
856 }
857 for (const auto &Key : ToRemove)
858 SemaRef.SpecialMemberCache.erase(Key);
859}
860
862 SemaRef.VTablesUsed.erase(RD->getCanonicalDecl());
863}
864
866 PTUStateInfo &Cur = Tracker.current();
867 assert((!Cur.Commited || ThisTU == Cur.ThisPTU) &&
868 "MostRecentTU doesn't match the TU recorded at commit time");
869 PTUID ID = Cur.ID;
870
871 // 1. Check whether this PTU was committed. If the PTU failed, it was not
872 // committed and therefore did not go through the commit policy or register
873 // any declaration state, so there is nothing to undo from
874 // IncrementalStateTracker.
875 //
876 // If the PTU was successfully committed, the commit policy must have
877 // registered the declaration state and updated the state of declarations
878 // from the previous PTU in IncrementalStateTracker. First undo all state
879 // recorded by IncrementalStateTracker, then perform the regular undo so
880 // that mutated declarations are restored to the PTU(N-1) state rather
881 // than the current PTU state.
882 if (Cur.Commited) {
883 // remove sweep-tracked decls owned by this PTU,
884 // which would otherwise become stale references with no cleanup path.
885 Tracker.getHiddenMutationTracker().untrackIf(
886 [&](const Decl *D) { return Tracker.isFromThisPTU(D, ID); });
887 Tracker.undoLastEntries();
888 } else {
889 // Same as the CommitPTU() step, but performed here because this PTU failed
890 // and was never committed. Since the commit step was never executed, we
891 // need to perform it here for an uncommitted PTU.
892 Cur.verifyMutations(*this);
893 Tracker.getHiddenMutationTracker().sweep(
894 *this, [&](const Decl *D, DeclShape S, uint32_t K) {
895 Cur.noteMutated(D, S, K);
896 });
897 }
898
899 ASTDeclUnmerger Umerger(ID, Tracker, *this, SemaRef, SemaCache);
900
901 // 2. Same as the CommitPTU() step, but opposite of: CommitPTU() updates the
902 // IncrementalStateTracker with the mutated state of declarations from the
903 // previous state. Here, we restore each mutated declaration using its most
904 // recent state in IncrementalStateTracker (i.e., the PTU(N-1) state).
905 for (auto &[D, Rec] : Cur.Mutations)
906 Umerger.RestoreDecl(const_cast<Decl *>(D), Rec);
907
908 // 3. Cur.ImplicitlyGeneratedDecls: Declarations created by this PTU. Unlink
909 // them from
910 // the compiler's shared state.
911 //
912 // This is the counterpart to the commit, but
913 // performs the opposite operation by unlinking the declarations.
914 //
915 // ASTDeclUnmerger: Determines how to undo declarations mutated or created by
916 // the current PTU, such as unlinking declarations from redeclaration chains
917 // and DeclContext lookup structures, or restoring declaration state (e.g.,
918 // CXXRecordDecl::DefinitionData).
919 for (const Decl *D : Cur.ImplicitlyGeneratedDecls) {
920 if (isReachableFromThisTU(D, ThisTU))
921 continue;
922 Umerger.Visit(const_cast<Decl *>(D));
923 }
924
925 Umerger.Visit(ThisTU);
926
927 // SpecialMemberCache stores the CXXMethodDecl* from a previous
928 // LookupSpecialMember() call. If it was created by a PTU being rolled back,
929 // the cache entry is stale, so remove it here.
930 // FIXME: Uncomment once we handle restoration of CXXRecordDecl.
931 // SemaCache.restoreSpecialMemberCache(ID);
932
933 // Must be last: Cur/ID/ThisTU refer to data owned by this PTU, and
934 // popCurrentPTU() destroys that entry. This runs for both committed and
935 // rolled-back PTUs to reclaim the PTUStack and checkpoint entry.
936 Tracker.popCurrentPTU();
937}
938
939/// -----------------------------------------------------------------------
940////////////////////////// MutationListener ///////////////////////////////
941/// -----------------------------------------------------------------------
942
943/// This is the place for listener-related functionality. When Clang notifies
944/// us about an AST mutation, we record it in PTUStateInfo.
945///
946/// We only capture mutations here. For example, if a decl from a previous PTU
947/// is mutated, we record its Decl -> DeclShape -> mutation kind relationship.
948/// We do not process the mutation here. Processing is deferred until commit
949/// if the PTU succeeds; if the PTU fails, the flow goes through restore
950/// instead.
951///
952/// We also track implicit decls. During commit, we walk the current PTU and
953/// can only commit decls that are visible from that TU. However, implicit decls
954/// can be created and added to another PTU, so we need to track them as well
955/// so they can be committed or unlinked during restore.
956///
957/// We do not cover every mutation case here yet. Any new case added should
958/// follow the same rule: if a mutation affects a decl from a previous PTU,
959/// record it in PTUStateInfo.
960///
961/// There are two separate restore paths:
962/// 1. Restoring a mutated decl to its previous state.
963/// 2. Unlinking a decl from shared state, such as redecl chains or DC lookup.
964///
965/// For example, see noteDefinitionInstantiated, where a decl is created by
966/// Clang and added to another PTU even though it is not marked as implicit.
967/// Such a decl needs to be tracked for unlinking rather than restoring its
968/// previous state.
969
970template <typename TemplateT, typename SpecT>
971void PTUMutationRecorder::noteTemplateDeclMutation(const TemplateT *TD,
972 const SpecT *Spec) {
973 PTUStateInfo &Cur = Tracker.current();
974 if (Tracker.isFromThisPTU(TD, Cur.ID))
975 return;
976
977 Cur.noteMutated(TD, DeclShape::Template, MutationKind::SpecializationAdded);
978}
979
982 noteTemplateDeclMutation(TD, D);
983}
984
985void PTUMutationRecorder::noteDefinitionInstantiated(const Decl *D) {
986 PTUStateInfo &Cur = Tracker.current();
987 if (Tracker.isFromThisPTU(D, Cur.ID)) {
988 // Normally, VisitDecls covers declarations created in this PTU.
989 // But an out-of-line static data member is a separate VarDecl whose
990 // lexical context is the class, so the namespace/TU walk won't find it.
991 // Process it like other implicit declarations instead.
992 const auto *VD = dyn_cast<VarDecl>(D);
993 if (VD && VD->getPreviousDecl() &&
994 !Tracker.isFromThisPTU(VD->getCanonicalDecl(), Cur.ID))
995 Cur.ImplicitlyGeneratedDecls.insert(D);
996 return;
997 }
998
999 Cur.noteMutated(D, classifyShape(D), MutationKind::DefinitionInstantiate);
1000}
1001
1002// Remove all entries for each (Owner, Kind) key written by this PTU.
1004 PTUStateInfo &Cur = current();
1005 PTUID ID = Cur.ID;
1006
1007 for (auto &[Owner, K] : Cur.TouchedFootprints)
1008 Footprints.removeFrom(Owner, K, ID);
1009}
1010
1011} // end namespace clang
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
FormatToken * Next
The next token in the unwrapped line.
llvm::MachO::Record Record
Definition MachO.h:31
ExternCContextDecl * getExternCContextDecl() const
ASTDeclUnmerger handles two cases based on whether a declaration should be discarded or belongs to a ...
static void restoreDefinitionDataFootprint(const DefinitionDataFootprint &FP, CXXRecordDecl &RD)
void VisitNamedDecl(NamedDecl *ND)
Remove ND from its context and the lookup tables, and make the declaration it redeclares visible agai...
friend class PTUMutationActions
static void restoreFootprint(const FootprintT &FP, OwnerT &Owner)
void VisitClassTemplateDecl(ClassTemplateDecl *CTD)
void VisitVarTemplateDecl(VarTemplateDecl *VTD)
void VisitRedeclarable(Redeclarable< DeclT > *DBase)
Remove D like VisitNamedDecl() and restore its redeclaration chain to the previous state.
void RestoreDecl(Decl *D, MutationRecord &R)
void VisitFunctionDecl(FunctionDecl *FD)
void VisitTypedefNameDecl(TypedefNameDecl *D)
void VisitTranslationUnitDecl(TranslationUnitDecl *D)
static DefinitionDataFootprint createDefinitionDataFootprint(const CXXRecordDecl &RD)
void VisitCXXRecordDecl(CXXRecordDecl *RD)
void VisitTagDecl(TagDecl *TD)
void VisitFunctionTemplateDecl(FunctionTemplateDecl *FTD)
static FootprintT createFootprint(const OwnerT &Owner)
void VisitNamespaceDecl(NamespaceDecl *D)
These are the places where we restore or undo/unlink the incremental state of a decl based on its Dec...
void VisitVarDecl(VarDecl *VD)
void VisitUsingShadowDecl(UsingShadowDecl *D)
ASTDeclUnmerger(PTUID ID, IncrementalStateTracker &Tracker, PTUMutationActions &Action, Sema &SemaRef, SemaCacheReverter &SemaCache)
void VisitEnumDecl(EnumDecl *ED)
void VisitNamespaceAliasDecl(NamespaceAliasDecl *D)
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:549
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2054
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:523
Declaration of a class template.
llvm::FoldingSetVector< ClassTemplateSpecializationDecl > & getSpecializations() const
Retrieve the set of specializations of this class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
Represents a class template specialization, which refers to a class template with a given set of temp...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1468
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2113
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context,...
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2129
bool isTranslationUnit() const
Definition DeclBase.h:2209
Decl * FirstDecl
FirstDecl - The first declaration stored within this declaration context.
Definition DeclBase.h:2079
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Decl * LastDecl
LastDecl - The last declaration stored within this declaration context.
Definition DeclBase.h:2085
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2410
bool isInlineNamespace() const
StoredDeclsMap * getLookupPtr() const
Retrieve the internal representation of the lookup structure.
Definition DeclBase.h:2708
A simple visitor class that helps create declaration visitors.
Definition DeclVisitor.h:68
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1080
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition DeclBase.h:1095
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
Decl * getNextDeclInContext()
Definition DeclBase.h:455
llvm::PointerIntPair< Decl *, 3, ModuleOwnershipKind > NextInContextAndBits
The next declaration within the same lexical DeclContext.
Definition DeclBase.h:257
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition DeclBase.h:968
DeclContext * getDeclContext()
Definition DeclBase.h:458
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:937
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:997
const LangOptions & getLangOpts() const LLVM_READONLY
Helper to get the language options from the ASTContext.
Definition DeclBase.cpp:564
The name of a declaration.
void * getFETokenInfo() const
Get and set FETokenInfo.
bool isEmpty() const
Evaluates true when this declaration name is empty.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents an enum.
Definition Decl.h:4198
Declaration context for names declared as extern "C" in C++.
Definition Decl.h:249
const T * mostRecent(const Decl *Owner, MutationKind K) const
Represents a function declaration or definition.
Definition Decl.h:2082
Declaration of a template function.
FunctionTemplateDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FootprintStore & getFootprints()
PTUStateInfo & current() const
bool isFromThisPTU(const void *Ptr, PTUID ID) const
This represents a decl that may have a name.
Definition Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
Represents a C++ namespace alias.
Definition DeclCXX.h:3248
Represent a C++ namespace.
Definition Decl.h:594
NamespaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this namespace.
Definition Decl.h:686
uint32_t confirmMutation(const Decl *D, DeclShape S, uint32_t FlaggedKinds)
The single place to check whether a kind has actually changed.
bool shouldRecurseInto(const Decl *D)
These are the places where the incremental state of a declaration is registered based on its DeclKind...
void CommitDecl(const Decl *D, MutationRecord *Rec)
void CommitPTU(TranslationUnitDecl *MostRecentTU)
uint32_t DeclNeedingTracking(DeclShape S, const Decl *D)
This is called when a decl is created or seen for the first time.
void VisitDeclContext(const DeclContext *DC)
void untrackIfClosed(const Decl *D, DeclShape S, uint32_t Confirmed)
Stop tracking Decl D when it no longer needs verification.
void syncSweepTracking(const Decl *D, DeclShape S, uint32_t Kinds, bool IsNew)
void RestorePTU(TranslationUnitDecl *MostRecentTU)
void trackForSweep(const Decl *D, uint32_t Kinds)
Start tracking D for mutation kinds that need verification.
void AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) override
A template specialization (or partial one) was added to the template declaration.
Provides common interface for the Decls that can be redeclared.
static DeclLink LatestDeclLink(const ASTContext &Ctx)
void restoreSpecialMemberCache(PTUID ID)
void restoreVTableUsed(CXXRecordDecl *RD)
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
An array of decls optimized for the common case of only containing one entry.
void addOrReplaceDecl(NamedDecl *D)
If this is a redeclaration of an existing decl, replace the old one with D.
void sweep(PTUMutationActions &Act, OnConfirmedFn OnConfirmed)
A single function called during commit and restore (when the PTU is uncommitted).
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3904
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition Decl.h:4000
The top declaration context.
Definition Decl.h:107
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3749
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3446
Represents a variable declaration or definition.
Definition Decl.h:934
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
VarTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this template.
const internal::ArgumentAdaptingMatcherFunc< internal::HasMatcher > has
Matches AST nodes that have child AST nodes that match the provided matcher.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
unsigned PTUID
Index of a per PTU State.
static FootprintT Footprint(const OwnerT &Owner)
MutationRecord::MutationKind MutationKind
static DeclShape classifyShape(const Decl *D)
static constexpr uint32_t KindsNeedingVerification
These kinds have listeners, but listeners alone cannot reliably detect real changes.
static bool isReachableFromThisTU(const Decl *D, const TranslationUnitDecl *ThisTU)
static bool differsFromLast(IncrementalStateTracker &Tracker, const Decl *Owner, MutationKind K, const T &LiveValue)
MutationRecord::DeclShape DeclShape
U cast(CodeGen::Address addr)
Definition Address.h:327
A snapshot of the DefinitionData bits and bitfields that can change after a class gets a special impl...
void add(MutationKind K)
const TranslationUnitDecl * ThisPTU
llvm::MapVector< const Decl *, MutationRecord > Mutations
void verifyMutations(PTUMutationActions &Actions)
Verify recorded mutations and remove any false mutation ones.
bool HadImplicitCXXMember
Set exactly when AddedCXXImplicitMember fires this PTU.
void noteMutated(const Decl *D, DeclShape S, KindT K)
llvm::SmallVector< std::pair< const Decl *, MutationKind >, 8 > TouchedFootprints
Every (Owner, Kind) key this PTU's own commit() wrote a FootprintStore entry for.
llvm::SmallPtrSet< const Decl *, 4 > ImplicitlyGeneratedDecls