1 //===- TestPrintDefUse.cpp - Passes to illustrate the IR def-use chains ---===// 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 #include "mlir/IR/BuiltinOps.h" 10 #include "mlir/Pass/Pass.h" 11 12 using namespace mlir; 13 14 namespace { 15 /// This pass illustrates the IR def-use chains through printing. 16 struct TestPrintDefUsePass 17 : public PassWrapper<TestPrintDefUsePass, OperationPass<>> { 18 StringRef getArgument() const final { return "test-print-defuse"; } 19 StringRef getDescription() const final { return "Test various printing."; } 20 void runOnOperation() override { 21 // Recursively traverse the IR nested under the current operation and print 22 // every single operation and their operands and users. 23 getOperation()->walk([](Operation *op) { 24 llvm::outs() << "Visiting op '" << op->getName() << "' with " 25 << op->getNumOperands() << " operands:\n"; 26 27 // Print information about the producer of each of the operands. 28 for (Value operand : op->getOperands()) { 29 if (Operation *producer = operand.getDefiningOp()) { 30 llvm::outs() << " - Operand produced by operation '" 31 << producer->getName() << "'\n"; 32 } else { 33 // If there is no defining op, the Value is necessarily a Block 34 // argument. 35 auto blockArg = operand.cast<BlockArgument>(); 36 llvm::outs() << " - Operand produced by Block argument, number " 37 << blockArg.getArgNumber() << "\n"; 38 } 39 } 40 41 // Print information about the user of each of the result. 42 llvm::outs() << "Has " << op->getNumResults() << " results:\n"; 43 for (const auto &indexedResult : llvm::enumerate(op->getResults())) { 44 Value result = indexedResult.value(); 45 llvm::outs() << " - Result " << indexedResult.index(); 46 if (result.use_empty()) { 47 llvm::outs() << " has no uses\n"; 48 continue; 49 } 50 if (result.hasOneUse()) { 51 llvm::outs() << " has a single use: "; 52 } else { 53 llvm::outs() << " has " 54 << std::distance(result.getUses().begin(), 55 result.getUses().end()) 56 << " uses:\n"; 57 } 58 for (Operation *userOp : result.getUsers()) { 59 llvm::outs() << " - " << userOp->getName() << "\n"; 60 } 61 } 62 }); 63 } 64 }; 65 } // namespace 66 67 namespace mlir { 68 void registerTestPrintDefUsePass() { PassRegistration<TestPrintDefUsePass>(); } 69 } // namespace mlir 70