clang 24.0.0git
CIRPointsToAnalysis.cpp
Go to the documentation of this file.
1//===- CIRPointsToAnalysis.cpp - Points-to analysis for CIR ---------------===//
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
10#include "mlir/IR/Remarks.h"
12#include "llvm/ADT/STLExtras.h"
13#include "llvm/ADT/TypeSwitch.h"
14#include "llvm/Support/DebugLog.h"
15
16#include <algorithm>
17
18#define DEBUG_TYPE "cir-points-to-analysis"
19
20using namespace cir;
21
22/// The name used to print `object`: the name of the cir.alloca allocating it.
23static llvm::StringRef getObjectName(mlir::Value object) {
24 llvm::StringRef name = object.getDefiningOp<cir::AllocaOp>().getName();
25 return name.empty() ? "<unnamed>" : name;
26}
27
28/// The options of every remark emitted for the analysis of `root`.
29static mlir::remark::RemarkOpts getRemarkOpts(llvm::StringRef name,
30 mlir::Operation *root,
31 llvm::StringRef subCategory) {
32 mlir::remark::RemarkOpts opts = mlir::remark::RemarkOpts::name(name)
33 .category("points-to")
34 .subCategory(subCategory);
35 if (auto func = mlir::dyn_cast<cir::FuncOp>(root))
36 opts = opts.function(func.getSymName());
37 return opts;
38}
39
40/// Walk the operations nested in `op`, without `op` itself.
41static mlir::WalkResult
42walkNested(mlir::Operation *op,
43 llvm::function_ref<mlir::WalkResult(mlir::Operation *)> callback) {
44 for (mlir::Region &region : op->getRegions())
45 if (region.walk(callback).wasInterrupted())
46 return mlir::WalkResult::interrupt();
47 return mlir::WalkResult::advance();
48}
49
50//===----------------------------------------------------------------------===//
51// PointsToSet
52//===----------------------------------------------------------------------===//
53
54bool PointsToSet::merge(const PointsToSet &other) {
55 assert(!sizeLimitHit && "merging into a set that hit the size limit");
56 bool changed = objects.set_union(other.objects);
57 if (other.unknown)
58 changed |= insertUnknown();
59 return changed;
60}
61
62void PointsToSet::replaceWithUnknown() {
63 objects.clear();
64 unknown = true;
65 sizeLimitHit = true;
66}
67
68void PointsToSet::print(llvm::raw_ostream &os) const {
70 llvm::map_to_vector(objects, getObjectName);
71 llvm::sort(names);
72 if (unknown)
73 names.push_back("unknown");
74 os << '[';
75 llvm::interleaveComma(names, os);
76 os << ']';
77}
78
79#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
80void PointsToSet::dump() const {
81 print(llvm::errs());
82 llvm::errs() << '\n';
83}
84#endif
85
86//===----------------------------------------------------------------------===//
87// PointsToAnalysis
88//===----------------------------------------------------------------------===//
89
91 const PointsToLimits &limits)
92 : root(op), limits(limits) {
93 unknownSet.insertUnknown();
94 compute(op);
95}
96
97void PointsToAnalysis::compute(mlir::Operation *op) {
98 // Create the sets of the values the analysis computes before solving, so a
99 // value never changes from "not analyzed", which reads as "unknown", to a set
100 // with fewer members. Each cir.alloca result points to the object it
101 // allocates, each cir.load result starts out pointing to nothing, and a null
102 // pointer constant points to nothing.
103 uint64_t numOperations = 0;
104 mlir::WalkResult tooLarge = walkNested(op, [&](mlir::Operation *nested) {
105 if (++numOperations > limits.maxOperations)
106 return mlir::WalkResult::interrupt();
107 llvm::TypeSwitch<mlir::Operation *>(nested)
108 .Case([&](cir::AllocaOp alloca) {
109 valuePointsTo[alloca.getResult()].insert(alloca.getResult());
110 })
111 .Case([&](cir::LoadOp load) {
112 valuePointsTo.try_emplace(load.getResult());
113 })
114 .Case([&](cir::ConstantOp constant) {
115 if (constant.isNullPtr())
116 valuePointsTo.try_emplace(constant.getResult());
117 });
118 return mlir::WalkResult::advance();
119 });
120 if (tooLarge.wasInterrupted()) {
121 dropAllSets();
122 operationLimitHit = true;
123 return;
124 }
125
126 // Sets only grow, so revisiting every operation until nothing changes
127 // terminates. The work limit bounds how long that may take.
128 uint64_t budget = std::max<uint64_t>(
129 limits.minWork, uint64_t(limits.workPerOperation) * numOperations);
130 uint64_t work = 0;
131 unsigned iterations = 0;
132 bool changed;
133 do {
134 changed = false;
135 mlir::WalkResult result = walkNested(op, [&](mlir::Operation *nested) {
136 if (++work > budget)
137 return mlir::WalkResult::interrupt();
138 changed |= visit(nested);
139 return mlir::WalkResult::advance();
140 });
141 if (result.wasInterrupted()) {
142 dropAllSets();
143 workLimitHit = budget;
144 return;
145 }
146 ++iterations;
147 } while (changed);
148 LDBG() << "Solved in " << iterations << " iterations";
149}
150
151void PointsToAnalysis::emitRemarks(llvm::StringRef subCategory) const {
152 if (!root->getContext()->getRemarkEngine())
153 return;
154
155 if (operationLimitHit)
156 mlir::remark::missed(root->getLoc(),
157 getRemarkOpts("OperationLimit", root, subCategory))
158 << mlir::remark::add("gave up: more than {0} operations",
159 limits.maxOperations);
160 if (workLimitHit)
161 mlir::remark::missed(root->getLoc(),
162 getRemarkOpts("WorkLimit", root, subCategory))
163 << mlir::remark::add("gave up: more than {0} operation visits",
164 workLimitHit);
165 for (auto [object, op] : escaped)
166 mlir::remark::missed(op->getLoc(),
167 getRemarkOpts("Escaped", root, subCategory))
168 << mlir::remark::add("the address of {0} escapes",
169 getObjectName(object));
170 for (auto [op, size] : sizeLimitHits)
171 mlir::remark::missed(op->getLoc(),
172 getRemarkOpts("SizeLimit", root, subCategory))
173 << mlir::remark::add(
174 "a set of {0} objects is replaced by unknown, the limit is {1}",
175 size, limits.maxSetSize);
176
177 root->walk([&](cir::LoadOp load) {
178 if (!mlir::isa<cir::PointerType>(load.getType()))
179 return;
180 mlir::remark::analysis(load.getLoc(),
181 getRemarkOpts("PointsTo", root, subCategory))
182 << mlir::remark::add("points to {0}", getPointsTo(load.getResult()));
183 });
184}
185
186const PointsToSet &PointsToAnalysis::getPointsTo(mlir::Value value) const {
187 auto it = valuePointsTo.find(value);
188 if (it == valuePointsTo.end())
189 return unknownSet;
190 return it->second;
191}
192
193void PointsToAnalysis::dropAllSets() {
194 // Values without a set point to "unknown", so dropping every set is enough
195 // to make every answer conservative.
196 valuePointsTo.clear();
197 memoryPointsTo.clear();
198 escaped.clear();
199 sizeLimitHits.clear();
200}
201
202bool PointsToAnalysis::addTo(PointsToSet &to, const PointsToSet &from,
203 mlir::Operation *op) {
204 // A set that hit the size limit no longer names its objects, so the objects
205 // added to it are lost. Make them escape, so that dropping them is
206 // conservative.
207 if (to.hitSizeLimit())
208 return markEscaped(from.getObjects(), op);
209
210 bool changed = to.merge(from);
211 if (to.getObjects().size() <= limits.maxSetSize)
212 return changed;
213
214 // The objects the set held are lost too. They would escape when the
215 // operations that added them are visited again, but making them escape here
216 // doesn't depend on the order operations are visited in.
218 sizeLimitHits.emplace_back(op, objects.size());
219 to.replaceWithUnknown();
220 // `to` may be an element of memoryPointsTo, which markEscaped() can grow, so
221 // it must not be used after this point.
222 markEscaped(objects, op);
223 return true;
224}
225
226bool PointsToAnalysis::markEscaped(llvm::ArrayRef<mlir::Value> objects,
227 mlir::Operation *op) {
228 bool changed = false;
229 llvm::SmallVector<mlir::Value> worklist;
230 for (mlir::Value object : objects)
231 if (escaped.insert({object, op}).second)
232 worklist.push_back(object);
233
234 while (!worklist.empty()) {
235 mlir::Value object = worklist.pop_back_val();
236 changed = true;
237
238 // Code the analysis cannot see may store any address it can reach into an
239 // escaped object, and may follow the addresses already stored there.
240 PointsToSet &memory = memoryPointsTo[object];
241 memory.insertUnknown();
242 for (mlir::Value inner : memory.getObjects())
243 if (escaped.insert({inner, op}).second)
244 worklist.push_back(inner);
245 }
246 return changed;
247}
248
249bool PointsToAnalysis::visit(mlir::Operation *op) {
250 // The analysis does not know what any other operation does with an address
251 // it receives, so the objects it points to escape. The results of such an
252 // operation have no set, and so point to "unknown".
253 auto escapeOperands = [&] {
254 bool changed = false;
255 for (mlir::Value operand : op->getOperands())
256 changed |= markEscaped(getPointsTo(operand).getObjects(), op);
257 return changed;
258 };
259
260 return llvm::TypeSwitch<mlir::Operation *, bool>(op)
261 .Case([&](cir::StoreOp store) {
262 const PointsToSet &addr = getPointsTo(store.getAddr());
263 const PointsToSet &value = getPointsTo(store.getValue());
264 bool changed = false;
265 for (mlir::Value object : addr.getObjects()) {
266 changed |= addTo(memoryPointsTo[object], value, op);
267 if (escaped.contains(object))
268 changed |= markEscaped(value.getObjects(), op);
269 }
270 // A store through an address the analysis does not know may write to
271 // an escaped object or to memory it does not track at all.
272 if (addr.containsUnknown())
273 changed |= markEscaped(value.getObjects(), op);
274 return changed;
275 })
276 .Case([&](cir::LoadOp load) {
277 const PointsToSet &addr = getPointsTo(load.getAddr());
278 PointsToSet loaded;
279 for (mlir::Value object : addr.getObjects()) {
280 auto it = memoryPointsTo.find(object);
281 if (it != memoryPointsTo.end())
282 loaded.merge(it->second);
283 }
284 if (addr.containsUnknown())
285 loaded.insertUnknown();
286 return addTo(valuePointsTo[load.getResult()], loaded, op);
287 })
288 // Comparing addresses or testing one for null gives a boolean, from
289 // which no code can get back to an object, so nothing escapes.
290 .Case([&](cir::CmpOp) { return false; })
291 .Case([&](cir::CastOp cast) {
292 if (cast.getKind() == cir::CastKind::ptr_to_bool)
293 return false;
294 return escapeOperands();
295 })
296 .Default([&](mlir::Operation *) { return escapeOperands(); });
297}
static mlir::remark::RemarkOpts getRemarkOpts(llvm::StringRef name, mlir::Operation *root, llvm::StringRef subCategory)
The options of every remark emitted for the analysis of root.
static llvm::StringRef getObjectName(mlir::Value object)
The name used to print object: the name of the cir.alloca allocating it.
static mlir::WalkResult walkNested(mlir::Operation *op, llvm::function_ref< mlir::WalkResult(mlir::Operation *)> callback)
Walk the operations nested in op, without op itself.
const PointsToSet & getPointsTo(mlir::Value value) const
Return the objects value may point to.
PointsToAnalysis(mlir::Operation *op, const PointsToLimits &limits=PointsToLimits())
void emitRemarks(llvm::StringRef subCategory={}) const
Report the results as optimization remarks in the "points-to" category, when remarks are enabled for ...
The objects a value may point to.
bool containsUnknown() const
Whether the set contains "unknown".
LLVM_DUMP_METHOD void dump() const
llvm::ArrayRef< mlir::Value > getObjects() const
The tracked objects in the set.
void print(llvm::raw_ostream &os) const
Print the set as the sorted names of the cir.alloca operations of its objects, followed by "unknown" ...
@ Default
Set to the current date and time.
U cast(CodeGen::Address addr)
Definition Address.h:327
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
Limits on the work done by PointsToAnalysis.
unsigned maxOperations
The largest number of operations the analysis is computed for.
unsigned maxSetSize
The largest number of objects a set holds.