1 //===- AsyncRuntimeRefCounting.cpp - Async Runtime Ref Counting -----------===//
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 implements automatic reference counting for Async runtime
10 // operations and types.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PassDetail.h"
15 #include "mlir/Analysis/Liveness.h"
16 #include "mlir/Dialect/Async/IR/Async.h"
17 #include "mlir/Dialect/Async/Passes.h"
18 #include "mlir/Dialect/StandardOps/IR/Ops.h"
19 #include "mlir/IR/ImplicitLocOpBuilder.h"
20 #include "mlir/IR/PatternMatch.h"
21 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
22 #include "llvm/ADT/SmallSet.h"
23 
24 using namespace mlir;
25 using namespace mlir::async;
26 
27 #define DEBUG_TYPE "async-runtime-ref-counting"
28 
29 namespace {
30 
31 class AsyncRuntimeRefCountingPass
32     : public AsyncRuntimeRefCountingBase<AsyncRuntimeRefCountingPass> {
33 public:
34   AsyncRuntimeRefCountingPass() = default;
35   void runOnOperation() override;
36 
37 private:
38   /// Adds an automatic reference counting to the `value`.
39   ///
40   /// All values (token, group or value) are semantically created with a
41   /// reference count of +1 and it is the responsibility of the async value user
42   /// to place the `add_ref` and `drop_ref` operations to ensure that the value
43   /// is destroyed after the last use.
44   ///
45   /// The function returns failure if it can't deduce the locations where
46   /// to place the reference counting operations.
47   ///
48   /// Async values "semantically created" when:
49   ///   1. Operation returns async result (e.g. `async.runtime.create`)
50   ///   2. Async value passed in as a block argument (or function argument,
51   ///      because function arguments are just entry block arguments)
52   ///
53   /// Passing async value as a function argument (or block argument) does not
54   /// really mean that a new async value is created, it only means that the
55   /// caller of a function transfered ownership of `+1` reference to the callee.
56   /// It is convenient to think that from the callee perspective async value was
57   /// "created" with `+1` reference by the block argument.
58   ///
59   /// Automatic reference counting algorithm outline:
60   ///
61   /// #1 Insert `drop_ref` operations after last use of the `value`.
62   /// #2 Insert `add_ref` operations before functions calls with reference
63   ///    counted `value` operand (newly created `+1` reference will be
64   ///    transferred to the callee).
65   /// #3 Verify that divergent control flow does not lead to leaked reference
66   ///    counted objects.
67   ///
68   /// Async runtime reference counting optimization pass will optimize away
69   /// some of the redundant `add_ref` and `drop_ref` operations inserted by this
70   /// strategy (see `async-runtime-ref-counting-opt`).
71   LogicalResult addAutomaticRefCounting(Value value);
72 
73   /// (#1) Adds the `drop_ref` operation after the last use of the `value`
74   /// relying on the liveness analysis.
75   ///
76   /// If the `value` is in the block `liveIn` set and it is not in the block
77   /// `liveOut` set, it means that it "dies" in the block. We find the last
78   /// use of the value in such block and:
79   ///
80   ///   1. If the last user is a `ReturnLike` operation we do nothing, because
81   ///      it forwards the ownership to the caller.
82   ///   2. Otherwise we add a `drop_ref` operation immediately after the last
83   ///      use.
84   LogicalResult addDropRefAfterLastUse(Value value);
85 
86   /// (#2) Adds the `add_ref` operation before the function call taking `value`
87   /// operand to ensure that the value passed to the function entry block
88   /// has a `+1` reference count.
89   LogicalResult addAddRefBeforeFunctionCall(Value value);
90 
91   /// (#3) Verifies that if a block has a value in the `liveOut` set, then the
92   /// value is in `liveIn` set in all successors.
93   ///
94   /// Example:
95   ///
96   ///   ^entry:
97   ///     %token = async.runtime.create : !async.token
98   ///     cond_br %cond, ^bb1, ^bb2
99   ///   ^bb1:
100   ///     async.runtime.await %token
101   ///     return
102   ///   ^bb2:
103   ///     return
104   ///
105   /// This CFG will be rejected because ^bb2 does not have `value` in the
106   /// `liveIn` set, and it will leak a reference counted object.
107   ///
108   /// An exception to this rule are blocks with `async.coro.suspend` terminator,
109   /// because in Async to LLVM lowering it is guaranteed that the control flow
110   /// will jump into the resume block, and then follow into the cleanup and
111   /// suspend blocks.
112   ///
113   /// Example:
114   ///
115   ///  ^entry(%value: !async.value<f32>):
116   ///     async.runtime.await_and_resume %value, %hdl : !async.value<f32>
117   ///     async.coro.suspend %ret, ^suspend, ^resume, ^cleanup
118   ///   ^resume:
119   ///     %0 = async.runtime.load %value
120   ///     br ^cleanup
121   ///   ^cleanup:
122   ///     ...
123   ///   ^suspend:
124   ///     ...
125   ///
126   /// Although cleanup and suspend blocks do not have the `value` in the
127   /// `liveIn` set, it is guaranteed that execution will eventually continue in
128   /// the resume block (we never explicitly destroy coroutines).
129   LogicalResult verifySuccessors(Value value);
130 };
131 
132 } // namespace
133 
134 LogicalResult AsyncRuntimeRefCountingPass::addDropRefAfterLastUse(Value value) {
135   OpBuilder builder(value.getContext());
136   Location loc = value.getLoc();
137 
138   // Use liveness analysis to find the placement of `drop_ref`operation.
139   auto &liveness = getAnalysis<Liveness>();
140 
141   // We analyse only the blocks of the region that defines the `value`, and do
142   // not check nested blocks attached to operations.
143   //
144   // By analyzing only the `definingRegion` CFG we potentially loose an
145   // opportunity to drop the reference count earlier and can extend the lifetime
146   // of reference counted value longer then it is really required.
147   //
148   // We also assume that all nested regions finish their execution before the
149   // completion of the owner operation. The only exception to this rule is
150   // `async.execute` operation, and we verify that they are lowered to the
151   // `async.runtime` operations before adding automatic reference counting.
152   Region *definingRegion = value.getParentRegion();
153 
154   // Last users of the `value` inside all blocks where the value dies.
155   llvm::SmallSet<Operation *, 4> lastUsers;
156 
157   // Find blocks in the `definingRegion` that have users of the `value` (if
158   // there are multiple users in the block, which one will be selected is
159   // undefined). User operation might be not the actual user of the value, but
160   // the operation in the block that has a "real user" in one of the attached
161   // regions.
162   llvm::DenseMap<Block *, Operation *> usersInTheBlocks;
163 
164   for (Operation *user : value.getUsers()) {
165     Block *userBlock = user->getBlock();
166     Block *ancestor = definingRegion->findAncestorBlockInRegion(*userBlock);
167     usersInTheBlocks[ancestor] = ancestor->findAncestorOpInBlock(*user);
168     assert(ancestor && "ancestor block must be not null");
169     assert(usersInTheBlocks[ancestor] && "ancestor op must be not null");
170   }
171 
172   // Find blocks where the `value` dies: the value is in `liveIn` set and not
173   // in the `liveOut` set. We place `drop_ref` immediately after the last use
174   // of the `value` in such regions (after handling few special cases).
175   //
176   // We do not traverse all the blocks in the `definingRegion`, because the
177   // `value` can be in the live in set only if it has users in the block, or it
178   // is defined in the block.
179   //
180   // Values with zero users (only definition) handled explicitly above.
181   for (auto &blockAndUser : usersInTheBlocks) {
182     Block *block = blockAndUser.getFirst();
183     Operation *userInTheBlock = blockAndUser.getSecond();
184 
185     const LivenessBlockInfo *blockLiveness = liveness.getLiveness(block);
186 
187     // Value must be in the live input set or defined in the block.
188     assert(blockLiveness->isLiveIn(value) ||
189            blockLiveness->getBlock() == value.getParentBlock());
190 
191     // If value is in the live out set, it means it doesn't "die" in the block.
192     if (blockLiveness->isLiveOut(value))
193       continue;
194 
195     // At this point we proved that `value` dies in the `block`. Find the last
196     // use of the `value` inside the `block`, this is where it "dies".
197     Operation *lastUser = blockLiveness->getEndOperation(value, userInTheBlock);
198     assert(lastUsers.count(lastUser) == 0 && "last users must be unique");
199     lastUsers.insert(lastUser);
200   }
201 
202   // Process all the last users of the `value` inside each block where the value
203   // dies.
204   for (Operation *lastUser : lastUsers) {
205     // Return like operations forward reference count.
206     if (lastUser->hasTrait<OpTrait::ReturnLike>())
207       continue;
208 
209     // We can't currently handle other types of terminators.
210     if (lastUser->hasTrait<OpTrait::IsTerminator>())
211       return lastUser->emitError() << "async reference counting can't handle "
212                                       "terminators that are not ReturnLike";
213 
214     // Add a drop_ref immediately after the last user.
215     builder.setInsertionPointAfter(lastUser);
216     builder.create<RuntimeDropRefOp>(loc, value, builder.getI32IntegerAttr(1));
217   }
218 
219   return success();
220 }
221 
222 LogicalResult
223 AsyncRuntimeRefCountingPass::addAddRefBeforeFunctionCall(Value value) {
224   OpBuilder builder(value.getContext());
225   Location loc = value.getLoc();
226 
227   for (Operation *user : value.getUsers()) {
228     if (!isa<CallOp>(user))
229       continue;
230 
231     // Add a reference before the function call to pass the value at `+1`
232     // reference to the function entry block.
233     builder.setInsertionPoint(user);
234     builder.create<RuntimeAddRefOp>(loc, value, builder.getI32IntegerAttr(1));
235   }
236 
237   return success();
238 }
239 
240 LogicalResult AsyncRuntimeRefCountingPass::verifySuccessors(Value value) {
241   OpBuilder builder(value.getContext());
242 
243   // Blocks with successfors with different `liveIn` properties of the `value`.
244   llvm::SmallSet<Block *, 4> divergentLivenessBlocks;
245 
246   // Use liveness analysis to find the placement of `drop_ref`operation.
247   auto &liveness = getAnalysis<Liveness>();
248 
249   // Because we only add `drop_ref` operations to the region that defines the
250   // `value` we can only process CFG for the same region.
251   Region *definingRegion = value.getParentRegion();
252 
253   // Collect blocks with successors with mismatching `liveIn` sets.
254   for (Block &block : definingRegion->getBlocks()) {
255     const LivenessBlockInfo *blockLiveness = liveness.getLiveness(&block);
256 
257     // Skip the block if value is not in the `liveOut` set.
258     if (!blockLiveness->isLiveOut(value))
259       continue;
260 
261     // Sucessors with value in `liveIn` set and not value in `liveIn` set.
262     llvm::SmallSet<Block *, 4> liveInSuccessors;
263     llvm::SmallSet<Block *, 4> noLiveInSuccessors;
264 
265     // Collect successors that do not have `value` in the `liveIn` set.
266     for (Block *successor : block.getSuccessors()) {
267       const LivenessBlockInfo *succLiveness = liveness.getLiveness(successor);
268       if (succLiveness->isLiveIn(value))
269         liveInSuccessors.insert(successor);
270       else
271         noLiveInSuccessors.insert(successor);
272     }
273 
274     // Block has successors with different `liveIn` property of the `value`.
275     if (!liveInSuccessors.empty() && !noLiveInSuccessors.empty())
276       divergentLivenessBlocks.insert(&block);
277   }
278 
279   // Verify that divergent `liveIn` property only present in blocks with
280   // async.coro.suspend terminator.
281   for (Block *block : divergentLivenessBlocks) {
282     Operation *terminator = block->getTerminator();
283     if (isa<CoroSuspendOp>(terminator))
284       continue;
285 
286     return terminator->emitOpError("successor have different `liveIn` property "
287                                    "of the reference counted value: ");
288   }
289 
290   return success();
291 }
292 
293 LogicalResult
294 AsyncRuntimeRefCountingPass::addAutomaticRefCounting(Value value) {
295   OpBuilder builder(value.getContext());
296   Location loc = value.getLoc();
297 
298   // Set inserton point after the operation producing a value, or at the
299   // beginning of the block if the value defined by the block argument.
300   if (Operation *op = value.getDefiningOp())
301     builder.setInsertionPointAfter(op);
302   else
303     builder.setInsertionPointToStart(value.getParentBlock());
304 
305   // Drop the reference count immediately if the value has no uses.
306   if (value.getUses().empty()) {
307     builder.create<RuntimeDropRefOp>(loc, value, builder.getI32IntegerAttr(1));
308     return success();
309   }
310 
311   // Add `drop_ref` operations based on the liveness analysis.
312   if (failed(addDropRefAfterLastUse(value)))
313     return failure();
314 
315   // Add `add_ref` operations before function calls.
316   if (failed(addAddRefBeforeFunctionCall(value)))
317     return failure();
318 
319   // Verify that the `value` is in `liveIn` set of all successors.
320   if (failed(verifySuccessors(value)))
321     return failure();
322 
323   return success();
324 }
325 
326 void AsyncRuntimeRefCountingPass::runOnOperation() {
327   Operation *op = getOperation();
328 
329   // Check that we do not have high level async operations in the IR because
330   // otherwise automatic reference counting will produce incorrect results after
331   // execute operations will be lowered to `async.runtime`
332   WalkResult executeOpWalk = op->walk([&](Operation *op) -> WalkResult {
333     if (!isa<ExecuteOp, AwaitOp, AwaitAllOp, YieldOp>(op))
334       return WalkResult::advance();
335 
336     return op->emitError()
337            << "async operations must be lowered to async runtime operations";
338   });
339 
340   if (executeOpWalk.wasInterrupted()) {
341     signalPassFailure();
342     return;
343   }
344 
345   // Add reference counting to block arguments.
346   WalkResult blockWalk = op->walk([&](Block *block) -> WalkResult {
347     for (BlockArgument arg : block->getArguments())
348       if (isRefCounted(arg.getType()))
349         if (failed(addAutomaticRefCounting(arg)))
350           return WalkResult::interrupt();
351 
352     return WalkResult::advance();
353   });
354 
355   if (blockWalk.wasInterrupted()) {
356     signalPassFailure();
357     return;
358   }
359 
360   // Add reference counting to operation results.
361   WalkResult opWalk = op->walk([&](Operation *op) -> WalkResult {
362     for (unsigned i = 0; i < op->getNumResults(); ++i)
363       if (isRefCounted(op->getResultTypes()[i]))
364         if (failed(addAutomaticRefCounting(op->getResult(i))))
365           return WalkResult::interrupt();
366 
367     return WalkResult::advance();
368   });
369 
370   if (opWalk.wasInterrupted())
371     signalPassFailure();
372 }
373 
374 std::unique_ptr<Pass> mlir::createAsyncRuntimeRefCountingPass() {
375   return std::make_unique<AsyncRuntimeRefCountingPass>();
376 }
377