clang 24.0.0git
Loans.h
Go to the documentation of this file.
1//===- Loans.h - Loan and Access Path Definitions --------------*- 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 Loan and AccessPath structures, which represent
10// borrows of storage locations, and the LoanManager, which manages the
11// creation and retrieval of loans during lifetime analysis.
12//
13//===----------------------------------------------------------------------===//
14#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_LOANS_H
15#define LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_LOANS_H
16
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/ExprCXX.h"
21#include "llvm/ADT/FoldingSet.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/Support/Allocator.h"
24#include "llvm/Support/raw_ostream.h"
25
27
29inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, LoanID ID) {
30 return OS << ID.Value;
31}
32
33/// Represents one step in an access path: either a field access or an
34/// access to an unnamed interior region (denoted by '*').
35///
36/// Examples:
37/// - Field access: `obj.field` has PathElement 'field'
38/// - Interior access: `owner.*` has '*'
39/// - In `std::string s; std::string_view v = s;`, v has loan to s.*
40/// - Array element: `arr[i]` has PathElement '*' (same as interior access)
41class PathElement {
42public:
43 enum class Kind { Field, Interior };
44
45 static PathElement getField(const FieldDecl &FD) {
46 return PathElement(Kind::Field, &FD);
47 }
48 static PathElement getInterior() {
49 return PathElement(Kind::Interior, nullptr);
50 }
51
52 bool isField() const { return K == Kind::Field; }
53 bool isInterior() const { return K == Kind::Interior; }
54 const FieldDecl *getFieldDecl() const { return FD; }
55
56 bool operator==(const PathElement &Other) const {
57 return K == Other.K && FD == Other.FD;
58 }
59 bool operator!=(const PathElement &Other) const { return !(*this == Other); }
60
61 void dump(llvm::raw_ostream &OS) const {
62 if (isField())
63 OS << "." << FD->getNameAsString();
64 else
65 OS << ".*";
66 }
67
68private:
69 PathElement(Kind K, const FieldDecl *FD) : K(K), FD(FD) {}
70 Kind K;
71 const FieldDecl *FD;
72};
73
74/// Represents the base of a placeholder access path, which is a function
75/// parameter, the implicit 'this' object of an instance method, or a field of
76/// the enclosing class. Placeholder paths never expire within the function
77/// scope, as they represent storage from the caller's or object's scope.
78class PlaceholderBase : public llvm::FoldingSetNode {
79 llvm::PointerUnion<const ParmVarDecl *, const CXXMethodDecl *,
80 const FieldDecl *>
81 ParamMethodOrField;
82
83public:
84 PlaceholderBase(const ParmVarDecl *PVD) : ParamMethodOrField(PVD) {}
85 PlaceholderBase(const CXXMethodDecl *MD) : ParamMethodOrField(MD) {}
86 PlaceholderBase(const FieldDecl *FD) : ParamMethodOrField(FD) {}
87
88 const ParmVarDecl *getParmVarDecl() const {
89 return dyn_cast<const ParmVarDecl *>(ParamMethodOrField);
90 }
91
93 return dyn_cast<const CXXMethodDecl *>(ParamMethodOrField);
94 }
95
96 const FieldDecl *getFieldDecl() const {
97 return dyn_cast<const FieldDecl *>(ParamMethodOrField);
98 }
99
100 using KeyTy = llvm::PointerUnion<const ParmVarDecl *, const CXXMethodDecl *,
101 const FieldDecl *>;
102
103 static void Profile(llvm::FoldingSetNodeID &ID, KeyTy ParamMethodOrField) {
104 ID.AddPointer(ParamMethodOrField.getOpaqueValue());
105 }
106
107 void Profile(llvm::FoldingSetNodeID &ID) const {
108 Profile(ID, ParamMethodOrField);
109 }
110};
111
112/// Represents the storage location being borrowed, e.g., a specific stack
113/// variable or a field within it: var.field.*
114///
115/// An AccessPath consists of:
116/// - A base: either a ValueDecl, MaterializeTemporaryExpr, or PlaceholderBase
117/// - A sequence of PathElements representing field accesses or interior
118/// regions
119///
120/// Examples:
121/// - `x` -> Base=x, Elements=[]
122/// - `x.field` -> Base=x, Elements=[.field]
123/// - `x.*` (e.g., string_view from string) -> Base=x, Elements=[.*]
124/// - `x.field.*` -> Base=x, Elements=[.field, .*]
125/// - `$param.field` -> Base=$param, Elements=[.field]
126///
127/// TODO: Model access paths of other types, e.g. heap and globals.
129 /// The base of the access path: a variable, temporary, placeholder, or an
130 /// allocation expression (a `CXXNewExpr` or an allocating `CallExpr`).
131 ///
132 /// NOTE: Keep the number of alternatives low; PointerUnion packs the
133 /// discriminator in the low bits of the pointer, so more alternatives
134 /// require more alignment than 32-bit builds can always provide.
135 const llvm::PointerUnion<const clang::ValueDecl *, const PlaceholderBase *,
136 const clang::Expr *>
137 Base;
138 /// The path elements representing field accesses and access to unnamed
139 /// interior regions.
141
142public:
143 AccessPath(const clang::ValueDecl *D) : Base(D) {}
145 AccessPath(const PlaceholderBase *PB) : Base(PB) {}
147 AccessPath(const clang::CallExpr *CE) : Base(CE) {}
148
149 /// Creates an extended access path by appending a path element.
150 /// Example: AccessPath(x_path, field) creates path to `x.field`.
152 : Base(Other.Base), Elements(Other.Elements) {
153 Elements.push_back(E);
154 }
155
157 return dyn_cast<const clang::ValueDecl *>(Base);
158 }
159
161 return dyn_cast_or_null<clang::MaterializeTemporaryExpr>(
162 dyn_cast<const clang::Expr *>(Base));
163 }
164
166 return dyn_cast<const PlaceholderBase *>(Base);
167 }
168
169 /// Returns the allocation expression that created this loan: a
170 /// `CXXNewExpr` or an allocating `CallExpr`.
172 const auto *E = dyn_cast<const clang::Expr *>(Base);
173 return isa_and_nonnull<clang::CXXNewExpr, clang::CallExpr>(E) ? E : nullptr;
174 }
175
176 bool operator==(const AccessPath &RHS) const {
177 return Base == RHS.Base && Elements == RHS.Elements;
178 }
179 bool operator!=(const AccessPath &RHS) const { return !(*this == RHS); }
180
181 /// Returns true if this path is a prefix of Other (or same as Other).
182 /// Examples:
183 /// - `x` is a prefix of `x`, `x.field`, `x.field.*`
184 /// - `x.field` is a prefix of `x.field` and `x.field.nested`
185 /// - `x.field` is NOT a prefix of `x.other_field`
186 bool isPrefixOf(const AccessPath &Other) const {
187 if (Base != Other.Base || Elements.size() > Other.Elements.size())
188 return false;
189 return std::equal(Elements.begin(), Elements.end(), Other.Elements.begin());
190 }
191
192 /// Returns true if this path is a strict prefix of Other.
193 /// Example:
194 /// - `x` is a strict prefix of `x.field` but NOT of `x`
195 bool isStrictPrefixOf(const AccessPath &Other) const {
196 return Elements.size() < Other.Elements.size() && isPrefixOf(Other);
197 }
198 llvm::ArrayRef<PathElement> getElements() const { return Elements; }
199
200 void dump(llvm::raw_ostream &OS) const;
201};
202
203/// Represents a component of an access path: either a named field access or an
204/// abstract unnamed interior region (denoted by '*').
205///
206/// The interior access (`*`) represents the borrowable content of an object
207/// without exposing its internal implementation details. It may abstract over
208/// multiple underlying fields or memory regions.
209///
210/// Examples:
211/// - `int* p = &x;` creates a loan to `x`
212/// - `std::string_view v = s;` creates a loan to `s.*` (interior)
213/// - `int* p = &obj.field;` creates a loan to `obj.field`
214/// - Parameter loans have no IssueExpr (created at function entry)
215class Loan {
216 const LoanID ID;
217 const AccessPath Path;
218 /// The expression that creates the loan, e.g., &x. Optional for placeholder
219 /// loans.
220 const Expr *IssueExpr;
221
222public:
223 Loan(LoanID ID, AccessPath Path, const Expr *IssueExpr = nullptr)
224 : ID(ID), Path(Path), IssueExpr(IssueExpr) {}
225
226 LoanID getID() const { return ID; }
227 const AccessPath &getAccessPath() const { return Path; }
228 const Expr *getIssueExpr() const { return IssueExpr; }
229
230 void dump(llvm::raw_ostream &OS) const;
231};
232
233/// Manages the creation, storage and retrieval of loans.
235
236public:
237 explicit LoanManager(llvm::BumpPtrAllocator &Alloc) : LoanAllocator(Alloc) {}
238
239 Loan *createLoan(AccessPath Path, const Expr *IssueExpr = nullptr) {
240 void *Mem = LoanAllocator.Allocate<Loan>();
241 auto *NewLoan = new (Mem) Loan(getNextLoanID(), Path, IssueExpr);
242 AllLoans.push_back(NewLoan);
243 return NewLoan;
244 }
245
247 return createLoan(AccessPath(getOrCreatePlaceholderBase(PVD)));
248 }
250 return createLoan(AccessPath(getOrCreatePlaceholderBase(MD)));
251 }
253 return createLoan(AccessPath(getOrCreatePlaceholderBase(FD)));
254 }
255
256 const Loan *getLoan(LoanID ID) const {
257 assert(ID.Value < AllLoans.size());
258 return AllLoans[ID.Value];
259 }
260
261 llvm::ArrayRef<const Loan *> getLoans() const { return AllLoans; }
262
263private:
264 LoanID getNextLoanID() { return NextLoanID++; }
265
266 /// Gets or creates a placeholder base for a given parameter, method, or
267 /// field.
268 const PlaceholderBase *getOrCreatePlaceholderBase(const ParmVarDecl *PVD);
269 const PlaceholderBase *getOrCreatePlaceholderBase(const CXXMethodDecl *MD);
270 const PlaceholderBase *getOrCreatePlaceholderBase(const FieldDecl *FD);
271
272 LoanID NextLoanID{0};
273
274 llvm::FoldingSet<PlaceholderBase> PlaceholderBases;
275
276 /// TODO(opt): Profile and evaluate the usefullness of small buffer
277 /// optimisation.
279 llvm::BumpPtrAllocator &LoanAllocator;
280};
281} // namespace clang::lifetimes::internal
282
283#endif // LLVM_CLANG_ANALYSIS_ANALYSES_LIFETIMESAFETY_LOANS_H
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2360
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
This represents one expression.
Definition Expr.h:114
Represents a member of a struct/union/class.
Definition Decl.h:3341
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4974
Represents a parameter to a function.
Definition Decl.h:1832
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
Represents the storage location being borrowed, e.g., a specific stack variable or a field within it:...
Definition Loans.h:128
bool isStrictPrefixOf(const AccessPath &Other) const
Returns true if this path is a strict prefix of Other.
Definition Loans.h:195
AccessPath(const clang::CallExpr *CE)
Definition Loans.h:147
bool isPrefixOf(const AccessPath &Other) const
Returns true if this path is a prefix of Other (or same as Other).
Definition Loans.h:186
bool operator!=(const AccessPath &RHS) const
Definition Loans.h:179
AccessPath(const clang::ValueDecl *D)
Definition Loans.h:143
const clang::ValueDecl * getAsValueDecl() const
Definition Loans.h:156
bool operator==(const AccessPath &RHS) const
Definition Loans.h:176
AccessPath(const clang::MaterializeTemporaryExpr *MTE)
Definition Loans.h:144
const clang::MaterializeTemporaryExpr * getAsMaterializeTemporaryExpr() const
Definition Loans.h:160
llvm::ArrayRef< PathElement > getElements() const
Definition Loans.h:198
const PlaceholderBase * getAsPlaceholderBase() const
Definition Loans.h:165
void dump(llvm::raw_ostream &OS) const
Definition Loans.cpp:13
AccessPath(const PlaceholderBase *PB)
Definition Loans.h:145
const clang::Expr * getAsAllocation() const
Returns the allocation expression that created this loan: a CXXNewExpr or an allocating CallExpr.
Definition Loans.h:171
AccessPath(const AccessPath &Other, PathElement E)
Creates an extended access path by appending a path element.
Definition Loans.h:151
AccessPath(const clang::CXXNewExpr *New)
Definition Loans.h:146
Loan * createPlaceholderLoan(const ParmVarDecl *PVD)
Definition Loans.h:246
llvm::ArrayRef< const Loan * > getLoans() const
Definition Loans.h:261
LoanManager(llvm::BumpPtrAllocator &Alloc)
Definition Loans.h:237
const Loan * getLoan(LoanID ID) const
Definition Loans.h:256
Loan * createLoan(AccessPath Path, const Expr *IssueExpr=nullptr)
Definition Loans.h:239
Loan * createPlaceholderLoan(const FieldDecl *FD)
Definition Loans.h:252
Loan * createPlaceholderLoan(const CXXMethodDecl *MD)
Definition Loans.h:249
Represents a component of an access path: either a named field access or an abstract unnamed interior...
Definition Loans.h:215
const Expr * getIssueExpr() const
Definition Loans.h:228
Loan(LoanID ID, AccessPath Path, const Expr *IssueExpr=nullptr)
Definition Loans.h:223
const AccessPath & getAccessPath() const
Definition Loans.h:227
void dump(llvm::raw_ostream &OS) const
Definition Loans.cpp:39
Represents one step in an access path: either a field access or an access to an unnamed interior regi...
Definition Loans.h:41
static PathElement getInterior()
Definition Loans.h:48
const FieldDecl * getFieldDecl() const
Definition Loans.h:54
void dump(llvm::raw_ostream &OS) const
Definition Loans.h:61
bool operator==(const PathElement &Other) const
Definition Loans.h:56
bool operator!=(const PathElement &Other) const
Definition Loans.h:59
static PathElement getField(const FieldDecl &FD)
Definition Loans.h:45
Represents the base of a placeholder access path, which is a function parameter, the implicit 'this' ...
Definition Loans.h:78
static void Profile(llvm::FoldingSetNodeID &ID, KeyTy ParamMethodOrField)
Definition Loans.h:103
PlaceholderBase(const ParmVarDecl *PVD)
Definition Loans.h:84
llvm::PointerUnion< const ParmVarDecl *, const CXXMethodDecl *, const FieldDecl * > KeyTy
Definition Loans.h:100
PlaceholderBase(const CXXMethodDecl *MD)
Definition Loans.h:85
PlaceholderBase(const FieldDecl *FD)
Definition Loans.h:86
const ParmVarDecl * getParmVarDecl() const
Definition Loans.h:88
const CXXMethodDecl * getImplicitThisParent() const
Definition Loans.h:92
const FieldDecl * getFieldDecl() const
Definition Loans.h:96
void Profile(llvm::FoldingSetNodeID &ID) const
Definition Loans.h:107
utils::ID< struct LoanTag > LoanID
Definition Loans.h:28
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, LoanID ID)
Definition Loans.h:29
A generic, type-safe wrapper for an ID, distinguished by its Tag type.
Definition Utils.h:21