clang 23.0.0git
LifetimeSafety.h
Go to the documentation of this file.
1//===- LifetimeSafety.h - C++ Lifetime Safety Analysis -*----------- C++-*-===//
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 defines the main entry point and orchestrator for the C++ Lifetime
10// Safety Analysis. It coordinates the entire analysis pipeline: fact
11// generation, loan propagation, live origins analysis, and enforcement of
12// lifetime safety policy.
13//
14// The analysis is based on the concepts of "origins" and "loans" to track
15// pointer lifetimes and detect issues like use-after-free and dangling
16// pointers. See the RFC for more details:
17// https://discourse.llvm.org/t/rfc-intra-procedural-lifetime-analysis-in-clang/86291
18//
19//===----------------------------------------------------------------------===//
20#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_H
21#define LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_H
22
23#include "clang/AST/Decl.h"
31#include "llvm/ADT/PointerUnion.h"
32#include <cstddef>
33#include <memory>
34
35namespace clang::lifetimes {
36
38 /// Maximum number of CFG blocks to analyze. Functions with larger CFGs will
39 /// be skipped.
41};
42
43/// Enum to track functions visible across or within TU.
44enum class WarningScope {
45 CrossTU, // For warnings on declarations visible across Translation Units.
46 IntraTU // For warnings on functions local to a Translation Unit.
47};
48
49/// Abstract interface for operations requiring Sema access.
50///
51/// This class exists to break a circular dependency: the LifetimeSafety
52/// analysis target cannot directly depend on clangSema (which would create the
53/// cycle: clangSema -> clangAnalysis -> clangAnalysisLifetimeSafety ->
54/// clangSema).
55///
56/// Instead, this interface is implemented in AnalysisBasedWarnings.cpp (part of
57/// clangSema), allowing the analysis to report diagnostics and modify the AST
58/// through Sema without introducing a circular dependency.
60public:
62 virtual ~LifetimeSafetySemaHelper() = default;
63
64 virtual void reportUseAfterScope(const Expr *IssueExpr, const Expr *UseExpr,
65 const Expr *MovedExpr,
66 SourceLocation FreeLoc) {}
67
68 virtual void reportUseAfterReturn(const Expr *IssueExpr,
69 const Expr *ReturnExpr,
70 const Expr *MovedExpr) {}
71
72 virtual void reportDanglingField(const Expr *IssueExpr,
73 const FieldDecl *Field,
74 const Expr *MovedExpr,
75 SourceLocation ExpiryLoc) {}
76
77 virtual void reportDanglingGlobal(const Expr *IssueExpr,
78 const VarDecl *DanglingGlobal,
79 const Expr *MovedExpr,
80 SourceLocation ExpiryLoc) {}
81
82 // Reports when a reference/iterator is used after the container operation
83 // that invalidated it.
84 virtual void reportUseAfterInvalidation(const Expr *IssueExpr,
85 const Expr *UseExpr,
86 const Expr *InvalidationExpr) {}
87 virtual void reportUseAfterInvalidation(const ParmVarDecl *PVD,
88 const Expr *UseExpr,
89 const Expr *InvalidationExpr) {}
90 virtual void reportInvalidatedField(const Expr *IssueExpr,
91 const FieldDecl *Field,
92 const Expr *InvalidationExpr) {}
93 virtual void reportInvalidatedField(const ParmVarDecl *PVD,
94 const FieldDecl *Field,
95 const Expr *InvalidationExpr) {}
96 virtual void reportInvalidatedGlobal(const Expr *IssueExpr,
97 const VarDecl *Global,
98 const Expr *InvalidationExpr) {}
99 virtual void reportInvalidatedGlobal(const ParmVarDecl *PVD,
100 const VarDecl *Global,
101 const Expr *InvalidationExpr) {}
102
104 llvm::PointerUnion<const Expr *, const FieldDecl *, const VarDecl *>;
105
106 // Suggests lifetime bound annotations for function parameters.
108 const ParmVarDecl *ParmToAnnotate,
110
111 // Reports misuse of [[clang::noescape]] when parameter escapes through return
112 virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
113 const Expr *EscapeExpr) {}
114 // Reports misuse of [[clang::noescape]] when parameter escapes through field
115 virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
116 const FieldDecl *EscapeField) {}
117 // Reports misuse of [[clang::noescape]] when parameter escapes through
118 // assignment to a global variable
119 virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
120 const VarDecl *EscapeGlobal) {}
121
122 // Reports misuse of [[clang::lifetimebound]] when parameter doesn't escape
123 // through return.
124 virtual void
125 reportLifetimeboundViolation(const ParmVarDecl *ParmWithLifetimebound) {}
126
127 // Reports misuse of [[clang::lifetimebound]] when implicit this parameter
128 // doesn't escape through return.
129 virtual void
130 reportLifetimeboundViolation(const CXXMethodDecl *MDWithLifetimebound) {}
131
132 // Reports a member function definition that has [[clang::lifetimebound]] on
133 // the implicit this parameter when the canonical declaration does not.
135 const CXXMethodDecl *FDef,
136 const CXXMethodDecl *FDecl) {}
137
138 // Reports a function definition parameter that has [[clang::lifetimebound]]
139 // when the corresponding parameter in the canonical declaration.
141 const ParmVarDecl *PVDDef,
142 const ParmVarDecl *PVDDecl) {}
143
144 // Suggests lifetime bound annotations for implicit this.
146 const CXXMethodDecl *MD,
147 const Expr *EscapeExpr) {}
148
149 // Adds inferred lifetime bound attribute for implicit this to its
150 // TypeSourceInfo.
152};
153
154/// The main entry point for the analysis.
156 LifetimeSafetySemaHelper *SemaHelper,
157 LifetimeSafetyStats &Stats, bool CollectStats);
158
159namespace internal {
160
161void collectLifetimeStats(AnalysisDeclContext &AC, OriginManager &OM,
162 LifetimeSafetyStats &Stats);
163
164/// An object to hold the factories for immutable collections, ensuring
165/// that all created states share the same underlying memory management.
167 OriginLoanMap::Factory OriginMapFactory{/*canonicalize=*/false};
168 LoanSet::Factory LoanSetFactory{/*canonicalize=*/false};
169 MovedLoansMap::Factory MovedLoansMapFactory{/*canonicalize=*/false};
170 LivenessMap::Factory LivenessMapFactory{/*canonicalize=*/false};
171};
172
173/// Running the lifetime safety analysis and querying its results. It
174/// encapsulates the various dataflow analyses.
176public:
178 LifetimeSafetySemaHelper *SemaHelper,
179 const LifetimeSafetyOpts &LSOpts);
180
181 void run();
182
183 /// \note These are provided only for testing purposes.
185 return *LoanPropagation;
186 }
187 LiveOriginsAnalysis &getLiveOrigins() const { return *LiveOrigins; }
188 FactManager &getFactManager() { return *FactMgr; }
189
190private:
192 LifetimeSafetySemaHelper *SemaHelper;
193 const LifetimeSafetyOpts LSOpts;
194 LifetimeFactory Factory;
195 std::unique_ptr<FactManager> FactMgr;
196 std::unique_ptr<LiveOriginsAnalysis> LiveOrigins;
197 std::unique_ptr<LoanPropagationAnalysis> LoanPropagation;
198 std::unique_ptr<MovedLoansAnalysis> MovedLoans;
199};
200} // namespace internal
201} // namespace clang::lifetimes
202
203#endif // LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_H
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
AnalysisDeclContext contains the context data for the function, method or block under analysis.
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
This represents one expression.
Definition Expr.h:112
Represents a member of a struct/union/class.
Definition Decl.h:3166
Represents a parameter to a function.
Definition Decl.h:1808
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Encodes a location in the source.
Represents a variable declaration or definition.
Definition Decl.h:924
Abstract interface for operations requiring Sema access.
virtual void reportUseAfterInvalidation(const ParmVarDecl *PVD, const Expr *UseExpr, const Expr *InvalidationExpr)
llvm::PointerUnion< const Expr *, const FieldDecl *, const VarDecl * > EscapingTarget
virtual void suggestLifetimeboundToParmVar(WarningScope Scope, const ParmVarDecl *ParmToAnnotate, EscapingTarget Target)
virtual void reportDanglingGlobal(const Expr *IssueExpr, const VarDecl *DanglingGlobal, const Expr *MovedExpr, SourceLocation ExpiryLoc)
virtual void reportInvalidatedField(const ParmVarDecl *PVD, const FieldDecl *Field, const Expr *InvalidationExpr)
virtual void reportMisplacedLifetimebound(WarningScope Scope, const ParmVarDecl *PVDDef, const ParmVarDecl *PVDDecl)
virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape, const VarDecl *EscapeGlobal)
virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape, const FieldDecl *EscapeField)
virtual void reportDanglingField(const Expr *IssueExpr, const FieldDecl *Field, const Expr *MovedExpr, SourceLocation ExpiryLoc)
virtual void reportLifetimeboundViolation(const ParmVarDecl *ParmWithLifetimebound)
virtual void addLifetimeBoundToImplicitThis(const CXXMethodDecl *MD)
virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape, const Expr *EscapeExpr)
virtual void reportMisplacedLifetimebound(WarningScope Scope, const CXXMethodDecl *FDef, const CXXMethodDecl *FDecl)
virtual void reportUseAfterScope(const Expr *IssueExpr, const Expr *UseExpr, const Expr *MovedExpr, SourceLocation FreeLoc)
virtual void suggestLifetimeboundToImplicitThis(WarningScope Scope, const CXXMethodDecl *MD, const Expr *EscapeExpr)
virtual void reportLifetimeboundViolation(const CXXMethodDecl *MDWithLifetimebound)
virtual void reportUseAfterInvalidation(const Expr *IssueExpr, const Expr *UseExpr, const Expr *InvalidationExpr)
virtual void reportUseAfterReturn(const Expr *IssueExpr, const Expr *ReturnExpr, const Expr *MovedExpr)
virtual void reportInvalidatedGlobal(const ParmVarDecl *PVD, const VarDecl *Global, const Expr *InvalidationExpr)
virtual void reportInvalidatedGlobal(const Expr *IssueExpr, const VarDecl *Global, const Expr *InvalidationExpr)
virtual void reportInvalidatedField(const Expr *IssueExpr, const FieldDecl *Field, const Expr *InvalidationExpr)
LifetimeSafetyAnalysis(AnalysisDeclContext &AC, LifetimeSafetySemaHelper *SemaHelper, const LifetimeSafetyOpts &LSOpts)
LoanPropagationAnalysis & getLoanPropagation() const
void collectLifetimeStats(AnalysisDeclContext &AC, OriginManager &OM, LifetimeSafetyStats &Stats)
WarningScope
Enum to track functions visible across or within TU.
void runLifetimeSafetyAnalysis(AnalysisDeclContext &AC, LifetimeSafetySemaHelper *SemaHelper, LifetimeSafetyStats &Stats, bool CollectStats)
The main entry point for the analysis.
size_t MaxCFGBlocks
Maximum number of CFG blocks to analyze.
An object to hold the factories for immutable collections, ensuring that all created states share the...