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 // DFS loop to trace loan backwards through CFG
191 while (!PendingStates.empty()) {
192 DFSNode CurrNode = PendingStates.pop_back_val();
193 auto [CurrBlock, CurrOID] = CurrNode.CurrState;
194
195 // Trace origins within the current block
196 const auto [BuildResult, Complete] =
197 buildOriginFlowChain(CurrBlock, CurrOID, TargetLoan);
198 if (!BuildResult.empty()) {
199 for (OriginID OID : BuildResult)
200 CurrNode.OriginFlowChain =
201 OriginFlowChainFactory.add(OID, CurrNode.OriginFlowChain);
202 CurrOID = BuildResult.back();
203 }
204
205 // If we found the IssueFact, we're done
206 if (Complete) {
207 llvm::SmallVector<OriginID> Result(CurrNode.OriginFlowChain.begin(),
208 CurrNode.OriginFlowChain.end());
209 std::reverse(Result.begin(), Result.end());
210 return Result;
211 }
212
213 // Only explore predecessor blocks where the target loan is present in the
214 // current origin.
215 for (const CFGBlock *PredBlock : CurrBlock->preds()) {
216 SearchState NextState = {PredBlock, CurrOID};
217 if (getLoans(getOutState(PredBlock), CurrOID).contains(TargetLoan) &&
218 VistedStates.insert(NextState).second)
219 PendingStates.push_back({NextState, CurrNode.OriginFlowChain});
220 }
221 }
222
223 llvm_unreachable("Could not reconstruct origin flow. Search finished "
224 "without reaching IssueFact");
225 }
226
227 llvm::SmallVector<OriginID> buildOriginFlowChain(const UseFact *UF,
228 const LoanID TargetLoan,
229 const CFG *Cfg) const {
230 for (const OriginList *Cur = UF->getUsedOrigins(); Cur;
231 Cur = Cur->peelOuterOrigin())
232 if (getLoans(Cur->getOuterOriginID(), UF).contains(TargetLoan))
233 return dropLoadsInUse(
234 buildOriginFlowChain(UF, Cur->getOuterOriginID(), TargetLoan, Cfg));
235
236 return {};
237 }
238
239private:
240 /// An expression's origin only receives loans from its subexpressions, so
241 /// until the chain reaches a declaration it is inside the use expression.
242 /// Casts there just load the used variable, so drop them.
243 llvm::SmallVector<OriginID>
244 dropLoadsInUse(llvm::SmallVector<OriginID> Chain) const {
245 const OriginManager &OM = FactMgr.getOriginMgr();
246 auto FirstDecl = llvm::find_if(
247 Chain, [&](OriginID OID) { return !OM.getOrigin(OID).getExpr(); });
248 Chain.erase(std::remove_if(Chain.begin(), FirstDecl,
249 [&](OriginID OID) {
250 return isa<ImplicitCastExpr>(
251 OM.getOrigin(OID).getExpr());
252 }),
253 FirstDecl);
254 return Chain;
255 }
256
257 /// Returns true if the origin is persistent (referenced in multiple blocks).
258 bool isPersistent(OriginID OID) const {
259 return PersistentOrigins.test(OID.Value);
260 }
261
262 Lattice setLoans(Lattice L, OriginID OID, LoanSet Loans) {
263 if (isPersistent(OID))
264 return Lattice(OriginLoanMapFactory.add(L.PersistentOrigins, OID, Loans),
265 L.BlockLocalOrigins);
266 return Lattice(L.PersistentOrigins,
267 OriginLoanMapFactory.add(L.BlockLocalOrigins, OID, Loans));
268 }
269
270 LoanSet getLoans(Lattice L, OriginID OID) const {
271 const OriginLoanMap *Map =
272 isPersistent(OID) ? &L.PersistentOrigins : &L.BlockLocalOrigins;
273 if (auto *Loans = Map->lookup(OID))
274 return *Loans;
275 return LoanSetFactory.getEmptySet();
276 }
277
278 /// Builds the chain of origins through which a loan has propagated.
279 ///
280 /// This procedure operates strictly within a single Block. Starting from the
281 /// last fact of the Block, it traces backwards through OriginFlowFacts to
282 /// identify the sequence of origins through which the loan flowed.
283 ///
284 /// Returns (chain, true) if the target loan origin is found during the
285 /// traversal, otherwise returns (chain, false).
286 std::pair<llvm::SmallVector<OriginID>, bool>
287 buildOriginFlowChain(const CFGBlock *Block, const OriginID StartOID,
288 const LoanID TargetLoan) const {
289 OriginID CurrOID = StartOID;
290 llvm::SmallVector<OriginID> OriginFlowChain;
291
292 for (const Fact *F : llvm::reverse(FactMgr.getFacts(Block))) {
293 if (const auto *IF = F->getAs<IssueFact>())
294 if (IF->getLoanID() == TargetLoan && IF->getOriginID() == CurrOID)
295 return {OriginFlowChain, true};
296
297 const auto *OFF = F->getAs<OriginFlowFact>();
298 if (!OFF || OFF->getDestOriginID() != CurrOID)
299 continue;
300
301 const OriginID SrcOriginID = OFF->getSrcOriginID();
302 if (!getLoans(SrcOriginID, OFF).contains(TargetLoan))
303 continue;
304
305 OriginFlowChain.push_back(SrcOriginID);
306 CurrOID = SrcOriginID;
307 }
308
309 return {OriginFlowChain, false};
310 }
311
312 OriginLoanMap::Factory &OriginLoanMapFactory;
313 LoanSet::Factory &LoanSetFactory;
314 /// Origins referenced from more than one basic block; see
315 /// `FactManager::getPersistentOrigins`.
316 const llvm::BitVector &PersistentOrigins;
317};
318} // namespace
319
320class LoanPropagationAnalysis::Impl final : public AnalysisImpl {
321 using AnalysisImpl::AnalysisImpl;
322};
323
325 const CFG &C, AnalysisDeclContext &AC, FactManager &F,
326 OriginLoanMap::Factory &OriginLoanMapFactory,
327 LoanSet::Factory &LoanSetFactory)
328 : PImpl(std::make_unique<Impl>(C, AC, F, OriginLoanMapFactory,
329 LoanSetFactory)) {
330 PImpl->run();
331}
332
334
336 return PImpl->getLoans(OID, P);
337}
338
340 ProgramPoint StartPoint, const OriginID StartOID, const LoanID TargetLoan,
341 const CFG *Cfg) const {
342 return PImpl->buildOriginFlowChain(StartPoint, StartOID, TargetLoan, Cfg);
343}
344
346 const UseFact *UF, const LoanID TargetLoan, const CFG *Cfg) const {
347 return PImpl->buildOriginFlowChain(UF, TargetLoan, Cfg);
348}
349} // 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:1271
A generic, policy-based driver for dataflow analyses.
Definition Dataflow.h:60
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:98
utils::ID< struct LoanTag > LoanID
Definition Loans.h:27
utils::ID< struct OriginTag > OriginID
Definition Origins.h:28
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)
@ Other
Other implicit parameter.
Definition Decl.h:1775