1 //===- Hoisting.cpp - Linalg hoisting transformations ---------------------===//
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 functions concerned with hoisting invariant operations
10 // in the context of Linalg transformations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Dialect/Linalg/Transforms/Hoisting.h"
15 #include "mlir/Analysis/AffineStructures.h"
16 #include "mlir/Analysis/SliceAnalysis.h"
17 #include "mlir/Dialect/Affine/IR/AffineValueMap.h"
18 #include "mlir/Dialect/Affine/Utils.h"
19 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
20 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
21 #include "mlir/Dialect/SCF/SCF.h"
22 #include "mlir/Dialect/SCF/Utils.h"
23 #include "mlir/Dialect/StandardOps/IR/Ops.h"
24 #include "mlir/Dialect/Tensor/IR/Tensor.h"
25 #include "mlir/Dialect/Vector/VectorOps.h"
26 #include "mlir/Dialect/Vector/VectorUtils.h"
27 #include "mlir/IR/BuiltinOps.h"
28 #include "mlir/IR/Dominance.h"
29 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
30 #include "mlir/Transforms/LoopUtils.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/Support/Debug.h"
33 
34 using llvm::dbgs;
35 
36 #define DEBUG_TYPE "linalg-hoisting"
37 
38 #define DBGS() (dbgs() << '[' << DEBUG_TYPE << "] ")
39 
40 using namespace mlir;
41 using namespace mlir::linalg;
42 
43 namespace {
44 /// Represents a unit of hoistable TransferWriteOp. This may comprise other
45 /// instructions that need to be hoisted too.
46 struct HoistableWrite {
47   vector::TransferWriteOp transferWriteOp;
48   tensor::InsertSliceOp insertSliceOp;
49 };
50 /// Represents a unit of hoistable TransferReadOp. This may comprise other
51 /// instructions that need to be hoisted too.
52 struct HoistableRead {
53   vector::TransferReadOp transferReadOp;
54   tensor::ExtractSliceOp extractSliceOp;
55 };
56 } // namespace
57 
58 /// Return true if op1 and op2 are the same constant or the same SSA value.
59 static bool isEqualOffsetSizeOrStride(OpFoldResult op1, OpFoldResult op2) {
60   auto getConstantIntValue = [](OpFoldResult ofr) -> llvm::Optional<int64_t> {
61     Attribute attr = ofr.dyn_cast<Attribute>();
62     // Note: isa+cast-like pattern allows writing the condition below as 1 line.
63     if (!attr && ofr.get<Value>().getDefiningOp<ConstantOp>())
64       attr = ofr.get<Value>().getDefiningOp<ConstantOp>().getValue();
65     if (auto intAttr = attr.dyn_cast_or_null<IntegerAttr>())
66       return intAttr.getValue().getSExtValue();
67     return llvm::None;
68   };
69   auto cst1 = getConstantIntValue(op1), cst2 = getConstantIntValue(op2);
70   if (cst1 && cst2 && *cst1 == *cst2)
71     return true;
72   auto v1 = op1.dyn_cast<Value>(), v2 = op2.dyn_cast<Value>();
73   return v1 && v2 && v1 == v2;
74 }
75 
76 /// Return true is all offsets, sizes and strides are equal.
77 static bool sameOffsetsSizesAndStrides(tensor::ExtractSliceOp s,
78                                        tensor::InsertSliceOp si) {
79   if (s.static_offsets().size() != si.static_offsets().size())
80     return false;
81   if (s.static_sizes().size() != si.static_sizes().size())
82     return false;
83   if (s.static_strides().size() != si.static_strides().size())
84     return false;
85   for (auto it : llvm::zip(s.getMixedOffsets(), si.getMixedOffsets()))
86     if (!isEqualOffsetSizeOrStride(std::get<0>(it), std::get<1>(it)))
87       return false;
88   for (auto it : llvm::zip(s.getMixedSizes(), si.getMixedSizes()))
89     if (!isEqualOffsetSizeOrStride(std::get<0>(it), std::get<1>(it)))
90       return false;
91   for (auto it : llvm::zip(s.getMixedStrides(), si.getMixedStrides()))
92     if (!isEqualOffsetSizeOrStride(std::get<0>(it), std::get<1>(it)))
93       return false;
94   return true;
95 }
96 
97 /// Look for a HoistableRead, in the given tensor uses, accessing the same
98 /// offset as the HoistableWrite.
99 static HoistableRead findMatchingTransferRead(HoistableWrite write,
100                                               Value srcTensor) {
101   assert(write.transferWriteOp &&
102          "expected hoistable write to have a .transfer_write");
103 
104   LLVM_DEBUG(DBGS() << "findMatchingTransferRead for: "
105                     << *write.transferWriteOp.getOperation() << "\n");
106   if (write.insertSliceOp)
107     LLVM_DEBUG(DBGS() << "findMatchingTransferRead inserSliceOp: "
108                       << *write.insertSliceOp.getOperation() << "\n");
109 
110   for (Operation *user : srcTensor.getUsers()) {
111     LLVM_DEBUG(DBGS() << "findMatchingTransferRead inspect user: " << *user
112                       << "\n");
113 
114     // If HoistableWrite involves a InsertSliceOp, we need to find a
115     // matching ExtractSliceOp.
116     tensor::ExtractSliceOp sliceOp;
117     Operation *maybeTransferReadUser = user;
118     if (write.insertSliceOp) {
119       sliceOp = dyn_cast<tensor::ExtractSliceOp>(user);
120       if (!sliceOp || sliceOp.getResult().getType() !=
121                           write.insertSliceOp.source().getType())
122         continue;
123 
124       LLVM_DEBUG(DBGS() << "check whether sameOffsetsSizesAndStrides: "
125                         << *sliceOp << " vs " << *write.insertSliceOp << "\n");
126       if (!sameOffsetsSizesAndStrides(sliceOp, write.insertSliceOp))
127         continue;
128 
129       LLVM_DEBUG(DBGS() << "sameOffsetsSizesAndStrides: SUCCESS\n");
130       // If we got here, sliceOp is hoistable iff it has exactly 2 uses:
131       //   1. the transfer_write we want to hoist.
132       //   2. a matching transfer_read.
133       // Anything else, we skip.
134       bool skip = false;
135       Operation *otherUser = nullptr;
136       for (Operation *u : sliceOp->getUsers()) {
137         if (u == write.transferWriteOp)
138           continue;
139         if (otherUser) {
140           skip = true;
141           break;
142         }
143         otherUser = u;
144       }
145       if (skip || !otherUser)
146         continue;
147       maybeTransferReadUser = otherUser;
148     }
149 
150     LLVM_DEBUG(DBGS() << "maybeTransferReadUser: " << *maybeTransferReadUser
151                       << "\n");
152     auto read = dyn_cast<vector::TransferReadOp>(maybeTransferReadUser);
153     if (read && read.indices() == write.transferWriteOp.indices() &&
154         read.getVectorType() == write.transferWriteOp.getVectorType())
155       return HoistableRead{read, sliceOp};
156   }
157   return HoistableRead();
158 }
159 
160 /// Check if the chunk of data inserted by the HoistableWrite are read by any
161 /// other op than the HoistableRead candidate.
162 static bool tensorChunkAccessedByUnknownOp(HoistableWrite write,
163                                            HoistableRead candidateRead,
164                                            BlockArgument tensorArg) {
165   // Make sure none of the other uses read the part of the tensor modified
166   // by the transfer_write.
167   llvm::SmallVector<Value::use_range, 1> uses;
168   uses.push_back(tensorArg.getUses());
169   while (!uses.empty()) {
170     for (OpOperand &use : uses.pop_back_val()) {
171       Operation *user = use.getOwner();
172       // Skip the candidate use, only inspect the "other" uses.
173       if (user == candidateRead.transferReadOp ||
174           user == candidateRead.extractSliceOp ||
175           user == write.transferWriteOp || user == write.insertSliceOp)
176         continue;
177       // Consider all transitive uses through a extract_slice / insert_slice.
178       // TODO: atm we just bail because a stronger analysis is needed for these
179       // cases.
180       if (isa<tensor::ExtractSliceOp, tensor::InsertSliceOp>(user))
181         return true;
182       // Consider all transitive uses through a vector.transfer_write.
183       if (auto writeUser = dyn_cast<vector::TransferWriteOp>(user)) {
184         uses.push_back(writeUser->getResult(0).getUses());
185         continue;
186       }
187       // Consider all nested uses through an scf::ForOp. We may have
188       // pass-through tensor arguments left from previous level of
189       // hoisting.
190       if (auto forUser = dyn_cast<scf::ForOp>(user)) {
191         Value arg = forUser.getLoopBody().getArgument(
192             use.getOperandNumber() - forUser.getNumControlOperands() +
193             /*iv value*/ 1);
194         uses.push_back(arg.getUses());
195         continue;
196       }
197       // Follow the use yield as long as it doesn't escape the original
198       // region.
199       scf::YieldOp yieldUser = dyn_cast<scf::YieldOp>(user);
200       if (yieldUser && write.transferWriteOp->getParentOp()->isAncestor(
201                            yieldUser->getParentOp())) {
202         Value ret = yieldUser->getParentOp()->getResult(use.getOperandNumber());
203         uses.push_back(ret.getUses());
204         continue;
205       }
206       auto read = dyn_cast<vector::TransferReadOp>(user);
207       if (!read || !isDisjointTransferIndices(
208                        cast<VectorTransferOpInterface>(read.getOperation()),
209                        cast<VectorTransferOpInterface>(
210                            write.transferWriteOp.getOperation()))) {
211         return true;
212       }
213     }
214   }
215   return false;
216 }
217 
218 /// Return the `forOp`-invariant HoistableWrite that produces `yieldOperand`.
219 /// Return the null HoistableWrite() if it is not comprised of a
220 /// vector.transfer_write + optional insert_slice or if any of the indexings
221 /// is `forOp`-dependent.
222 static HoistableWrite
223 getLoopInvariantTransferWriteOpDefining(scf::ForOp forOp,
224                                         OpOperand &yieldOperand) {
225   Value v = yieldOperand.get();
226   if (auto write = v.getDefiningOp<vector::TransferWriteOp>()) {
227     // Indexing must not depend on `forOp`.
228     for (Value operand : write.indices())
229       if (!forOp.isDefinedOutsideOfLoop(operand))
230         return HoistableWrite();
231 
232     return HoistableWrite{write, nullptr};
233   }
234 
235   if (auto insertSliceOp = v.getDefiningOp<tensor::InsertSliceOp>()) {
236     // Inserted slice must come from vector.transfer_write.
237     auto write =
238         insertSliceOp.source().getDefiningOp<vector::TransferWriteOp>();
239     if (!write)
240       return HoistableWrite();
241 
242     // Tensor inserted into must be a BBArg at position matching yieldOperand's.
243     auto bbArg = insertSliceOp.dest().dyn_cast<BlockArgument>();
244     if (!bbArg || bbArg.getOwner()->getParentOp() != forOp ||
245         bbArg.getArgNumber() != /*num iv=*/1 + yieldOperand.getOperandNumber())
246       return HoistableWrite();
247 
248     // Indexing inserted into must not depend on `forOp`.
249     for (Value operand : insertSliceOp->getOperands().drop_front(
250              tensor::InsertSliceOp::getOffsetSizeAndStrideStartOperandIndex()))
251       if (!forOp.isDefinedOutsideOfLoop(operand))
252         return HoistableWrite();
253 
254     return HoistableWrite{write, insertSliceOp};
255   }
256 
257   return HoistableWrite();
258 }
259 
260 /// Mechanical hoisting of a matching HoistableRead / HoistableWrite pair.
261 static void hoistReadWrite(HoistableRead read, HoistableWrite write,
262                            BlockArgument tensorBBArg) {
263   scf::ForOp forOp = cast<scf::ForOp>(tensorBBArg.getOwner()->getParentOp());
264   assert(read.transferReadOp && write.transferWriteOp &&
265          "expected transfer_read and transfer_write ops to be set");
266   assert(((read.extractSliceOp && write.insertSliceOp) ||
267           (!read.extractSliceOp && !write.insertSliceOp)) &&
268          "expected matching extract_slice / insert_slice");
269   LLVM_DEBUG(DBGS() << "In forOp:\n"
270                     << *forOp.getOperation()
271                     << "\nHoist: " << *read.transferReadOp.getOperation()
272                     << "\nHoist: " << *write.transferWriteOp.getOperation()
273                     << "\nInvolving: " << tensorBBArg << "\n");
274 
275   // If a read slice is present, hoist it.
276   if (read.extractSliceOp && failed(forOp.moveOutOfLoop({read.extractSliceOp})))
277     llvm_unreachable("Unexpected failure moving extract_slice out of loop");
278 
279   // Hoist the transfer_read op.
280   if (failed(forOp.moveOutOfLoop({read.transferReadOp})))
281     llvm_unreachable("Unexpected failure moving transfer read out of loop");
282 
283   // TODO: don't hardcode /*numIvs=*/1.
284   assert(tensorBBArg.getArgNumber() >= /*numIvs=*/1);
285   unsigned initArgNumber = tensorBBArg.getArgNumber() - /*numIvs=*/1;
286 
287   // Update the source tensor.
288   if (read.extractSliceOp)
289     read.extractSliceOp.sourceMutable().assign(forOp.initArgs()[initArgNumber]);
290   else
291     read.transferReadOp.sourceMutable().assign(forOp.initArgs()[initArgNumber]);
292 
293   // Hoist write after.
294   if (write.insertSliceOp)
295     write.insertSliceOp->moveAfter(forOp);
296   write.transferWriteOp->moveAfter(forOp);
297 
298   // Update the yield.
299   auto yieldOp = cast<scf::YieldOp>(forOp.region().front().getTerminator());
300   if (write.insertSliceOp)
301     yieldOp->setOperand(initArgNumber, write.insertSliceOp.dest());
302   else
303     yieldOp->setOperand(initArgNumber, write.transferWriteOp.source());
304 
305   // Rewrite `loop` with additional new yields.
306   OpBuilder b(read.transferReadOp);
307   auto newForOp = cloneWithNewYields(b, forOp, read.transferReadOp.vector(),
308                                      write.transferWriteOp.vector());
309   // Transfer write has been hoisted, need to update the vector and tensor
310   // source. Replace the result of the loop to use the new tensor created
311   // outside the loop.
312   // Depending on whether a insert_slice is present or not, it carries the
313   // update on the tensor operands.
314   if (write.insertSliceOp) {
315     newForOp.getResult(initArgNumber)
316         .replaceAllUsesWith(write.insertSliceOp.getResult());
317     write.transferWriteOp.sourceMutable().assign(read.extractSliceOp.result());
318     write.insertSliceOp.destMutable().assign(read.extractSliceOp.source());
319   } else {
320     newForOp.getResult(initArgNumber)
321         .replaceAllUsesWith(write.transferWriteOp.getResult(0));
322     write.transferWriteOp.sourceMutable().assign(
323         newForOp.getResult(initArgNumber));
324   }
325 
326   // Always update with the newly yield tensor and vector.
327   write.transferWriteOp.vectorMutable().assign(newForOp.getResults().back());
328 }
329 
330 // To hoist transfer op on tensor the logic can be significantly simplified
331 // compared to the case on buffer. The transformation follows this logic:
332 // 1. Look for transfer_write with a single use from ForOp yield
333 // 2. Check the uses of the matching block argument and look for a transfer_read
334 // with the same indices.
335 // 3. Check that all the other uses of the tensor argument are either disjoint
336 // tensor_read or transfer_write. For transfer_write uses recurse to make sure
337 // the new tensor has the same restrictions on its uses.
338 // 4. Hoist the tensor_read/tensor_write and update the tensor SSA links.
339 // After this transformation the scf.forOp may have unused arguments that can be
340 // remove by the canonicalization pass.
341 void mlir::linalg::hoistRedundantVectorTransfersOnTensor(FuncOp func) {
342   bool changed = true;
343   while (changed) {
344     changed = false;
345     func.walk([&](scf::ForOp forOp) {
346       Operation *yield = forOp.getBody()->getTerminator();
347       for (auto it : llvm::enumerate(forOp.getRegionIterArgs())) {
348         OpOperand &ret = yield->getOpOperand(it.index());
349         HoistableWrite write =
350             getLoopInvariantTransferWriteOpDefining(forOp, ret);
351         if (!write.transferWriteOp || !write.transferWriteOp->hasOneUse())
352           continue;
353         LLVM_DEBUG(dbgs() << "\n";
354                    DBGS() << "Candidate write for hoisting: "
355                           << *write.transferWriteOp.getOperation() << "\n");
356         if (write.insertSliceOp)
357           LLVM_DEBUG(DBGS() << "Candidate insert_slice for hoisting: "
358                             << *write.insertSliceOp.getOperation() << "\n");
359         if (llvm::any_of(write.transferWriteOp.indices(),
360                          [&forOp](Value index) {
361                            return !forOp.isDefinedOutsideOfLoop(index);
362                          }))
363           continue;
364         // Find a read with the same type and indices.
365         HoistableRead matchingRead =
366             findMatchingTransferRead(write, it.value());
367         // Make sure none of the other uses read the part of the tensor modified
368         // by the transfer_write.
369         if (!matchingRead.transferReadOp ||
370             tensorChunkAccessedByUnknownOp(write, matchingRead, it.value()))
371           continue;
372 
373         LLVM_DEBUG(DBGS() << "Start hoisting\n");
374         hoistReadWrite(matchingRead, write, it.value());
375         changed = true;
376         forOp.erase();
377 
378         // Need to interrupt and restart: erasing the loop messes up the walk.
379         return WalkResult::interrupt();
380       }
381       return WalkResult::advance();
382     });
383     // Apply canonicalization so the newForOp + yield folds immediately, thus
384     // cleaning up the IR and potentially enabling more hoisting.
385     if (changed) {
386       RewritePatternSet patterns(func->getContext());
387       scf::ForOp::getCanonicalizationPatterns(patterns, func->getContext());
388       (void)applyPatternsAndFoldGreedily(func, std::move(patterns));
389     }
390   }
391 }
392 
393 void mlir::linalg::hoistRedundantVectorTransfers(FuncOp func) {
394   bool changed = true;
395   while (changed) {
396     changed = false;
397     // First move loop invariant ops outside of their loop. This needs to be
398     // done before as we cannot move ops without interputing the function walk.
399     func.walk([&](LoopLikeOpInterface loopLike) {
400       if (failed(moveLoopInvariantCode(loopLike)))
401         llvm_unreachable(
402             "Unexpected failure to move invariant code out of loop");
403     });
404 
405     func.walk([&](vector::TransferReadOp transferRead) {
406       if (!transferRead.getShapedType().isa<MemRefType>())
407         return WalkResult::advance();
408 
409       LLVM_DEBUG(DBGS() << "Candidate for hoisting: "
410                         << *transferRead.getOperation() << "\n");
411       auto loop = dyn_cast<scf::ForOp>(transferRead->getParentOp());
412       LLVM_DEBUG(DBGS() << "Parent op: " << *transferRead->getParentOp()
413                         << "\n");
414       if (!loop)
415         return WalkResult::advance();
416 
417       LLVM_DEBUG(DBGS() << "Candidate read: " << *transferRead.getOperation()
418                         << "\n");
419 
420       SetVector<Operation *> forwardSlice;
421       getForwardSlice(transferRead.getOperation(), &forwardSlice);
422 
423       // Look for the last TransferWriteOp in the forwardSlice of
424       // `transferRead` that operates on the same memref.
425       vector::TransferWriteOp transferWrite;
426       for (auto *sliceOp : llvm::reverse(forwardSlice)) {
427         auto candidateWrite = dyn_cast<vector::TransferWriteOp>(sliceOp);
428         if (!candidateWrite || candidateWrite.source() != transferRead.source())
429           continue;
430         transferWrite = candidateWrite;
431       }
432 
433       // All operands of the TransferRead must be defined outside of the loop.
434       for (auto operand : transferRead.getOperands())
435         if (!loop.isDefinedOutsideOfLoop(operand))
436           return WalkResult::advance();
437 
438       // Only hoist transfer_read / transfer_write pairs for now.
439       if (!transferWrite)
440         return WalkResult::advance();
441 
442       LLVM_DEBUG(DBGS() << "Candidate: " << *transferWrite.getOperation()
443                         << "\n");
444 
445       // Approximate aliasing by checking that:
446       //   1. indices are the same,
447       //   2. no other operations in the loop access the same memref except
448       //      for transfer_read/transfer_write accessing statically disjoint
449       //      slices.
450       if (transferRead.indices() != transferWrite.indices() &&
451           transferRead.getVectorType() == transferWrite.getVectorType())
452         return WalkResult::advance();
453 
454       // TODO: may want to memoize this information for performance but it
455       // likely gets invalidated often.
456       DominanceInfo dom(loop);
457       if (!dom.properlyDominates(transferRead.getOperation(), transferWrite))
458         return WalkResult::advance();
459       for (auto &use : transferRead.source().getUses()) {
460         if (!loop->isAncestor(use.getOwner()))
461           continue;
462         if (use.getOwner() == transferRead.getOperation() ||
463             use.getOwner() == transferWrite.getOperation())
464           continue;
465         if (auto transferWriteUse =
466                 dyn_cast<vector::TransferWriteOp>(use.getOwner())) {
467           if (!isDisjointTransferSet(
468                   cast<VectorTransferOpInterface>(transferWrite.getOperation()),
469                   cast<VectorTransferOpInterface>(
470                       transferWriteUse.getOperation())))
471             return WalkResult::advance();
472         } else if (auto transferReadUse =
473                        dyn_cast<vector::TransferReadOp>(use.getOwner())) {
474           if (!isDisjointTransferSet(
475                   cast<VectorTransferOpInterface>(transferWrite.getOperation()),
476                   cast<VectorTransferOpInterface>(
477                       transferReadUse.getOperation())))
478             return WalkResult::advance();
479         } else {
480           // Unknown use, we cannot prove that it doesn't alias with the
481           // transferRead/transferWrite operations.
482           return WalkResult::advance();
483         }
484       }
485 
486       // Hoist read before.
487       if (failed(loop.moveOutOfLoop({transferRead})))
488         llvm_unreachable(
489             "Unexpected failure to move transfer read out of loop");
490 
491       // Hoist write after.
492       transferWrite->moveAfter(loop);
493 
494       // Rewrite `loop` with new yields by cloning and erase the original loop.
495       OpBuilder b(transferRead);
496       auto newForOp = cloneWithNewYields(b, loop, transferRead.vector(),
497                                          transferWrite.vector());
498 
499       // Transfer write has been hoisted, need to update the written value to
500       // the value yielded by the newForOp.
501       transferWrite.vector().replaceAllUsesWith(
502           newForOp.getResults().take_back()[0]);
503 
504       changed = true;
505       loop.erase();
506       // Need to interrupt and restart because erasing the loop messes up the
507       // walk.
508       return WalkResult::interrupt();
509     });
510   }
511 }
512 
513 /// Return success if `v` is a value that is only transitively defined by ops of
514 /// type in `OpTypeList`.
515 template <typename... OpTypeList>
516 static bool backwardsSliceOnlyHasOpsOfType(scf::ForOp outerLimit, Value v) {
517   // Compute a backward slice up to, but not including, `outerLimit`.
518   SetVector<Operation *> backwardSlice;
519   getBackwardSlice(v, &backwardSlice, [&](Operation *op) {
520     return outerLimit->isProperAncestor(op);
521   });
522   // Traverse the backward slice and ensure we can perform the computation to
523   // hoist.
524   for (Operation *op : backwardSlice) {
525     if (isa<OpTypeList...>(op))
526       continue;
527     LLVM_DEBUG(DBGS() << "Abort: unadmissible op in slice " << *op << "\n");
528     return false;
529   }
530   return true;
531 }
532 
533 bool isDefinedOutsideOrConstant(scf::ForOp outer, Value v) {
534   return outer.isDefinedOutsideOfLoop(v) || v.getDefiningOp<ConstantOp>();
535 }
536 
537 /// Return the current iteration number in the loop (iv - lb).ceilDiv(step).
538 /// The returned Value is guaranteed not to depend on any loop comprised in
539 /// [`outer`, `forOp`].
540 /// Return null if such a loop-independent quantity cannot be computed.
541 static Value buildLoopIterationCount(OpBuilder &b, scf::ForOp outer,
542                                      scf::ForOp forOp) {
543   MLIRContext *ctx = forOp->getContext();
544   AffineExpr iv, lb, step;
545   bindDims(ctx, iv, lb);
546   bindSymbols(ctx, step);
547   if (!isDefinedOutsideOrConstant(outer, forOp.lowerBound()) ||
548       !isDefinedOutsideOrConstant(outer, forOp.step()))
549     return Value();
550   Value ivVal = forOp.getInductionVar(), lbVal = forOp.lowerBound(),
551         stepVal = forOp.step();
552   auto loc = forOp->getLoc();
553   return b.createOrFold<AffineApplyOp>(loc, (iv - lb).ceilDiv(step),
554                                        ValueRange{ivVal, lbVal, stepVal});
555 }
556 
557 /// Given a set of loops, assumed to be scf::ForOp, create a constraint set
558 /// containing the inequalities `iv - lb >= 0` and `-iv + ub - 1 >= 0` for each
559 /// loop.
560 static FlatAffineValueConstraints
561 initLoopIvsAndBounds(ArrayRef<Operation *> loops) {
562   FlatAffineValueConstraints constraints;
563   for (Operation *op : loops)
564     constraints.appendDimId(cast<scf::ForOp>(op).getInductionVar());
565   for (Operation *op : loops)
566     constraints.appendDimId(cast<scf::ForOp>(op).lowerBound());
567   for (Operation *op : loops)
568     constraints.appendDimId(cast<scf::ForOp>(op).upperBound());
569   unsigned numLoops = loops.size();
570   for (unsigned ivIdx = 0, e = numLoops; ivIdx < e; ++ivIdx) {
571     // iv - lb >= 0
572     SmallVector<int64_t, 8> ineqLb(constraints.getNumCols(), 0);
573     ineqLb[ivIdx] = 1;
574     ineqLb[ivIdx + numLoops] = -1;
575     // -iv + ub >= 0
576     SmallVector<int64_t, 8> ineqUb(constraints.getNumCols(), 0);
577     ineqUb[ivIdx] = -1;
578     ineqUb[ivIdx + 2 * numLoops] = 1;
579     ineqUb[constraints.getNumCols() - 1] = -1;
580     constraints.addInequality(ineqLb);
581     constraints.addInequality(ineqUb);
582   }
583   return constraints;
584 }
585 
586 /// For each loop in `loops`, determine the ops involved in the construction of
587 /// its upper bound---up to the outerLimit loop--- and fold them as new
588 /// inequalities in the constraint set.
589 /// This is achieved by computing the backwardSlice of the loop's upper bound
590 /// and iteratively folding each op in reverse topological order to guarantee
591 /// use-def ordering.
592 /// As operations are folded in, their result is projected out of the
593 /// constraints set.
594 /// The following operations are supported:
595 ///   - scf::ForOp are simply skipped.
596 ///   - AffineApplyOp are composed to replace the result by an equality.
597 ///   - AffineMinOp are composed by adding each entry as an upper bound.
598 /// If any other operation is met, return failure.
599 // TODO: extend on a per-need basis.
600 static LogicalResult
601 foldUpperBoundsIntoConstraintsSet(FlatAffineValueConstraints &constraints,
602                                   scf::ForOp outerLimit,
603                                   ArrayRef<Operation *> loops) {
604   SetVector<Value> toProjectOut;
605   for (Operation *loop : loops) {
606     auto ub = cast<scf::ForOp>(loop).upperBound();
607     if (isDefinedOutsideOrConstant(outerLimit, ub))
608       continue;
609 
610     // Compute a backward slice up to, but not including, `outerLimit`.
611     SetVector<Operation *> backwardSlice;
612     getBackwardSlice(ub, &backwardSlice, [&](Operation *op) {
613       return outerLimit->isProperAncestor(op);
614     });
615     backwardSlice.insert(ub.getDefiningOp());
616 
617     // Iterate over all ops in the slice and compose them in the constraints.
618     for (Operation *op : llvm::reverse(backwardSlice)) {
619       if (!isa<scf::ForOp, AffineApplyOp, AffineMinOp>(op))
620         return failure();
621       if (isa<scf::ForOp>(op))
622         continue;
623       // Ensure there is a
624       auto ensureIdFailed = [&](Value v) {
625         if (constraints.containsId(v)) {
626           unsigned pos;
627           constraints.findId(v, &pos);
628           return pos >= constraints.getNumDimIds();
629         }
630         constraints.appendDimId(v);
631         return false;
632       };
633 
634       // Ensure all ids exist and add results for later projection.
635       if (llvm::any_of(op->getResults(), ensureIdFailed) ||
636           llvm::any_of(op->getOperands(), ensureIdFailed))
637         return failure();
638 
639       // All supported ops have 1 result.
640       // TODO: extend when needed.
641       toProjectOut.insert(op->getResult(0));
642 
643       // Compose supported ops.
644       if (auto affineApplyOp = dyn_cast<AffineApplyOp>(op)) {
645         AffineValueMap avm(affineApplyOp.getAffineMap(),
646                            affineApplyOp.getOperands(),
647                            affineApplyOp.getResult());
648         if (failed(constraints.composeMap(&avm)))
649           return failure();
650         continue;
651       }
652       auto affineMinOp = cast<AffineMinOp>(op);
653       unsigned pos;
654       bool foundMinOp = constraints.findId(affineMinOp.getResult(), &pos);
655       (void)foundMinOp;
656       assert(foundMinOp);
657       AffineMap alignedMap = constraints.computeAlignedMap(
658           affineMinOp.getAffineMap(), affineMinOp.getOperands());
659       if (failed(
660               constraints.addBound(FlatAffineConstraints::UB, pos, alignedMap)))
661         return failure();
662     }
663   }
664   for (Value v : toProjectOut)
665     constraints.projectOut(v);
666   return success();
667 }
668 
669 /// Ensure prerequisites that guarantee pad op hoisting can occur.
670 /// Return failure in the cases when we cannot perform hoisting; i.e. if either:
671 ///   1. There exists a use of `padTensorOp` that is not a linalg input operand.
672 ///   2. There isn't an enclosing `outermostEnclosingForOp` loop.
673 ///   3. There exists an op with a region that is dominated by
674 ///   `outermostEnclosingForOp` and that isn't a LoopLikeInterface or a
675 ///    LinalgOp.
676 ///   4. There exists an op with side effects that is dominated by
677 ///   `outermostEnclosingForOp` and that isn't a LoopLikeInterface.
678 ///   5. The lower bound, upper bound and step of all the loops involved in the
679 ///   hoisting can be
680 ///
681 /// While ensuring prerequisites:
682 ///   1. Fill the `backwardSlice` to contain the topologically sorted ops
683 ///   dominated by `outermostEnclosingForOp`.
684 ///   2. Fill the `packingLoops` to contain only the enclosing loops of
685 ///   `backwardSlice` whose IV is actually used in computing padding. Loops that
686 ///   remain in `backwardSlice` but that are not in `packingLoops` are
687 ///   dimensions of reuse.
688 static LogicalResult
689 hoistPaddingOnTensorsPrerequisites(linalg::PadTensorOp padTensorOp, int nLevels,
690                                    SetVector<Operation *> &backwardSlice,
691                                    SetVector<Operation *> &packingLoops,
692                                    SmallVector<Value> &dynamicTensorSizes) {
693   // Bail on any use that isn't an input of a Linalg op.
694   // Hoisting of inplace updates happens after vectorization.
695   for (OpOperand &use : padTensorOp.result().getUses()) {
696     auto linalgUser = dyn_cast<linalg::LinalgOp>(use.getOwner());
697     if (!linalgUser || !linalgUser.isInputTensor(&use))
698       return failure();
699   }
700 
701   // Get at most nLevels of enclosing loops.
702   SmallVector<LoopLikeOpInterface> reverseEnclosingLoops;
703   Operation *outermostEnclosingForOp = nullptr,
704             *nextEnclosingForOp =
705                 padTensorOp->getParentOfType<LoopLikeOpInterface>();
706   while (nLevels-- > 0 && nextEnclosingForOp) {
707     outermostEnclosingForOp = nextEnclosingForOp;
708     reverseEnclosingLoops.push_back(outermostEnclosingForOp);
709     nextEnclosingForOp =
710         nextEnclosingForOp->getParentOfType<LoopLikeOpInterface>();
711   }
712   if (!outermostEnclosingForOp)
713     return failure();
714 
715   // Get the backwards slice from `padTensorOp` that is dominated by the
716   // outermost enclosing loop.
717   DominanceInfo domInfo(outermostEnclosingForOp);
718   getBackwardSlice(padTensorOp.getOperation(), &backwardSlice,
719                    [&](Operation *op) {
720                      return domInfo.dominates(outermostEnclosingForOp, op);
721                    });
722 
723   // Bail on any op with a region that is not a LoopLikeInterface or a LinalgOp.
724   if (llvm::any_of(backwardSlice, [](Operation *op) {
725         return op->getNumRegions() > 0 && !isa<LoopLikeOpInterface>(op) &&
726                !isa<LinalgOp>(op);
727       }))
728     return failure();
729 
730   // Filter out the loops whose induction variable is not used to compute the
731   // padded result. As a first approximation, just look for IVs that have no use
732   // in the backwardSlice.
733   // These are the dimensions of reuse that we can exploit to reduce the amount
734   // of work / memory.
735   // TODO: would this optimization compose better as a canonicalization?
736   for (LoopLikeOpInterface loop : llvm::reverse(reverseEnclosingLoops)) {
737     auto forOp = dyn_cast<scf::ForOp>(loop.getOperation());
738     if (!forOp)
739       continue;
740     for (Operation *user : forOp.getInductionVar().getUsers()) {
741       if (backwardSlice.contains(user)) {
742         packingLoops.insert(forOp);
743         break;
744       }
745     }
746   }
747 
748   // Backward slice is a topologically sorted list of ops starting at
749   // `outermostEnclosingForOp`.
750   assert(outermostEnclosingForOp == backwardSlice.front());
751 
752   scf::ForOp outer = cast<scf::ForOp>(outermostEnclosingForOp);
753 
754   FlatAffineValueConstraints constraints =
755       initLoopIvsAndBounds(packingLoops.getArrayRef());
756   if (failed(foldUpperBoundsIntoConstraintsSet(constraints, outer,
757                                                packingLoops.getArrayRef())))
758     return failure();
759 
760   unsigned numLoops = packingLoops.size();
761   SmallVector<AffineMap> lbs(numLoops), ubs(numLoops);
762   // Compute the bounds of the first positions, assuming the others are fixed.
763   constraints.getSliceBounds(/*pos=*/0, /*num=*/packingLoops.size(),
764                              outer->getContext(), &lbs, &ubs);
765 
766   SmallVector<Value> allValues;
767   constraints.getAllValues(&allValues);
768   SmallVector<Value> allNonLoopValues(allValues.begin() + numLoops,
769                                       allValues.end());
770 
771   // For each packingLoop, create the extent by (ub - lb).ceilDiv(step).
772   // IP just before the outermost loop considered that we hoist above.
773   ImplicitLocOpBuilder b(outer->getLoc(), outer);
774   assert(packingLoops.size() == lbs.size() && "expected matching lb sizes");
775   assert(packingLoops.size() == ubs.size() && "expected matching ub sizes");
776   for (auto it : llvm::zip(packingLoops, lbs, ubs)) {
777     scf::ForOp loop = cast<scf::ForOp>(std::get<0>(it));
778     AffineMap lbMap = std::get<1>(it);
779     AffineMap ubMap = std::get<2>(it);
780     SmallVector<Value> lbOperands(allNonLoopValues);
781     canonicalizeMapAndOperands(&lbMap, &lbOperands);
782     Value lbVal = b.createOrFold<AffineMaxOp>(lbMap, lbOperands);
783 
784     SmallVector<Value> ubOperands(allNonLoopValues);
785     canonicalizeMapAndOperands(&ubMap, &ubOperands);
786     Value ubVal = b.createOrFold<AffineMinOp>(ubMap, ubOperands);
787 
788     AffineExpr lb, ub, step;
789     bindDims(b.getContext(), lb, ub);
790     bindSymbols(b.getContext(), step);
791     Value res = b.createOrFold<AffineApplyOp>(
792         (ub - lb).ceilDiv(step),
793         ValueRange{lbVal, ubVal, cast<scf::ForOp>(loop).step()});
794 
795     dynamicTensorSizes.push_back(res);
796   }
797 
798   return success();
799 }
800 
801 LogicalResult mlir::linalg::hoistPaddingOnTensors(PadTensorOp &padTensorOp,
802                                                   unsigned nLoops) {
803   SmallVector<Value> dynamicTensorSizes;
804   SetVector<Operation *> backwardSlice, packingLoops;
805   if (failed(hoistPaddingOnTensorsPrerequisites(padTensorOp, nLoops,
806                                                 backwardSlice, packingLoops,
807                                                 dynamicTensorSizes)))
808     return failure();
809 
810   // Update actual number of loops, which may be smaller.
811   nLoops = packingLoops.size();
812 
813   Location loc = padTensorOp->getLoc();
814   RankedTensorType paddedTensorType = padTensorOp.getResultType();
815   unsigned paddedRank = paddedTensorType.getRank();
816 
817   // Backward slice is a topologically sorted list of ops starting at
818   // `outermostEnclosingForOp`.
819   Operation *outermostEnclosingForOp = backwardSlice.front();
820   // IP just before the outermost loop considered that we hoist above.
821   OpBuilder b(outermostEnclosingForOp);
822 
823   // Create the packed tensor<?x?x..?xpadded_shape> into which we amortize
824   // padding.
825   SmallVector<int64_t> packedShape(nLoops, ShapedType::kDynamicSize);
826   // TODO: go grab dims when necessary, for now PadTensorOp returns a static
827   // tensor.
828   llvm::append_range(packedShape, paddedTensorType.getShape());
829   auto packedTensorType =
830       RankedTensorType::get(packedShape, paddedTensorType.getElementType());
831   Value packedTensor = b.create<linalg::InitTensorOp>(
832       loc, dynamicTensorSizes, packedTensorType.getShape(),
833       packedTensorType.getElementType());
834 
835   // Clone the operations involved in the backward slice, iteratively stepping
836   // into the loops that we encounter.
837   // The implementation proceeds in a stack-like fashion:
838   //   1. Iteratively clone and step into the loops, pushing the `packedTensor`
839   //      deeper in the stack.
840   //   2. Create a InsertSliceOp at the top of the stack.
841   //   3. Iteratively pop and yield the result of the InsertSliceOp across
842   //     the cloned loops.
843   SmallVector<Value> clonedLoopIvs, leadingPackedTensorIndexings;
844   clonedLoopIvs.reserve(nLoops);
845   leadingPackedTensorIndexings.reserve(nLoops);
846   BlockAndValueMapping bvm;
847   // Insert `padTensorOp` into the backwardSlice so we clone it too.
848   backwardSlice.insert(padTensorOp);
849   // Stack step 1. iteratively clone loops and push `packedTensor`.
850   for (Operation *op : backwardSlice) {
851     // Specifically sit out in the extract_slice(packedTensor) case: this is the
852     // piece we seek to replace.
853     if (auto sliceOp = dyn_cast<tensor::ExtractSliceOp>(op))
854       if (bvm.lookupOrDefault(sliceOp.source()) == packedTensor)
855         continue;
856     auto effects = dyn_cast<MemoryEffectOpInterface>(op);
857     bool hasNoEffects = !effects || effects.hasNoEffect();
858     if (hasNoEffects &&
859         (op->getNumRegions() == 0 || isa<linalg::PadTensorOp>(op))) {
860       b.clone(*op, bvm);
861       continue;
862     }
863     // TODO: support more cases as they appear.
864     auto forOp = dyn_cast<scf::ForOp>(op);
865     assert(forOp && "Expected scf::ForOp when hoisting pad ops");
866     // Unused loop, just skip it.
867     if (!packingLoops.contains(forOp))
868       continue;
869 
870     auto clonedForOp =
871         b.create<scf::ForOp>(loc, bvm.lookupOrDefault(forOp.lowerBound()),
872                              bvm.lookupOrDefault(forOp.upperBound()),
873                              bvm.lookupOrDefault(forOp.step()), packedTensor);
874     // Map the induction var, region args and results to the `clonedForOp`.
875     bvm.map(forOp.getInductionVar(), clonedForOp.getInductionVar());
876     bvm.map(forOp.getRegionIterArgs(), clonedForOp.getRegionIterArgs());
877     bvm.map(forOp.getResults(), clonedForOp.getResults());
878     assert(clonedForOp->getNumRegions() == 1);
879     clonedLoopIvs.push_back(clonedForOp.getInductionVar());
880 
881     b.setInsertionPointToStart(&clonedForOp->getRegion(0).front());
882     Value loopIndependentIterationCount = buildLoopIterationCount(
883         b, cast<scf::ForOp>(outermostEnclosingForOp), clonedForOp);
884     // Assert the loop-independent iteration count can be computed.
885     if (!loopIndependentIterationCount)
886       llvm_unreachable("loop independence prerequisite not met");
887     leadingPackedTensorIndexings.push_back(loopIndependentIterationCount);
888     packedTensor = clonedForOp.getRegionIterArgs().front();
889   }
890 
891   // Stack step 2. create InsertSliceOp at the top of the stack.
892   // offsets = [clonedLoopIvs, 0 .. 0].
893   SmallVector<OpFoldResult> offsets(leadingPackedTensorIndexings.begin(),
894                                     leadingPackedTensorIndexings.end());
895   offsets.append(paddedRank, b.getIndexAttr(0));
896   // sizes = [1 .. 1, paddedShape].
897   SmallVector<OpFoldResult> sizes(nLoops, b.getIndexAttr(1));
898   for (int64_t sz : paddedTensorType.getShape()) {
899     // TODO: go grab dims when necessary, for now PadTensorOp returns a static
900     // tensor.
901     assert(!ShapedType::isDynamic(sz) && "padded tensor needs static sizes");
902     sizes.push_back(b.getIndexAttr(sz));
903   }
904   // strides = [1 .. 1].
905   SmallVector<OpFoldResult> strides(nLoops + paddedRank, b.getIndexAttr(1));
906 
907   Value inserted =
908       b.create<tensor::InsertSliceOp>(loc, bvm.lookup(padTensorOp.result()),
909                                       packedTensor, offsets, sizes, strides);
910 
911   // Stack step 3. iteratively pop the stack and propagate the yield.
912   Value valueToYield = inserted;
913   for (Value iv : llvm::reverse(clonedLoopIvs)) {
914     auto forOp = scf::getForInductionVarOwner(iv);
915     b.setInsertionPointToEnd(&forOp.getRegion().front());
916     b.create<scf::YieldOp>(loc, valueToYield);
917     valueToYield = forOp.getResult(0);
918   }
919 
920   // Now the packed tensor is ready, replace the original padding op by a
921   // 1x..x1 slice [originalLoopIvs, 0 .. 0][1 .. 1, paddedShape][1 .. 1].
922   b.setInsertionPoint(padTensorOp);
923   SmallVector<Value> loopIterationCounts =
924       llvm::to_vector<4>(llvm::map_range(packingLoops, [&](Operation *loop) {
925         return buildLoopIterationCount(
926             b, cast<scf::ForOp>(outermostEnclosingForOp),
927             cast<scf::ForOp>(loop));
928       }));
929   // Assert all loop iteration counts can be computed.
930   if (llvm::any_of(loopIterationCounts, [](Value v) { return !v; }))
931     llvm_unreachable("loop independence prerequisite not met");
932   // offsets = [originalLoopIvs, 0 .. 0].
933   offsets.assign(loopIterationCounts.begin(), loopIterationCounts.end());
934   offsets.append(paddedRank, b.getIndexAttr(0));
935   // sizes = [1 .. 1, paddedShape] (definedabove).
936   // strides = [1 .. 1] (defined above)
937   packedTensor =
938       scf::getForInductionVarOwner(clonedLoopIvs.front())->getResult(0);
939   padTensorOp.replaceAllUsesWith(
940       b.create<tensor::ExtractSliceOp>(loc, padTensorOp.getResultType(),
941                                        packedTensor, offsets, sizes, strides)
942           ->getResult(0));
943 
944   Operation *toErase = padTensorOp;
945 
946   // Make the newly cloned `padTensorOp` available to the caller.
947   padTensorOp =
948       cast<PadTensorOp>(bvm.lookup(padTensorOp.result()).getDefiningOp());
949 
950   toErase->erase();
951 
952   return success();
953 }
954