[clang] [Clang][LifetimeSafety] Model lifetime_capture_by_global via GlobalEscapeFact (PR #249245)

via cfe-commits cfe-commits at lists.llvm.org
Sat Dec 5 07:40:33 PST 2026


https://github.com/etiennep-chromium created https://github.com/llvm/llvm-project/pull/249245

Implement CFG lifetime-safety support for `[[clang::lifetime_capture_by_global]]` (addressing the `FIXME` in `FactsGenerator::handleLifetimeCaptureBy`).

### Summary
- **`Origins.h`**: Add `OriginManager::createSyntheticOrigin()` and switch `Origin::getDecl()` / `Origin::getExpr()` to `dyn_cast_if_present()` so anonymous sink origins have null `Ptr` and do not pollute aliasing note chains.
- **`Facts.h` / `LifetimeSafety.h`**: Generalize `GlobalEscapeFact` (and `LifetimeSafetySemaHelper::GlobalEscapeTarget`) to `llvm::PointerUnion<const VarDecl *, const Expr *>`, storing the capturing call expression when no concrete global `VarDecl` exists.
- **`FactsGenerator.{h,cpp}`**: In `handleLifetimeCaptureBy()`, flow arguments annotated with `[[clang::lifetime_capture_by_global]]` into a synthetic sink origin and emit a `GlobalEscapeFact` for each in `handleExitBlock()`. Reuses existing `-Wlifetime-safety-dangling-global` (incl. `-in-main` and `-moved`), `-Wlifetime-safety-invalidation`, `-Wlifetime-safety-noescape`, and `-Wlifetime-safety-capture-by-violation` machinery across functions, lambdas, implicit `this`, and coroutines (incl. implicit `return_void`).
- **`Checker.cpp` / `LiveOrigins.cpp`**: Use `GlobalEscapeFact::getLoc()` / `getTarget()`, and key `NoescapeWarningsMap` on `const OriginEscapesFact *` so global-capture calls emit the global-capture note rather than `"returned here"`.
- **`SemaLifetimeSafety.h` / `DiagnosticSemaKinds.td`**: Deduplicate global/static note emission into `reportGlobalEscapeNote()`, add `%select{global storage|the %2}1` to global diagnostics (preserving existing `VarDecl` wording verbatim), and add `note_lifetime_safety_captured_by_global_here`.
- **Tests**: Extend `capture-by.cpp`, `capture-by-violation.cpp`, `dangling-global.cpp`, `invalidations.cpp`, and `noescape-violation.cpp`.

Leaves `[[clang::lifetime_capture_by_unknown]]` as a follow-up `FIXME`.

### Testing
- `llvm-lit -sv tools/clang/test/Sema/LifetimeSafety/` (26/26 passed)
- `llvm-lit -sv tools/clang/test/SemaCXX/ --filter='lifetime|dangling|warn-lifetime'` (8/8 passed)
- `git clang-format --diff --style=LLVM` clean

>From 8c1e6c22f13e96ab758a668bb19243c984d70d8f Mon Sep 17 00:00:00 2001
From: Etienne Pierre-doray <etiennep at chromium.org>
Date: Sat, 5 Dec 2026 15:37:12 +0000
Subject: [PATCH] [Clang][LifetimeSafety] Model lifetime_capture_by_global via
 GlobalEscapeFact

Implement CFG lifetime-safety support for [[clang::lifetime_capture_by_global]]
(addressing the FIXME in FactsGenerator::handleLifetimeCaptureBy).

- Add OriginManager::createSyntheticOrigin() (switching Origin::getDecl()/getExpr()
  to dyn_cast_if_present() so anonymous origins have null Ptr and do not pollute
  aliasing note chains).
- Extend GlobalEscapeFact (and LifetimeSafetySemaHelper::GlobalEscapeTarget) to
  hold PointerUnion<const VarDecl *, const Expr *>, storing the capturing call
  expression when no concrete global VarDecl exists.
- In FactsGenerator::handleLifetimeCaptureBy(), flow arguments annotated with
  [[clang::lifetime_capture_by_global]] into a synthetic sink origin and emit a
  GlobalEscapeFact for each in handleExitBlock(). This reuses existing
  -Wlifetime-safety-dangling-global (including -in-main and -moved),
  -Wlifetime-safety-invalidation, -Wlifetime-safety-noescape, and
  -Wlifetime-safety-capture-by-violation machinery, and works across functions,
  lambdas, implicit 'this', and coroutines (including implicit return_void).
- Update SemaLifetimeSafety.h (deduplicating global/static note emission into
  reportGlobalEscapeNote()) and DiagnosticSemaKinds.td (%select{global storage|
  the %2}1 + note_lifetime_safety_captured_by_global_here), preserving existing
  VarDecl diagnostic text verbatim.
- Key NoescapeWarningsMap on const OriginEscapesFact * in Checker.cpp so
  GlobalEscapeFact call expressions emit the global-capture note rather than
  'returned here'.
- Extend capture-by.cpp, capture-by-violation.cpp, dangling-global.cpp,
  invalidations.cpp, and noescape-violation.cpp.

Leave [[clang::lifetime_capture_by_unknown]] as a follow-up FIXME.
---
 .../Analysis/Analyses/LifetimeSafety/Facts.h  | 22 ++++--
 .../Analyses/LifetimeSafety/FactsGenerator.h  |  8 +-
 .../Analyses/LifetimeSafety/LifetimeSafety.h  | 15 ++--
 .../Analyses/LifetimeSafety/Origins.h         | 13 +++-
 .../clang/Basic/DiagnosticSemaKinds.td        |  9 ++-
 clang/lib/Analysis/LifetimeSafety/Checker.cpp | 40 +++++-----
 .../LifetimeSafety/FactsGenerator.cpp         | 22 ++++--
 .../Analysis/LifetimeSafety/LiveOrigins.cpp   |  2 +-
 clang/lib/Sema/SemaLifetimeSafety.h           | 78 +++++++++----------
 .../LifetimeSafety/capture-by-violation.cpp   |  8 ++
 clang/test/Sema/LifetimeSafety/capture-by.cpp | 77 ++++++++++++++++--
 .../Sema/LifetimeSafety/dangling-global.cpp   |  6 ++
 .../Sema/LifetimeSafety/invalidations.cpp     | 12 +++
 .../LifetimeSafety/noescape-violation.cpp     |  5 ++
 14 files changed, 224 insertions(+), 93 deletions(-)

diff --git a/clang/include/clang/Analysis/Analyses/LifetimeSafety/Facts.h b/clang/include/clang/Analysis/Analyses/LifetimeSafety/Facts.h
index 7d32db996b356e..7843ac008c0f7d 100644
--- a/clang/include/clang/Analysis/Analyses/LifetimeSafety/Facts.h
+++ b/clang/include/clang/Analysis/Analyses/LifetimeSafety/Facts.h
@@ -287,21 +287,33 @@ class FieldEscapeFact : public OriginEscapesFact {
             const LoanPropagationAnalysis *LPA = nullptr) const override;
 };
 
