MLIR 23.0.0git
RemoveDeadValues.cpp
Go to the documentation of this file.
1//===- RemoveDeadValues.cpp - Remove Dead Values --------------------------===//
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// The goal of this pass is optimization (reducing runtime) by removing
10// unnecessary instructions. Unlike other passes that rely on local information
11// gathered from patterns to accomplish optimization, this pass uses a full
12// analysis of the IR, specifically, liveness analysis, and is thus more
13// powerful.
14//
15// Currently, this pass performs the following optimizations:
16// (A) Removes function arguments that are not live,
17// (B) Removes function return values that are not live across all callers of
18// the function,
19// (C) Removes unneccesary operands, results, region arguments, and region
20// terminator operands of region branch ops, and,
21// (D) Removes simple and region branch ops that have all non-live results and
22// don't affect memory in any way.
23//
24// Here, a "simple op" refers to an op that isn't a symbol op, symbol-user op,
25// region branch op, branch op, region branch terminator op, or return-like.
26//
27//===----------------------------------------------------------------------===//
28
32#include "mlir/IR/Builders.h"
34#include "mlir/IR/Dialect.h"
35#include "mlir/IR/Operation.h"
37#include "mlir/IR/SymbolTable.h"
38#include "mlir/IR/Value.h"
39#include "mlir/IR/ValueRange.h"
40#include "mlir/IR/Visitors.h"
45#include "mlir/Pass/Pass.h"
46#include "mlir/Support/LLVM.h"
49#include "llvm/ADT/STLExtras.h"
50#include "llvm/Support/Debug.h"
51#include "llvm/Support/DebugLog.h"
52#include <cassert>
53#include <cstddef>
54#include <memory>
55#include <optional>
56#include <vector>
57
58#define DEBUG_TYPE "remove-dead-values"
59
60namespace mlir {
61#define GEN_PASS_DEF_REMOVEDEADVALUESPASS
62#include "mlir/Transforms/Passes.h.inc"
63} // namespace mlir
64
65using namespace mlir;
66using namespace mlir::dataflow;
67
68//===----------------------------------------------------------------------===//
69// RemoveDeadValues Pass
70//===----------------------------------------------------------------------===//
71
72namespace {
73
74// Set of structures below to be filled with operations and arguments to erase.
75// This is done to separate analysis and tree modification phases,
76// otherwise analysis is operating on half-deleted tree which is incorrect.
77
78struct FunctionToCleanUp {
79 FunctionOpInterface funcOp;
80 BitVector nonLiveArgs;
81 BitVector nonLiveRets;
82};
83
84struct ResultsToCleanup {
85 Operation *op;
86 BitVector nonLive;
87};
88
89struct OperandsToCleanup {
90 Operation *op;
91 BitVector nonLive;
92 // Optional: For CallOpInterface ops, stores the callee function.
93 Operation *callee = nullptr;
94 // Determines whether the operand should be replaced with a ub.poison result
95 // or erased entirely.
96 bool replaceWithPoison = false;
97};
98
99struct BlockArgsToCleanup {
100 Block *b;
101 BitVector nonLiveArgs;
102};
103
104struct SuccessorOperandsToCleanup {
105 BranchOpInterface branch;
106 unsigned successorIndex;
107 BitVector nonLiveOperands;
108};
109
110struct RDVFinalCleanupList {
111 SmallVector<Operation *> operations;
112 SmallVector<FunctionToCleanUp> functions;
113 SmallVector<OperandsToCleanup> operands;
114 SmallVector<ResultsToCleanup> results;
115 SmallVector<BlockArgsToCleanup> blocks;
116 SmallVector<SuccessorOperandsToCleanup> successorOperands;
117};
118
119// Some helper functions...
120
121/// Return true iff at least one value in `values` is live, given the liveness
122/// information in `la`.
123static bool hasLive(ValueRange values, const DenseSet<Value> &nonLiveSet,
125 for (Value value : values) {
126 if (nonLiveSet.contains(value)) {
127 LDBG() << "Value " << value << " is already marked non-live (dead)";
128 continue;
129 }
130
131 const Liveness *liveness = la.getLiveness(value);
132 if (!liveness) {
133 LDBG() << "Value " << value
134 << " has no liveness info, conservatively considered live";
135 return true;
136 }
137 if (liveness->isLive) {
138 LDBG() << "Value " << value << " is live according to liveness analysis";
139 return true;
140 }
141 LDBG() << "Value " << value << " is dead according to liveness analysis";
142 }
143 return false;
144}
145
146/// Return a BitVector of size `values.size()` where its i-th bit is 1 iff the
147/// i-th value in `values` is live, given the liveness information in `la`.
148static BitVector markLives(ValueRange values, const DenseSet<Value> &nonLiveSet,
150 BitVector lives(values.size(), true);
151
152 for (auto [index, value] : llvm::enumerate(values)) {
153 if (nonLiveSet.contains(value)) {
154 lives.reset(index);
155 LDBG() << "Value " << value
156 << " is already marked non-live (dead) at index " << index;
157 continue;
158 }
159
160 const Liveness *liveness = la.getLiveness(value);
161 // It is important to note that when `liveness` is null, we can't tell if
162 // `value` is live or not. So, the safe option is to consider it live. Also,
163 // the execution of this pass might create new SSA values when erasing some
164 // of the results of an op and we know that these new values are live
165 // (because they weren't erased) and also their liveness is null because
166 // liveness analysis ran before their creation.
167 if (!liveness) {
168 LDBG() << "Value " << value << " at index " << index
169 << " has no liveness info, conservatively considered live";
170 continue;
171 }
172 if (!liveness->isLive) {
173 lives.reset(index);
174 LDBG() << "Value " << value << " at index " << index
175 << " is dead according to liveness analysis";
176 } else {
177 LDBG() << "Value " << value << " at index " << index
178 << " is live according to liveness analysis";
179 }
180 }
181
182 return lives;
183}
184
185/// Collects values marked as "non-live" in the provided range and inserts them
186/// into the nonLiveSet. A value is considered "non-live" if the corresponding
187/// index in the `nonLive` bit vector is set.
188static void collectNonLiveValues(DenseSet<Value> &nonLiveSet, ValueRange range,
189 const BitVector &nonLive) {
190 for (auto [index, result] : llvm::enumerate(range)) {
191 if (!nonLive[index])
192 continue;
193 nonLiveSet.insert(result);
194 LDBG() << "Marking value " << result << " as non-live (dead) at index "
195 << index;
196 }
197}
198
199/// Drop the uses of the i-th result of `op` and then erase it iff toErase[i]
200/// is 1.
201static void dropUsesAndEraseResults(RewriterBase &rewriter, Operation *op,
202 BitVector toErase) {
203 assert(op->getNumResults() == toErase.size() &&
204 "expected the number of results in `op` and the size of `toErase` to "
205 "be the same");
206 for (auto idx : toErase.set_bits())
207 op->getResult(idx).dropAllUses();
208 rewriter.eraseOpResults(op, toErase);
209}
210
211/// Process a simple operation `op` using the liveness analysis `la`.
212/// If the operation has no memory effects and none of its results are live:
213/// 1. Add the operation to a list for future removal, and
214/// 2. Mark all its results as non-live values
215///
216/// The operation `op` is assumed to be simple. A simple operation is one that
217/// is NOT:
218/// - Function-like
219/// - Call-like
220/// - A region branch operation
221/// - A branch operation
222/// - A region branch terminator
223/// - Return-like
224static void processSimpleOp(Operation *op, RunLivenessAnalysis &la,
225 DenseSet<Value> &nonLiveSet,
226 RDVFinalCleanupList &cl) {
227 // Operations that have dead operands can be erased regardless of their
228 // side effects. The liveness analysis would not have marked an SSA value as
229 // "dead" if it had a side-effecting user that is reachable.
230 bool hasDeadOperand =
231 markLives(op->getOperands(), nonLiveSet, la).flip().any();
232 if (hasDeadOperand) {
233 LDBG() << "Simple op has dead operands, so the op must be dead: "
234 << OpWithFlags(op,
235 OpPrintingFlags().skipRegions().printGenericOpForm());
236 assert(!hasLive(op->getResults(), nonLiveSet, la) &&
237 "expected the op to have no live results");
238 cl.operations.push_back(op);
239 collectNonLiveValues(nonLiveSet, op->getResults(),
240 BitVector(op->getNumResults(), true));
241 return;
242 }
243
244 if (!isMemoryEffectFree(op) || hasLive(op->getResults(), nonLiveSet, la)) {
245 LDBG() << "Simple op is not memory effect free or has live results, "
246 "preserving it: "
247 << OpWithFlags(op,
248 OpPrintingFlags().skipRegions().printGenericOpForm());
249 return;
250 }
251
252 LDBG()
253 << "Simple op has all dead results and is memory effect free, scheduling "
254 "for removal: "
255 << OpWithFlags(op, OpPrintingFlags().skipRegions().printGenericOpForm());
256 cl.operations.push_back(op);
257 collectNonLiveValues(nonLiveSet, op->getResults(),
258 BitVector(op->getNumResults(), true));
259}
260
261/// Process a function-like operation `funcOp` using the liveness analysis `la`
262/// and `symbolUserMap`. If it is not public or external:
263/// (1) Adding its non-live arguments to a list for future removal.
264/// (2) Marking their corresponding operands in its callers for removal.
265/// (3) Identifying and enqueueing unnecessary terminator operands
266/// (return values that are non-live across all callers) for removal.
267/// (4) Enqueueing the non-live arguments and return values for removal.
268/// (5) Collecting the uses of these return values in its callers for future
269/// removal.
270/// (6) Marking all its results as non-live values.
271static void processFuncOp(FunctionOpInterface funcOp,
272 const SymbolUserMap &symbolUserMap,
273 RunLivenessAnalysis &la, DenseSet<Value> &nonLiveSet,
274 RDVFinalCleanupList &cl) {
275 LDBG() << "Processing function op: "
276 << OpWithFlags(funcOp,
277 OpPrintingFlags().skipRegions().printGenericOpForm());
278 if (funcOp.isPublic() || funcOp.isExternal()) {
279 LDBG() << "Function is public or external, skipping: "
280 << funcOp.getOperation()->getName();
281 return;
282 }
283 ArrayRef<Operation *> users = symbolUserMap.getUsers(funcOp);
284 if (!llvm::all_of(users, llvm::IsaPred<CallOpInterface>)) {
285 // If a non-call operation references the function (e.g. spirv.EntryPoint),
286 // we cannot safely remove arguments or return values since we don't know
287 // what the user expects. Skip this function entirely.
288 return;
289 }
290 // Get the list of unnecessary (non-live) arguments in `nonLiveArgs`.
291 SmallVector<Value> arguments(funcOp.getArguments());
292 BitVector nonLiveArgs = markLives(arguments, nonLiveSet, la);
293 nonLiveArgs = nonLiveArgs.flip();
294
295 // Do (1).
296 for (auto [index, arg] : llvm::enumerate(arguments))
297 if (arg && nonLiveArgs[index])
298 nonLiveSet.insert(arg);
299
300 // Do (2). (Skip creating generic operand cleanup entries for call ops.
301 // Call arguments will be removed in the call-site specific segment-aware
302 // cleanup, avoiding generic eraseOperands bitvector mechanics.)
303 for (Operation *callOp : users) {
304 // Push an empty operand cleanup entry so that call-site specific logic in
305 // cleanUpDeadVals runs (it keys off CallOpInterface). The BitVector is
306 // intentionally all false to avoid generic erasure.
307 // Store the funcOp as the callee to avoid expensive symbol lookup later.
308 cl.operands.push_back({callOp, BitVector(callOp->getNumOperands(), false),
309 funcOp.getOperation()});
310 }
311
312 // Do (3).
313 // Get the list of unnecessary terminator operands (return values that are
314 // non-live across all callers) in `nonLiveRets`. There is a very important
315 // subtlety here. Unnecessary terminator operands are NOT the operands of the
316 // terminator that are non-live. Instead, these are the return values of the
317 // callers such that a given return value is non-live across all callers. Such
318 // corresponding operands in the terminator could be live. An example to
319 // demonstrate this:
320 // func.func private @f(%arg0: memref<i32>) -> (i32, i32) {
321 // %c0_i32 = arith.constant 0 : i32
322 // %0 = arith.addi %c0_i32, %c0_i32 : i32
323 // memref.store %0, %arg0[] : memref<i32>
324 // return %c0_i32, %0 : i32, i32
325 // }
326 // func.func @main(%arg0: i32, %arg1: memref<i32>) -> (i32) {
327 // %1:2 = call @f(%arg1) : (memref<i32>) -> i32
328 // return %1#0 : i32
329 // }
330 // Here, we can see that %1#1 is never used. It is non-live. Thus, @f doesn't
331 // need to return %0. But, %0 is live. And, still, we want to stop it from
332 // being returned, in order to optimize our IR. So, this demonstrates how we
333 // can make our optimization strong by even removing a live return value (%0),
334 // since it forwards only to non-live value(s) (%1#1).
335 size_t numReturns = funcOp.getNumResults();
336 BitVector nonLiveRets(numReturns, true);
337 for (Operation *callOp : users) {
338 assert(isa<CallOpInterface>(callOp) && "expected a call-like user");
339 BitVector liveCallRets = markLives(callOp->getResults(), nonLiveSet, la);
340 nonLiveRets &= liveCallRets.flip();
341 }
342
343 // Note that in the absence of control flow ops forcing the control to go from
344 // the entry (first) block to the other blocks, the control never reaches any
345 // block other than the entry block, because every block has a terminator.
346 for (Block &block : funcOp.getBlocks()) {
347 Operation *returnOp = block.getTerminator();
348 if (!returnOp->hasTrait<OpTrait::ReturnLike>())
349 continue;
350 if (returnOp && returnOp->getNumOperands() == numReturns)
351 cl.operands.push_back({returnOp, nonLiveRets});
352 }
353
354 // Do (4).
355 cl.functions.push_back({funcOp, nonLiveArgs, nonLiveRets});
356
357 // Do (5) and (6).
358 if (numReturns == 0)
359 return;
360 for (Operation *callOp : users) {
361 assert(isa<CallOpInterface>(callOp) && "expected a call-like user");
362 cl.results.push_back({callOp, nonLiveRets});
363 collectNonLiveValues(nonLiveSet, callOp->getResults(), nonLiveRets);
364 }
365}
366
367/// Process a region branch operation `regionBranchOp` using the liveness
368/// information in `la`. The processing involves two scenarios:
369///
370/// Scenario 1: If the operation has no memory effects and none of its results
371/// are live:
372/// 1.1. Enqueue all its uses for deletion.
373/// 1.2. Enqueue the branch itself for deletion.
374///
375/// Scenario 2: Otherwise:
376/// 2.1. Find all operands that are forwarded to only dead region successor
377/// inputs. I.e., forwarded to block arguments / op results that we do
378/// not want to keep.
379/// 2.2. Also find operands who's values are dead (i.e., are scheduled for
380/// erasure) due to other operations.
381/// 2.3. Enqueue all such operands for replacement with ub.poison.
382///
383/// Note: In scenario 2, block arguments and op results are not removed.
384/// However, the IR is simplified such that canonicalization patterns can
385/// remove them later.
386static void processRegionBranchOp(RegionBranchOpInterface regionBranchOp,
388 DenseSet<Value> &nonLiveSet,
389 RDVFinalCleanupList &cl) {
390 LDBG() << "Processing region branch op: "
391 << OpWithFlags(regionBranchOp,
392 OpPrintingFlags().skipRegions().printGenericOpForm());
393
394 // Scenario 1. This is the only case where the entire `regionBranchOp`
395 // is removed. It will not happen in any other scenario. Note that in this
396 // case, a non-forwarded operand of `regionBranchOp` could be live/non-live.
397 // It could never be live because of this op but its liveness could have been
398 // attributed to something else.
399 if (isMemoryEffectFree(regionBranchOp.getOperation()) &&
400 !hasLive(regionBranchOp->getResults(), nonLiveSet, la)) {
401 cl.operations.push_back(regionBranchOp.getOperation());
402 return;
403 }
404
405 // Mapping from operands to forwarded successor inputs. An operand can be
406 // forwarded to multiple successors.
407 //
408 // Example:
409 //
410 // %0 = scf.while : () -> i32 {
411 // scf.condition(...) %forwarded_value : i32
412 // } do {
413 // ^bb0(%arg0: i32):
414 // scf.yield
415 // }
416 // // No uses of %0.
417 //
418 // In the above example, %forwarded_value is forwarded to %arg0 and %0. Both
419 // %arg0 and %0 are dead, so %forwarded_value can be replaced with a
420 // ub.poison result.
421 //
422 // operandToSuccessorInputs[%forwarded_value] = {%arg0, %0}
423 //
424 RegionBranchSuccessorMapping operandToSuccessorInputs;
425 regionBranchOp.getSuccessorOperandInputMapping(operandToSuccessorInputs);
426
427 DenseMap<Operation *, BitVector> deadOperandsPerOp;
428 for (auto [opOperand, successorInputs] : operandToSuccessorInputs) {
429 // Helper function to mark the operand as dead, to be replaced with a
430 // ub.poison result.
431 auto markOperandDead = [&opOperand = opOperand, &deadOperandsPerOp]() {
432 // Create an entry in `deadOperandsPerOp` (initialized to "false", i.e.,
433 // no "dead" op operands) if it's the first time that we are seeing an op
434 // operand for this op. Otherwise, just take the existing bit vector from
435 // the map.
436 BitVector &deadOperands =
437 deadOperandsPerOp
438 .try_emplace(opOperand->getOwner(),
439 opOperand->getOwner()->getNumOperands(), false)
440 .first->second;
441 deadOperands.set(opOperand->getOperandNumber());
442 };
443
444 // The operand value is scheduled for removal. Mark it as dead.
445 if (!hasLive(opOperand->get(), nonLiveSet, la)) {
446 markOperandDead();
447 continue;
448 }
449
450 // If one of the successor inputs is live, the respective operand must be
451 // kept. Otherwise, ub.poison can be passed as operand.
452 if (!hasLive(successorInputs, nonLiveSet, la))
453 markOperandDead();
454 }
455
456 for (auto [op, deadOperands] : deadOperandsPerOp) {
457 cl.operands.push_back(
458 {op, deadOperands, nullptr, /*replaceWithPoison=*/true});
459 }
460}
461
462/// Steps to process a `BranchOpInterface` operation:
463///
464/// When a non-forwarded operand is dead (e.g., the condition value of a
465/// conditional branch op), the entire operation is dead.
466///
467/// Otherwise, iterate through each successor block of `branchOp`.
468/// (1) For each successor block, gather all operands from all successors.
469/// (2) Fetch their associated liveness analysis data and collect for future
470/// removal.
471/// (3) Identify and collect the dead operands from the successor block
472/// as well as their corresponding arguments.
473
474static void processBranchOp(BranchOpInterface branchOp, RunLivenessAnalysis &la,
475 DenseSet<Value> &nonLiveSet,
476 RDVFinalCleanupList &cl) {
477 LDBG() << "Processing branch op: " << *branchOp;
478
479 // Check for dead non-forwarded operands.
480 BitVector deadNonForwardedOperands =
481 markLives(branchOp->getOperands(), nonLiveSet, la).flip();
482 unsigned numSuccessors = branchOp->getNumSuccessors();
483 for (unsigned succIdx = 0; succIdx < numSuccessors; ++succIdx) {
484 SuccessorOperands successorOperands =
485 branchOp.getSuccessorOperands(succIdx);
486 // Remove all non-forwarded operands from the bit vector.
487 for (OpOperand &opOperand : successorOperands.getMutableForwardedOperands())
488 deadNonForwardedOperands[opOperand.getOperandNumber()] = false;
489 }
490 if (deadNonForwardedOperands.any()) {
491 cl.operations.push_back(branchOp.getOperation());
492 return;
493 }
494
495 for (unsigned succIdx = 0; succIdx < numSuccessors; ++succIdx) {
496 Block *successorBlock = branchOp->getSuccessor(succIdx);
497
498 // Do (1)
499 SuccessorOperands successorOperands =
500 branchOp.getSuccessorOperands(succIdx);
501 SmallVector<Value> operandValues;
502 for (unsigned operandIdx = 0; operandIdx < successorOperands.size();
503 ++operandIdx) {
504 operandValues.push_back(successorOperands[operandIdx]);
505 }
506
507 // Do (2)
508 BitVector successorNonLive =
509 markLives(operandValues, nonLiveSet, la).flip();
510 collectNonLiveValues(nonLiveSet, successorBlock->getArguments(),
511 successorNonLive);
512
513 // Do (3)
514 cl.blocks.push_back({successorBlock, successorNonLive});
515 cl.successorOperands.push_back({branchOp, succIdx, successorNonLive});
516 }
517}
518
519/// Create a ub.poison op for the given value. If it has no uses, return an
520/// "empty" value.
521static Value createPoisonedValue(OpBuilder &b, Value value) {
522 if (value.use_empty())
523 return Value();
524 return ub::PoisonOp::create(b, value.getLoc(), value.getType()).getResult();
525}
526
527namespace {
528/// A listener that keeps track of ub.poison ops.
529struct TrackingListener : public RewriterBase::Listener {
530 void notifyOperationErased(Operation *op) override {
531 if (auto poisonOp = dyn_cast<ub::PoisonOp>(op))
532 poisonOps.erase(poisonOp);
533 }
534 void notifyOperationInserted(Operation *op,
535 OpBuilder::InsertPoint previous) override {
536 if (auto poisonOp = dyn_cast<ub::PoisonOp>(op))
537 poisonOps.insert(poisonOp);
538 }
539 DenseSet<ub::PoisonOp> poisonOps;
540};
541} // namespace
542
543/// Removes dead values collected in RDVFinalCleanupList.
544/// To be run once when all dead values have been collected.
545static void cleanUpDeadVals(MLIRContext *ctx, RDVFinalCleanupList &list) {
546 LDBG() << "Starting cleanup of dead values...";
547
548 // New ub.poison ops may be inserted during cleanup. Some of these ops may no
549 // longer be needed after the cleanup. A tracking listener keeps track of all
550 // new ub.poison ops, so that they can be removed again after the cleanup.
551 TrackingListener listener;
552 IRRewriter rewriter(ctx, &listener);
553
554 // 1. Operands to replace with poison. These rewrites need the original
555 // operand values for their location and type, so they must run before any
556 // cleanup that can drop uses and leave operands temporarily null.
557 LDBG() << "Replacing dead operands with poison in " << list.operands.size()
558 << " operand lists";
559 for (OperandsToCleanup &o : list.operands) {
560 if (!o.replaceWithPoison || !o.nonLive.any())
561 continue;
562 LDBG_OS([&](raw_ostream &os) {
563 os << "Replacing non-live operands [";
564 llvm::interleaveComma(o.nonLive.set_bits(), os);
565 os << "] with poison in operation: "
566 << OpWithFlags(o.op,
567 OpPrintingFlags().skipRegions().printGenericOpForm());
568 });
569 rewriter.setInsertionPoint(o.op);
570 for (auto deadIdx : o.nonLive.set_bits()) {
571 Value operand = o.op->getOperand(deadIdx);
572 assert(operand && "expected non-null operand for poison replacement");
573 o.op->setOperand(deadIdx, createPoisonedValue(rewriter, operand));
574 }
575 }
576
577 // 2. Blocks, We must remove the block arguments and successor operands before
578 // deleting the operation, as they may reside in the region operation.
579 LDBG() << "Cleaning up " << list.blocks.size() << " block argument lists";
580 for (auto &b : list.blocks) {
581 // blocks that are accessed via multiple codepaths processed once
582 if (b.b->getNumArguments() != b.nonLiveArgs.size())
583 continue;
584 LDBG_OS([&](raw_ostream &os) {
585 os << "Erasing non-live arguments [";
586 llvm::interleaveComma(b.nonLiveArgs.set_bits(), os);
587 os << "] from block #" << b.b->computeBlockNumber() << " in region #"
588 << b.b->getParent()->getRegionNumber() << " of operation "
589 << OpWithFlags(b.b->getParent()->getParentOp(),
590 OpPrintingFlags().skipRegions().printGenericOpForm());
591 });
592 // Note: Iterate from the end to make sure that that indices of not yet
593 // processes arguments do not change.
594 for (int i = b.nonLiveArgs.size() - 1; i >= 0; --i) {
595 if (!b.nonLiveArgs[i])
596 continue;
597 b.b->getArgument(i).dropAllUses();
598 b.b->eraseArgument(i);
599 }
600 }
601
602 // 3. Successor Operands
603 LDBG() << "Cleaning up " << list.successorOperands.size()
604 << " successor operand lists";
605 for (auto &op : list.successorOperands) {
606 SuccessorOperands successorOperands =
607 op.branch.getSuccessorOperands(op.successorIndex);
608 // blocks that are accessed via multiple codepaths processed once
609 if (successorOperands.size() != op.nonLiveOperands.size())
610 continue;
611 LDBG_OS([&](raw_ostream &os) {
612 os << "Erasing non-live successor operands [";
613 llvm::interleaveComma(op.nonLiveOperands.set_bits(), os);
614 os << "] from successor " << op.successorIndex << " of branch: "
615 << OpWithFlags(op.branch.getOperation(),
616 OpPrintingFlags().skipRegions().printGenericOpForm());
617 });
618 // it iterates backwards because erase invalidates all successor indexes
619 for (int i = successorOperands.size() - 1; i >= 0; --i) {
620 if (!op.nonLiveOperands[i])
621 continue;
622 successorOperands.erase(i);
623 }
624 }
625
626 // 4. Functions
627 LDBG() << "Cleaning up " << list.functions.size() << " functions";
628 // Record which function arguments were erased so we can shrink call-site
629 // argument segments for CallOpInterface operations (e.g. ops using
630 // AttrSizedOperandSegments) in the next phase.
632 for (auto &f : list.functions) {
633 LDBG() << "Cleaning up function: " << f.funcOp.getName() << " ("
634 << f.funcOp.getOperation() << ")";
635 LDBG_OS([&](raw_ostream &os) {
636 os << " Erasing non-live arguments [";
637 llvm::interleaveComma(f.nonLiveArgs.set_bits(), os);
638 os << "]\n";
639 os << " Erasing non-live return values [";
640 llvm::interleaveComma(f.nonLiveRets.set_bits(), os);
641 os << "]";
642 });
643 // Drop all uses of the dead arguments.
644 for (auto deadIdx : f.nonLiveArgs.set_bits())
645 f.funcOp.getArgument(deadIdx).dropAllUses();
646 // Some functions may not allow erasing arguments or results. These calls
647 // return failure in such cases without modifying the function, so it's okay
648 // to proceed.
649 if (succeeded(f.funcOp.eraseArguments(f.nonLiveArgs))) {
650 // Record only if we actually erased something.
651 if (f.nonLiveArgs.any())
652 erasedFuncArgs.try_emplace(f.funcOp.getOperation(), f.nonLiveArgs);
653 } else {
654 LDBG() << "Failed to erase arguments for function: "
655 << f.funcOp.getName();
656 }
657 (void)f.funcOp.eraseResults(f.nonLiveRets);
658 }
659
660 // 5. Operands
661 LDBG() << "Cleaning up " << list.operands.size() << " operand lists";
662 for (OperandsToCleanup &o : list.operands) {
663 if (o.replaceWithPoison)
664 continue;
665 // Handle call-specific cleanup only when we have a cached callee reference.
666 // This avoids expensive symbol lookup and is defensive against future
667 // changes.
668 bool handledAsCall = false;
669 if (o.callee && isa<CallOpInterface>(o.op)) {
670 auto call = cast<CallOpInterface>(o.op);
671 auto it = erasedFuncArgs.find(o.callee);
672 if (it != erasedFuncArgs.end()) {
673 const BitVector &deadArgIdxs = it->second;
674 MutableOperandRange args = call.getArgOperandsMutable();
675 // First, erase the call arguments corresponding to erased callee
676 // args. We iterate backwards to preserve indices.
677 for (unsigned argIdx : llvm::reverse(deadArgIdxs.set_bits()))
678 args.erase(argIdx);
679 // If this operand cleanup entry also has a generic nonLive bitvector,
680 // clear bits for call arguments we already erased above to avoid
681 // double-erasing (which could impact other segments of ops with
682 // AttrSizedOperandSegments).
683 if (o.nonLive.any()) {
684 // Map the argument logical index to the operand number(s) recorded.
685 int operandOffset = call.getArgOperands().getBeginOperandIndex();
686 for (int argIdx : deadArgIdxs.set_bits()) {
687 int operandNumber = operandOffset + argIdx;
688 if (operandNumber < static_cast<int>(o.nonLive.size()))
689 o.nonLive.reset(operandNumber);
690 }
691 }
692 handledAsCall = true;
693 }
694 }
695 // Perform generic operand erasure for:
696 // - Non-call operations
697 // - Call operations without cached callee (where handledAsCall is false)
698 // But skip call operations that were already handled via segment-aware path
699 if (!handledAsCall && o.nonLive.any()) {
700 LDBG_OS([&](raw_ostream &os) {
701 os << "Erasing non-live operands [";
702 llvm::interleaveComma(o.nonLive.set_bits(), os);
703 os << "] from operation: "
704 << OpWithFlags(o.op,
705 OpPrintingFlags().skipRegions().printGenericOpForm());
706 });
707 o.op->eraseOperands(o.nonLive);
708 }
709 }
710
711 // 6. Results
712 LDBG() << "Cleaning up " << list.results.size() << " result lists";
713 for (auto &r : list.results) {
714 LDBG_OS([&](raw_ostream &os) {
715 os << "Erasing non-live results [";
716 llvm::interleaveComma(r.nonLive.set_bits(), os);
717 os << "] from operation: "
718 << OpWithFlags(r.op,
719 OpPrintingFlags().skipRegions().printGenericOpForm());
720 });
721 dropUsesAndEraseResults(rewriter, r.op, r.nonLive);
722 }
723
724 // 7. Operations
725 LDBG() << "Cleaning up " << list.operations.size() << " operations";
726 for (Operation *op : list.operations) {
727 LDBG() << "Erasing operation: "
728 << OpWithFlags(op,
729 OpPrintingFlags().skipRegions().printGenericOpForm());
730 rewriter.setInsertionPoint(op);
731 if (op->hasTrait<OpTrait::IsTerminator>()) {
732 // When erasing a terminator, insert an unreachable op in its place.
733 ub::UnreachableOp::create(rewriter, op->getLoc());
734 }
735
736 // Before erasing the operation, replace all result values with live-uses by
737 // ub.poison values. This is important to maintain IR validity. For example,
738 // if we have an op with one of its results used by another op, erasing the
739 // op without replacing its corresponding result would leave us with a
740 // dangling operand in the user op. By replacing the result with a ub.poison
741 // value, we ensure that the user op still has a valid operand, even though
742 // it's a poison value which will be cleaned up later if it can be cleaned
743 // up. This keeps the IR valid for further simplification and
744 // canonicalization.
745 auto opResults = op->getResults();
746 for (Value opResult : opResults) {
747 // Early continue for the case where the op result has no uses. No need to
748 // create a poison op here.
749 if (opResult.use_empty())
750 continue;
751
752 rewriter.setInsertionPoint(op);
753 Value poisonedValue = createPoisonedValue(rewriter, opResult);
754 rewriter.replaceAllUsesWith(opResult, poisonedValue);
755 }
756
757 op->dropAllUses();
758 rewriter.eraseOp(op);
759 }
760
761 // 8. Remove all dead poison ops.
762 for (ub::PoisonOp poisonOp : listener.poisonOps) {
763 if (poisonOp.use_empty())
764 poisonOp.erase();
765 }
766
767 LDBG() << "Finished cleanup of dead values";
768}
769
770struct RemoveDeadValues
771 : public impl::RemoveDeadValuesPassBase<RemoveDeadValues> {
772 using impl::RemoveDeadValuesPassBase<
773 RemoveDeadValues>::RemoveDeadValuesPassBase;
774 void runOnOperation() override;
775};
776} // namespace
777
778void RemoveDeadValues::runOnOperation() {
779 auto &la = getAnalysis<RunLivenessAnalysis>();
780 Operation *module = getOperation();
781
782 // Build a symbol user map once up front so that processFuncOp can look up the
783 // callers of each function in O(1). Otherwise, each call would walk the
784 // entire module to find the callers, making the pass O(numFunctions *
785 // numOperations).
786 SymbolTableCollection symbolTableCollection;
787 SymbolUserMap symbolUserMap(symbolTableCollection, module);
788
789 // Tracks values eligible for erasure - complements liveness analysis to
790 // identify "droppable" values.
791 DenseSet<Value> deadVals;
792
793 // Maintains a list of Ops, values, branches, etc., slated for cleanup at the
794 // end of this pass.
795 RDVFinalCleanupList finalCleanupList;
796
797 module->walk([&](Operation *op) {
798 if (auto funcOp = dyn_cast<FunctionOpInterface>(op)) {
799 processFuncOp(funcOp, symbolUserMap, la, deadVals, finalCleanupList);
800 } else if (auto regionBranchOp = dyn_cast<RegionBranchOpInterface>(op)) {
801 processRegionBranchOp(regionBranchOp, la, deadVals, finalCleanupList);
802 } else if (auto branchOp = dyn_cast<BranchOpInterface>(op)) {
803 processBranchOp(branchOp, la, deadVals, finalCleanupList);
804 } else if (op->hasTrait<::mlir::OpTrait::IsTerminator>()) {
805 // Nothing to do here because this is a terminator op and it should be
806 // honored with respect to its parent
807 } else if (isa<CallOpInterface>(op)) {
808 // Nothing to do because this op is associated with a function op and gets
809 // cleaned when the latter is cleaned.
810 } else {
811 processSimpleOp(op, la, deadVals, finalCleanupList);
812 }
813 });
814
815 MLIRContext *context = module->getContext();
816 cleanUpDeadVals(context, finalCleanupList);
817
818 if (!canonicalize)
819 return;
820
821 // Canonicalize all region branch ops.
822 SmallVector<Operation *> opsToCanonicalize;
823 module->walk([&](RegionBranchOpInterface regionBranchOp) {
824 opsToCanonicalize.push_back(regionBranchOp.getOperation());
825 });
826 // Collect all canonicalization patterns for region branch ops.
827 RewritePatternSet owningPatterns(context);
828 DenseSet<RegisteredOperationName> populatedPatterns;
829 for (Operation *op : opsToCanonicalize)
830 if (std::optional<RegisteredOperationName> info = op->getRegisteredInfo())
831 if (populatedPatterns.insert(*info).second)
832 info->getCanonicalizationPatterns(owningPatterns, context);
833 if (failed(applyOpPatternsGreedily(opsToCanonicalize,
834 std::move(owningPatterns)))) {
835 module->emitError("greedy pattern rewrite failed to converge");
836 signalPassFailure();
837 }
838}
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
Block represents an ordered list of Operations.
Definition Block.h:33
BlockArgListType getArguments()
Definition Block.h:111
Block * getSuccessor(unsigned i)
Definition Block.cpp:274
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:63
This class provides a mutable adaptor for a range of operands.
Definition ValueRange.h:119
void erase(unsigned subStart, unsigned subLen=1)
Erase the operands within the given sub-range.
This class helps build Operations.
Definition Builders.h:209
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:400
This class represents an operand of an operation.
Definition Value.h:254
Set of flags used to control the behavior of the various IR print methods (e.g.
This class provides the API for ops that are known to be terminators.
A wrapper class that allows for printing an operation with a set of flags, useful to act as a "stream...
Definition Operation.h:1142
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Value getOperand(unsigned idx)
Definition Operation.h:375
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:774
void dropAllUses()
Drop all uses of results of this operation.
Definition Operation.h:859
void setOperand(unsigned idx, Value value)
Definition Operation.h:376
void eraseOperands(unsigned idx, unsigned length=1)
Erase the operands starting at position idx and ending at position 'idx'+'length'.
Definition Operation.h:385
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:432
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
std::optional< RegisteredOperationName > getRegisteredInfo()
If this operation has a registered operation description, return it.
Definition Operation.h:119
unsigned getNumOperands()
Definition Operation.h:371
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:403
result_range getResults()
Definition Operation.h:440
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:429
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
Operation * eraseOpResults(Operation *op, const BitVector &eraseIndices)
Erase the specified results of the given operation.
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
This class models how operands are forwarded to block arguments in control flow.
void erase(unsigned subStart, unsigned subLen=1)
Erase operands forwarded to the successor.
MutableOperandRange getMutableForwardedOperands() const
Get the range of operands that are simply forwarded to the successor.
unsigned size() const
Returns the amount of operands passed to the successor.
This class represents a map of symbols to users, and provides efficient implementations of symbol que...
ArrayRef< Operation * > getUsers(Operation *symbol) const
Return the users of the provided symbol operation.
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:389
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
bool use_empty() const
Returns true if this value has no uses.
Definition Value.h:208
void dropAllUses()
Drop all uses of this object from their respective owners.
Definition Value.h:144
Type getType() const
Return the type of this value.
Definition Value.h:105
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:717
Include the generated interface declarations.
DenseMap< OpOperand *, SmallVector< Value > > RegionBranchSuccessorMapping
A mapping from successor operands to successor inputs.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:122
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
LogicalResult applyOpPatternsGreedily(ArrayRef< Operation * > ops, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr, bool *allErased=nullptr)
Rewrite the specified ops by repeatedly applying the highest benefit patterns in a greedy worklist dr...
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:120
This trait indicates that a terminator operation is "return-like".
This lattice represents, for a given value, whether or not it is "live".
Runs liveness analysis on the IR defined by op.
const Liveness * getLiveness(Value val)