MLIR  20.0.0git
EmptyTensorElimination.cpp
Go to the documentation of this file.
1 //===- EmptyTensorElimination.cpp - tensor.empty op 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 
10 
17 #include "mlir/IR/Dominance.h"
19 #include "mlir/Pass/Pass.h"
20 
21 namespace mlir {
22 namespace bufferization {
23 #define GEN_PASS_DEF_EMPTYTENSORELIMINATION
24 #include "mlir/Dialect/Bufferization/Transforms/Passes.h.inc"
25 } // namespace bufferization
26 } // namespace mlir
27 
28 using namespace mlir;
29 using namespace mlir::bufferization;
30 
31 /// Return true if all `neededValues` are in scope at the given
32 /// `insertionPoint`.
33 static bool
35  Operation *insertionPoint,
36  const SmallVector<Value> &neededValues) {
37  for (Value val : neededValues) {
38  if (auto bbArg = dyn_cast<BlockArgument>(val)) {
39  Block *owner = bbArg.getOwner();
40  if (!owner->findAncestorOpInBlock(*insertionPoint))
41  return false;
42  } else {
43  auto opResult = cast<OpResult>(val);
44  if (!domInfo.properlyDominates(opResult.getOwner(), insertionPoint))
45  return false;
46  }
47  }
48  return true;
49 }
50 
51 /// Find a valid insertion point for a replacement of `emptyTensorOp`'s
52 /// use of `user` operation, assuming that the replacement may use any
53 /// value from `neededValues`.
54 static Operation *
56  const SmallVector<Value> &neededValues) {
57  DominanceInfo domInfo;
58  Operation *candidateInsertionPoint = emptyTensorOp;
59 
60  // Gather all possible insertion points: the location of
61  // `candidateInsertionPoint` and right after the definition of each value in
62  // `neededValues`.
63  SmallVector<Operation *> insertionPointCandidates;
64  insertionPointCandidates.push_back(candidateInsertionPoint);
65  for (Value val : neededValues) {
66  // Note: The anchor op is using all of `neededValues`, so:
67  // * in case of a block argument: There must be at least one op in the block
68  // (the anchor op or one of its parents).
69  // * in case of an OpResult: There must be at least one op right after the
70  // defining op (the anchor op or one of its
71  // parents).
72  if (auto bbArg = dyn_cast<BlockArgument>(val)) {
73  insertionPointCandidates.push_back(
74  &bbArg.getOwner()->getOperations().front());
75  } else {
76  insertionPointCandidates.push_back(val.getDefiningOp()->getNextNode());
77  }
78  }
79 
80  // Select first matching insertion point.
81  for (Operation *insertionPoint : insertionPointCandidates) {
82  // Check if all needed values are in scope.
83  if (!neededValuesDominateInsertionPoint(domInfo, insertionPoint,
84  neededValues))
85  continue;
86  // Check if the insertion point is before the use to be replaced.
87  if (!domInfo.dominates(insertionPoint, user))
88  continue;
89  return insertionPoint;
90  }
91 
92  // No suitable insertion point was found.
93  return nullptr;
94 }
95 
97  RewriterBase &rewriter, Operation *op, OneShotAnalysisState &state) {
98  OpBuilder::InsertionGuard g(rewriter);
99  llvm::DenseSet<OpOperand *> visitedOpOperands;
100  op->walk([&](SubsetInsertionOpInterface op) {
101  visitedOpOperands.clear();
102  OpOperand &source = op.getSourceOperand();
103  // Skip operands that do not bufferize inplace. "tensor.empty" could still
104  // be replaced, but the transformation may not be beneficial.
105  if (!state.isInPlace(source))
106  return WalkResult::skip();
107 
108  // All values that are needed to create the replacement op.
109  SmallVector<Value> neededValues =
110  op.getValuesNeededToBuildSubsetExtraction();
111 
112  // Find tensor.empty ops on the reverse SSA use-def chain. Only follow
113  // equivalent tensors. I.e., stop when there are ops such as extract_slice
114  // on the path.
116  config.followEquivalentOnly = true;
117  config.alwaysIncludeLeaves = false;
118  // Replace only if the types match or are static <-> dynamic casts. We do
119  // not support slices or reshapes.
120  // TODO: This could be extended to support IR such as:
121  // %0 = tensor.empty() : tensor<128xf32>
122  // %1 = "some_op"(%0) : (tensor<128xf32>) -> (tensor<128xf32>)
123  // %2 = tensor.expand_shape %1 ...
124  // %3 = tensor.insert_slice %2 into ...
125  config.followSameTypeOrCastsOnly = true;
126  SetVector<Value> emptyTensors = state.findValueInReverseUseDefChain(
127  source.get(), /*condition=*/
128  [&](Value val) { return val.getDefiningOp<tensor::EmptyOp>(); }, config,
129  &visitedOpOperands);
130 
131  for (Value v : emptyTensors) {
132  Operation *emptyTensorOp = v.getDefiningOp();
133 
134  // Find the use to be replaced from the use-def chain.
135  auto iter = llvm::find_if(
136  visitedOpOperands, [&emptyTensorOp](OpOperand *opOperand) {
137  return llvm::count(emptyTensorOp->getUses(), *opOperand);
138  });
139  // This could be achieved when a use of `emptyTensorOp` is being
140  // consumed by `SubsetInsertionOpInterface`'s source directly.
141  if (iter == visitedOpOperands.end())
142  continue;
143  OpOperand *useToBeReplaced = *iter;
144  Operation *user = useToBeReplaced->getOwner();
145 
146  // Find a suitable insertion point. If no suitable insertion point for
147  // the replacement can be found, skip this replacement.
148  Operation *insertionPoint =
149  findValidInsertionPoint(emptyTensorOp, user, neededValues);
150  if (!insertionPoint)
151  continue;
152 
153  rewriter.setInsertionPoint(insertionPoint);
154  Value replacement =
155  op.buildSubsetExtraction(rewriter, emptyTensorOp->getLoc());
156  if (!replacement)
157  continue;
158  if (emptyTensorOp == replacement.getDefiningOp())
159  continue;
160  if (replacement.getType() != v.getType()) {
161  if (cast<ShapedType>(replacement.getType()).getElementType() !=
162  cast<ShapedType>(v.getType()).getElementType())
163  continue;
164  rewriter.setInsertionPointAfterValue(replacement);
165  replacement = rewriter.create<tensor::CastOp>(v.getLoc(), v.getType(),
166  replacement);
167  }
168  // Replace the specific use of the tensor::EmptyOp.
169  rewriter.modifyOpInPlace(user, [&]() {
170  user->setOperand(useToBeReplaced->getOperandNumber(), replacement);
171  });
172  state.resetCache();
173  }
174 
175  return WalkResult::advance();
176  });
177 
178  return success();
179 }
180 
181 namespace {
182 struct EmptyTensorElimination
183  : public bufferization::impl::EmptyTensorEliminationBase<
184  EmptyTensorElimination> {
185  EmptyTensorElimination() = default;
186 
187  void runOnOperation() override;
188 
189  void getDependentDialects(DialectRegistry &registry) const override {
190  registry
191  .insert<bufferization::BufferizationDialect, tensor::TensorDialect>();
192  }
193 };
194 } // namespace
195 
197  Operation *op) {
198  auto moduleOp = dyn_cast<ModuleOp>(op);
200  options.allowReturnAllocsFromLoops = true;
201  if (moduleOp)
202  options.bufferizeFunctionBoundaries = true;
203  OneShotAnalysisState state(op, options);
204  if (moduleOp) {
205  // Module analysis takes into account function boundaries.
206  if (failed(analyzeModuleOp(moduleOp, state)))
207  return failure();
208  } else {
209  // Regular One-Shot Bufferize ignores func.func block arguments, func.call,
210  // func.return.
211  if (failed(analyzeOp(op, state)))
212  return failure();
213  }
214 
215  return bufferization::eliminateEmptyTensors(rewriter, op, state);
216 }
217 
218 void EmptyTensorElimination::runOnOperation() {
219  IRRewriter rewriter(getOperation()->getContext());
220  if (failed(bufferization::eliminateEmptyTensors(rewriter, getOperation())))
221  signalPassFailure();
222 }
223 
225  return std::make_unique<EmptyTensorElimination>();
226 }
static Operation * findValidInsertionPoint(Operation *emptyTensorOp, Operation *user, const SmallVector< Value > &neededValues)
Find a valid insertion point for a replacement of emptyTensorOp's use of user operation,...
static bool neededValuesDominateInsertionPoint(const DominanceInfo &domInfo, Operation *insertionPoint, const SmallVector< Value > &neededValues)
Return true if all neededValues are in scope at the given insertionPoint.
static MLIRContext * getContext(OpFoldResult val)
static llvm::ManagedStatic< PassManagerOptions > options
Block represents an ordered list of Operations.
Definition: Block.h:33
Operation * findAncestorOpInBlock(Operation &op)
Returns 'op' if 'op' lies in this block, or otherwise finds the ancestor operation of 'op' that lies ...
Definition: Block.cpp:76
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
A class for computing basic dominance information.
Definition: Dominance.h:140
bool properlyDominates(Operation *a, Operation *b, bool enclosingOpOk=true) const
Return true if operation A properly dominates operation B, i.e.
Definition: Dominance.h:153
bool dominates(Operation *a, Operation *b) const
Return true if operation A dominates operation B, i.e.
Definition: Dominance.h:160
IRValueT get() const
Return the current value being used by this operand.
Definition: UseDefLists.h:160
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
Definition: PatternMatch.h:772
RAII guard to reset the insertion point of the builder when destroyed.
Definition: Builders.h:357
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition: Builders.h:407
void setInsertionPointAfterValue(Value val)
Sets the insertion point to the node after the specified value.
Definition: Builders.h:430
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:497
This class represents an operand of an operation.
Definition: Value.h:267
unsigned getOperandNumber()
Return which operand this is in the OpOperand list of the Operation.
Definition: Value.cpp:216
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
void setOperand(unsigned idx, Value value)
Definition: Operation.h:351
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition: Operation.h:798
Location getLoc()
The source location the operation was defined or derived from.
Definition: Operation.h:223
use_range getUses()
Returns a range of all uses, which is useful for iterating over all uses.
Definition: Operation.h:847
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
Definition: PatternMatch.h:400
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
Definition: PatternMatch.h:636
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition: Value.h:96
Type getType() const
Return the type of this value.
Definition: Value.h:129
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition: Value.cpp:20
static WalkResult skip()
Definition: Visitors.h:52
static WalkResult advance()
Definition: Visitors.h:51
State for analysis-enabled bufferization.
Operation * getOwner() const
Return the owner of this operand.
Definition: UseDefLists.h:38
LogicalResult analyzeOp(Operation *op, OneShotAnalysisState &state, BufferizationStatistics *statistics=nullptr)
Analyze op and its nested ops.
llvm::LogicalResult analyzeModuleOp(ModuleOp moduleOp, OneShotAnalysisState &state, BufferizationStatistics *statistics=nullptr)
Analyze moduleOp and its nested ops.
LogicalResult eliminateEmptyTensors(RewriterBase &rewriter, Operation *op)
Try to eliminate "tensor.empty" ops inside op.
std::unique_ptr< Pass > createEmptyTensorEliminationPass()
Create a pass that tries to eliminate tensor.empty ops that are anchored on insert_slice ops.
Include the generated interface declarations.
const FrozenRewritePatternSet GreedyRewriteConfig config
Options for analysis-enabled bufferization.
Traversal parameters for findValueInReverseUseDefChain.