-/// Represents that an origin escapes via assignment to global or static
-/// storage. Example: `global_storage = local_var;`
+/// Represents that an origin escapes to global or static storage, either via
+/// assignment (`global_storage = local_var;`) or a call whose parameter is
+/// annotated with `[[clang::lifetime_capture_by_global]]`.
 class GlobalEscapeFact : public OriginEscapesFact {
-  const VarDecl *Global;
+  llvm::PointerUnion<const VarDecl *, const Expr *> Target;
 
 public:
   GlobalEscapeFact(OriginID OID, const VarDecl *VDecl)
-      : OriginEscapesFact(OID, EscapeKind::Global), Global(VDecl) {}
+      : OriginEscapesFact(OID, EscapeKind::Global), Target(VDecl) {}
+  GlobalEscapeFact(OriginID OID, const Expr *CaptureExpr)
+      : OriginEscapesFact(OID, EscapeKind::Global), Target(CaptureExpr) {}
 
   static bool classof(const Fact *F) {
     return F->getKind() == Kind::OriginEscapes &&
            static_cast<const OriginEscapesFact *>(F)->getEscapeKind() ==
                EscapeKind::Global;
   }
-  const VarDecl *getGlobal() const { return Global; };
+  const VarDecl *getGlobal() const { return dyn_cast<const VarDecl *>(Target); }
+  const Expr *getCaptureExpr() const { return dyn_cast<const Expr *>(Target); }
+  llvm::PointerUnion<const VarDecl *, const Expr *> getTarget() const {
+    return Target;
+  }
+  SourceLocation getLoc() const {
+    if (const auto *VD = getGlobal())
+      return VD->getLocation();
+    return getCaptureExpr()->getExprLoc();
+  }
   void dump(llvm::raw_ostream &OS, const LoanManager &, const OriginManager &OM,
             const LoanPropagationAnalysis *LPA = nullptr) const override;
 };
diff --git a/clang/include/clang/Analysis/Analyses/LifetimeSafety/FactsGenerator.h b/clang/include/clang/Analysis/Analyses/LifetimeSafety/FactsGenerator.h
index 1005a664a2dcca..f03027d556018b 100644
--- a/clang/include/clang/Analysis/Analyses/LifetimeSafety/FactsGenerator.h
+++ b/clang/include/clang/Analysis/Analyses/LifetimeSafety/FactsGenerator.h
@@ -118,8 +118,8 @@ class FactsGenerator : public ConstStmtVisitor<FactsGenerator> {
                              ArrayRef<const Expr *> Args);
 
   // Handles [[clang::lifetime_capture_by(X)]] annotations on a function call to
-  // create flow facts from captured arguments to the capturer
-  void handleLifetimeCaptureBy(const FunctionDecl *FD,
+  // create flow facts from captured arguments to the capturer.
+  void handleLifetimeCaptureBy(const Expr *Call, const FunctionDecl *FD,
                                ArrayRef<const Expr *> Args);
 
   /// Checks if a call-like expression creates a borrow by passing a value to a
@@ -201,6 +201,10 @@ class FactsGenerator : public ConstStmtVisitor<FactsGenerator> {
   // handleImplicitObjectFieldUses.
   llvm::DenseMap<const CXXRecordDecl *, llvm::SmallVector<OriginList *>>
       ImplicitObjectFieldLists;
+  // Synthetic sink origins created for calls with
+  // [[clang::lifetime_capture_by_global]], emitted as GlobalEscapeFacts at
+  // function exit.
+  llvm::SmallVector<std::pair<OriginID, const Expr *>> GlobalCaptures;
   const CFGBlock *CurrentBlock;
   bool IsCMode = false;
 };
diff --git a/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h b/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h
index 6368c1f2a48f4d..00286727fd1532 100644
--- a/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h
+++ b/clang/include/clang/Analysis/Analyses/LifetimeSafety/LifetimeSafety.h
@@ -97,8 +97,10 @@ class LifetimeSafetySemaHelper {
                                    SourceLocation ExpiryLoc,
                                    llvm::ArrayRef<const Expr *> ExprChain) {}
 
+  using GlobalEscapeTarget = llvm::PointerUnion<const VarDecl *, const Expr *>;
+
   virtual void reportDanglingGlobal(const Expr *IssueExpr,
-                                    const VarDecl *DanglingGlobal,
+                                    GlobalEscapeTarget DanglingGlobal,
                                     const Expr *MovedExpr,
                                     SourceLocation ExpiryLoc,
                                     llvm::ArrayRef<const Expr *> ExprChain,
@@ -123,12 +125,12 @@ class LifetimeSafetySemaHelper {
                                       const Expr *InvalidationExpr,
                                       llvm::ArrayRef<const Expr *> ExprChain) {}
   virtual void reportInvalidatedGlobal(const Expr *IssueExpr,
-                                       const VarDecl *Global,
+                                       GlobalEscapeTarget Global,
                                        const Expr *InvalidationExpr,
                                        llvm::ArrayRef<const Expr *> ExprChain) {
   }
   virtual void reportInvalidatedGlobal(const ParmVarDecl *PVD,
-                                       const VarDecl *Global,
+                                       GlobalEscapeTarget Global,
                                        const Expr *InvalidationExpr,
                                        llvm::ArrayRef<const Expr *> ExprChain) {
   }
@@ -148,10 +150,11 @@ class LifetimeSafetySemaHelper {
   // Reports misuse of [[clang::noescape]] when parameter escapes through field
   virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
                                        const FieldDecl *EscapeField) {}
-  // Reports misuse of [[clang::noescape]] when parameter escapes through
-  // assignment to a global variable
+  // Reports misuse of [[clang::noescape]] when parameter escapes to global
+  // storage (via a global/static variable or
+  // [[clang::lifetime_capture_by_global]]).
   virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
-                                       const VarDecl *EscapeGlobal) {}
+                                       GlobalEscapeTarget EscapeGlobal) {}
   // Reports misuse of [[clang::noescape]] when parameter escapes into the
   // object of the method, e.g. through a base initializer or
   // [[clang::lifetime_capture_by_this]].
