|
| 1 | +//===- DCEUtils.cpp - Dead Code Elimination ------------------------===// |
| 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 transformation implements method for eliminating dead code. |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +#include "mlir/Transforms/DCEUtils.h" |
| 14 | +#include "mlir/IR/PatternMatch.h" |
| 15 | +#include "mlir/Interfaces/SideEffectInterfaces.h" |
| 16 | +#include "llvm/ADT/SetVector.h" |
| 17 | + |
| 18 | +using namespace mlir; |
| 19 | + |
| 20 | +void mlir::deadCodeElimination(RewriterBase &rewriter, Operation *target) { |
| 21 | + // Maintain a worklist of potentially dead ops. |
| 22 | + mlir::SetVector<Operation *> worklist; |
| 23 | + |
| 24 | + // Helper function that adds all defining ops of used values (operands and |
| 25 | + // operands of nested ops). |
| 26 | + auto addDefiningOpsToWorklist = [&](Operation *op) { |
| 27 | + op->walk([&](Operation *op) { |
| 28 | + for (Value v : op->getOperands()) |
| 29 | + if (Operation *defOp = v.getDefiningOp()) |
| 30 | + if (target->isProperAncestor(defOp)) |
| 31 | + worklist.insert(defOp); |
| 32 | + }); |
| 33 | + }; |
| 34 | + |
| 35 | + // Helper function that erases an op. |
| 36 | + auto eraseOp = [&](Operation *op) { |
| 37 | + // Remove op and nested ops from the worklist. |
| 38 | + op->walk([&](Operation *op) { |
| 39 | + const auto *it = llvm::find(worklist, op); |
| 40 | + if (it != worklist.end()) |
| 41 | + worklist.erase(it); |
| 42 | + }); |
| 43 | + rewriter.eraseOp(op); |
| 44 | + }; |
| 45 | + |
| 46 | + // Initial walk over the IR. |
| 47 | + target->walk<WalkOrder::PostOrder>([&](Operation *op) { |
| 48 | + if (op != target && isOpTriviallyDead(op)) { |
| 49 | + addDefiningOpsToWorklist(op); |
| 50 | + eraseOp(op); |
| 51 | + } |
| 52 | + }); |
| 53 | + |
| 54 | + // Erase all ops that have become dead. |
| 55 | + while (!worklist.empty()) { |
| 56 | + Operation *op = worklist.pop_back_val(); |
| 57 | + if (!isOpTriviallyDead(op)) |
| 58 | + continue; |
| 59 | + addDefiningOpsToWorklist(op); |
| 60 | + eraseOp(op); |
| 61 | + } |
| 62 | +} |
0 commit comments