clang 22.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 <cassert>
9#include <memory>
10
11#include "Dataflow.h"
18#include "clang/Analysis/CFG.h"
19#include "clang/Basic/LLVM.h"
20#include "llvm/ADT/BitVector.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/Support/TimeProfiler.h"
23#include "llvm/Support/raw_ostream.h"
24
26
27// Prepass to find persistent origins. An origin is persistent if it is
28// referenced in more than one basic block.
29static llvm::BitVector computePersistentOrigins(const FactManager &FactMgr,
30 const CFG &C) {
31 llvm::TimeTraceScope("ComputePersistentOrigins");
32 unsigned NumOrigins = FactMgr.getOriginMgr().getNumOrigins();
33 llvm::BitVector PersistentOrigins(NumOrigins);
34
35 llvm::SmallVector<const CFGBlock *> OriginToFirstSeenBlock(NumOrigins,
36 nullptr);
37 for (const CFGBlock *B : C) {
38 for (const Fact *F : FactMgr.getFacts(B)) {
39 auto CheckOrigin = [&](OriginID OID) {
40 if (PersistentOrigins.test(OID.Value))
41 return;
42 auto &FirstSeenBlock = OriginToFirstSeenBlock[OID.Value];
43 if (FirstSeenBlock == nullptr)
44 FirstSeenBlock = B;
45 if (FirstSeenBlock != B) {
46 // We saw this origin in more than one block.
47 PersistentOrigins.set(OID.Value);
48 }
49 };
50
51 switch (F->getKind()) {
53 CheckOrigin(F->getAs<IssueFact>()->getOriginID());
54 break;
56 const auto *OF = F->getAs<OriginFlowFact>();
57 CheckOrigin(OF->getDestOriginID());
58 CheckOrigin(OF->getSrcOriginID());
59 break;
60 }
61 case Fact::Kind::Use:
62 CheckOrigin(F->getAs<UseFact>()->getUsedOrigin());
63 break;
67 break;
68 }
69 }
70 }
71 return PersistentOrigins;
72}
73
74namespace {
75
76/// Represents the dataflow lattice for loan propagation.
77///
78/// This lattice tracks which loans each origin may hold at a given program
79/// point.The lattice has a finite height: An origin's loan set is bounded by
80/// the total number of loans in the function.
81struct Lattice {
82 /// The map from an origin to the set of loans it contains.
83 /// Origins that appear in multiple blocks. Participates in join operations.
84 OriginLoanMap PersistentOrigins = OriginLoanMap(nullptr);
85 /// Origins confined to a single block. Discarded at block boundaries.
86 OriginLoanMap BlockLocalOrigins = OriginLoanMap(nullptr);
87
88 explicit Lattice(const OriginLoanMap &Persistent,
89 const OriginLoanMap &BlockLocal)
90 : PersistentOrigins(Persistent), BlockLocalOrigins(BlockLocal) {}
91 Lattice() = default;
92
93 bool operator==(const Lattice &Other) const {
94 return PersistentOrigins == Other.PersistentOrigins &&
95 BlockLocalOrigins == Other.BlockLocalOrigins;
96 }
97 bool operator!=(const Lattice &Other) const { return !(*this == Other); }
98
99 void dump(llvm::raw_ostream &OS) const {
100 OS << "LoanPropagationLattice State:\n";
101 OS << " Persistent Origins:\n";
102 if (PersistentOrigins.isEmpty())
103 OS << " <empty>\n";
104 for (const auto &Entry : PersistentOrigins) {
105 if (Entry.second.isEmpty())
106 OS << " Origin " << Entry.first << " contains no loans\n";
107 for (const LoanID &LID : Entry.second)
108 OS << " Origin " << Entry.first << " contains Loan " << LID << "\n";
109 }
110 OS << " Block-Local Origins:\n";
111 if (BlockLocalOrigins.isEmpty())
112 OS << " <empty>\n";
113 for (const auto &Entry : BlockLocalOrigins) {
114 if (Entry.second.isEmpty())
115 OS << " Origin " << Entry.first << " contains no loans\n";
116 for (const LoanID &LID : Entry.second)
117 OS << " Origin " << Entry.first << " contains Loan " << LID << "\n";
118 }
119 }
120};
121
122class AnalysisImpl
123 : public DataflowAnalysis<AnalysisImpl, Lattice, Direction::Forward> {
124public:
125 AnalysisImpl(const CFG &C, AnalysisDeclContext &AC, FactManager &F,
126 OriginLoanMap::Factory &OriginLoanMapFactory,
127 LoanSet::Factory &LoanSetFactory)
128 : DataflowAnalysis(C, AC, F), OriginLoanMapFactory(OriginLoanMapFactory),
129 LoanSetFactory(LoanSetFactory),
130 PersistentOrigins(computePersistentOrigins(F, C)) {}
131
132 using Base::transfer;
133
134 StringRef getAnalysisName() const { return "LoanPropagation"; }
135
136 Lattice getInitialState() { return Lattice{}; }
137
138 /// Merges two lattices by taking the union of loans for each origin.
139 /// Only persistent origins are joined; block-local origins are discarded.
140 Lattice join(Lattice A, Lattice B) {
141 OriginLoanMap JoinedOrigins = utils::join(
142 A.PersistentOrigins, B.PersistentOrigins, OriginLoanMapFactory,
143 [&](const LoanSet *S1, const LoanSet *S2) {
144 assert((S1 || S2) && "unexpectedly merging 2 empty sets");
145 if (!S1)
146 return *S2;
147 if (!S2)
148 return *S1;
149 return utils::join(*S1, *S2, LoanSetFactory);
150 },
151 // Asymmetric join is a performance win. For origins present only on one
152 // branch, the loan set can be carried over as-is.
154 return Lattice(JoinedOrigins, OriginLoanMapFactory.getEmptyMap());
155 }
156
157 /// A new loan is issued to the origin. Old loans are erased.
158 Lattice transfer(Lattice In, const IssueFact &F) {
159 OriginID OID = F.getOriginID();
160 LoanID LID = F.getLoanID();
161 LoanSet NewLoans = LoanSetFactory.add(LoanSetFactory.getEmptySet(), LID);
162 return setLoans(In, OID, NewLoans);
163 }
164
165 /// A flow from source to destination. If `KillDest` is true, this replaces
166 /// the destination's loans with the source's. Otherwise, the source's loans
167 /// are merged into the destination's.
168 Lattice transfer(Lattice In, const OriginFlowFact &F) {
169 OriginID DestOID = F.getDestOriginID();
170 OriginID SrcOID = F.getSrcOriginID();
171
172 LoanSet DestLoans =
173 F.getKillDest() ? LoanSetFactory.getEmptySet() : getLoans(In, DestOID);
174 LoanSet SrcLoans = getLoans(In, SrcOID);
175 LoanSet MergedLoans = utils::join(DestLoans, SrcLoans, LoanSetFactory);
176
177 return setLoans(In, DestOID, MergedLoans);
178 }
179
180 LoanSet getLoans(OriginID OID, ProgramPoint P) const {
181 return getLoans(getState(P), OID);
182 }
183
184private:
185 /// Returns true if the origin is persistent (referenced in multiple blocks).
186 bool isPersistent(OriginID OID) const {
187 return PersistentOrigins.test(OID.Value);
188 }
189
190 Lattice setLoans(Lattice L, OriginID OID, LoanSet Loans) {
191 if (isPersistent(OID))
192 return Lattice(OriginLoanMapFactory.add(L.PersistentOrigins, OID, Loans),
193 L.BlockLocalOrigins);
194 return Lattice(L.PersistentOrigins,
195 OriginLoanMapFactory.add(L.BlockLocalOrigins, OID, Loans));
196 }
197
198 LoanSet getLoans(Lattice L, OriginID OID) const {
199 const OriginLoanMap *Map =
200 isPersistent(OID) ? &L.PersistentOrigins : &L.BlockLocalOrigins;
201 if (auto *Loans = Map->lookup(OID))
202 return *Loans;
203 return LoanSetFactory.getEmptySet();
204 }
205
206 OriginLoanMap::Factory &OriginLoanMapFactory;
207 LoanSet::Factory &LoanSetFactory;
208 /// Boolean vector indexed by origin ID. If true, the origin appears in
209 /// multiple basic blocks and must participate in join operations. If false,
210 /// the origin is block-local and can be discarded at block boundaries.
211 llvm::BitVector PersistentOrigins;
212};
213} // namespace
214
215class LoanPropagationAnalysis::Impl final : public AnalysisImpl {
216 using AnalysisImpl::AnalysisImpl;
217};
218
220 const CFG &C, AnalysisDeclContext &AC, FactManager &F,
221 OriginLoanMap::Factory &OriginLoanMapFactory,
222 LoanSet::Factory &LoanSetFactory)
223 : PImpl(std::make_unique<Impl>(C, AC, F, OriginLoanMapFactory,
224 LoanSetFactory)) {
225 PImpl->run();
226}
227
229
231 return PImpl->getLoans(OID, P);
232}
233} // 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.
AnalysisDeclContext contains the context data for the function, method or block under analysis.
Represents a single basic block in a source-level CFG.
Definition CFG.h:605
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
Definition CFG.h:1222
A generic, policy-based driver for dataflow analyses.
Definition Dataflow.h:57
llvm::ArrayRef< const Fact * > getFacts(const CFGBlock *B) const
Definition Facts.h:202
An abstract base class for a single, atomic lifetime-relevant event.
Definition Facts.h:31
@ TestPoint
A marker for a specific point in the code, for testing.
Definition Facts.h:48
@ Expire
A loan expires as its underlying storage is freed (e.g., variable goes out of scope).
Definition Facts.h:39
@ Issue
A new loan is issued from a borrow expression (e.g., &x).
Definition Facts.h:36
@ OriginFlow
An origin is propagated from a source to a destination (e.g., p = q).
Definition Facts.h:44
@ Use
An origin is used (eg. appears as l-value expression like DeclRefExpr).
Definition Facts.h:46
@ OriginEscapes
An origin that escapes the function scope (e.g., via return).
Definition Facts.h:50
LoanSet getLoans(OriginID OID, ProgramPoint P) const
LoanPropagationAnalysis(const CFG &C, AnalysisDeclContext &AC, FactManager &F, OriginLoanMap::Factory &OriginLoanMapFactory, LoanSet::Factory &LoanSetFactory)
OriginID getUsedOrigin() const
Definition Facts.h:169
void transfer(const StmtToEnvMap &StmtToEnv, const Stmt &S, Environment &Env, Environment::ValueModel &Model)
Evaluates S and updates Env accordingly.
Definition Transfer.cpp:956
@ 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:62
static llvm::ImmutableSet< T > join(llvm::ImmutableSet< T > A, llvm::ImmutableSet< T > B, typename llvm::ImmutableSet< T >::Factory &F)
Computes the union of two ImmutableSets.
Definition Utils.h:39
const Fact * ProgramPoint
A ProgramPoint identifies a location in the CFG by pointing to a specific Fact.
Definition Facts.h:82
llvm::ImmutableSet< LoanID > LoanSet
utils::ID< struct LoanTag > LoanID
Definition Loans.h:23
utils::ID< struct OriginTag > OriginID
Definition Origins.h:23
llvm::ImmutableMap< OriginID, LoanSet > OriginLoanMap
static llvm::BitVector computePersistentOrigins(const FactManager &FactMgr, const CFG &C)
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition CallGraph.h:204
bool operator!=(CanQual< T > x, CanQual< U > y)
@ Other
Other implicit parameter.
Definition Decl.h:1746