diff --git a/clang/include/clang/Analysis/Analyses/LifetimeSafety/Origins.h b/clang/include/clang/Analysis/Analyses/LifetimeSafety/Origins.h
index 6f672b49387906..b99e855d7c0db9 100644
--- a/clang/include/clang/Analysis/Analyses/LifetimeSafety/Origins.h
+++ b/clang/include/clang/Analysis/Analyses/LifetimeSafety/Origins.h
@@ -70,10 +70,10 @@ struct Origin {
       : ID(ID), Ptr(E), Ty(QT), NamesDeclStorage(NamesDeclStorage) {}
 
   const clang::ValueDecl *getDecl() const {
-    return dyn_cast<const clang::ValueDecl *>(Ptr);
+    return dyn_cast_if_present<const clang::ValueDecl *>(Ptr);
   }
   const clang::Expr *getExpr() const {
-    return dyn_cast<const clang::Expr *>(Ptr);
+    return dyn_cast_if_present<const clang::Expr *>(Ptr);
   }
 };
 
@@ -159,6 +159,15 @@ class OriginManager {
   /// can refer to a single level of an existing OriginList.
   OriginList *createSingleOriginList(OriginID OID);
 
+  /// Creates an anonymous origin not tied to a declaration or expression
+  /// (e.g. a sink for `[[clang::lifetime_capture_by_global]]`).
+  OriginID createSyntheticOrigin() {
+    OriginID NewID = getNextOriginID();
+    AllOrigins.emplace_back(NewID, static_cast<const ValueDecl *>(nullptr),
+                            /*QT=*/nullptr, /*NamesDeclStorage=*/false);
+    return NewID;
+  }
+
   /// Returns the OriginList for the implicit 'this' parameter if the current
   /// declaration is an instance method.
   std::optional<OriginList *> getThisOrigins() const { return ThisOrigins; }
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index d2c1128d92c253..aa63b5a90baa84 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -11139,7 +11139,7 @@ def warn_lifetime_safety_invalidated_field
       InGroup<LifetimeSafetyInvalidation>,
       DefaultIgnore;
 def warn_lifetime_safety_invalidated_global
-    : Warning<"%0 escapes to the %1 and is later invalidated">,
+    : Warning<"%0 escapes to %select{global storage|the %2}1 and is later invalidated">,
       InGroup<LifetimeSafetyInvalidation>,
       DefaultIgnore;
 
@@ -11160,17 +11160,17 @@ def warn_lifetime_safety_dangling_field_lambda_capture
       InGroup<LifetimeSafetyDanglingFieldLambdaCapture>,
       DefaultIgnore;
 def warn_lifetime_safety_dangling_global
-    : Warning<"stack memory associated with %0 escapes to the %1 which will dangle">,
+    : Warning<"stack memory associated with %0 escapes to %select{global storage|the %2}1 which will dangle">,
       InGroup<LifetimeSafetyDanglingGlobal>,
       DefaultIgnore;
 def warn_lifetime_safety_dangling_global_moved
-    : Warning<"stack memory associated with %0 may escape to the %1 which will dangle. "
+    : Warning<"stack memory associated with %0 may escape to %select{global storage|the %2}1 which will dangle. "
       "This could be a false positive as the storage may have been moved. "
       "Consider moving first and then aliasing later to resolve the issue">,
       InGroup<LifetimeSafetyDanglingGlobalMoved>,
       DefaultIgnore;
 def warn_lifetime_safety_dangling_global_in_main
-    : Warning<"stack memory associated with %0 escapes to the %1 which will dangle after main returns">,
+    : Warning<"stack memory associated with %0 escapes to %select{global storage|the %2}1 which will dangle after main returns">,
       InGroup<LifetimeSafetyDanglingGlobalInMain>,
       DefaultIgnore;
 
@@ -11214,6 +11214,7 @@ def note_lifetime_safety_moved_here : Note<"potentially moved here">;
 def note_lifetime_safety_dangling_field_here: Note<"this field dangles">;
 def note_lifetime_safety_dangling_global_here: Note<"this global dangles">;
 def note_lifetime_safety_dangling_static_here: Note<"this static storage dangles">;
+def note_lifetime_safety_captured_by_global_here: Note<"captured by global storage here">;
 def note_lifetime_safety_escapes_to_field_here: Note<"escapes to this field">;
 def note_lifetime_safety_escapes_to_global_here: Note<"escapes to this global storage">;
 def note_lifetime_safety_escapes_to_static_storage_here: Note<"escapes to this static storage">;
diff --git a/clang/lib/Analysis/LifetimeSafety/Checker.cpp b/clang/lib/Analysis/LifetimeSafety/Checker.cpp
index 59e382a8aef234..6cd115f57f24b1 100644
--- a/clang/lib/Analysis/LifetimeSafety/Checker.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/Checker.cpp
@@ -63,7 +63,8 @@ class LifetimeChecker {
 private:
   llvm::DenseMap<LoanID, PendingWarning> FinalWarningsMap;
   llvm::DenseMap<AnnotationTarget, EscapingTarget> AnnotationWarningsMap;
-  llvm::DenseMap<const ParmVarDecl *, EscapingTarget> NoescapeWarningsMap;
+  llvm::DenseMap<const ParmVarDecl *, const OriginEscapesFact *>
+      NoescapeWarningsMap;
   llvm::DenseMap<const FieldDecl *, const Expr *> FieldOriginEscapesMap;
   struct CaptureByViolation {
     /// The first written [[clang::lifetime_capture_by]] attribute.
@@ -149,14 +150,9 @@ class LifetimeChecker {
     auto CheckParam = [&](const ParmVarDecl *PVD, bool IsMoved) {
       // NoEscape param should not escape.
       if (PVD->hasAttr<NoEscapeAttr>()) {
-        if (auto *ReturnEsc = dyn_cast<ReturnEscapeFact>(OEF))
-          NoescapeWarningsMap.try_emplace(PVD, ReturnEsc->getReturnExpr());
-        if (auto *FieldEsc = dyn_cast<FieldEscapeFact>(OEF))
-          NoescapeWarningsMap.try_emplace(PVD, FieldEsc->getFieldDecl());
-        if (auto *GlobalEsc = dyn_cast<GlobalEscapeFact>(OEF))
-          NoescapeWarningsMap.try_emplace(PVD, GlobalEsc->getGlobal());
-        if (isa<ThisEscapeFact>(OEF))
-          NoescapeWarningsMap.try_emplace(PVD, cast<CXXMethodDecl>(FD));
+        if (isa<ReturnEscapeFact, FieldEscapeFact, GlobalEscapeFact,
+                ThisEscapeFact>(OEF))
+          NoescapeWarningsMap.try_emplace(PVD, OEF);
         return;
       }
       // Skip annotation suggestion for moved loans, as ownership transfer
@@ -430,12 +426,12 @@ class LifetimeChecker {
               // Invalidated object on stack escapes to global or static
               // storage.
               SemaHelper->reportInvalidatedGlobal(
-                  IssueExpr, GlobalEscape->getGlobal(),
+                  IssueExpr, GlobalEscape->getTarget(),
                   Warning.InvalidatedByExpr, ExprChain);
             else if (InvalidatedPVD)
               // Invalidated parameter escapes to global or static storage.
               SemaHelper->reportInvalidatedGlobal(
-                  InvalidatedPVD, GlobalEscape->getGlobal(),
+                  InvalidatedPVD, GlobalEscape->getTarget(),
                   Warning.InvalidatedByExpr, ExprChain);
           } else if (isa<ReturnEscapeFact, ThisEscapeFact>(OEF)) {
             // An invalidated loan is returned, or is still held by the object
@@ -468,7 +464,7 @@ class LifetimeChecker {
           bool IsMain = false;
           if (const auto *Func = dyn_cast_if_present<FunctionDecl>(FD))
             IsMain = Func->isMain();
-          SemaHelper->reportDanglingGlobal(IssueExpr, GlobalEscape->getGlobal(),
+          SemaHelper->reportDanglingGlobal(IssueExpr, GlobalEscape->getTarget(),
                                            MovedExpr, ExpiryLoc, ExprChain,
                                            IsMain);
         } else if (const auto *ThisEscape = dyn_cast<ThisEscapeFact>(OEF))
@@ -590,17 +586,17 @@ class LifetimeChecker {
 
   void reportNoescapeViolations() {
     llvm::TimeTraceScope TimeTrace("ReportNoescapeViolations");
-    for (auto [PVD, EscapeTarget] : NoescapeWarningsMap) {
-      if (const auto *E = dyn_cast<const Expr *>(EscapeTarget))
-        SemaHelper->reportNoescapeViolation(PVD, E);
-      else if (const auto *FD = dyn_cast<const FieldDecl *>(EscapeTarget))
-        SemaHelper->reportNoescapeViolation(PVD, FD);
-      else if (const auto *G = dyn_cast<const VarDecl *>(EscapeTarget))
-        SemaHelper->reportNoescapeViolation(PVD, G);
-      else if (const auto *MD = dyn_cast<const CXXMethodDecl *>(EscapeTarget))
-        SemaHelper->reportNoescapeViolation(PVD, MD);
+    for (auto [PVD, OEF] : NoescapeWarningsMap) {
+      if (const auto *ReturnEsc = dyn_cast<ReturnEscapeFact>(OEF))
+        SemaHelper->reportNoescapeViolation(PVD, ReturnEsc->getReturnExpr());
+      else if (const auto *FieldEsc = dyn_cast<FieldEscapeFact>(OEF))
+        SemaHelper->reportNoescapeViolation(PVD, FieldEsc->getFieldDecl());
+      else if (const auto *GlobalEsc = dyn_cast<GlobalEscapeFact>(OEF))
+        SemaHelper->reportNoescapeViolation(PVD, GlobalEsc->getTarget());
+      else if (isa<ThisEscapeFact>(OEF))
+        SemaHelper->reportNoescapeViolation(PVD, cast<CXXMethodDecl>(FD));
       else
-        llvm_unreachable("Unhandled EscapingTarget type");
+        llvm_unreachable("Unhandled OriginEscapesFact type");
     }
   }
 
diff --git a/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp b/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
index 7fc7c933f72186..84e910b8686550 100644
--- a/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/FactsGenerator.cpp
@@ -945,6 +945,10 @@ void FactsGenerator::handleExitBlock() {
       }
     }
 
+  for (auto [OID, CaptureExpr] : GlobalCaptures)
+    EscapesInCurrentBlock.push_back(
+        FactMgr.createFact<GlobalEscapeFact>(OID, CaptureExpr));
+
   // Keep the never-expiring `this` origin live at exit: the object outlives
   // the method, so whatever it holds (e.g. borrows captured via
   // [[clang::lifetime_capture_by_this]], or loans reachable through its
@@ -1120,7 +1124,8 @@ void FactsGenerator::handleImplicitObjectFieldUses(const Expr *Call,
     CurrentBlockFacts.push_back(FactMgr.createFact<UseFact>(*Call, FieldList));
 }
 
-void FactsGenerator::handleLifetimeCaptureBy(const FunctionDecl *FD,
+void FactsGenerator::handleLifetimeCaptureBy(const Expr *Call,
+                                             const FunctionDecl *FD,
                                              ArrayRef<const Expr *> Args) {
   if (Args.empty())
     return;
@@ -1151,9 +1156,16 @@ void FactsGenerator::handleLifetimeCaptureBy(const FunctionDecl *FD,
         CapturedOriginList->getLength() > 1)
       CapturedOriginList = CapturedOriginList->peelOuterOrigin();
     for (int CapturingArgIdx : Attr->params()) {
-      // FIXME: Add support for capturing to Global/unknown.
-      if (CapturingArgIdx == LifetimeCaptureByAttr::Global ||
-          CapturingArgIdx == LifetimeCaptureByAttr::Unknown ||
+      if (CapturingArgIdx == LifetimeCaptureByAttr::Global) {
+        OriginID CaptureOID = FactMgr.getOriginMgr().createSyntheticOrigin();
+        CurrentBlockFacts.push_back(FactMgr.createFact<OriginFlowFact>(
+            CaptureOID, CapturedOriginList->getOuterOriginID(),
+            /*KillDest=*/false));
+        GlobalCaptures.push_back({CaptureOID, Call});
+        continue;
+      }
+      // FIXME: Add support for capturing to unknown.
+      if (CapturingArgIdx == LifetimeCaptureByAttr::Unknown ||
           CapturingArgIdx == LifetimeCaptureByAttr::Invalid)
         continue;
       // FIXME: Diagnose bad CapturingArgIdx.
@@ -1244,7 +1256,7 @@ void FactsGenerator::handleFunctionCall(const Expr *Call,
   handleDestructiveCall(Call, FD, Args);
   handleMovedArgsInCall(FD, Args);
   handleImplicitObjectFieldUses(Call, FD);
-  handleLifetimeCaptureBy(FD, Args);
+  handleLifetimeCaptureBy(Call, FD, Args);
   handleFreeingCall(Call, FD, Args);
   handleAllocatingCall(Call, FD);
   if (!CallList)
diff --git a/clang/lib/Analysis/LifetimeSafety/LiveOrigins.cpp b/clang/lib/Analysis/LifetimeSafety/LiveOrigins.cpp
index 5456dc2987c638..7d4195e1fdeb82 100644
--- a/clang/lib/Analysis/LifetimeSafety/LiveOrigins.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/LiveOrigins.cpp
@@ -68,7 +68,7 @@ static SourceLocation GetFactLoc(CausingFactType F) {
     if (auto *FieldEsc = dyn_cast<FieldEscapeFact>(OEF))
       return FieldEsc->getFieldDecl()->getLocation();
     if (auto *GlobalEsc = dyn_cast<GlobalEscapeFact>(OEF))
-      return GlobalEsc->getGlobal()->getLocation();
+      return GlobalEsc->getLoc();
     if (auto *ThisEsc = dyn_cast<ThisEscapeFact>(OEF))
       return ThisEsc->getLoc();
   }
diff --git a/clang/lib/Sema/SemaLifetimeSafety.h b/clang/lib/Sema/SemaLifetimeSafety.h
index c0e41ad3162fc4..8b6b4e5fbb19d9 100644
--- a/clang/lib/Sema/SemaLifetimeSafety.h
+++ b/clang/lib/Sema/SemaLifetimeSafety.h
@@ -229,7 +229,7 @@ class LifetimeSafetySemaHelperImpl final : public LifetimeSafetySemaHelper {
   }
 
   void reportDanglingGlobal(const Expr *IssueExpr,
-                            const VarDecl *DanglingGlobal,
+                            GlobalEscapeTarget DanglingGlobal,
                             const Expr *MovedExpr, SourceLocation ExpiryLoc,
                             llvm::ArrayRef<const Expr *> ExprChain,
                             bool IsMain = false) override {
@@ -242,22 +242,16 @@ class LifetimeSafetySemaHelperImpl final : public LifetimeSafetySemaHelper {
                          : diag::warn_lifetime_safety_dangling_global;
     }
 
+    const auto *GlobalVD = dyn_cast<const VarDecl *>(DanglingGlobal);
     S.Diag(IssueExpr->getExprLoc(), DiagID)
-        << getDiagSubjectDescription(IssueExpr)
-        << getDiagSubjectDescription(DanglingGlobal)
+        << getDiagSubjectDescription(IssueExpr) << (GlobalVD != nullptr)
+        << (GlobalVD ? getDiagSubjectDescription(GlobalVD) : std::string())
         << IssueExpr->getSourceRange();
     if (MovedExpr)
       S.Diag(MovedExpr->getExprLoc(), diag::note_lifetime_safety_moved_here)
           << MovedExpr->getSourceRange();
     reportAliasingChain(ExprChain);
-    if (DanglingGlobal->isStaticLocal() || DanglingGlobal->isStaticDataMember())
-      S.Diag(DanglingGlobal->getLocation(),
-             diag::note_lifetime_safety_dangling_static_here)
-          << DanglingGlobal->getEndLoc();
-    else
-      S.Diag(DanglingGlobal->getLocation(),
-             diag::note_lifetime_safety_dangling_global_here)
-          << DanglingGlobal->getEndLoc();
+    reportGlobalEscapeNote(DanglingGlobal, /*IsNoescape=*/false);
   }
 
   void
@@ -310,45 +304,37 @@ class LifetimeSafetySemaHelperImpl final : public LifetimeSafetySemaHelper {
   }
 
   void
-  reportInvalidatedGlobal(const Expr *IssueExpr, const VarDecl *DanglingGlobal,
+  reportInvalidatedGlobal(const Expr *IssueExpr,
+                          GlobalEscapeTarget DanglingGlobal,
                           const Expr *InvalidationExpr,
                           llvm::ArrayRef<const Expr *> ExprChain) override {
     std::string InvalidatedSubject = getDiagSubjectDescription(IssueExpr);
+    const auto *GlobalVD = dyn_cast<const VarDecl *>(DanglingGlobal);
     S.Diag(IssueExpr->getExprLoc(),
            diag::warn_lifetime_safety_invalidated_global)
-        << InvalidatedSubject << getDiagSubjectDescription(DanglingGlobal)
+        << InvalidatedSubject << (GlobalVD != nullptr)
+        << (GlobalVD ? getDiagSubjectDescription(GlobalVD) : std::string())
         << IssueExpr->getSourceRange();
     reportInvalidationSite(InvalidationExpr, InvalidatedSubject);
     reportAliasingChain(ExprChain);
-    if (DanglingGlobal->isStaticLocal() || DanglingGlobal->isStaticDataMember())
-      S.Diag(DanglingGlobal->getLocation(),
-             diag::note_lifetime_safety_dangling_static_here)
-          << DanglingGlobal->getEndLoc();
-    else
-      S.Diag(DanglingGlobal->getLocation(),
-             diag::note_lifetime_safety_dangling_global_here)
-          << DanglingGlobal->getEndLoc();
+    reportGlobalEscapeNote(DanglingGlobal, /*IsNoescape=*/false);
   }
 
   void
-  reportInvalidatedGlobal(const ParmVarDecl *PVD, const VarDecl *DanglingGlobal,
+  reportInvalidatedGlobal(const ParmVarDecl *PVD,
+                          GlobalEscapeTarget DanglingGlobal,
                           const Expr *InvalidationExpr,
                           llvm::ArrayRef<const Expr *> ExprChain) override {
     std::string InvalidatedSubject = getDiagSubjectDescription(PVD);
+    const auto *GlobalVD = dyn_cast<const VarDecl *>(DanglingGlobal);
     S.Diag(PVD->getSourceRange().getBegin(),
            diag::warn_lifetime_safety_invalidated_global)
-        << InvalidatedSubject << getDiagSubjectDescription(DanglingGlobal)
+        << InvalidatedSubject << (GlobalVD != nullptr)
+        << (GlobalVD ? getDiagSubjectDescription(GlobalVD) : std::string())
         << PVD->getSourceRange();
     reportInvalidationSite(InvalidationExpr, InvalidatedSubject);
     reportAliasingChain(ExprChain);
-    if (DanglingGlobal->isStaticLocal() || DanglingGlobal->isStaticDataMember())
-      S.Diag(DanglingGlobal->getLocation(),
-             diag::note_lifetime_safety_dangling_static_here)
-          << DanglingGlobal->getEndLoc();
-    else
-      S.Diag(DanglingGlobal->getLocation(),
-             diag::note_lifetime_safety_dangling_global_here)
-          << DanglingGlobal->getEndLoc();
+    reportGlobalEscapeNote(DanglingGlobal, /*IsNoescape=*/false);
   }
 
   void suggestLifetimeboundToParmVar(WarningScope Scope,
@@ -579,18 +565,11 @@ class LifetimeSafetySemaHelperImpl final : public LifetimeSafetySemaHelper {
   }
 
   void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
-                               const VarDecl *EscapeGlobal) override {
+                               GlobalEscapeTarget EscapeGlobal) override {
     S.Diag(ParmWithNoescape->getBeginLoc(),
            diag::warn_lifetime_safety_noescape_escapes)
         << ParmWithNoescape->getSourceRange();
-    if (EscapeGlobal->isStaticLocal() || EscapeGlobal->isStaticDataMember())
-      S.Diag(EscapeGlobal->getLocation(),
-             diag::note_lifetime_safety_escapes_to_static_storage_here)
-          << EscapeGlobal->getEndLoc();
-    else
-      S.Diag(EscapeGlobal->getLocation(),
-             diag::note_lifetime_safety_escapes_to_global_here)
-          << EscapeGlobal->getEndLoc();
+    reportGlobalEscapeNote(EscapeGlobal, /*IsNoescape=*/true);
   }
 
   void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
@@ -607,6 +586,25 @@ class LifetimeSafetySemaHelperImpl final : public LifetimeSafetySemaHelper {
   }
 
 private:
+  void reportGlobalEscapeNote(GlobalEscapeTarget Target, bool IsNoescape) {
+    if (const auto *VD = dyn_cast<const VarDecl *>(Target)) {
+      bool IsStatic = VD->isStaticLocal() || VD->isStaticDataMember();
+      unsigned NoteID =
+          IsNoescape
+              ? (IsStatic
+                     ? diag::note_lifetime_safety_escapes_to_static_storage_here
+                     : diag::note_lifetime_safety_escapes_to_global_here)
+              : (IsStatic ? diag::note_lifetime_safety_dangling_static_here
+                          : diag::note_lifetime_safety_dangling_global_here);
+      S.Diag(VD->getLocation(), NoteID) << VD->getEndLoc();
+      return;
+    }
+    const auto *CaptureExpr = cast<const Expr *>(Target);
+    S.Diag(CaptureExpr->getExprLoc(),
+           diag::note_lifetime_safety_captured_by_global_here)
+        << CaptureExpr->getSourceRange();
+  }
+
   // Returns true if the expression frees memory: a `delete` expression or a
   // call to a freeing function (e.g. annotated with `ownership_takes`).
   static bool isFreeingExpr(const Expr *InvalidationExpr) {
diff --git a/clang/test/Sema/LifetimeSafety/capture-by-violation.cpp b/clang/test/Sema/LifetimeSafety/capture-by-violation.cpp
index ee1c4812ca24c3..27cfdf036e4429 100644
--- a/clang/test/Sema/LifetimeSafety/capture-by-violation.cpp
+++ b/clang/test/Sema/LifetimeSafety/capture-by-violation.cpp
@@ -282,6 +282,14 @@ void free_captured_by_global(const int &x [[clang::lifetime_capture_by_global]])
   global = &x;
 }
 
+void sink_global(const int &x [[clang::lifetime_capture_by_global]]);
+void free_into_global_call(Cap &c, const int &x [[clang::lifetime_capture_by(c)]]) { // expected-warning {{'x' is captured by global storage but is not marked [[clang::lifetime_capture_by_global]]}}
+  sink_global(x);
+}
+void free_into_global_call_ok(const int &x [[clang::lifetime_capture_by_global]]) {
+  sink_global(x);
+}
+
 void deprecated_global(const int &x [[clang::lifetime_capture_by(global)]]) { // expected-warning {{'lifetime_capture_by(global)' is deprecated; use 'lifetime_capture_by_global' instead}}
   global = &x;
 }
diff --git a/clang/test/Sema/LifetimeSafety/capture-by.cpp b/clang/test/Sema/LifetimeSafety/capture-by.cpp
index afb544f94e2bce..73683e90643575 100644
--- a/clang/test/Sema/LifetimeSafety/capture-by.cpp
+++ b/clang/test/Sema/LifetimeSafety/capture-by.cpp
@@ -349,26 +349,91 @@ void test() {
 // ****************************************************************************
 namespace capture_by_global_unknown {
 void captureByGlobal(std::string_view s [[clang::lifetime_capture_by_global]]);
+void captureByGlobalRef(const std::string &s [[clang::lifetime_capture_by_global]]);
+void captureByGlobalViewRef(const std::string_view &s [[clang::lifetime_capture_by_global]]);
+template <typename F>
+void captureCallbackByGlobal(F f [[clang::lifetime_capture_by_global]]) {
+  (void)f;
+}
 void captureByUnknown(std::string_view s [[clang::lifetime_capture_by_unknown]]);
 
 std::string_view getLifetimeBoundView(const std::string& s [[clang::lifetimebound]]);
 
-// FIXME: Add support for capture by global and unknown in -Wlifetime-safety
-void test() {
+std::string g_string;
+
+struct SelfRegistering {
+  void registerSelf() [[clang::lifetime_capture_by_global]];
+};
+
+void test(bool cond, std::string by_val_param) {
   std::string_view local_string_view;
   std::string local_string;
   // capture by global.
-  captureByGlobal(std::string()); // expected-warning {{object whose reference is captured will be destroyed at the end of the full-expression}}
-  captureByGlobal(getLifetimeBoundView(std::string())); // expected-warning {{object whose reference is captured will be destroyed at the end of the full-expression}}
-  captureByGlobal(local_string);
+  captureByGlobal(std::string()); // expected-warning {{object whose reference is captured will be destroyed at the end of the full-expression}} \
+                                  // cfg-warning {{stack memory associated with temporary object escapes to global storage which will dangle}} \
+                                  // cfg-note {{captured by global storage here}}
+  captureByGlobal(getLifetimeBoundView(std::string())); // expected-warning {{object whose reference is captured will be destroyed at the end of the full-expression}} \
+                                                        // cfg-warning {{stack memory associated with temporary object escapes to global storage which will dangle}} \
+                                                        // cfg-note {{result of call to 'getLifetimeBoundView' aliases the storage of temporary object because parameter 's' is marked as lifetimebound}} \
+                                                        // cfg-note {{captured by global storage here}}
+  captureByGlobal(local_string); // cfg-warning {{stack memory associated with local variable 'local_string' escapes to global storage which will dangle}} \
+                                 // cfg-note {{captured by global storage here}}
   captureByGlobal(local_string_view);
+  captureByGlobal("literal");
+  captureByGlobal(g_string);
+  static std::string static_string;
+  captureByGlobal(static_string);
+
+  captureByGlobal(by_val_param); // cfg-warning {{stack memory associated with parameter 'by_val_param' escapes to global storage which will dangle}} \
+                                 // cfg-note {{captured by global storage here}}
+
+  std::string local_ref_target;
+  captureByGlobalRef(local_ref_target); // cfg-warning {{stack memory associated with local variable 'local_ref_target' escapes to global storage which will dangle}} \
+                                        // cfg-note {{captured by global storage here}}
+  captureByGlobalRef(std::string()); // expected-warning {{object whose reference is captured will be destroyed at the end of the full-expression}} \
+                                     // cfg-warning {{stack memory associated with temporary object escapes to global storage which will dangle}} \
+                                     // cfg-note {{captured by global storage here}}
+  captureByGlobalRef(g_string);
+
+  std::string view_ref_backing;
+  captureByGlobalViewRef(view_ref_backing); // cfg-warning {{stack memory associated with local variable 'view_ref_backing' escapes to global storage which will dangle}} \
+                                            // cfg-note {{captured by global storage here}}
+  captureByGlobalViewRef("literal");
+  captureByGlobalViewRef(g_string);
+
+  if (cond) {
+    std::string inner;
+    captureByGlobal(inner); // cfg-warning {{stack memory associated with local variable 'inner' escapes to global storage which will dangle}} \
+                            // cfg-note {{captured by global storage here}}
+  }
 
-  // capture by unknown.
+  SelfRegistering sr;
+  sr.registerSelf(); // cfg-warning {{stack memory associated with local variable 'sr' escapes to global storage which will dangle}} \
+                     // cfg-note {{captured by global storage here}}
+
+  int x = 0;
+  captureCallbackByGlobal([&x]() { (void)x; }); // cfg-warning {{stack memory associated with local variable 'x' escapes to global storage which will dangle}} \
+                                                // cfg-note {{captured by global storage here}}
+  int y = 0;
+  int *p = &y; // cfg-warning {{stack memory associated with local variable 'y' escapes to global storage which will dangle}}
+  captureCallbackByGlobal([p]() { (void)p; }); // cfg-note {{local variable 'p' aliases the storage of local variable 'y'}} \
+                                               // cfg-note {{captured by global storage here}}
+  captureCallbackByGlobal([x]() { (void)x; });
+  captureCallbackByGlobal([]() {});
+
+  // FIXME: Add support for capture by unknown in -Wlifetime-safety
   captureByUnknown(std::string()); // expected-warning {{object whose reference is captured will be destroyed at the end of the full-expression}}
   captureByUnknown(getLifetimeBoundView(std::string())); // expected-warning {{object whose reference is captured will be destroyed at the end of the full-expression}}
   captureByUnknown(local_string);
   captureByUnknown(local_string_view);
 }
+
+struct CaptureThisOk {
+  int m = 0;
+  void run() {
+    captureCallbackByGlobal([this]() { (void)m; });
+  }
+};
 } // namespace capture_by_global_unknown
 
 // ****************************************************************************
diff --git a/clang/test/Sema/LifetimeSafety/dangling-global.cpp b/clang/test/Sema/LifetimeSafety/dangling-global.cpp
index 2d3bf2638c8aee..61ffbaf156c577 100644
--- a/clang/test/Sema/LifetimeSafety/dangling-global.cpp
+++ b/clang/test/Sema/LifetimeSafety/dangling-global.cpp
@@ -202,6 +202,8 @@ void store_local_in_global_under_constant_condition() {
   }
 }
 
+void capture_global_view(std::string_view sv [[clang::lifetime_capture_by_global]]);
+
 int main() {
   int local = 0;
   global = &local; // expected-warning {{stack memory associated with local variable 'local' escapes to the global variable 'global' which will dangle after main returns}}
@@ -209,5 +211,9 @@ int main() {
   std::string s;
   global_view = s; // expected-warning-re {{stack memory associated with local variable 's' may escape to the global variable 'global_view' which will dangle{{.*}} may have been moved}}
   takeString(std::move(s)); //expected-note {{potentially moved here}}
+
+  std::string s2;
+  capture_global_view(s2); // expected-warning {{stack memory associated with local variable 's2' escapes to global storage which will dangle after main returns}} \
+                           // expected-note {{captured by global storage here}}
   return 0;
 }
diff --git a/clang/test/Sema/LifetimeSafety/invalidations.cpp b/clang/test/Sema/LifetimeSafety/invalidations.cpp
index e9b2f3897e9be2..159ec1a65b77a9 100644
--- a/clang/test/Sema/LifetimeSafety/invalidations.cpp
+++ b/clang/test/Sema/LifetimeSafety/invalidations.cpp
@@ -722,6 +722,18 @@ void GlobalReassignedBeforeInvalidation() {
   GlobalReassigned = StableString;
   strings.push_back("1");
 }
+
+void CaptureGlobalView(std::string_view sv [[clang::lifetime_capture_by_global]]);
+void InvalidatedCaptureByGlobalLocal() {
+  std::string s;
+  CaptureGlobalView(s); // expected-warning {{local variable 's' escapes to global storage and is later invalidated}} \
+                        // expected-note {{captured by global storage here}}
+  s.clear();            // expected-note {{local variable 's' is invalidated here}}
+}
+void InvalidatedCaptureByGlobalRefParam(std::string &s) { // expected-warning {{parameter 's' escapes to global storage and is later invalidated}}
+  CaptureGlobalView(s); // expected-note {{captured by global storage here}}
+  s.clear();            // expected-note {{parameter 's' is invalidated here}}
+}
 } // namespace InvalidatedGlobal
 
 namespace ownership_functions {
diff --git a/clang/test/Sema/LifetimeSafety/noescape-violation.cpp b/clang/test/Sema/LifetimeSafety/noescape-violation.cpp
index 41a08b28c67e13..fc7eb24e9f6c87 100644
--- a/clang/test/Sema/LifetimeSafety/noescape-violation.cpp
+++ b/clang/test/Sema/LifetimeSafety/noescape-violation.cpp
@@ -239,4 +239,9 @@ std::function<void()> escape_noescape_via_function(int &x [[clang::noescape]]) {
   return [&]() { (void)x; }; // expected-note {{returned here}}
 }
 
+void capture_globally(const int *p [[clang::lifetime_capture_by_global]]);
+void escape_noescape_via_capture_by_global(const int *p [[clang::noescape]]) { // expected-warning {{parameter is marked [[clang::noescape]] but escapes}}
+  capture_globally(p); // expected-note {{captured by global storage here}}
+}
+
 } // namespace callable_wrappers



More information about the cfe-commits mailing list