1 //===- SCFToSPIRV.cpp - SCF to SPIR-V Patterns ----------------------------===//
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 patterns to convert SCF dialect to SPIR-V dialect.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Conversion/SCFToSPIRV/SCFToSPIRV.h"
14 #include "mlir/Dialect/SCF/SCF.h"
15 #include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
16 #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
17 #include "mlir/Dialect/SPIRV/Transforms/SPIRVConversion.h"
18 #include "mlir/IR/BuiltinOps.h"
19 #include "mlir/Transforms/DialectConversion.h"
20 
21 using namespace mlir;
22 
23 //===----------------------------------------------------------------------===//
24 // Context
25 //===----------------------------------------------------------------------===//
26 
27 namespace mlir {
28 struct ScfToSPIRVContextImpl {
29   // Map between the spirv region control flow operation (spv.mlir.loop or
30   // spv.mlir.selection) to the VariableOp created to store the region results.
31   // The order of the VariableOp matches the order of the results.
32   DenseMap<Operation *, SmallVector<spirv::VariableOp, 8>> outputVars;
33 };
34 } // namespace mlir
35 
36 /// We use ScfToSPIRVContext to store information about the lowering of the scf
37 /// region that need to be used later on. When we lower scf.for/scf.if we create
38 /// VariableOp to store the results. We need to keep track of the VariableOp
39 /// created as we need to insert stores into them when lowering Yield. Those
40 /// StoreOp cannot be created earlier as they may use a different type than
41 /// yield operands.
42 ScfToSPIRVContext::ScfToSPIRVContext() {
43   impl = std::make_unique<ScfToSPIRVContextImpl>();
44 }
45 
46 ScfToSPIRVContext::~ScfToSPIRVContext() = default;
47 
48 //===----------------------------------------------------------------------===//
49 // Pattern Declarations
50 //===----------------------------------------------------------------------===//
51 
52 namespace {
53 /// Common class for all vector to GPU patterns.
54 template <typename OpTy>
55 class SCFToSPIRVPattern : public OpConversionPattern<OpTy> {
56 public:
57   SCFToSPIRVPattern<OpTy>(MLIRContext *context, SPIRVTypeConverter &converter,
58                           ScfToSPIRVContextImpl *scfToSPIRVContext)
59       : OpConversionPattern<OpTy>::OpConversionPattern(context),
60         scfToSPIRVContext(scfToSPIRVContext), typeConverter(converter) {}
61 
62 protected:
63   ScfToSPIRVContextImpl *scfToSPIRVContext;
64   // FIXME: We explicitly keep a reference of the type converter here instead of
65   // passing it to OpConversionPattern during construction. This effectively
66   // bypasses the conversion framework's automation on type conversion. This is
67   // needed right now because the conversion framework will unconditionally
68   // legalize all types used by SCF ops upon discovering them, for example, the
69   // types of loop carried values. We use SPIR-V variables for those loop
70   // carried values. Depending on the available capabilities, the SPIR-V
71   // variable can be different, for example, cooperative matrix or normal
72   // variable. We'd like to detach the conversion of the loop carried values
73   // from the SCF ops (which is mainly a region). So we need to "mark" types
74   // used by SCF ops as legal, if to use the conversion framework for type
75   // conversion. There isn't a straightforward way to do that yet, as when
76   // converting types, ops aren't taken into consideration. Therefore, we just
77   // bypass the framework's type conversion for now.
78   SPIRVTypeConverter &typeConverter;
79 };
80 
81 /// Pattern to convert a scf::ForOp within kernel functions into spirv::LoopOp.
82 class ForOpConversion final : public SCFToSPIRVPattern<scf::ForOp> {
83 public:
84   using SCFToSPIRVPattern<scf::ForOp>::SCFToSPIRVPattern;
85 
86   LogicalResult
87   matchAndRewrite(scf::ForOp forOp, ArrayRef<Value> operands,
88                   ConversionPatternRewriter &rewriter) const override;
89 };
90 
91 /// Pattern to convert a scf::IfOp within kernel functions into
92 /// spirv::SelectionOp.
93 class IfOpConversion final : public SCFToSPIRVPattern<scf::IfOp> {
94 public:
95   using SCFToSPIRVPattern<scf::IfOp>::SCFToSPIRVPattern;
96 
97   LogicalResult
98   matchAndRewrite(scf::IfOp ifOp, ArrayRef<Value> operands,
99                   ConversionPatternRewriter &rewriter) const override;
100 };
101 
102 class TerminatorOpConversion final : public SCFToSPIRVPattern<scf::YieldOp> {
103 public:
104   using SCFToSPIRVPattern<scf::YieldOp>::SCFToSPIRVPattern;
105 
106   LogicalResult
107   matchAndRewrite(scf::YieldOp terminatorOp, ArrayRef<Value> operands,
108                   ConversionPatternRewriter &rewriter) const override;
109 };
110 } // namespace
111 
112 /// Helper function to replaces SCF op outputs with SPIR-V variable loads.
113 /// We create VariableOp to handle the results value of the control flow region.
114 /// spv.mlir.loop/spv.mlir.selection currently don't yield value. Right after
115 /// the loop we load the value from the allocation and use it as the SCF op
116 /// result.
117 template <typename ScfOp, typename OpTy>
118 static void replaceSCFOutputValue(ScfOp scfOp, OpTy newOp,
119                                   ConversionPatternRewriter &rewriter,
120                                   ScfToSPIRVContextImpl *scfToSPIRVContext,
121                                   ArrayRef<Type> returnTypes) {
122 
123   Location loc = scfOp.getLoc();
124   auto &allocas = scfToSPIRVContext->outputVars[newOp];
125   // Clearing the allocas is necessary in case a dialect conversion path failed
126   // previously, and this is the second attempt of this conversion.
127   allocas.clear();
128   SmallVector<Value, 8> resultValue;
129   for (Type convertedType : returnTypes) {
130     auto pointerType =
131         spirv::PointerType::get(convertedType, spirv::StorageClass::Function);
132     rewriter.setInsertionPoint(newOp);
133     auto alloc = rewriter.create<spirv::VariableOp>(
134         loc, pointerType, spirv::StorageClass::Function,
135         /*initializer=*/nullptr);
136     allocas.push_back(alloc);
137     rewriter.setInsertionPointAfter(newOp);
138     Value loadResult = rewriter.create<spirv::LoadOp>(loc, alloc);
139     resultValue.push_back(loadResult);
140   }
141   rewriter.replaceOp(scfOp, resultValue);
142 }
143 
144 //===----------------------------------------------------------------------===//
145 // scf::ForOp
146 //===----------------------------------------------------------------------===//
147 
148 LogicalResult
149 ForOpConversion::matchAndRewrite(scf::ForOp forOp, ArrayRef<Value> operands,
150                                  ConversionPatternRewriter &rewriter) const {
151   // scf::ForOp can be lowered to the structured control flow represented by
152   // spirv::LoopOp by making the continue block of the spirv::LoopOp the loop
153   // latch and the merge block the exit block. The resulting spirv::LoopOp has a
154   // single back edge from the continue to header block, and a single exit from
155   // header to merge.
156   scf::ForOpAdaptor forOperands(operands);
157   auto loc = forOp.getLoc();
158   auto loopOp = rewriter.create<spirv::LoopOp>(loc, spirv::LoopControl::None);
159   loopOp.addEntryAndMergeBlock();
160 
161   OpBuilder::InsertionGuard guard(rewriter);
162   // Create the block for the header.
163   auto *header = new Block();
164   // Insert the header.
165   loopOp.body().getBlocks().insert(std::next(loopOp.body().begin(), 1), header);
166 
167   // Create the new induction variable to use.
168   BlockArgument newIndVar =
169       header->addArgument(forOperands.lowerBound().getType());
170   for (Value arg : forOperands.initArgs())
171     header->addArgument(arg.getType());
172   Block *body = forOp.getBody();
173 
174   // Apply signature conversion to the body of the forOp. It has a single block,
175   // with argument which is the induction variable. That has to be replaced with
176   // the new induction variable.
177   TypeConverter::SignatureConversion signatureConverter(
178       body->getNumArguments());
179   signatureConverter.remapInput(0, newIndVar);
180   for (unsigned i = 1, e = body->getNumArguments(); i < e; i++)
181     signatureConverter.remapInput(i, header->getArgument(i));
182   body = rewriter.applySignatureConversion(&forOp.getLoopBody(),
183                                            signatureConverter);
184 
185   // Move the blocks from the forOp into the loopOp. This is the body of the
186   // loopOp.
187   rewriter.inlineRegionBefore(forOp->getRegion(0), loopOp.body(),
188                               std::next(loopOp.body().begin(), 2));
189 
190   SmallVector<Value, 8> args(1, forOperands.lowerBound());
191   args.append(forOperands.initArgs().begin(), forOperands.initArgs().end());
192   // Branch into it from the entry.
193   rewriter.setInsertionPointToEnd(&(loopOp.body().front()));
194   rewriter.create<spirv::BranchOp>(loc, header, args);
195 
196   // Generate the rest of the loop header.
197   rewriter.setInsertionPointToEnd(header);
198   auto *mergeBlock = loopOp.getMergeBlock();
199   auto cmpOp = rewriter.create<spirv::SLessThanOp>(
200       loc, rewriter.getI1Type(), newIndVar, forOperands.upperBound());
201 
202   rewriter.create<spirv::BranchConditionalOp>(
203       loc, cmpOp, body, ArrayRef<Value>(), mergeBlock, ArrayRef<Value>());
204 
205   // Generate instructions to increment the step of the induction variable and
206   // branch to the header.
207   Block *continueBlock = loopOp.getContinueBlock();
208   rewriter.setInsertionPointToEnd(continueBlock);
209 
210   // Add the step to the induction variable and branch to the header.
211   Value updatedIndVar = rewriter.create<spirv::IAddOp>(
212       loc, newIndVar.getType(), newIndVar, forOperands.step());
213   rewriter.create<spirv::BranchOp>(loc, header, updatedIndVar);
214 
215   // Infer the return types from the init operands. Vector type may get
216   // converted to CooperativeMatrix or to Vector type, to avoid having complex
217   // extra logic to figure out the right type we just infer it from the Init
218   // operands.
219   SmallVector<Type, 8> initTypes;
220   for (auto arg : forOperands.initArgs())
221     initTypes.push_back(arg.getType());
222   replaceSCFOutputValue(forOp, loopOp, rewriter, scfToSPIRVContext, initTypes);
223   return success();
224 }
225 
226 //===----------------------------------------------------------------------===//
227 // scf::IfOp
228 //===----------------------------------------------------------------------===//
229 
230 LogicalResult
231 IfOpConversion::matchAndRewrite(scf::IfOp ifOp, ArrayRef<Value> operands,
232                                 ConversionPatternRewriter &rewriter) const {
233   // When lowering `scf::IfOp` we explicitly create a selection header block
234   // before the control flow diverges and a merge block where control flow
235   // subsequently converges.
236   scf::IfOpAdaptor ifOperands(operands);
237   auto loc = ifOp.getLoc();
238 
239   // Create `spv.selection` operation, selection header block and merge block.
240   auto selectionOp =
241       rewriter.create<spirv::SelectionOp>(loc, spirv::SelectionControl::None);
242   auto *mergeBlock =
243       rewriter.createBlock(&selectionOp.body(), selectionOp.body().end());
244   rewriter.create<spirv::MergeOp>(loc);
245 
246   OpBuilder::InsertionGuard guard(rewriter);
247   auto *selectionHeaderBlock =
248       rewriter.createBlock(&selectionOp.body().front());
249 
250   // Inline `then` region before the merge block and branch to it.
251   auto &thenRegion = ifOp.thenRegion();
252   auto *thenBlock = &thenRegion.front();
253   rewriter.setInsertionPointToEnd(&thenRegion.back());
254   rewriter.create<spirv::BranchOp>(loc, mergeBlock);
255   rewriter.inlineRegionBefore(thenRegion, mergeBlock);
256 
257   auto *elseBlock = mergeBlock;
258   // If `else` region is not empty, inline that region before the merge block
259   // and branch to it.
260   if (!ifOp.elseRegion().empty()) {
261     auto &elseRegion = ifOp.elseRegion();
262     elseBlock = &elseRegion.front();
263     rewriter.setInsertionPointToEnd(&elseRegion.back());
264     rewriter.create<spirv::BranchOp>(loc, mergeBlock);
265     rewriter.inlineRegionBefore(elseRegion, mergeBlock);
266   }
267 
268   // Create a `spv.BranchConditional` operation for selection header block.
269   rewriter.setInsertionPointToEnd(selectionHeaderBlock);
270   rewriter.create<spirv::BranchConditionalOp>(loc, ifOperands.condition(),
271                                               thenBlock, ArrayRef<Value>(),
272                                               elseBlock, ArrayRef<Value>());
273 
274   SmallVector<Type, 8> returnTypes;
275   for (auto result : ifOp.results()) {
276     auto convertedType = typeConverter.convertType(result.getType());
277     returnTypes.push_back(convertedType);
278   }
279   replaceSCFOutputValue(ifOp, selectionOp, rewriter, scfToSPIRVContext,
280                         returnTypes);
281   return success();
282 }
283 
284 //===----------------------------------------------------------------------===//
285 // scf::YieldOp
286 //===----------------------------------------------------------------------===//
287 
288 /// Yield is lowered to stores to the VariableOp created during lowering of the
289 /// parent region. For loops we also need to update the branch looping back to
290 /// the header with the loop carried values.
291 LogicalResult TerminatorOpConversion::matchAndRewrite(
292     scf::YieldOp terminatorOp, ArrayRef<Value> operands,
293     ConversionPatternRewriter &rewriter) const {
294   // If the region is return values, store each value into the associated
295   // VariableOp created during lowering of the parent region.
296   if (!operands.empty()) {
297     auto loc = terminatorOp.getLoc();
298     auto &allocas = scfToSPIRVContext->outputVars[terminatorOp->getParentOp()];
299     assert(allocas.size() == operands.size());
300     for (unsigned i = 0, e = operands.size(); i < e; i++)
301       rewriter.create<spirv::StoreOp>(loc, allocas[i], operands[i]);
302     if (isa<spirv::LoopOp>(terminatorOp->getParentOp())) {
303       // For loops we also need to update the branch jumping back to the header.
304       auto br =
305           cast<spirv::BranchOp>(rewriter.getInsertionBlock()->getTerminator());
306       SmallVector<Value, 8> args(br.getBlockArguments());
307       args.append(operands.begin(), operands.end());
308       rewriter.setInsertionPoint(br);
309       rewriter.create<spirv::BranchOp>(terminatorOp.getLoc(), br.getTarget(),
310                                        args);
311       rewriter.eraseOp(br);
312     }
313   }
314   rewriter.eraseOp(terminatorOp);
315   return success();
316 }
317 
318 //===----------------------------------------------------------------------===//
319 // Hooks
320 //===----------------------------------------------------------------------===//
321 
322 void mlir::populateSCFToSPIRVPatterns(SPIRVTypeConverter &typeConverter,
323                                       ScfToSPIRVContext &scfToSPIRVContext,
324                                       RewritePatternSet &patterns) {
325   patterns.add<ForOpConversion, IfOpConversion, TerminatorOpConversion>(
326       patterns.getContext(), typeConverter, scfToSPIRVContext.getImpl());
327 }
328