clang 24.0.0git
LoanPropagation.cpp
Go to the documentation of this file.
1//===- LoanPropagation.cpp - Loan Propagation 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#include <algorithm>
9#include <cassert>
10#include <memory>
11
12#include "Dataflow.h"
13#include "clang/AST/Expr.h"
20#include "clang/Analysis/CFG.h"
21#include "clang/Basic/LLVM.h"
22#include "llvm/ADT/BitVector.h"
23#include "llvm/ADT/ImmutableList.h"
24#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/Support/raw_ostream.h"
27
29
30namespace {
31
32/// Represents the dataflow lattice for loan propagation.
33///
34/// This lattice tracks which loans each origin may hold at a given program
35/// point.The lattice has a finite height: An origin's loan set is bounded by
36/// the total number of loans in the function.
37struct Lattice {
38 /// The map from an origin to the set of loans it contains.
39 /// Origins that appear in multiple blocks. Participates in join operations.
40 OriginLoanMap PersistentOrigins = OriginLoanMap(nullptr);
41 /// Origins confined to a single block. Discarded at block boundaries.
42 OriginLoanMap BlockLocalOrigins = OriginLoanMap(nullptr);
43
44 explicit Lattice(const OriginLoanMap &Persistent,
45 const OriginLoanMap &BlockLocal)
46 : PersistentOrigins(Persistent), BlockLocalOrigins(BlockLocal) {}
47 Lattice() = default;
48
49 bool operator==(const Lattice &Other) const {
50 return PersistentOrigins == Other.PersistentOrigins &&
51 BlockLocalOrigins == Other.BlockLocalOrigins;
52 }
53 bool operator!=(const Lattice &Other) const { return !(*this == Other); }
54
55 void dump(llvm::raw_ostream &OS) const {
56 OS << "LoanPropagationLattice State:\n";
57 OS << " Persistent Origins:\n";
58 if (PersistentOrigins.isEmpty())
59 OS << " <empty>\n";
60 for (const auto &Entry : PersistentOrigins) {
61 if (Entry.second.isEmpty())
62 OS << " Origin " << Entry.first << " contains no loans\n";
63 for (const LoanID &LID : Entry.second)
64 OS << " Origin " << Entry.first << " contains Loan " << LID << "\n";
65 }
66 OS << " Block-Local Origins:\n";
67 if (BlockLocalOrigins.isEmpty())
68 OS << " <empty>\n";
69 for (const auto &Entry : BlockLocalOrigins) {
70 if (Entry.second.isEmpty())
71 OS << " Origin " << Entry.first << " contains no loans\n";
72 for (const LoanID &LID : Entry.second)
73 OS << " Origin " << Entry.first << " contains Loan " << LID << "\n";
74 }
75 }
76};
77
78class AnalysisImpl
79 : public DataflowAnalysis<AnalysisImpl, Lattice, Direction::Forward> {
80public:
81 AnalysisImpl(const CFG &C, AnalysisDeclContext &AC, FactManager &F,
82 OriginLoanMap::Factory &OriginLoanMapFactory,
83 LoanSet::Factory &LoanSetFactory)
84 : DataflowAnalysis(C, AC, F), OriginLoanMapFactory(OriginLoanMapFactory),
85 LoanSetFactory(LoanSetFactory),
86 PersistentOrigins(F.getPersistentOrigins()) {}
87
88 using Base::transfer;
89
90 StringRef getAnalysisName() const { return "LoanPropagation"; }
91
92 Lattice getInitialState() { return Lattice{}; }
93
94 /// Merges two lattices by taking the union of loans for each origin.
95 Lattice join(Lattice A, Lattice B) {
96 assert(A.BlockLocalOrigins.isEmpty() && B.BlockLocalOrigins.isEmpty() &&
97 "block-local origins must not reach a block boundary");
98 OriginLoanMap JoinedOrigins = utils::join(
99 A.PersistentOrigins, B.PersistentOrigins, OriginLoanMapFactory,
100 [&](const LoanSet *S1, const LoanSet *S2) {
101 assert((S1 || S2) && "unexpectedly merging 2 empty sets");
102 if (!S1)
103 return *S2;
104 if (!S2)
105 return *S1;
106 return utils::join(*S1, *S2, LoanSetFactory);
107 },
108 // Asymmetric join is a performance win. For origins present only on one
109 // branch, the loan set can be carried over as-is.
111 return Lattice(JoinedOrigins, OriginLoanMapFactory.getEmptyMap());
112 }
113
114 /// Block-local origins are not referenced outside the block that computed
115 /// them, so they are dropped here rather than propagated to adjacent blocks.
116 /// Dropping them at the boundary (instead of in `join`) also covers edges
117 /// where `join` is never called, such as blocks with a single predecessor.
118 Lattice transferAtBlockExit(Lattice L) {
119 return Lattice(L.PersistentOrigins, OriginLoanMapFactory.getEmptyMap());
120 }
121
122 /// A new loan is issued to the origin. Old loans are erased.
123 Lattice transfer(Lattice In, const IssueFact &F) {
124 OriginID OID = F.getOriginID();
125 LoanID LID = F.getLoanID();
126 LoanSet NewLoans = LoanSetFactory.add(LoanSetFactory.getEmptySet(), LID);
127 return setLoans(In, OID, NewLoans);
128 }
129
130 /// A flow from source to destination. If `KillDest` is true, this replaces
131 /// the destination's loans with the source's. Otherwise, the source's loans
132 /// are merged into the destination's.
133 Lattice transfer(Lattice In, const OriginFlowFact &F) {
134 OriginID DestOID = F.getDestOriginID();
135 OriginID SrcOID = F.getSrcOriginID();
136
137 LoanSet DestLoans =
138 F.getKillDest() ? LoanSetFactory.getEmptySet() : getLoans(In, DestOID);
139 LoanSet SrcLoans = getLoans(In, SrcOID);
140 LoanSet MergedLoans = utils::join(DestLoans, SrcLoans, LoanSetFactory);
141
142 return setLoans(In, DestOID, MergedLoans);
143 }
144
145 Lattice transfer(Lattice In, const KillOriginFact &F) {
146 return setLoans(In, F.getKilledOrigin(), LoanSetFactory.getEmptySet());
147 }
148
149 Lattice transfer(Lattice In, const ExpireFact &F) {
150 if (auto OID = F.getOriginID())
151 return setLoans(In, *OID, LoanSetFactory.getEmptySet());
152 return In;
153 }
154
155 LoanSet getLoans(OriginID OID, ProgramPoint P) const {
156 return getLoans(getState(P), OID);
157 }
158
159 llvm::SmallVector<OriginID> buildOriginFlowChain(ProgramPoint StartPoint,
160 const OriginID StartOID,
161 const LoanID TargetLoan,
162 const CFG *Cfg) const {
163 assert(getLoans(StartOID, StartPoint).contains(TargetLoan) &&
164 "TargetLoan must be present in the StartOID at the StartPoint");
165
166 // Locate the CFG block containing the StartPoint
167 const CFGBlock *EndBlock = nullptr;
168 size_t BlockID = FactMgr.getBlockID(StartPoint);
169 for (const CFGBlock *Block : *Cfg)
170 if (Block->getBlockID() == BlockID) {
171 EndBlock = Block;
172 break;
173 }
174
175 // Set up DFS traversal state
176 // SearchState tracks which block we're in and which origin we're tracing
177 // Each DFSNode maintains its own OriginFlowChain.
178 using SearchState = std::pair<const CFGBlock *, OriginID>;
179 struct DFSNode {
180 SearchState CurrState;
181 llvm::ImmutableList<OriginID> OriginFlowChain;
182 };
183
184 llvm::SmallVector<DFSNode> PendingStates;
185 llvm::SmallSet<SearchState, 16> VistedStates;
186 llvm::ImmutableList<OriginID>::Factory OriginFlowChainFactory;
187 PendingStates.push_back(
188 {{EndBlock, StartOID}, OriginFlowChainFactory.getEmptyList()});
189
190 // The loans held at StartPoint cannot come from later flows, so the first
191 // scan starts there. A loop may lead back to StartPoint's block; that visit
192 // is its previous iteration, which ran entirely before StartPoint, so scan
193 // the whole block.
194 ProgramPoint ScanFrom = StartPoint;
195
196 // DFS loop to trace loan backwards through CFG
197 while (!PendingStates.empty()) {
198 DFSNode CurrNode = PendingStates.pop_back_val();
199 auto [CurrBlock, CurrOID] = CurrNode.CurrState;
200
201 // Trace origins within the current block
202 const auto [BuildResult, Complete] =
203 buildOriginFlowChain(CurrBlock, CurrOID, TargetLoan, ScanFrom);
204 ScanFrom = nullptr;
205 if (!BuildResult.empty()) {
206 for (OriginID OID : BuildResult)
207 CurrNode.OriginFlowChain =
208 OriginFlowChainFactory.add(OID, CurrNode.OriginFlowChain);
209 CurrOID = BuildResult.back();
210 }
211
212 // If we found the IssueFact, we're done
213 if (Complete) {
214 llvm::SmallVector<OriginID> Result(CurrNode.OriginFlowChain.begin(),
215 CurrNode.OriginFlowChain.end());
216 std::reverse(Result.begin(), Result.end());
217 return Result;
218 }
219
220 // Only explore predecessor blocks where the target loan is present in the
221 // current origin.
222 for (const CFGBlock *PredBlock : CurrBlock->preds()) {
223 if (!PredBlock)
224 continue;
225 SearchState NextState = {PredBlock, CurrOID};
226 if (getLoans(getOutState(PredBlock), CurrOID).contains(TargetLoan) &&
227 VistedStates.insert(NextState).second)
228 PendingStates.push_back({NextState, CurrNode.OriginFlowChain});
229 }
230 }
231
232 llvm_unreachable("Could not reconstruct origin flow. Search finished "
233 "without reaching IssueFact");
234 }
235
236 llvm::SmallVector<OriginID> buildOriginFlowChain(const UseFact *UF,
237 const LoanID TargetLoan,
238 const CFG *Cfg) const {
239 for (const OriginList *Cur = UF->getUsedOrigins(); Cur;
240 Cur = Cur->peelOuterOrigin())
241 if (getLoans(Cur->getOuterOriginID(), UF).contains(TargetLoan))
242 return dropLeadingLoads(
243 Cur->getOuterOriginID(),
244 buildOriginFlowChain(UF, Cur->getOuterOriginID(), TargetLoan, Cfg));
245
246 return {};
247 }
248
249 llvm::SmallVector<OriginID> buildOriginFlowChain(const OriginEscapesFact *OEF,
250 const LoanID TargetLoan,
251 const CFG *Cfg) const {
252 OriginID OID = OEF->getEscapedOriginID();
253 if (!getLoans(OID, OEF).contains(TargetLoan))
254 return {};
255 return dropLeadingLoads(OID,
256 buildOriginFlowChain(OEF, OID, TargetLoan, Cfg));
257 }
258
259private:
260 /// An expression's origin only receives loans from its subexpressions, so
261 /// until the chain reaches a declaration it is inside the expression the
262 /// chain starts from. Casts there just load its variable, so drop them.
263 llvm::SmallVector<OriginID>
264 dropLeadingLoads(OriginID StartOID, llvm::SmallVector<OriginID> Chain) const {
265 const OriginManager &OM = FactMgr.getOriginMgr();
266 // When the chain starts from a declaration, e.g. field `p_` read by a
267 // member call, the leading casts come from the write that stored the loan
268 // in it, such as `p` loaded in `p_ = p`. They name the alias, so keep them.
269 if (!OM.getOrigin(StartOID).getExpr())
270 return Chain;
271 auto FirstDecl = llvm::find_if(
272 Chain, [&](OriginID OID) { return !OM.getOrigin(OID).getExpr(); });
273 Chain.erase(std::remove_if(Chain.begin(), FirstDecl,
274 [&](OriginID OID) {
275 return isa<ImplicitCastExpr>(
276 OM.getOrigin(OID).getExpr());
277 }),
278 FirstDecl);
279 return Chain;
280 }
281
282 /// Returns true if the origin is persistent (referenced in multiple blocks).
283 bool isPersistent(OriginID OID) const {
284 return PersistentOrigins.test(OID.Value);
285 }
286
287 Lattice setLoans(Lattice L, OriginID OID, LoanSet Loans) {
288 OriginLoanMap &Map =
289 isPersistent(OID) ? L.PersistentOrigins : L.BlockLocalOrigins;
290 // An origin that is not in the map has no loans, so do not store those.
291 Map = Loans.isEmpty() ? OriginLoanMapFactory.remove(Map, OID)
292 : OriginLoanMapFactory.add(Map, OID, Loans);
293 return L;
294 }
295
296 LoanSet getLoans(Lattice L, OriginID OID) const {
297 const OriginLoanMap *Map =
298 isPersistent(OID) ? &L.PersistentOrigins : &L.BlockLocalOrigins;
299 if (auto *Loans = Map->lookup(OID))
300 return *Loans;
301 return LoanSetFactory.getEmptySet();
302 }
303
304 /// Builds the chain of origins through which a loan has propagated.
305 ///
306 /// This procedure operates strictly within a single Block. Starting from
307 /// \p ScanFrom, or from the last fact of the Block if it is null, it traces
308 /// backwards through OriginFlowFacts to identify the sequence of origins
309 /// through which the loan flowed.
310 ///
311 /// Returns (chain, true) if the target loan origin is found during the
312 /// traversal, otherwise returns (chain, false).
313 std::pair<llvm::SmallVector<OriginID>, bool>
314 buildOriginFlowChain(const CFGBlock *Block, const OriginID StartOID,
315 const LoanID TargetLoan, ProgramPoint ScanFrom) const {
316 OriginID CurrOID = StartOID;
317 llvm::SmallVector<OriginID> OriginFlowChain;
318
319 auto Facts = llvm::reverse(FactMgr.getFacts(Block));
320 auto Begin = Facts.begin();
321 if (ScanFrom) {
322 Begin = llvm::find(Facts, ScanFrom);
323 assert(Begin != Facts.end() && "ScanFrom must be in Block");
324 }
325 for (const Fact *F : llvm::make_range(Begin, Facts.end())) {
326 if (const auto *IF = F->getAs<IssueFact>())
327 if (IF->getLoanID() == TargetLoan && IF->getOriginID() == CurrOID)
328 return {OriginFlowChain, true};
329
330 const auto *OFF = F->getAs<OriginFlowFact>();
331 if (!OFF || OFF->getDestOriginID() != CurrOID)
332 continue;
333
334 const OriginID SrcOriginID = OFF->getSrcOriginID();
335 if (!getLoans(SrcOriginID, OFF).contains(TargetLoan))
336 continue;
337
338 OriginFlowChain.push_back(SrcOriginID);
339 CurrOID = SrcOriginID;
340 }
341
342 return {OriginFlowChain, false};
343 }
344
345 OriginLoanMap::Factory &OriginLoanMapFactory;
346 LoanSet::Factory &LoanSetFactory;
347 /// Origins referenced from more than one basic block; see
348 /// `FactManager::getPersistentOrigins`.
349 const llvm::BitVector &PersistentOrigins;
350};
351} // namespace
352
353class LoanPropagationAnalysis::Impl final : public AnalysisImpl {
354 using AnalysisImpl::AnalysisImpl;
355};
356
358 const CFG &C, AnalysisDeclContext &AC, FactManager &F,
359 OriginLoanMap::Factory &OriginLoanMapFactory,
360 LoanSet::Factory &LoanSetFactory)
361 : PImpl(std::make_unique<Impl>(C, AC, F, OriginLoanMapFactory,
362 LoanSetFactory)) {
363 PImpl->run();
364}
365
367
369 return PImpl->getLoans(OID, P);
370}
371
373 ProgramPoint StartPoint, const OriginID StartOID, const LoanID TargetLoan,
374 const CFG *Cfg) const {
375 return PImpl->buildOriginFlowChain(StartPoint, StartOID, TargetLoan, Cfg);
376}
377
379 const Fact *F, const LoanID TargetLoan, const CFG *Cfg) const {
380 if (const auto *UF = llvm::dyn_cast<UseFact>(F))
381 return PImpl->buildOriginFlowChain(UF, TargetLoan, Cfg);
382 if (const auto *OEF = llvm::dyn_cast<OriginEscapesFact>(F))
383 return PImpl->buildOriginFlowChain(OEF, TargetLoan, Cfg);
384 llvm_unreachable("Unhandled Fact type");
385}
386} // namespace clang::lifetimes::internal
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
static bool contains(const std::set< tok::TokenKind > &Terminators, const Token &Tok)
AnalysisDeclContext contains the context data for the function, method or block under analysis.
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
Definition CFG.h:1294
A generic, policy-based driver for dataflow analyses.
Definition Dataflow.h:60
An abstract base class for a single, atomic lifetime-relevant event.
Definition Facts.h:100
llvm::SmallVector< OriginID > buildOriginFlowChain(ProgramPoint StartPoint, const OriginID StartOID, const LoanID TargetLoan, const CFG *Cfg) const
Builds the chain of origins through which a loan has propagated.
LoanSet getLoans(OriginID OID, ProgramPoint P) const
LoanPropagationAnalysis(const CFG &C, AnalysisDeclContext &AC, FactManager &F, OriginLoanMap::Factory &OriginLoanMapFactory, LoanSet::Factory &LoanSetFactory)
BlockID
The various types of blocks that can occur within a API notes file.
void transfer(const StmtToEnvMap &StmtToEnv, const Stmt &S, Environment &Env, Environment::ValueModel &Model)
Evaluates S and updates Env accordingly.
Definition Transfer.cpp:986
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ Asymmetric
An asymmetric join preserves keys unique to the first map as-is, while applying the JoinValues operat...
Definition Utils.h:66
SetTy< T > join(SetTy< T > A, SetTy< T > B, typename SetTy< T >::Factory &F)
Computes the union of two ImmutableSets.
Definition Utils.h:49
const Fact * ProgramPoint
A ProgramPoint identifies a location in the CFG by pointing to a specific Fact.
Definition Facts.h:158
utils::ID< struct LoanTag > LoanID
Definition Loans.h:28
utils::ID< struct OriginTag > OriginID
Definition Origins.h:29
utils::SetTy< LoanID > LoanSet
utils::MapTy< OriginID, LoanSet > OriginLoanMap
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:218
@ Result
The result type of a method or function.
Definition TypeBase.h:906
bool operator!=(CanQual< T > x, CanQual< U > y)