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