1 //===- SCFToOpenMP.cpp - Structured Control Flow to OpenMP conversion -----===//
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 convert scf.parallel operations into OpenMP
10 // parallel loops.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Conversion/SCFToOpenMP/SCFToOpenMP.h"
15 #include "../PassDetail.h"
16 #include "mlir/Analysis/SliceAnalysis.h"
17 #include "mlir/Dialect/Affine/Analysis/LoopAnalysis.h"
18 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
19 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
20 #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
21 #include "mlir/Dialect/SCF/SCF.h"
22 #include "mlir/Dialect/StandardOps/IR/Ops.h"
23 #include "mlir/IR/ImplicitLocOpBuilder.h"
24 #include "mlir/IR/SymbolTable.h"
25 #include "mlir/Transforms/DialectConversion.h"
26 
27 using namespace mlir;
28 
29 /// Matches a block containing a "simple" reduction. The expected shape of the
30 /// block is as follows.
31 ///
32 ///   ^bb(%arg0, %arg1):
33 ///     %0 = OpTy(%arg0, %arg1)
34 ///     scf.reduce.return %0
35 template <typename... OpTy>
36 static bool matchSimpleReduction(Block &block) {
37   if (block.empty() || llvm::hasSingleElement(block) ||
38       std::next(block.begin(), 2) != block.end())
39     return false;
40 
41   if (block.getNumArguments() != 2)
42     return false;
43 
44   SmallVector<Operation *, 4> combinerOps;
45   Value reducedVal = matchReduction({block.getArguments()[1]},
46                                     /*redPos=*/0, combinerOps);
47 
48   if (!reducedVal || !reducedVal.isa<BlockArgument>() ||
49       combinerOps.size() != 1)
50     return false;
51 
52   return isa<OpTy...>(combinerOps[0]) &&
53          isa<scf::ReduceReturnOp>(block.back()) &&
54          block.front().getOperands() == block.getArguments();
55 }
56 
57 /// Matches a block containing a select-based min/max reduction. The types of
58 /// select and compare operations are provided as template arguments. The
59 /// comparison predicates suitable for min and max are provided as function
60 /// arguments. If a reduction is matched, `ifMin` will be set if the reduction
61 /// compute the minimum and unset if it computes the maximum, otherwise it
62 /// remains unmodified. The expected shape of the block is as follows.
63 ///
64 ///   ^bb(%arg0, %arg1):
65 ///     %0 = CompareOpTy(<one-of-predicates>, %arg0, %arg1)
66 ///     %1 = SelectOpTy(%0, %arg0, %arg1)  // %arg0, %arg1 may be swapped here.
67 ///     scf.reduce.return %1
68 template <
69     typename CompareOpTy, typename SelectOpTy,
70     typename Predicate = decltype(std::declval<CompareOpTy>().getPredicate())>
71 static bool
72 matchSelectReduction(Block &block, ArrayRef<Predicate> lessThanPredicates,
73                      ArrayRef<Predicate> greaterThanPredicates, bool &isMin) {
74   static_assert(llvm::is_one_of<SelectOpTy, SelectOp, LLVM::SelectOp>::value,
75                 "only std and llvm select ops are supported");
76 
77   // Expect exactly three operations in the block.
78   if (block.empty() || llvm::hasSingleElement(block) ||
79       std::next(block.begin(), 2) == block.end() ||
80       std::next(block.begin(), 3) != block.end())
81     return false;
82 
83   // Check op kinds.
84   auto compare = dyn_cast<CompareOpTy>(block.front());
85   auto select = dyn_cast<SelectOpTy>(block.front().getNextNode());
86   auto terminator = dyn_cast<scf::ReduceReturnOp>(block.back());
87   if (!compare || !select || !terminator)
88     return false;
89 
90   // Block arguments must be compared.
91   if (compare->getOperands() != block.getArguments())
92     return false;
93 
94   // Detect whether the comparison is less-than or greater-than, otherwise bail.
95   bool isLess;
96   if (llvm::find(lessThanPredicates, compare.getPredicate()) !=
97       lessThanPredicates.end()) {
98     isLess = true;
99   } else if (llvm::find(greaterThanPredicates, compare.getPredicate()) !=
100              greaterThanPredicates.end()) {
101     isLess = false;
102   } else {
103     return false;
104   }
105 
106   if (select.getCondition() != compare.getResult())
107     return false;
108 
109   // Detect if the operands are swapped between cmpf and select. Match the
110   // comparison type with the requested type or with the opposite of the
111   // requested type if the operands are swapped. Use generic accessors because
112   // std and LLVM versions of select have different operand names but identical
113   // positions.
114   constexpr unsigned kTrueValue = 1;
115   constexpr unsigned kFalseValue = 2;
116   bool sameOperands = select.getOperand(kTrueValue) == compare.getLhs() &&
117                       select.getOperand(kFalseValue) == compare.getRhs();
118   bool swappedOperands = select.getOperand(kTrueValue) == compare.getRhs() &&
119                          select.getOperand(kFalseValue) == compare.getLhs();
120   if (!sameOperands && !swappedOperands)
121     return false;
122 
123   if (select.getResult() != terminator.getResult())
124     return false;
125 
126   // The reduction is a min if it uses less-than predicates with same operands
127   // or greather-than predicates with swapped operands. Similarly for max.
128   isMin = (isLess && sameOperands) || (!isLess && swappedOperands);
129   return isMin || (isLess & swappedOperands) || (!isLess && sameOperands);
130 }
131 
132 /// Returns the float semantics for the given float type.
133 static const llvm::fltSemantics &fltSemanticsForType(FloatType type) {
134   if (type.isF16())
135     return llvm::APFloat::IEEEhalf();
136   if (type.isF32())
137     return llvm::APFloat::IEEEsingle();
138   if (type.isF64())
139     return llvm::APFloat::IEEEdouble();
140   if (type.isF128())
141     return llvm::APFloat::IEEEquad();
142   if (type.isBF16())
143     return llvm::APFloat::BFloat();
144   if (type.isF80())
145     return llvm::APFloat::x87DoubleExtended();
146   llvm_unreachable("unknown float type");
147 }
148 
149 /// Returns an attribute with the minimum (if `min` is set) or the maximum value
150 /// (otherwise) for the given float type.
151 static Attribute minMaxValueForFloat(Type type, bool min) {
152   auto fltType = type.cast<FloatType>();
153   return FloatAttr::get(
154       type, llvm::APFloat::getLargest(fltSemanticsForType(fltType), min));
155 }
156 
157 /// Returns an attribute with the signed integer minimum (if `min` is set) or
158 /// the maximum value (otherwise) for the given integer type, regardless of its
159 /// signedness semantics (only the width is considered).
160 static Attribute minMaxValueForSignedInt(Type type, bool min) {
161   auto intType = type.cast<IntegerType>();
162   unsigned bitwidth = intType.getWidth();
163   return IntegerAttr::get(type, min ? llvm::APInt::getSignedMinValue(bitwidth)
164                                     : llvm::APInt::getSignedMaxValue(bitwidth));
165 }
166 
167 /// Returns an attribute with the unsigned integer minimum (if `min` is set) or
168 /// the maximum value (otherwise) for the given integer type, regardless of its
169 /// signedness semantics (only the width is considered).
170 static Attribute minMaxValueForUnsignedInt(Type type, bool min) {
171   auto intType = type.cast<IntegerType>();
172   unsigned bitwidth = intType.getWidth();
173   return IntegerAttr::get(type, min ? llvm::APInt::getNullValue(bitwidth)
174                                     : llvm::APInt::getAllOnesValue(bitwidth));
175 }
176 
177 /// Creates an OpenMP reduction declaration and inserts it into the provided
178 /// symbol table. The declaration has a constant initializer with the neutral
179 /// value `initValue`, and the reduction combiner carried over from `reduce`.
180 static omp::ReductionDeclareOp createDecl(PatternRewriter &builder,
181                                           SymbolTable &symbolTable,
182                                           scf::ReduceOp reduce,
183                                           Attribute initValue) {
184   OpBuilder::InsertionGuard guard(builder);
185   auto decl = builder.create<omp::ReductionDeclareOp>(
186       reduce.getLoc(), "__scf_reduction", reduce.getOperand().getType());
187   symbolTable.insert(decl);
188 
189   Type type = reduce.getOperand().getType();
190   builder.createBlock(&decl.initializerRegion(), decl.initializerRegion().end(),
191                       {type});
192   builder.setInsertionPointToEnd(&decl.initializerRegion().back());
193   Value init =
194       builder.create<LLVM::ConstantOp>(reduce.getLoc(), type, initValue);
195   builder.create<omp::YieldOp>(reduce.getLoc(), init);
196 
197   Operation *terminator = &reduce.getRegion().front().back();
198   assert(isa<scf::ReduceReturnOp>(terminator) &&
199          "expected reduce op to be terminated by redure return");
200   builder.setInsertionPoint(terminator);
201   builder.replaceOpWithNewOp<omp::YieldOp>(terminator,
202                                            terminator->getOperands());
203   builder.inlineRegionBefore(reduce.getRegion(), decl.reductionRegion(),
204                              decl.reductionRegion().end());
205   return decl;
206 }
207 
208 /// Adds an atomic reduction combiner to the given OpenMP reduction declaration
209 /// using llvm.atomicrmw of the given kind.
210 static omp::ReductionDeclareOp addAtomicRMW(OpBuilder &builder,
211                                             LLVM::AtomicBinOp atomicKind,
212                                             omp::ReductionDeclareOp decl,
213                                             scf::ReduceOp reduce) {
214   OpBuilder::InsertionGuard guard(builder);
215   Type type = reduce.getOperand().getType();
216   Type ptrType = LLVM::LLVMPointerType::get(type);
217   builder.createBlock(&decl.atomicReductionRegion(),
218                       decl.atomicReductionRegion().end(), {ptrType, ptrType});
219   Block *atomicBlock = &decl.atomicReductionRegion().back();
220   builder.setInsertionPointToEnd(atomicBlock);
221   Value loaded = builder.create<LLVM::LoadOp>(reduce.getLoc(),
222                                               atomicBlock->getArgument(1));
223   builder.create<LLVM::AtomicRMWOp>(reduce.getLoc(), type, atomicKind,
224                                     atomicBlock->getArgument(0), loaded,
225                                     LLVM::AtomicOrdering::monotonic);
226   builder.create<omp::YieldOp>(reduce.getLoc(), ArrayRef<Value>());
227   return decl;
228 }
229 
230 /// Creates an OpenMP reduction declaration that corresponds to the given SCF
231 /// reduction and returns it. Recognizes common reductions in order to identify
232 /// the neutral value, necessary for the OpenMP declaration. If the reduction
233 /// cannot be recognized, returns null.
234 static omp::ReductionDeclareOp declareReduction(PatternRewriter &builder,
235                                                 scf::ReduceOp reduce) {
236   Operation *container = SymbolTable::getNearestSymbolTable(reduce);
237   SymbolTable symbolTable(container);
238 
239   // Insert reduction declarations in the symbol-table ancestor before the
240   // ancestor of the current insertion point.
241   Operation *insertionPoint = reduce;
242   while (insertionPoint->getParentOp() != container)
243     insertionPoint = insertionPoint->getParentOp();
244   OpBuilder::InsertionGuard guard(builder);
245   builder.setInsertionPoint(insertionPoint);
246 
247   assert(llvm::hasSingleElement(reduce.getRegion()) &&
248          "expected reduction region to have a single element");
249 
250   // Match simple binary reductions that can be expressed with atomicrmw.
251   Type type = reduce.getOperand().getType();
252   Block &reduction = reduce.getRegion().front();
253   if (matchSimpleReduction<arith::AddFOp, LLVM::FAddOp>(reduction)) {
254     omp::ReductionDeclareOp decl = createDecl(builder, symbolTable, reduce,
255                                               builder.getFloatAttr(type, 0.0));
256     return addAtomicRMW(builder, LLVM::AtomicBinOp::fadd, decl, reduce);
257   }
258   if (matchSimpleReduction<arith::AddIOp, LLVM::AddOp>(reduction)) {
259     omp::ReductionDeclareOp decl = createDecl(builder, symbolTable, reduce,
260                                               builder.getIntegerAttr(type, 0));
261     return addAtomicRMW(builder, LLVM::AtomicBinOp::add, decl, reduce);
262   }
263   if (matchSimpleReduction<arith::OrIOp, LLVM::OrOp>(reduction)) {
264     omp::ReductionDeclareOp decl = createDecl(builder, symbolTable, reduce,
265                                               builder.getIntegerAttr(type, 0));
266     return addAtomicRMW(builder, LLVM::AtomicBinOp::_or, decl, reduce);
267   }
268   if (matchSimpleReduction<arith::XOrIOp, LLVM::XOrOp>(reduction)) {
269     omp::ReductionDeclareOp decl = createDecl(builder, symbolTable, reduce,
270                                               builder.getIntegerAttr(type, 0));
271     return addAtomicRMW(builder, LLVM::AtomicBinOp::_xor, decl, reduce);
272   }
273   if (matchSimpleReduction<arith::AndIOp, LLVM::AndOp>(reduction)) {
274     omp::ReductionDeclareOp decl = createDecl(
275         builder, symbolTable, reduce,
276         builder.getIntegerAttr(
277             type, llvm::APInt::getAllOnesValue(type.getIntOrFloatBitWidth())));
278     return addAtomicRMW(builder, LLVM::AtomicBinOp::_and, decl, reduce);
279   }
280 
281   // Match simple binary reductions that cannot be expressed with atomicrmw.
282   // TODO: add atomic region using cmpxchg (which needs atomic load to be
283   // available as an op).
284   if (matchSimpleReduction<arith::MulFOp, LLVM::FMulOp>(reduction)) {
285     return createDecl(builder, symbolTable, reduce,
286                       builder.getFloatAttr(type, 1.0));
287   }
288 
289   // Match select-based min/max reductions.
290   bool isMin;
291   if (matchSelectReduction<arith::CmpFOp, SelectOp>(
292           reduction, {arith::CmpFPredicate::OLT, arith::CmpFPredicate::OLE},
293           {arith::CmpFPredicate::OGT, arith::CmpFPredicate::OGE}, isMin) ||
294       matchSelectReduction<LLVM::FCmpOp, LLVM::SelectOp>(
295           reduction, {LLVM::FCmpPredicate::olt, LLVM::FCmpPredicate::ole},
296           {LLVM::FCmpPredicate::ogt, LLVM::FCmpPredicate::oge}, isMin)) {
297     return createDecl(builder, symbolTable, reduce,
298                       minMaxValueForFloat(type, !isMin));
299   }
300   if (matchSelectReduction<arith::CmpIOp, SelectOp>(
301           reduction, {arith::CmpIPredicate::slt, arith::CmpIPredicate::sle},
302           {arith::CmpIPredicate::sgt, arith::CmpIPredicate::sge}, isMin) ||
303       matchSelectReduction<LLVM::ICmpOp, LLVM::SelectOp>(
304           reduction, {LLVM::ICmpPredicate::slt, LLVM::ICmpPredicate::sle},
305           {LLVM::ICmpPredicate::sgt, LLVM::ICmpPredicate::sge}, isMin)) {
306     omp::ReductionDeclareOp decl = createDecl(
307         builder, symbolTable, reduce, minMaxValueForSignedInt(type, !isMin));
308     return addAtomicRMW(builder,
309                         isMin ? LLVM::AtomicBinOp::min : LLVM::AtomicBinOp::max,
310                         decl, reduce);
311   }
312   if (matchSelectReduction<arith::CmpIOp, SelectOp>(
313           reduction, {arith::CmpIPredicate::ult, arith::CmpIPredicate::ule},
314           {arith::CmpIPredicate::ugt, arith::CmpIPredicate::uge}, isMin) ||
315       matchSelectReduction<LLVM::ICmpOp, LLVM::SelectOp>(
316           reduction, {LLVM::ICmpPredicate::ugt, LLVM::ICmpPredicate::ule},
317           {LLVM::ICmpPredicate::ugt, LLVM::ICmpPredicate::uge}, isMin)) {
318     omp::ReductionDeclareOp decl = createDecl(
319         builder, symbolTable, reduce, minMaxValueForUnsignedInt(type, !isMin));
320     return addAtomicRMW(
321         builder, isMin ? LLVM::AtomicBinOp::umin : LLVM::AtomicBinOp::umax,
322         decl, reduce);
323   }
324 
325   return nullptr;
326 }
327 
328 namespace {
329 
330 struct ParallelOpLowering : public OpRewritePattern<scf::ParallelOp> {
331   using OpRewritePattern<scf::ParallelOp>::OpRewritePattern;
332 
333   LogicalResult matchAndRewrite(scf::ParallelOp parallelOp,
334                                 PatternRewriter &rewriter) const override {
335     // Replace SCF yield with OpenMP yield.
336     {
337       OpBuilder::InsertionGuard guard(rewriter);
338       rewriter.setInsertionPointToEnd(parallelOp.getBody());
339       assert(llvm::hasSingleElement(parallelOp.getRegion()) &&
340              "expected scf.parallel to have one block");
341       rewriter.replaceOpWithNewOp<omp::YieldOp>(
342           parallelOp.getBody()->getTerminator(), ValueRange());
343     }
344 
345     // Declare reductions.
346     // TODO: consider checking it here is already a compatible reduction
347     // declaration and use it instead of redeclaring.
348     SmallVector<Attribute> reductionDeclSymbols;
349     for (auto reduce : parallelOp.getOps<scf::ReduceOp>()) {
350       omp::ReductionDeclareOp decl = declareReduction(rewriter, reduce);
351       if (!decl)
352         return failure();
353       reductionDeclSymbols.push_back(
354           SymbolRefAttr::get(rewriter.getContext(), decl.sym_name()));
355     }
356 
357     // Allocate reduction variables. Make sure the we don't overflow the stack
358     // with local `alloca`s by saving and restoring the stack pointer.
359     Location loc = parallelOp.getLoc();
360     Value one = rewriter.create<LLVM::ConstantOp>(
361         loc, rewriter.getIntegerType(64), rewriter.getI64IntegerAttr(1));
362     SmallVector<Value> reductionVariables;
363     reductionVariables.reserve(parallelOp.getNumReductions());
364     Value token = rewriter.create<LLVM::StackSaveOp>(
365         loc, LLVM::LLVMPointerType::get(rewriter.getIntegerType(8)));
366     for (Value init : parallelOp.getInitVals()) {
367       assert((LLVM::isCompatibleType(init.getType()) ||
368               init.getType().isa<LLVM::PointerElementTypeInterface>()) &&
369              "cannot create a reduction variable if the type is not an LLVM "
370              "pointer element");
371       Value storage = rewriter.create<LLVM::AllocaOp>(
372           loc, LLVM::LLVMPointerType::get(init.getType()), one, 0);
373       rewriter.create<LLVM::StoreOp>(loc, init, storage);
374       reductionVariables.push_back(storage);
375     }
376 
377     // Replace the reduction operations contained in this loop. Must be done
378     // here rather than in a separate pattern to have access to the list of
379     // reduction variables.
380     for (auto pair :
381          llvm::zip(parallelOp.getOps<scf::ReduceOp>(), reductionVariables)) {
382       OpBuilder::InsertionGuard guard(rewriter);
383       scf::ReduceOp reduceOp = std::get<0>(pair);
384       rewriter.setInsertionPoint(reduceOp);
385       rewriter.replaceOpWithNewOp<omp::ReductionOp>(
386           reduceOp, reduceOp.getOperand(), std::get<1>(pair));
387     }
388 
389     // Create the parallel wrapper.
390     auto ompParallel = rewriter.create<omp::ParallelOp>(loc);
391     {
392       OpBuilder::InsertionGuard guard(rewriter);
393       rewriter.createBlock(&ompParallel.region());
394 
395       // Replace SCF yield with OpenMP yield.
396       {
397         OpBuilder::InsertionGuard innerGuard(rewriter);
398         rewriter.setInsertionPointToEnd(parallelOp.getBody());
399         assert(llvm::hasSingleElement(parallelOp.getRegion()) &&
400                "expected scf.parallel to have one block");
401         rewriter.replaceOpWithNewOp<omp::YieldOp>(
402             parallelOp.getBody()->getTerminator(), ValueRange());
403       }
404 
405       // Replace the loop.
406       auto loop = rewriter.create<omp::WsLoopOp>(
407           parallelOp.getLoc(), parallelOp.getLowerBound(),
408           parallelOp.getUpperBound(), parallelOp.getStep());
409       rewriter.create<omp::TerminatorOp>(loc);
410 
411       rewriter.inlineRegionBefore(parallelOp.getRegion(), loop.region(),
412                                   loop.region().begin());
413       if (!reductionVariables.empty()) {
414         loop.reductionsAttr(
415             ArrayAttr::get(rewriter.getContext(), reductionDeclSymbols));
416         loop.reduction_varsMutable().append(reductionVariables);
417       }
418     }
419 
420     // Load loop results.
421     SmallVector<Value> results;
422     results.reserve(reductionVariables.size());
423     for (Value variable : reductionVariables) {
424       Value res = rewriter.create<LLVM::LoadOp>(loc, variable);
425       results.push_back(res);
426     }
427     rewriter.replaceOp(parallelOp, results);
428 
429     rewriter.create<LLVM::StackRestoreOp>(loc, token);
430     return success();
431   }
432 };
433 
434 /// Applies the conversion patterns in the given function.
435 static LogicalResult applyPatterns(ModuleOp module) {
436   ConversionTarget target(*module.getContext());
437   target.addIllegalOp<scf::ReduceOp, scf::ReduceReturnOp, scf::ParallelOp>();
438   target.addLegalDialect<omp::OpenMPDialect, LLVM::LLVMDialect>();
439 
440   RewritePatternSet patterns(module.getContext());
441   patterns.add<ParallelOpLowering>(module.getContext());
442   FrozenRewritePatternSet frozen(std::move(patterns));
443   return applyPartialConversion(module, target, frozen);
444 }
445 
446 /// A pass converting SCF operations to OpenMP operations.
447 struct SCFToOpenMPPass : public ConvertSCFToOpenMPBase<SCFToOpenMPPass> {
448   /// Pass entry point.
449   void runOnOperation() override {
450     if (failed(applyPatterns(getOperation())))
451       signalPassFailure();
452   }
453 };
454 
455 } // namespace
456 
457 std::unique_ptr<OperationPass<ModuleOp>> mlir::createConvertSCFToOpenMPPass() {
458   return std::make_unique<SCFToOpenMPPass>();
459 }
460