llvmorg-github-actions[bot] wrote:

<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang-analysis

Author: Gábor Horváth (Xazax-hun)

<details>
<summary>Changes</summary>

Before generating facts, the OriginManager collects the return types of 
lifetimebound calls by traversing the function body and the constructor 
initializers with a RecursiveASTVisitor. The analysis builds its CFG with every 
evaluated statement as an element, so visit those elements instead.

This also covers the calls the visitor skipped as implicit code but the facts 
are generated for, such as those in the default member initializers of a 
constructor, so a dangling field initialized there is now reported. Calls that 
only appear in unevaluated operands are no longer collected.

On some LLVM TUs (GVN, LiveVariables, RegionStore, SemaExpr) this reduces the 
instructions of the analysis by 5.0-6.0% (0.37-0.54% of -fsyntax-only). The 
diagnostics on these TUs are unchanged.

Assisted-by: Claude Opus 5.5

---
Full diff: https://github.com/llvm/llvm-project/pull/246623.diff


4 Files Affected:

- (modified) clang/include/clang/Analysis/Analyses/LifetimeSafety/Facts.h 
(+1-1) 
- (modified) clang/include/clang/Analysis/Analyses/LifetimeSafety/Origins.h 
(+10-5) 
- (modified) clang/lib/Analysis/LifetimeSafety/Origins.cpp (+26-27) 
- (modified) clang/test/Sema/LifetimeSafety/dangling-field-implicit-ctor.cpp 
(+22) 


