clang 24.0.0git
FactsGenerator.h
Go to the documentation of this file.
1//===- FactsGenerator.h - Lifetime Facts Generation -------------*- 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 FactsGenerator, which traverses the AST to generate
10// lifetime-relevant facts (such as loan issuance, expiration, origin flow,
11// and use) from CFG statements. These facts are used by the dataflow analyses
12// to track pointer lifetimes and detect use-after-free errors.
13//
14//===----------------------------------------------------------------------===//
15#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_FACTSGENERATOR_H
16#define LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_FACTSGENERATOR_H
17
23#include "clang/Analysis/CFG.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/SmallVector.h"
26
28
29class FactsGenerator : public ConstStmtVisitor<FactsGenerator> {
31
32public:
34 const LifetimeSafetyOpts &LSOpts)
35 : FactMgr(FactMgr), AC(AC), LSOpts(LSOpts),
36 IsCMode(!AC.getASTContext().getLangOpts().CPlusPlus &&
37 !AC.getASTContext().getLangOpts().ObjC) {}
38
39 void run();
40
41 void VisitDeclStmt(const DeclStmt *DS);
42 void VisitDeclRefExpr(const DeclRefExpr *DRE);
47 void VisitMemberExpr(const MemberExpr *ME);
48 void VisitCallExpr(const CallExpr *CE);
50 void VisitCastExpr(const CastExpr *CE);
51 void VisitUnaryOperator(const UnaryOperator *UO);
52 void VisitReturnStmt(const ReturnStmt *RS);
53 void VisitBinaryOperator(const BinaryOperator *BO);
57 void VisitInitListExpr(const InitListExpr *ILE);
60 void VisitLambdaExpr(const LambdaExpr *LE);
62 void VisitCXXNewExpr(const CXXNewExpr *NE);
63 void VisitCXXDeleteExpr(const CXXDeleteExpr *DE);
64 void VisitCXXThrowExpr(const CXXThrowExpr *TE);
65 void VisitGCCAsmStmt(const GCCAsmStmt *AS);
66 void VisitCXXTypeidExpr(const CXXTypeidExpr *TE);
67 void VisitStmtExpr(const StmtExpr *SE);
68
69private:
70 OriginList *getOriginsList(const ValueDecl &D);
71 OriginList *getOriginsList(const Expr &E);
72
73 bool hasOrigins(QualType QT) const;
74 bool hasOrigins(const Expr *E) const;
75
76 void flow(OriginList *Dst, OriginList *Src, bool Kill,
77 const CFGBlock *Block = nullptr);
78
79 /// Handles assignment for both BinaryOperator and CXXOperatorCallExpr.
80 ///
81 /// LHSExpr is the destination whose stored loans are replaced by RHSExpr's
82 /// loans. TargetExpr is the assignment expression itself; it receives
83 /// LHSExpr's origins so chained assignments like `a = b = c` can propagate
84 /// through the result of `b = c`.
85 void handleAssignment(const Expr *TargetExpr, const Expr *LHSExpr,
86 const Expr *RHSExpr);
87
88 /// Models a call to an overloaded `operator=`, spelled `a = b` or
89 /// `a.operator=(b)`, as an assignment. Returns true if the call was modeled
90 /// as an assignment.
91 bool handleAssignmentOperatorCall(const CallExpr *CE, const Expr *LHSExpr,
92 const Expr *RHSExpr);
93
94 void handlePointerArithmetic(const BinaryOperator *BO);
95
96 bool handlePlacementNew(const CXXNewExpr *NE, OriginList *NewList);
97
98 void handleCXXCtorInitializer(const CXXCtorInitializer *CII);
99
100 void handleLifetimeEnds(const CFGLifetimeEnds &LifetimeEnds);
101
102 void handleFullExprCleanup(const CFGFullExprCleanup &FullExprCleanup);
103
104 void handleExitBlock();
105
106 /// Mark all fields of the implicit object as used for an instance method
107 /// call, since the callee may access any part of the object.
108 void handleImplicitObjectFieldUses(const Expr *Call, const FunctionDecl *FD);
109
110 void handleGSLPointerConstruction(const CXXConstructExpr *CCE);
111
112 /// Detects arguments passed to rvalue reference parameters and creates
113 /// MovedOriginFact for them. The MovedLoansAnalysis then uses these facts
114 /// to track in a flow-sensitive manner which loans have been moved at each
115 /// program point, allowing warnings to distinguish potentially moved storage
116 /// from other use-after-free errors.
117 void handleMovedArgsInCall(const FunctionDecl *FD,
119
120 // Handles [[clang::lifetime_capture_by(X)]] annotations on a function call to
121 // create flow facts from captured arguments to the capturer
122 void handleLifetimeCaptureBy(const FunctionDecl *FD,
124
125 /// Checks if a call-like expression creates a borrow by passing a value to a
126 /// reference parameter, creating an IssueFact if it does.
127 /// \param IsGslConstruction True if this is a GSL construction where all
128 /// argument origins should flow to the returned origin.
129 void handleFunctionCall(const Expr *Call, bool IsGslConstruction = false);
130
131 // Handles calls that allocate memory (e.g. functions annotated with
132 // `ownership_returns`): the call result is a fresh allocation, so a new
133 // loan is issued for it.
134 void handleAllocatingCall(const Expr *Call, const FunctionDecl *FD);
135
136 // Handles calls that free memory (e.g. functions annotated with
137 // `ownership_takes`): the freed arguments' origins are invalidated.
138 void handleFreeingCall(const Expr *Call, const FunctionDecl *FD,
140
141 // Detect methods that invalidate iterators/references/pointees.
142 // For instance methods, Args[0] is the implicit 'this' pointer.
143 void handleInvalidatingCall(const Expr *Call, const FunctionDecl *FD,
145
146 // Detect explicit destructor calls/`std::destroy_at`
147 void handleDestructiveCall(const Expr *Call, const FunctionDecl *FD,
149
150 template <typename Destination, typename Source>
151 void flowOrigin(const Destination &D, const Source &S) {
152 flow(getOriginsList(D), getOriginsList(S), /*Kill=*/false);
153 }
154
155 template <typename Destination, typename Source>
156 void killAndFlowOrigin(const Destination &D, const Source &S) {
157 flow(getOriginsList(D), getOriginsList(S), /*Kill=*/true);
158 }
159
160 /// Checks if the expression is a `void("__lifetime_test_point_...")` cast.
161 /// If so, creates a `TestPointFact` and returns true.
162 bool handleTestPoint(const CXXFunctionalCastExpr *FCE);
163
164 /// Whether \p List's outer origin names a declaration's storage outright, so
165 /// it can never hold an expired loan (see Origin::NamesDeclStorage).
166 bool namesDeclStorage(const OriginList *List) const;
167
168 /// Returns the origins of the value \p E evaluates to, recording the read of
169 /// a glvalue. Callers that write to \p E peel the outer origin themselves.
170 ///
171 /// Example: For `View& v`, returns the origin of what v points to, not v's
172 /// storage.
173 OriginList *readValue(const Expr *E);
174
175 /// Records an access (read or write) of the storage \p E designates, or that
176 /// a prvalue pointer \p E points to.
177 void handleAccess(const Expr *E);
178
179 /// Records that \p E's value is handed to opaque code, which may dereference
180 /// it to any depth.
181 void handleUse(const Expr *E);
182
183 bool escapesViaReturn(OriginID OID) const;
184
185 llvm::SmallVector<Fact *> issuePlaceholderLoans();
186 void issueFieldPlaceholderLoans(const CXXRecordDecl *ClassDef,
188 FactManager &FactMgr;
190 const LifetimeSafetyOpts &LSOpts;
191 llvm::SmallVector<Fact *> CurrentBlockFacts;
192 // Collect origins that escape the function in this block (OriginEscapesFact),
193 // appended at the end of CurrentBlockFacts to ensure they appear after
194 // ExpireFact entries.
195 llvm::SmallVector<Fact *> EscapesInCurrentBlock;
196 // Lifetime-extended temporaries, keyed by the variable they expire with.
197 llvm::DenseMap<const ValueDecl *,
199 ExtendedTemporaries;
200 const CFGBlock *CurrentBlock;
201 bool IsCMode = false;
202};
203
204} // namespace clang::lifetimes::internal
205
206#endif // LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_FACTSGENERATOR_H
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, APValue &Val)
Perform an assignment of Val to LVal. Takes ownership of Val.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4422
AnalysisDeclContext contains the context data for the function, method or block under analysis.
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2790
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
Represents a single basic block in a source-level CFG.
Definition CFG.h:651
Represents the point where the lifetime of an automatic object ends.
Definition CFG.h:321
Represents binding an expression to a temporary.
Definition ExprCXX.h:1498
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
Represents a C++ base or member initializer.
Definition DeclCXX.h:2410
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1275
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1382
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2631
Represents an explicit C++ type conversion that uses "functional" notation (C++ [expr....
Definition ExprCXX.h:1836
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:184
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2360
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:773
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:86
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
A C++ throw-expression (C++ [except.throw]).
Definition ExprCXX.h:1213
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:853
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3745
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1642
This represents one expression.
Definition Expr.h:114
Represents a function declaration or definition.
Definition Decl.h:2082
This represents a GCC inline-assembly statement extension.
Definition Stmt.h:3459
Describes an C or C++ initializer list.
Definition Expr.h:5377
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1973
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4974
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3433
A (possibly-)qualified type.
Definition TypeBase.h:938
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3173
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4664
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
void VisitDeclRefExpr(const DeclRefExpr *DRE)
void VisitBinaryOperator(const BinaryOperator *BO)
void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *MTE)
void VisitCXXConstructExpr(const CXXConstructExpr *CCE)
void VisitCXXTypeidExpr(const CXXTypeidExpr *TE)
FactsGenerator(FactManager &FactMgr, AnalysisDeclContext &AC, const LifetimeSafetyOpts &LSOpts)
void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO)
Visits conditional operators (e.g., cond ?
void VisitCXXDeleteExpr(const CXXDeleteExpr *DE)
void VisitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *FCE)
void VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *DIE)
void VisitInitListExpr(const InitListExpr *ILE)
void VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *DAE)
void VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *N)
void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE)
void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE)
void VisitUnaryOperator(const UnaryOperator *UO)
void VisitCXXThrowExpr(const CXXThrowExpr *TE)
void VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE)
void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *BTE)
A list of origins representing levels of indirection for pointer-like types.
Definition Origins.h:105
utils::ID< struct OriginTag > OriginID
Definition Origins.h:28
@ CPlusPlus