1 //===- Interchange.cpp - Linalg interchange transformation ----------------===//
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 the linalg interchange transformation.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Dialect/Linalg/Analysis/DependenceAnalysis.h"
14 #include "mlir/Dialect/Linalg/IR/LinalgOps.h"
15 #include "mlir/Dialect/Linalg/Transforms/Transforms.h"
16 #include "mlir/Dialect/Linalg/Utils/Utils.h"
17 #include "mlir/Dialect/StandardOps/EDSC/Intrinsics.h"
18 #include "mlir/Dialect/Utils/StructuredOpsUtils.h"
19 #include "mlir/Dialect/Vector/VectorOps.h"
20 #include "mlir/IR/AffineExpr.h"
21 #include "mlir/IR/Matchers.h"
22 #include "mlir/IR/PatternMatch.h"
23 #include "mlir/Pass/Pass.h"
24 #include "mlir/Support/LLVM.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <type_traits>
28 
29 #define DEBUG_TYPE "linalg-interchange"
30 
31 using namespace mlir;
32 using namespace mlir::linalg;
33 
34 LogicalResult mlir::linalg::interchangeGenericOpPrecondition(
35     GenericOp genericOp, ArrayRef<unsigned> interchangeVector) {
36   // Interchange vector must be non-empty and match the number of loops.
37   if (interchangeVector.empty() ||
38       genericOp.getNumLoops() != interchangeVector.size())
39     return failure();
40   // Permutation map must be invertible.
41   if (!inversePermutation(AffineMap::getPermutationMap(interchangeVector,
42                                                        genericOp.getContext())))
43     return failure();
44   return success();
45 }
46 
47 void mlir::linalg::interchangeGenericOp(PatternRewriter &rewriter,
48                                         GenericOp genericOp,
49                                         ArrayRef<unsigned> interchangeVector) {
50   // 1. Compute the inverse permutation map.
51   MLIRContext *context = genericOp.getContext();
52   AffineMap permutationMap = inversePermutation(
53       AffineMap::getPermutationMap(interchangeVector, context));
54   assert(permutationMap && "expected permutation to be invertible");
55   assert(interchangeVector.size() == genericOp.getNumLoops() &&
56          "expected interchange vector to have entry for every loop");
57 
58   // 2. Compute the interchanged indexing maps.
59   SmallVector<Attribute, 4> newIndexingMaps;
60   ArrayRef<Attribute> indexingMaps = genericOp.indexing_maps().getValue();
61   for (unsigned i = 0, e = genericOp.getNumShapedOperands(); i != e; ++i) {
62     AffineMap m = indexingMaps[i].cast<AffineMapAttr>().getValue();
63     if (!permutationMap.isEmpty())
64       m = m.compose(permutationMap);
65     newIndexingMaps.push_back(AffineMapAttr::get(m));
66   }
67   genericOp->setAttr(getIndexingMapsAttrName(),
68                      ArrayAttr::get(context, newIndexingMaps));
69 
70   // 3. Compute the interchanged iterator types.
71   ArrayRef<Attribute> itTypes = genericOp.iterator_types().getValue();
72   SmallVector<Attribute, 4> itTypesVector;
73   llvm::append_range(itTypesVector, itTypes);
74   applyPermutationToVector(itTypesVector, interchangeVector);
75   genericOp->setAttr(getIteratorTypesAttrName(),
76                      ArrayAttr::get(context, itTypesVector));
77 
78   // 4. Transform the index operations by applying the permutation map.
79   if (genericOp.hasIndexSemantics()) {
80     // TODO: Remove the assertion and add a getBody() method to LinalgOp
81     // interface once every LinalgOp has a body.
82     assert(genericOp->getNumRegions() == 1 &&
83            genericOp->getRegion(0).getBlocks().size() == 1 &&
84            "expected generic operation to have one block.");
85     Block &block = genericOp->getRegion(0).front();
86     OpBuilder::InsertionGuard guard(rewriter);
87     for (IndexOp indexOp :
88          llvm::make_early_inc_range(block.getOps<IndexOp>())) {
89       rewriter.setInsertionPoint(indexOp);
90       SmallVector<Value> allIndices;
91       allIndices.reserve(genericOp.getNumLoops());
92       llvm::transform(llvm::seq<uint64_t>(0, genericOp.getNumLoops()),
93                       std::back_inserter(allIndices), [&](uint64_t dim) {
94                         return rewriter.create<IndexOp>(indexOp->getLoc(), dim);
95                       });
96       rewriter.replaceOpWithNewOp<AffineApplyOp>(
97           indexOp, permutationMap.getSubMap(indexOp.dim()), allIndices);
98     }
99   }
100 }
101