Initial implementation of the experimental C++ Lifetime Safety Analysis (-Wexperimental-lifetime-safety) has just landed in Clang
18 points by aapoalas
18 points by aapoalas
An initial implementation of the experimental C++ Lifetime Safety Analysis (-Wexperimental-lifetime-safety) has just landed in Clang. The work was originally announced in the linked post with the following status:
Lifetime Analysis: Current StatusFor those not already familiar, we’re working on a new lifetime analysis in Clang to catch issues like use-after-scope or returning pointers to stack memory. The analysis is alias-based and draws inspiration from Rust’s borrow checker (specifically, Polonius). More details in the RFC: https://discourse.llvm.org/t/rfc-intra-procedural-lifetime-analysis-in-clang/86291
The initial implementation targets intra-procedural analysis for C++ raw pointers. This keeps the surface area small while we iterate. Over time, we aim to enable this analysis by default in Clang, with both “permissive” and “strict” modes to balance noise and coverage.
The landed PR is this:
Example: [LifetimeSafety] Introduce intra-procedural analysis in Clang
Key Components
- Conceptual Model: Introduces the fundamental concepts of Loan, Origin, and Path to model memory borrows and the lifetime of pointers.
- Fact Generation: A frontend pass traverses the Clang CFG to generate a representation of lifetime-relevant events, such as pointer assignments, taking an address, and variables going out of scope.
- Testing: llvm-lit tests validate the analysis by checking the generated facts.
I didn’t read that carefully, but what I was interested in is if you need more annotations, i.e. if you are “changing the language you’re writing in”
https://discourse.llvm.org/t/rfc-intra-procedural-lifetime-analysis-in-clang/86291
That’s necessary if you want to be 100% correct, but it looks like this is aimed at issuing warnings, with tradeoffs for false negatives and false positives:
The analysis offers different strictness levels (-Wdangling-safety and -Wdangling-safety-permissive). This configuration allows users to control the sensitivity of the warnings issued, managing the trade-off between finding more potential bugs and reducing false positive reports (as detailed in the Permissive vs. Strict Modes section).
But there are also hints at new language annotations:
Future enhancements
Annotation Suggestions: Diagnostics suggesting the addition of [[clang::lifetimebound]] where the analysis detects lifetimes escaping functions, helping users improve function contracts.
Annotation Verification: Diagnostics verifying that function implementations adhere to their declared [[clang::lifetimebound]] contracts, catching mismatches between declaration and behavior.
Clang already has [[clang::lifetimebound]] annotations; I’ve used them in our code in some places and they do sometimes detect dangling references. I imagine this work will make them a lot more effective.