[clang] [analyzer] Add cplusplus.DestroyedAsWrongType checker (PR #237801)

DonĂ¡t Nagy via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 16 10:51:54 PST 2026


================
@@ -249,18 +194,37 @@ void DestroyedAsWrongTypeChecker::reportOrDefer(const MemRegion *R,
   reportBug(R, W, C);
 }
 
-static const MemRegion *getDestroyedRegion(const CallEvent &Call,
-                                           CheckerContext &C) {
+static const MemRegion *getDestroyedRegion(const CallEvent &Call) {
   const auto *Instance = dyn_cast<CXXInstanceCall>(&Call);
-  return Instance ? getStorageRegion(Instance->getCXXThisVal(), C) : nullptr;
+  if (!Instance)
+    return nullptr;
+  const MemRegion *R = Instance->getCXXThisVal().getAsRegion();
+  if (!R)
+    return nullptr;
+  return R->StripCasts();
+}
+
+// The array of which R is an element, or R itself if it is an array.
+static const MemRegion *getEnclosingArray(const MemRegion *R, ASTContext &Ctx) {
+  if (const auto *ER = dyn_cast<ElementRegion>(R))
+    return ER->getSuperRegion();
+  const auto *TR = dyn_cast<TypedValueRegion>(R);
+  if (!TR || !Ctx.getAsArrayType(TR->getValueType()))
+    return nullptr;
+  return R;
 }
 
 static std::optional<WrongDestruction>
 findWrongDestruction(const CallEvent &Call, const CXXDestructorDecl *Dtor,
                      const MemRegion *R, ProgramStateRef State) {
-  const QualType *Placed = State->get<PlacedObjectTypes>(R);
+  const DynamicTypeInfo *DTI = getRawDynamicTypeInfo(State, R);
+  if (!DTI)
+    return std::nullopt;
+  std::optional<QualType> Placed = getPlacedType(*DTI);
   const CXXRecordDecl *DtorClass = Dtor->getParent();
-  if (!Placed || isSameRecord(*Placed, DtorClass))
+  // An object placed at the address of a union may be its member.
----------------
NagyDonat wrote:

This is a valuable comment, but it is bit confusing to see it directly above a large if where it only describes one of the four conditions.

I think the code would be more readable if you would split off
```c++
if (DtorClass->isUnion())
  return std::nullopt;
```
below this comment, then leave a blank line and continue with the rest of the `if`.

(This is a subjective suggestion.)

https://github.com/llvm/llvm-project/pull/237801


More information about the cfe-commits mailing list