``````````diff
diff --git a/clang/include/clang/Analysis/Analyses/LifetimeSafety/Facts.h 
b/clang/include/clang/Analysis/Analyses/LifetimeSafety/Facts.h
index 7d32db996b356e..9feed1f338f6dc 100644
--- a/clang/include/clang/Analysis/Analyses/LifetimeSafety/Facts.h
+++ b/clang/include/clang/Analysis/Analyses/LifetimeSafety/Facts.h
@@ -456,7 +456,7 @@ class FactManager {
 public:
   FactManager(const AnalysisDeclContext &AC, const CFG &Cfg,
               llvm::BumpPtrAllocator &Alloc)
-      : LoanMgr(Alloc), OriginMgr(AC, Alloc), FactAllocator(Alloc) {
+      : LoanMgr(Alloc), OriginMgr(AC, Cfg, Alloc), FactAllocator(Alloc) {
     BlockToFacts.resize(Cfg.getNumBlockIDs());
   }
 
diff --git a/clang/include/clang/Analysis/Analyses/LifetimeSafety/Origins.h 
b/clang/include/clang/Analysis/Analyses/LifetimeSafety/Origins.h
index 6f672b49387906..a2beaeaa7e0391 100644
--- a/clang/include/clang/Analysis/Analyses/LifetimeSafety/Origins.h
+++ b/clang/include/clang/Analysis/Analyses/LifetimeSafety/Origins.h
@@ -24,6 +24,10 @@
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/raw_ostream.h"
 
+namespace clang {
+class CFG;
+} // namespace clang
+
 namespace clang::lifetimes::internal {
 
 using OriginID = utils::ID<struct OriginTag>;
@@ -135,7 +139,8 @@ bool doesDeclHaveStorage(const ValueDecl *D);
 /// variables and expressions.
 class OriginManager {
 public:
-  OriginManager(const AnalysisDeclContext &AC, llvm::BumpPtrAllocator &Alloc);
+  OriginManager(const AnalysisDeclContext &AC, const CFG &Cfg,
+                llvm::BumpPtrAllocator &Alloc);
 
   /// Gets or creates the OriginList for a given ValueDecl.
   ///
@@ -213,10 +218,10 @@ class OriginManager {
 
   void initializeThisOrigins(const Decl *D);
 
-  /// Pre-scans the function body (and constructor init lists) to discover
-  /// return types of lifetime-annotated calls (currently
-  /// [[clang::lifetimebound]]), registering them for origin tracking.
-  void collectLifetimeAnnotatedOriginTypes(const AnalysisDeclContext &AC);
+  /// Pre-scans the calls in the CFG to discover return types of
+  /// lifetime-annotated calls (currently [[clang::lifetimebound]]),
+  /// registering them for origin tracking.
+  void collectLifetimeAnnotatedOriginTypes(const CFG &Cfg);
   void registerLifetimeAnnotatedOriginType(QualType QT);
 
   ASTContext &AST;
diff --git a/clang/lib/Analysis/LifetimeSafety/Origins.cpp 
b/clang/lib/Analysis/LifetimeSafety/Origins.cpp
index d5a55d4d3d0d35..15b80c53adb8c4 100644
--- a/clang/lib/Analysis/LifetimeSafety/Origins.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/Origins.cpp
@@ -19,6 +19,7 @@
 #include "clang/Analysis/Analyses/LifetimeSafety/LifetimeAnnotations.h"
 #include "clang/Analysis/Analyses/LifetimeSafety/LifetimeStats.h"
 #include "clang/Analysis/AnalysisDeclContext.h"
+#include "clang/Analysis/CFG.h"
 #include "llvm/ADT/StringMap.h"
 
 namespace clang::lifetimes::internal {
@@ -51,28 +52,24 @@ class MissingOriginCollector
   LifetimeSafetyStats &LSStats;
 };
 
-class LifetimeAnnotatedOriginTypeCollector
-    : public RecursiveASTVisitor<LifetimeAnnotatedOriginTypeCollector> {
+/// Collects the types that need origins because of the lifetime annotations of
+/// the functions and constructors called in the CFG.
+class LifetimeAnnotatedOriginTypeCollector {
 public:
-  bool VisitCallExpr(const CallExpr *CE) {
-    // Indirect calls (e.g., function pointers) are skipped because lifetime
-    // annotations currently apply to declarations, not types.
-    if (const auto *FD = CE->getDirectCallee()) {
-      collect(FD, FD->getReturnType());
-      collectCaptureBy(FD);
+  void visit(const Stmt *S) {
+    if (const auto *CE = dyn_cast<CallExpr>(S)) {
+      // Indirect calls (e.g., function pointers) are skipped because lifetime
+      // annotations currently apply to declarations, not types.
+      if (const auto *FD = CE->getDirectCallee()) {
+        collect(FD, FD->getReturnType());
+        collectCaptureBy(FD);
+      }
+    } else if (const auto *CCE = dyn_cast<CXXConstructExpr>(S)) {
+      collect(CCE->getConstructor(), CCE->getType());
+      collectCaptureBy(CCE->getConstructor());
     }
-    return true;
-  }
-
-  bool VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
-    collect(CCE->getConstructor(), CCE->getType());
-    collectCaptureBy(CCE->getConstructor());
-    return true;
   }
 
-  bool shouldVisitLambdaBody() const { return false; }
-  bool shouldVisitTemplateInstantiations() const { return true; }
-
   const llvm::SmallVector<QualType> &getCollectedTypes() const {
     return CollectedTypes;
   }
@@ -198,10 +195,10 @@ bool doesDeclHaveStorage(const ValueDecl *D) {
   return !D->getType()->isReferenceType();
 }
 
-OriginManager::OriginManager(const AnalysisDeclContext &AC,
+OriginManager::OriginManager(const AnalysisDeclContext &AC, const CFG &Cfg,
                              llvm::BumpPtrAllocator &Alloc)
     : AST(AC.getASTContext()), ListAllocator(Alloc) {
-  collectLifetimeAnnotatedOriginTypes(AC);
+  collectLifetimeAnnotatedOriginTypes(Cfg);
   initializeThisOrigins(AC.getDecl());
 }
 
@@ -396,14 +393,16 @@ void OriginManager::collectMissingOrigins(Stmt 
&FunctionBody,
   Collector.TraverseStmt(const_cast<Stmt *>(&FunctionBody));
 }
 
-void OriginManager::collectLifetimeAnnotatedOriginTypes(
-    const AnalysisDeclContext &AC) {
+void OriginManager::collectLifetimeAnnotatedOriginTypes(const CFG &Cfg) {
+  // The CFG has every evaluated statement as an element, including the
+  // constructor initializers and the default member initializers they use (see
+  // setLifetimeSafetyCFGBuildOptions), so these are the calls the facts are
+  // generated for.
   LifetimeAnnotatedOriginTypeCollector Collector;
-  if (Stmt *Body = AC.getBody())
-    Collector.TraverseStmt(Body);
-  if (const auto *CD = dyn_cast<CXXConstructorDecl>(AC.getDecl()))
-    for (const auto *Init : CD->inits())
-      Collector.TraverseStmt(Init->getInit());
+  for (const CFGBlock *Block : Cfg)
+    for (const CFGElement &Elt : *Block)
+      if (std::optional<CFGStmt> S = Elt.getAs<CFGStmt>())
+        Collector.visit(S->getStmt());
   for (QualType QT : Collector.getCollectedTypes())
     registerLifetimeAnnotatedOriginType(QT);
 }
diff --git a/clang/test/Sema/LifetimeSafety/dangling-field-implicit-ctor.cpp 
b/clang/test/Sema/LifetimeSafety/dangling-field-implicit-ctor.cpp
index e3ea0f583f06fb..2d08cac048289a 100644
--- a/clang/test/Sema/LifetimeSafety/dangling-field-implicit-ctor.cpp
+++ b/clang/test/Sema/LifetimeSafety/dangling-field-implicit-ctor.cpp
@@ -47,3 +47,25 @@ struct SafeLiteral {
   std::string_view v = "literal";
 };
 void use_safe() { SafeLiteral c; (void)c; }
+
+// A type that has origins only because a lifetimebound function returns it,
+// returned by such a call in a default member initializer.
+struct MyObj {};
+struct View {
+  const MyObj *p;
+};
+View makeView(const MyObj &obj [[clang::lifetimebound]]);
+
+struct ImplicitCtorView {
+  View view{makeView(MyObj{})}; // expected-warning {{stack memory associated 
with temporary object escapes to the field 'view' which will dangle}}
+                                // expected-note@-1 {{result of call to 
'makeView' aliases the storage of temporary object because parameter 'obj' is 
marked as lifetimebound}}
+                                // expected-note@-2 {{this field dangles}}
+};
+void use_implicit_view() { ImplicitCtorView c; (void)c; } // perfunc-note {{in 
implicit default constructor for 'ImplicitCtorView' first required here}}
+
+struct UserCtorView {
+  View view{makeView(MyObj{})}; // expected-warning {{stack memory associated 
with temporary object escapes to the field 'view' which will dangle}}
+                                // expected-note@-1 {{result of call to 
'makeView' aliases the storage of temporary object because parameter 'obj' is 
marked as lifetimebound}}
+                                // expected-note@-2 {{this field dangles}}
+  UserCtorView() {}
+};

``````````

</details>


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

Reply via email to