1 //===- VectorizerTestPass.cpp - VectorizerTestPass Pass Impl --------------===//
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 simple testing pass for vectorization functionality.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Analysis/AffineAnalysis.h"
14 #include "mlir/Analysis/NestedMatcher.h"
15 #include "mlir/Analysis/SliceAnalysis.h"
16 #include "mlir/Dialect/Affine/IR/AffineOps.h"
17 #include "mlir/Dialect/Vector/VectorUtils.h"
18 #include "mlir/IR/Builders.h"
19 #include "mlir/IR/Diagnostics.h"
20 #include "mlir/IR/StandardTypes.h"
21 #include "mlir/Pass/Pass.h"
22 #include "mlir/Support/Functional.h"
23 #include "mlir/Support/STLExtras.h"
24 #include "mlir/Transforms/Passes.h"
25 
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 
30 #define DEBUG_TYPE "affine-super-vectorizer-test"
31 
32 using namespace mlir;
33 
34 using llvm::SetVector;
35 
36 using functional::map;
37 
38 static llvm::cl::OptionCategory clOptionsCategory(DEBUG_TYPE " options");
39 
40 static llvm::cl::list<int> clTestVectorShapeRatio(
41     "vector-shape-ratio",
42     llvm::cl::desc("Specify the HW vector size for vectorization"),
43     llvm::cl::ZeroOrMore, llvm::cl::cat(clOptionsCategory));
44 static llvm::cl::opt<bool> clTestForwardSlicingAnalysis(
45     "forward-slicing",
46     llvm::cl::desc("Enable testing forward static slicing and topological sort "
47                    "functionalities"),
48     llvm::cl::cat(clOptionsCategory));
49 static llvm::cl::opt<bool> clTestBackwardSlicingAnalysis(
50     "backward-slicing",
51     llvm::cl::desc("Enable testing backward static slicing and "
52                    "topological sort functionalities"),
53     llvm::cl::cat(clOptionsCategory));
54 static llvm::cl::opt<bool> clTestSlicingAnalysis(
55     "slicing",
56     llvm::cl::desc("Enable testing static slicing and topological sort "
57                    "functionalities"),
58     llvm::cl::cat(clOptionsCategory));
59 static llvm::cl::opt<bool> clTestComposeMaps(
60     "compose-maps",
61     llvm::cl::desc(
62         "Enable testing the composition of AffineMap where each "
63         "AffineMap in the composition is specified as the affine_map attribute "
64         "in a constant op."),
65     llvm::cl::cat(clOptionsCategory));
66 static llvm::cl::opt<bool> clTestNormalizeMaps(
67     "normalize-maps",
68     llvm::cl::desc(
69         "Enable testing the normalization of AffineAffineApplyOp "
70         "where each AffineAffineApplyOp in the composition is a single output "
71         "operation."),
72     llvm::cl::cat(clOptionsCategory));
73 
74 namespace {
75 struct VectorizerTestPass
76     : public PassWrapper<VectorizerTestPass, FunctionPass> {
77   static constexpr auto kTestAffineMapOpName = "test_affine_map";
78   static constexpr auto kTestAffineMapAttrName = "affine_map";
79 
80   void runOnFunction() override;
81   void testVectorShapeRatio(llvm::raw_ostream &outs);
82   void testForwardSlicing(llvm::raw_ostream &outs);
83   void testBackwardSlicing(llvm::raw_ostream &outs);
84   void testSlicing(llvm::raw_ostream &outs);
85   void testComposeMaps(llvm::raw_ostream &outs);
86   void testNormalizeMaps();
87 };
88 
89 } // end anonymous namespace
90 
91 void VectorizerTestPass::testVectorShapeRatio(llvm::raw_ostream &outs) {
92   auto f = getFunction();
93   using matcher::Op;
94   SmallVector<int64_t, 8> shape(clTestVectorShapeRatio.begin(),
95                                 clTestVectorShapeRatio.end());
96   auto subVectorType =
97       VectorType::get(shape, FloatType::getF32(f.getContext()));
98   // Only filter operations that operate on a strict super-vector and have one
99   // return. This makes testing easier.
100   auto filter = [&](Operation &op) {
101     assert(subVectorType.getElementType().isF32() &&
102            "Only f32 supported for now");
103     if (!matcher::operatesOnSuperVectorsOf(op, subVectorType)) {
104       return false;
105     }
106     if (op.getNumResults() != 1) {
107       return false;
108     }
109     return true;
110   };
111   auto pat = Op(filter);
112   SmallVector<NestedMatch, 8> matches;
113   pat.match(f, &matches);
114   for (auto m : matches) {
115     auto *opInst = m.getMatchedOperation();
116     // This is a unit test that only checks and prints shape ratio.
117     // As a consequence we write only Ops with a single return type for the
118     // purpose of this test. If we need to test more intricate behavior in the
119     // future we can always extend.
120     auto superVectorType = opInst->getResult(0).getType().cast<VectorType>();
121     auto ratio = shapeRatio(superVectorType, subVectorType);
122     if (!ratio.hasValue()) {
123       opInst->emitRemark("NOT MATCHED");
124     } else {
125       outs << "\nmatched: " << *opInst << " with shape ratio: ";
126       interleaveComma(MutableArrayRef<int64_t>(*ratio), outs);
127     }
128   }
129 }
130 
131 static NestedPattern patternTestSlicingOps() {
132   using functional::map;
133   using matcher::Op;
134   // Match all operations with the kTestSlicingOpName name.
135   auto filter = [](Operation &op) {
136     // Just use a custom op name for this test, it makes life easier.
137     return op.getName().getStringRef() == "slicing-test-op";
138   };
139   return Op(filter);
140 }
141 
142 void VectorizerTestPass::testBackwardSlicing(llvm::raw_ostream &outs) {
143   auto f = getFunction();
144   outs << "\n" << f.getName();
145 
146   SmallVector<NestedMatch, 8> matches;
147   patternTestSlicingOps().match(f, &matches);
148   for (auto m : matches) {
149     SetVector<Operation *> backwardSlice;
150     getBackwardSlice(m.getMatchedOperation(), &backwardSlice);
151     outs << "\nmatched: " << *m.getMatchedOperation()
152          << " backward static slice: ";
153     for (auto *op : backwardSlice)
154       outs << "\n" << *op;
155   }
156 }
157 
158 void VectorizerTestPass::testForwardSlicing(llvm::raw_ostream &outs) {
159   auto f = getFunction();
160   outs << "\n" << f.getName();
161 
162   SmallVector<NestedMatch, 8> matches;
163   patternTestSlicingOps().match(f, &matches);
164   for (auto m : matches) {
165     SetVector<Operation *> forwardSlice;
166     getForwardSlice(m.getMatchedOperation(), &forwardSlice);
167     outs << "\nmatched: " << *m.getMatchedOperation()
168          << " forward static slice: ";
169     for (auto *op : forwardSlice)
170       outs << "\n" << *op;
171   }
172 }
173 
174 void VectorizerTestPass::testSlicing(llvm::raw_ostream &outs) {
175   auto f = getFunction();
176   outs << "\n" << f.getName();
177 
178   SmallVector<NestedMatch, 8> matches;
179   patternTestSlicingOps().match(f, &matches);
180   for (auto m : matches) {
181     SetVector<Operation *> staticSlice = getSlice(m.getMatchedOperation());
182     outs << "\nmatched: " << *m.getMatchedOperation() << " static slice: ";
183     for (auto *op : staticSlice)
184       outs << "\n" << *op;
185   }
186 }
187 
188 static bool customOpWithAffineMapAttribute(Operation &op) {
189   return op.getName().getStringRef() ==
190          VectorizerTestPass::kTestAffineMapOpName;
191 }
192 
193 void VectorizerTestPass::testComposeMaps(llvm::raw_ostream &outs) {
194   auto f = getFunction();
195 
196   using matcher::Op;
197   auto pattern = Op(customOpWithAffineMapAttribute);
198   SmallVector<NestedMatch, 8> matches;
199   pattern.match(f, &matches);
200   SmallVector<AffineMap, 4> maps;
201   maps.reserve(matches.size());
202   for (auto m : llvm::reverse(matches)) {
203     auto *opInst = m.getMatchedOperation();
204     auto map = opInst->getAttr(VectorizerTestPass::kTestAffineMapAttrName)
205                    .cast<AffineMapAttr>()
206                    .getValue();
207     maps.push_back(map);
208   }
209   AffineMap res;
210   for (auto m : maps) {
211     res = res ? res.compose(m) : m;
212   }
213   simplifyAffineMap(res).print(outs << "\nComposed map: ");
214 }
215 
216 static bool affineApplyOp(Operation &op) { return isa<AffineApplyOp>(op); }
217 
218 static bool singleResultAffineApplyOpWithoutUses(Operation &op) {
219   auto app = dyn_cast<AffineApplyOp>(op);
220   return app && app.use_empty();
221 }
222 
223 void VectorizerTestPass::testNormalizeMaps() {
224   using matcher::Op;
225 
226   auto f = getFunction();
227 
228   // Save matched AffineApplyOp that all need to be erased in the end.
229   auto pattern = Op(affineApplyOp);
230   SmallVector<NestedMatch, 8> toErase;
231   pattern.match(f, &toErase);
232   {
233     // Compose maps.
234     auto pattern = Op(singleResultAffineApplyOpWithoutUses);
235     SmallVector<NestedMatch, 8> matches;
236     pattern.match(f, &matches);
237     for (auto m : matches) {
238       auto app = cast<AffineApplyOp>(m.getMatchedOperation());
239       OpBuilder b(m.getMatchedOperation());
240       SmallVector<Value, 8> operands(app.getOperands());
241       makeComposedAffineApply(b, app.getLoc(), app.getAffineMap(), operands);
242     }
243   }
244   // We should now be able to erase everything in reverse order in this test.
245   for (auto m : llvm::reverse(toErase)) {
246     m.getMatchedOperation()->erase();
247   }
248 }
249 
250 void VectorizerTestPass::runOnFunction() {
251   // Thread-safe RAII local context, BumpPtrAllocator freed on exit.
252   NestedPatternContext mlContext;
253 
254   // Only support single block functions at this point.
255   FuncOp f = getFunction();
256   if (f.getBlocks().size() != 1)
257     return;
258 
259   std::string str;
260   llvm::raw_string_ostream outs(str);
261 
262   if (!clTestVectorShapeRatio.empty())
263     testVectorShapeRatio(outs);
264 
265   if (clTestForwardSlicingAnalysis)
266     testForwardSlicing(outs);
267 
268   if (clTestBackwardSlicingAnalysis)
269     testBackwardSlicing(outs);
270 
271   if (clTestSlicingAnalysis)
272     testSlicing(outs);
273 
274   if (clTestComposeMaps)
275     testComposeMaps(outs);
276 
277   if (clTestNormalizeMaps)
278     testNormalizeMaps();
279 
280   if (!outs.str().empty()) {
281     emitRemark(UnknownLoc::get(&getContext()), outs.str());
282   }
283 }
284 
285 namespace mlir {
286 void registerVectorizerTestPass() {
287   PassRegistration<VectorizerTestPass> pass(
288       "affine-super-vectorizer-test",
289       "Tests vectorizer standalone functionality.");
290 }
291 } // namespace mlir
292