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