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 <cstddef>
32#include <memory>
33
34namespace clang::lifetimes {
35
37 /// Maximum number of CFG blocks to analyze. Functions with larger CFGs will
38 /// be skipped.
40};
41
42/// Enum to track functions visible across or within TU.
43enum class SuggestionScope {
44 CrossTU, // For suggestions on declarations visible across Translation Units.
45 IntraTU // For suggestions on definitions local to a Translation Unit.
46};
47
48/// Abstract interface for operations requiring Sema access.
49///
50/// This class exists to break a circular dependency: the LifetimeSafety
51/// analysis target cannot directly depend on clangSema (which would create the
52/// cycle: clangSema -> clangAnalysis -> clangAnalysisLifetimeSafety ->
53/// clangSema).
54///
55/// Instead, this interface is implemented in AnalysisBasedWarnings.cpp (part of
56/// clangSema), allowing the analysis to report diagnostics and modify the AST
57/// through Sema without introducing a circular dependency.
59public:
61 virtual ~LifetimeSafetySemaHelper() = default;
62
63 virtual void reportUseAfterFree(const Expr *IssueExpr, const Expr *UseExpr,
64 const Expr *MovedExpr,
65 SourceLocation FreeLoc) {}
66
67 virtual void reportUseAfterReturn(const Expr *IssueExpr,
68 const Expr *ReturnExpr,
69 const Expr *MovedExpr,
70 SourceLocation ExpiryLoc) {}
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
91 // Suggests lifetime bound annotations for function paramters.
93 const ParmVarDecl *ParmToAnnotate,
94 const Expr *EscapeExpr) {}
95
96 // Reports misuse of [[clang::noescape]] when parameter escapes through return
97 virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
98 const Expr *EscapeExpr) {}
99 // Reports misuse of [[clang::noescape]] when parameter escapes through field
100 virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
101 const FieldDecl *EscapeField) {}
102 // Reports misuse of [[clang::noescape]] when parameter escapes through
103 // assignment to a global variable
104 virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape,
105 const VarDecl *EscapeGlobal) {}
106
107 // Suggests lifetime bound annotations for implicit this.
109 const CXXMethodDecl *MD,
110 const Expr *EscapeExpr) {}
111
112 // Adds inferred lifetime bound attribute for implicit this to its
113 // TypeSourceInfo.
115};
116
117/// The main entry point for the analysis.
119 LifetimeSafetySemaHelper *SemaHelper,
120 LifetimeSafetyStats &Stats, bool CollectStats);
121
122namespace internal {
123
124void collectLifetimeStats(AnalysisDeclContext &AC, OriginManager &OM,
125 LifetimeSafetyStats &Stats);
126
127/// An object to hold the factories for immutable collections, ensuring
128/// that all created states share the same underlying memory management.
130 OriginLoanMap::Factory OriginMapFactory{/*canonicalize=*/false};
131 LoanSet::Factory LoanSetFactory{/*canonicalize=*/false};
132 MovedLoansMap::Factory MovedLoansMapFactory{/*canonicalize=*/false};
133 LivenessMap::Factory LivenessMapFactory{/*canonicalize=*/false};
134};
135
136/// Running the lifetime safety analysis and querying its results. It
137/// encapsulates the various dataflow analyses.
139public:
141 LifetimeSafetySemaHelper *SemaHelper,
142 const LifetimeSafetyOpts &LSOpts);
143
144 void run();
145
146 /// \note These are provided only for testing purposes.
148 return *LoanPropagation;
149 }
150 LiveOriginsAnalysis &getLiveOrigins() const { return *LiveOrigins; }
151 FactManager &getFactManager() { return *FactMgr; }
152
153private:
155 LifetimeSafetySemaHelper *SemaHelper;
156 const LifetimeSafetyOpts LSOpts;
157 LifetimeFactory Factory;
158 std::unique_ptr<FactManager> FactMgr;
159 std::unique_ptr<LiveOriginsAnalysis> LiveOrigins;
160 std::unique_ptr<LoanPropagationAnalysis> LoanPropagation;
161 std::unique_ptr<MovedLoansAnalysis> MovedLoans;
162};
163} // namespace internal
164} // namespace clang::lifetimes
165
166#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:2136
This represents one expression.
Definition Expr.h:112
Represents a member of a struct/union/class.
Definition Decl.h:3160
Represents a parameter to a function.
Definition Decl.h:1790
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:926
Abstract interface for operations requiring Sema access.
virtual void reportUseAfterReturn(const Expr *IssueExpr, const Expr *ReturnExpr, const Expr *MovedExpr, SourceLocation ExpiryLoc)
virtual void reportUseAfterInvalidation(const ParmVarDecl *PVD, const Expr *UseExpr, const Expr *InvalidationExpr)
virtual void reportDanglingGlobal(const Expr *IssueExpr, const VarDecl *DanglingGlobal, const Expr *MovedExpr, SourceLocation ExpiryLoc)
virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape, const VarDecl *EscapeGlobal)
virtual void suggestLifetimeboundToImplicitThis(SuggestionScope Scope, const CXXMethodDecl *MD, const Expr *EscapeExpr)
virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape, const FieldDecl *EscapeField)
virtual void suggestLifetimeboundToParmVar(SuggestionScope Scope, const ParmVarDecl *ParmToAnnotate, const Expr *EscapeExpr)
virtual void reportDanglingField(const Expr *IssueExpr, const FieldDecl *Field, const Expr *MovedExpr, SourceLocation ExpiryLoc)
virtual void addLifetimeBoundToImplicitThis(const CXXMethodDecl *MD)
virtual void reportNoescapeViolation(const ParmVarDecl *ParmWithNoescape, const Expr *EscapeExpr)
virtual void reportUseAfterFree(const Expr *IssueExpr, const Expr *UseExpr, const Expr *MovedExpr, SourceLocation FreeLoc)
virtual void reportUseAfterInvalidation(const Expr *IssueExpr, const Expr *UseExpr, const Expr *InvalidationExpr)
LifetimeSafetyAnalysis(AnalysisDeclContext &AC, LifetimeSafetySemaHelper *SemaHelper, const LifetimeSafetyOpts &LSOpts)
LoanPropagationAnalysis & getLoanPropagation() const
void collectLifetimeStats(AnalysisDeclContext &AC, OriginManager &OM, LifetimeSafetyStats &Stats)
SuggestionScope
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...