1 //===- TestLoopPermutation.cpp - Test affine loop permutation -------------===//
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 a pass to test the affine for op permutation utility.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Dialect/Affine/Analysis/Utils.h"
14 #include "mlir/Dialect/Affine/IR/AffineOps.h"
15 #include "mlir/Dialect/Affine/LoopUtils.h"
16 #include "mlir/Pass/Pass.h"
17 
18 #define PASS_NAME "test-loop-permutation"
19 
20 using namespace mlir;
21 
22 namespace {
23 
24 /// This pass applies the permutation on the first maximal perfect nest.
25 struct TestLoopPermutation
26     : public PassWrapper<TestLoopPermutation, OperationPass<>> {
27   StringRef getArgument() const final { return PASS_NAME; }
28   StringRef getDescription() const final {
29     return "Tests affine loop permutation utility";
30   }
31   TestLoopPermutation() = default;
32   TestLoopPermutation(const TestLoopPermutation &pass) : PassWrapper(pass){};
33 
34   void runOnOperation() override;
35 
36 private:
37   /// Permutation specifying loop i is mapped to permList[i] in
38   /// transformed nest (with i going from outermost to innermost).
39   ListOption<unsigned> permList{*this, "permutation-map",
40                                 llvm::cl::desc("Specify the loop permutation"),
41                                 llvm::cl::OneOrMore, llvm::cl::CommaSeparated};
42 };
43 
44 } // namespace
45 
46 void TestLoopPermutation::runOnOperation() {
47 
48   SmallVector<unsigned, 4> permMap(permList.begin(), permList.end());
49 
50   SmallVector<AffineForOp, 2> forOps;
51   getOperation()->walk([&](AffineForOp forOp) { forOps.push_back(forOp); });
52 
53   for (auto forOp : forOps) {
54     SmallVector<AffineForOp, 6> nest;
55     // Get the maximal perfect nest.
56     getPerfectlyNestedLoops(nest, forOp);
57     // Permute if the nest's size is consistent with the specified
58     // permutation.
59     if (nest.size() >= 2 && nest.size() == permMap.size()) {
60       permuteLoops(nest, permMap);
61     }
62   }
63 }
64 
65 namespace mlir {
66 void registerTestLoopPermutationPass() {
67   PassRegistration<TestLoopPermutation>();
68 }
69 } // namespace mlir
70