clang 24.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.
40 size_t MaxCFGBlocks = 0;
41
42 /// Whether to suggest lifetime annotations.
43 bool SuggestAnnotations = false;
44
50 /// Whether to model non-trivial destructors at scope exit as uses.
51 bool CheckDestructorUses = false;
52};
53
54/// Enum to track functions visible across or within TU.
55enum class WarningScope {
56 CrossTU, // For warnings on declarations visible across Translation Units.
57 IntraTU // For warnings on functions local to a Translation Unit.
58};
59
60/// Abstract interface for operations requiring Sema access.
61///
62/// This class exists to break a circular dependency: the LifetimeSafety
63/// analysis target cannot directly depend on clangSema (which would create the
64/// cycle: clangSema -> clangAnalysis -> clangAnalysisLifetimeSafety ->
65/// clangSema).
66///
67/// Instead, this interface is implemented in AnalysisBasedWarnings.cpp (part of
68/// clangSema), allowing the analysis to report diagnostics and modify the AST
69/// through Sema without introducing a circular dependency.
71public:
73 virtual ~LifetimeSafetySemaHelper() = default;
74
75 virtual void reportUseAfterScope(const Expr *IssueExpr, const UseSite &Use,
76 const Expr *MovedExpr,
77 SourceLocation FreeLoc,
79
80 // TODO: Report where the object was destroyed when that happens before the
81 // return (inner scopes, temporaries).
82 virtual void reportUseAfterReturn(const Expr *IssueExpr,
83 const Expr *ReturnExpr,
84 const Expr *MovedExpr,
86
87 virtual void reportDanglingField(const Expr *IssueExpr,
88 const FieldDecl *Field,
89 const Expr *MovedExpr,
90 bool IsCapturedByLambda,
91 SourceLocation ExpiryLoc,
93
94 virtual void reportDanglingGlobal(const Expr *IssueExpr,
95 const VarDecl *DanglingGlobal,
96 const Expr *MovedExpr,
97 SourceLocation ExpiryLoc,
99 bool IsMain = false) {}
100
101 // Reports when a reference/iterator is used after the container operation
102 // that invalidated it.
103 virtual void
104 reportUseAfterInvalidation(const Expr *IssueExpr, const UseSite &Use,
105 const Expr *InvalidationExpr,
106 llvm::ArrayRef<const Expr *> ExprChain) {}
107 virtual void
109 const Expr *InvalidationExpr,
110 llvm::ArrayRef<const Expr *> ExprChain) {}
111 virtual void reportInvalidatedField(const Expr *IssueExpr,
112 const FieldDecl *Field,
113 const Expr *InvalidationExpr,
114 llvm::ArrayRef<const Expr *> ExprChain) {}
115 virtual void reportInvalidatedField(const ParmVarDecl *PVD,
116 const FieldDecl *Field,
117 const Expr *InvalidationExpr,
118 llvm::ArrayRef<const Expr *> ExprChain) {}
119 virtual void reportInvalidatedGlobal(const Expr *IssueExpr,
120 const VarDecl *Global,
121 const Expr *InvalidationExpr,
123 }
124 virtual void reportInvalidatedGlobal(const ParmVarDecl *PVD,
125 const VarDecl *Global,
126 const Expr *InvalidationExpr,
128 }
129
131 llvm::PointerUnion<const Expr *, const FieldDecl *, const VarDecl *>;
132
133 // Suggests lifetime bound annotations for function parameters.
135 const ParmVarDecl *ParmToAnnotate,
137
138 // Reports misuse of [[clang::noescape]] when parameter escapes through return
139 virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
140 const Expr *EscapeExpr) {}
141 // Reports misuse of [[clang::noescape]] when parameter escapes through field
142 virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
143 const FieldDecl *EscapeField) {}
144 // Reports misuse of [[clang::noescape]] when parameter escapes through
145 // assignment to a global variable
146 virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
147 const VarDecl *EscapeGlobal) {}
148
149 // Reports misuse of [[clang::lifetimebound]] when parameter doesn't escape
150 // through return.
151 virtual void
152 reportLifetimeboundViolation(const ParmVarDecl *ParmWithLifetimebound) {}
153
154 // Reports misuse of [[clang::lifetimebound]] when implicit this parameter
155 // doesn't escape through return.
156 virtual void
157 reportLifetimeboundViolation(const CXXMethodDecl *MDWithLifetimebound) {}
158
159 // Reports a member function definition that has [[clang::lifetimebound]] on
160 // the implicit this parameter when the canonical declaration does not.
162 const CXXMethodDecl *FDef,
163 const CXXMethodDecl *FDecl) {}
164
165 // Reports a function definition parameter that has [[clang::lifetimebound]]
166 // when the corresponding parameter in the canonical declaration.
168 const ParmVarDecl *PVDDef,
169 const ParmVarDecl *PVDDecl) {}
170
172
173 // Suggests lifetime bound annotations for implicit this.
175 const CXXMethodDecl *MD,
176 const Expr *EscapeExpr) {}
177
178 // Reports when a member function returns an origin of a field.
180 const FieldDecl *FD,
181 const Expr *EscapeExpr) {}
182
183 // Adds inferred lifetime bound attribute for implicit this to its
184 // TypeSourceInfo.
186};
187
188/// The main entry point for the analysis.
190 LifetimeSafetySemaHelper *SemaHelper,
191 const LifetimeSafetyOpts &Opts,
192 LifetimeSafetyStats &Stats, bool CollectStats);
193
194namespace internal {
195
196void collectLifetimeStats(AnalysisDeclContext &AC, OriginManager &OM,
197 LifetimeSafetyStats &Stats);
198
199/// An object to hold the factories for immutable collections, ensuring
200/// that all created states share the same underlying memory management.
202 OriginLoanMap::Factory OriginMapFactory;
203 LoanSet::Factory LoanSetFactory;
204 MovedLoansMap::Factory MovedLoansMapFactory;
205 LivenessMap::Factory LivenessMapFactory;
206};
207
208/// Running the lifetime safety analysis and querying its results. It
209/// encapsulates the various dataflow analyses.
211public:
213 LifetimeSafetySemaHelper *SemaHelper,
214 const LifetimeSafetyOpts &LSOpts);
215
216 void run();
217
218 /// \note These are provided only for testing purposes.
220 return *LoanPropagation;
221 }
222 LiveOriginsAnalysis &getLiveOrigins() const { return *LiveOrigins; }
223 FactManager &getFactManager() { return *FactMgr; }
224
225private:
227 LifetimeSafetySemaHelper *SemaHelper;
228 const LifetimeSafetyOpts LSOpts;
229 LifetimeFactory Factory;
230 std::unique_ptr<FactManager> FactMgr;
231 std::unique_ptr<LiveOriginsAnalysis> LiveOrigins;
232 std::unique_ptr<LoanPropagationAnalysis> LoanPropagation;
233 std::unique_ptr<MovedLoansAnalysis> MovedLoans;
234};
235} // namespace internal
236} // namespace clang::lifetimes
237
238#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:2153
This represents one expression.
Definition Expr.h:114
Represents a member of a struct/union/class.
Definition Decl.h:3341
Represents a parameter to a function.
Definition Decl.h:1832
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:934
Abstract interface for operations requiring Sema access.
virtual void reportInapplicableLifetimebound(const ParmVarDecl *PVD)
llvm::PointerUnion< const Expr *, const FieldDecl *, const VarDecl * > EscapingTarget
virtual void suggestLifetimeboundToParmVar(WarningScope Scope, const ParmVarDecl *ParmToAnnotate, EscapingTarget Target)
virtual void reportInvalidatedField(const ParmVarDecl *PVD, const FieldDecl *Field, const Expr *InvalidationExpr, llvm::ArrayRef< const Expr * > ExprChain)
virtual void reportUseAfterInvalidation(const Expr *IssueExpr, const UseSite &Use, const Expr *InvalidationExpr, llvm::ArrayRef< const Expr * > ExprChain)
virtual void reportUseAfterScope(const Expr *IssueExpr, const UseSite &Use, const Expr *MovedExpr, SourceLocation FreeLoc, llvm::ArrayRef< const Expr * > ExprChain)
virtual void reportInvalidatedGlobal(const Expr *IssueExpr, const VarDecl *Global, const Expr *InvalidationExpr, llvm::ArrayRef< const Expr * > ExprChain)
virtual void reportMisplacedLifetimebound(WarningScope Scope, const ParmVarDecl *PVDDef, const ParmVarDecl *PVDDecl)
virtual void reportInvalidatedField(const Expr *IssueExpr, const FieldDecl *Field, const Expr *InvalidationExpr, llvm::ArrayRef< const Expr * > ExprChain)
virtual void reportFieldOriginEscape(const CXXMethodDecl *MD, const FieldDecl *FD, const Expr *EscapeExpr)
virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape, const VarDecl *EscapeGlobal)
virtual void reportDanglingField(const Expr *IssueExpr, const FieldDecl *Field, const Expr *MovedExpr, bool IsCapturedByLambda, SourceLocation ExpiryLoc, llvm::ArrayRef< const Expr * > ExprChain)
virtual void reportUseAfterInvalidation(const ParmVarDecl *PVD, const UseSite &Use, const Expr *InvalidationExpr, llvm::ArrayRef< const Expr * > ExprChain)
virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape, const FieldDecl *EscapeField)
virtual void reportLifetimeboundViolation(const ParmVarDecl *ParmWithLifetimebound)
virtual void addLifetimeBoundToImplicitThis(const CXXMethodDecl *MD)
virtual void reportDanglingGlobal(const Expr *IssueExpr, const VarDecl *DanglingGlobal, const Expr *MovedExpr, SourceLocation ExpiryLoc, llvm::ArrayRef< const Expr * > ExprChain, bool IsMain=false)
virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape, const Expr *EscapeExpr)
virtual void reportMisplacedLifetimebound(WarningScope Scope, const CXXMethodDecl *FDef, const CXXMethodDecl *FDecl)
virtual void suggestLifetimeboundToImplicitThis(WarningScope Scope, const CXXMethodDecl *MD, const Expr *EscapeExpr)
virtual void reportLifetimeboundViolation(const CXXMethodDecl *MDWithLifetimebound)
virtual void reportInvalidatedGlobal(const ParmVarDecl *PVD, const VarDecl *Global, const Expr *InvalidationExpr, llvm::ArrayRef< const Expr * > ExprChain)
virtual void reportUseAfterReturn(const Expr *IssueExpr, const Expr *ReturnExpr, const Expr *MovedExpr, llvm::ArrayRef< const Expr * > ExprChain)
Where and how an origin is used, for diagnostics.
Definition Facts.h:40
LifetimeSafetyAnalysis(AnalysisDeclContext &AC, LifetimeSafetySemaHelper *SemaHelper, const LifetimeSafetyOpts &LSOpts)
LoanPropagationAnalysis & getLoanPropagation() const
void collectLifetimeStats(AnalysisDeclContext &AC, OriginManager &OM, LifetimeSafetyStats &Stats)
void runLifetimeSafetyAnalysis(AnalysisDeclContext &AC, LifetimeSafetySemaHelper *SemaHelper, const LifetimeSafetyOpts &Opts, LifetimeSafetyStats &Stats, bool CollectStats)
The main entry point for the analysis.
WarningScope
Enum to track functions visible across or within TU.
bool SuggestAnnotations
Whether to suggest lifetime annotations.
size_t MaxCFGBlocks
Maximum number of CFG blocks to analyze.
bool CheckDestructorUses
Whether to model non-trivial destructors at scope exit as uses.
An object to hold the factories for immutable collections, ensuring that all created states share the...