1 //===- OpenMPToLLVMIRTranslation.cpp - Translate OpenMP dialect to LLVM IR-===// 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 translation between the MLIR OpenMP dialect and LLVM 10 // IR. 11 // 12 //===----------------------------------------------------------------------===// 13 #include "mlir/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.h" 14 #include "mlir/Dialect/OpenMP/OpenMPDialect.h" 15 #include "mlir/IR/BlockAndValueMapping.h" 16 #include "mlir/IR/Operation.h" 17 #include "mlir/Support/LLVM.h" 18 #include "mlir/Target/LLVMIR/ModuleTranslation.h" 19 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/TypeSwitch.h" 22 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 23 #include "llvm/IR/IRBuilder.h" 24 25 using namespace mlir; 26 27 namespace { 28 /// ModuleTranslation stack frame for OpenMP operations. This keeps track of the 29 /// insertion points for allocas. 30 class OpenMPAllocaStackFrame 31 : public LLVM::ModuleTranslation::StackFrameBase<OpenMPAllocaStackFrame> { 32 public: 33 explicit OpenMPAllocaStackFrame(llvm::OpenMPIRBuilder::InsertPointTy allocaIP) 34 : allocaInsertPoint(allocaIP) {} 35 llvm::OpenMPIRBuilder::InsertPointTy allocaInsertPoint; 36 }; 37 38 /// ModuleTranslation stack frame containing the partial mapping between MLIR 39 /// values and their LLVM IR equivalents. 40 class OpenMPVarMappingStackFrame 41 : public LLVM::ModuleTranslation::StackFrameBase< 42 OpenMPVarMappingStackFrame> { 43 public: 44 explicit OpenMPVarMappingStackFrame( 45 const DenseMap<Value, llvm::Value *> &mapping) 46 : mapping(mapping) {} 47 48 DenseMap<Value, llvm::Value *> mapping; 49 }; 50 } // namespace 51 52 /// Find the insertion point for allocas given the current insertion point for 53 /// normal operations in the builder. 54 static llvm::OpenMPIRBuilder::InsertPointTy 55 findAllocaInsertPoint(llvm::IRBuilderBase &builder, 56 const LLVM::ModuleTranslation &moduleTranslation) { 57 // If there is an alloca insertion point on stack, i.e. we are in a nested 58 // operation and a specific point was provided by some surrounding operation, 59 // use it. 60 llvm::OpenMPIRBuilder::InsertPointTy allocaInsertPoint; 61 WalkResult walkResult = moduleTranslation.stackWalk<OpenMPAllocaStackFrame>( 62 [&](const OpenMPAllocaStackFrame &frame) { 63 allocaInsertPoint = frame.allocaInsertPoint; 64 return WalkResult::interrupt(); 65 }); 66 if (walkResult.wasInterrupted()) 67 return allocaInsertPoint; 68 69 // Otherwise, insert to the entry block of the surrounding function. 70 llvm::BasicBlock &funcEntryBlock = 71 builder.GetInsertBlock()->getParent()->getEntryBlock(); 72 return llvm::OpenMPIRBuilder::InsertPointTy( 73 &funcEntryBlock, funcEntryBlock.getFirstInsertionPt()); 74 } 75 76 /// Converts the given region that appears within an OpenMP dialect operation to 77 /// LLVM IR, creating a branch from the `sourceBlock` to the entry block of the 78 /// region, and a branch from any block with an successor-less OpenMP terminator 79 /// to `continuationBlock`. Populates `continuationBlockPHIs` with the PHI nodes 80 /// of the continuation block if provided. 81 static void convertOmpOpRegions( 82 Region ®ion, StringRef blockName, llvm::BasicBlock &sourceBlock, 83 llvm::BasicBlock &continuationBlock, llvm::IRBuilderBase &builder, 84 LLVM::ModuleTranslation &moduleTranslation, LogicalResult &bodyGenStatus, 85 SmallVectorImpl<llvm::PHINode *> *continuationBlockPHIs = nullptr) { 86 llvm::LLVMContext &llvmContext = builder.getContext(); 87 for (Block &bb : region) { 88 llvm::BasicBlock *llvmBB = llvm::BasicBlock::Create( 89 llvmContext, blockName, builder.GetInsertBlock()->getParent(), 90 builder.GetInsertBlock()->getNextNode()); 91 moduleTranslation.mapBlock(&bb, llvmBB); 92 } 93 94 llvm::Instruction *sourceTerminator = sourceBlock.getTerminator(); 95 96 // Terminators (namely YieldOp) may be forwarding values to the region that 97 // need to be available in the continuation block. Collect the types of these 98 // operands in preparation of creating PHI nodes. 99 SmallVector<llvm::Type *> continuationBlockPHITypes; 100 bool operandsProcessed = false; 101 unsigned numYields = 0; 102 for (Block &bb : region.getBlocks()) { 103 if (omp::YieldOp yield = dyn_cast<omp::YieldOp>(bb.getTerminator())) { 104 if (!operandsProcessed) { 105 for (unsigned i = 0, e = yield->getNumOperands(); i < e; ++i) { 106 continuationBlockPHITypes.push_back( 107 moduleTranslation.convertType(yield->getOperand(i).getType())); 108 } 109 operandsProcessed = true; 110 } else { 111 assert(continuationBlockPHITypes.size() == yield->getNumOperands() && 112 "mismatching number of values yielded from the region"); 113 for (unsigned i = 0, e = yield->getNumOperands(); i < e; ++i) { 114 llvm::Type *operandType = 115 moduleTranslation.convertType(yield->getOperand(i).getType()); 116 (void)operandType; 117 assert(continuationBlockPHITypes[i] == operandType && 118 "values of mismatching types yielded from the region"); 119 } 120 } 121 numYields++; 122 } 123 } 124 125 // Insert PHI nodes in the continuation block for any values forwarded by the 126 // terminators in this region. 127 if (!continuationBlockPHITypes.empty()) 128 assert( 129 continuationBlockPHIs && 130 "expected continuation block PHIs if converted regions yield values"); 131 if (continuationBlockPHIs) { 132 llvm::IRBuilderBase::InsertPointGuard guard(builder); 133 continuationBlockPHIs->reserve(continuationBlockPHITypes.size()); 134 builder.SetInsertPoint(&continuationBlock, continuationBlock.begin()); 135 for (llvm::Type *ty : continuationBlockPHITypes) 136 continuationBlockPHIs->push_back(builder.CreatePHI(ty, numYields)); 137 } 138 139 // Convert blocks one by one in topological order to ensure 140 // defs are converted before uses. 141 SetVector<Block *> blocks = 142 LLVM::detail::getTopologicallySortedBlocks(region); 143 for (Block *bb : blocks) { 144 llvm::BasicBlock *llvmBB = moduleTranslation.lookupBlock(bb); 145 // Retarget the branch of the entry block to the entry block of the 146 // converted region (regions are single-entry). 147 if (bb->isEntryBlock()) { 148 assert(sourceTerminator->getNumSuccessors() == 1 && 149 "provided entry block has multiple successors"); 150 assert(sourceTerminator->getSuccessor(0) == &continuationBlock && 151 "ContinuationBlock is not the successor of the entry block"); 152 sourceTerminator->setSuccessor(0, llvmBB); 153 } 154 155 llvm::IRBuilderBase::InsertPointGuard guard(builder); 156 if (failed( 157 moduleTranslation.convertBlock(*bb, bb->isEntryBlock(), builder))) { 158 bodyGenStatus = failure(); 159 return; 160 } 161 162 // Special handling for `omp.yield` and `omp.terminator` (we may have more 163 // than one): they return the control to the parent OpenMP dialect operation 164 // so replace them with the branch to the continuation block. We handle this 165 // here to avoid relying inter-function communication through the 166 // ModuleTranslation class to set up the correct insertion point. This is 167 // also consistent with MLIR's idiom of handling special region terminators 168 // in the same code that handles the region-owning operation. 169 Operation *terminator = bb->getTerminator(); 170 if (isa<omp::TerminatorOp, omp::YieldOp>(terminator)) { 171 builder.CreateBr(&continuationBlock); 172 173 for (unsigned i = 0, e = terminator->getNumOperands(); i < e; ++i) 174 (*continuationBlockPHIs)[i]->addIncoming( 175 moduleTranslation.lookupValue(terminator->getOperand(i)), llvmBB); 176 } 177 } 178 // After all blocks have been traversed and values mapped, connect the PHI 179 // nodes to the results of preceding blocks. 180 LLVM::detail::connectPHINodes(region, moduleTranslation); 181 182 // Remove the blocks and values defined in this region from the mapping since 183 // they are not visible outside of this region. This allows the same region to 184 // be converted several times, that is cloned, without clashes, and slightly 185 // speeds up the lookups. 186 moduleTranslation.forgetMapping(region); 187 } 188 189 /// Converts the OpenMP parallel operation to LLVM IR. 190 static LogicalResult 191 convertOmpParallel(Operation &opInst, llvm::IRBuilderBase &builder, 192 LLVM::ModuleTranslation &moduleTranslation) { 193 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 194 // TODO: support error propagation in OpenMPIRBuilder and use it instead of 195 // relying on captured variables. 196 LogicalResult bodyGenStatus = success(); 197 198 auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP, 199 llvm::BasicBlock &continuationBlock) { 200 // Save the alloca insertion point on ModuleTranslation stack for use in 201 // nested regions. 202 LLVM::ModuleTranslation::SaveStack<OpenMPAllocaStackFrame> frame( 203 moduleTranslation, allocaIP); 204 205 // ParallelOp has only one region associated with it. 206 auto ®ion = cast<omp::ParallelOp>(opInst).getRegion(); 207 convertOmpOpRegions(region, "omp.par.region", *codeGenIP.getBlock(), 208 continuationBlock, builder, moduleTranslation, 209 bodyGenStatus); 210 }; 211 212 // TODO: Perform appropriate actions according to the data-sharing 213 // attribute (shared, private, firstprivate, ...) of variables. 214 // Currently defaults to shared. 215 auto privCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP, 216 llvm::Value &, llvm::Value &vPtr, 217 llvm::Value *&replacementValue) -> InsertPointTy { 218 replacementValue = &vPtr; 219 220 return codeGenIP; 221 }; 222 223 // TODO: Perform finalization actions for variables. This has to be 224 // called for variables which have destructors/finalizers. 225 auto finiCB = [&](InsertPointTy codeGenIP) {}; 226 227 llvm::Value *ifCond = nullptr; 228 if (auto ifExprVar = cast<omp::ParallelOp>(opInst).if_expr_var()) 229 ifCond = moduleTranslation.lookupValue(ifExprVar); 230 llvm::Value *numThreads = nullptr; 231 if (auto numThreadsVar = cast<omp::ParallelOp>(opInst).num_threads_var()) 232 numThreads = moduleTranslation.lookupValue(numThreadsVar); 233 llvm::omp::ProcBindKind pbKind = llvm::omp::OMP_PROC_BIND_default; 234 if (auto bind = cast<omp::ParallelOp>(opInst).proc_bind_val()) 235 pbKind = llvm::omp::getProcBindKind(bind.getValue()); 236 // TODO: Is the Parallel construct cancellable? 237 bool isCancellable = false; 238 239 llvm::OpenMPIRBuilder::LocationDescription ompLoc( 240 builder.saveIP(), builder.getCurrentDebugLocation()); 241 builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createParallel( 242 ompLoc, findAllocaInsertPoint(builder, moduleTranslation), bodyGenCB, 243 privCB, finiCB, ifCond, numThreads, pbKind, isCancellable)); 244 245 return bodyGenStatus; 246 } 247 248 /// Converts an OpenMP 'master' operation into LLVM IR using OpenMPIRBuilder. 249 static LogicalResult 250 convertOmpMaster(Operation &opInst, llvm::IRBuilderBase &builder, 251 LLVM::ModuleTranslation &moduleTranslation) { 252 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 253 // TODO: support error propagation in OpenMPIRBuilder and use it instead of 254 // relying on captured variables. 255 LogicalResult bodyGenStatus = success(); 256 257 auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP, 258 llvm::BasicBlock &continuationBlock) { 259 // MasterOp has only one region associated with it. 260 auto ®ion = cast<omp::MasterOp>(opInst).getRegion(); 261 convertOmpOpRegions(region, "omp.master.region", *codeGenIP.getBlock(), 262 continuationBlock, builder, moduleTranslation, 263 bodyGenStatus); 264 }; 265 266 // TODO: Perform finalization actions for variables. This has to be 267 // called for variables which have destructors/finalizers. 268 auto finiCB = [&](InsertPointTy codeGenIP) {}; 269 270 llvm::OpenMPIRBuilder::LocationDescription ompLoc( 271 builder.saveIP(), builder.getCurrentDebugLocation()); 272 builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createMaster( 273 ompLoc, bodyGenCB, finiCB)); 274 return success(); 275 } 276 277 /// Converts an OpenMP 'critical' operation into LLVM IR using OpenMPIRBuilder. 278 static LogicalResult 279 convertOmpCritical(Operation &opInst, llvm::IRBuilderBase &builder, 280 LLVM::ModuleTranslation &moduleTranslation) { 281 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 282 auto criticalOp = cast<omp::CriticalOp>(opInst); 283 // TODO: support error propagation in OpenMPIRBuilder and use it instead of 284 // relying on captured variables. 285 LogicalResult bodyGenStatus = success(); 286 287 auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP, 288 llvm::BasicBlock &continuationBlock) { 289 // CriticalOp has only one region associated with it. 290 auto ®ion = cast<omp::CriticalOp>(opInst).getRegion(); 291 convertOmpOpRegions(region, "omp.critical.region", *codeGenIP.getBlock(), 292 continuationBlock, builder, moduleTranslation, 293 bodyGenStatus); 294 }; 295 296 // TODO: Perform finalization actions for variables. This has to be 297 // called for variables which have destructors/finalizers. 298 auto finiCB = [&](InsertPointTy codeGenIP) {}; 299 300 llvm::OpenMPIRBuilder::LocationDescription ompLoc( 301 builder.saveIP(), builder.getCurrentDebugLocation()); 302 llvm::LLVMContext &llvmContext = moduleTranslation.getLLVMContext(); 303 llvm::Constant *hint = nullptr; 304 305 // If it has a name, it probably has a hint too. 306 if (criticalOp.nameAttr()) { 307 // The verifiers in OpenMP Dialect guarentee that all the pointers are 308 // non-null 309 auto symbolRef = criticalOp.nameAttr().cast<SymbolRefAttr>(); 310 auto criticalDeclareOp = 311 SymbolTable::lookupNearestSymbolFrom<omp::CriticalDeclareOp>(criticalOp, 312 symbolRef); 313 hint = llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvmContext), 314 static_cast<int>(criticalDeclareOp.hint())); 315 } 316 builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createCritical( 317 ompLoc, bodyGenCB, finiCB, criticalOp.name().getValueOr(""), hint)); 318 return success(); 319 } 320 321 /// Returns a reduction declaration that corresponds to the given reduction 322 /// operation in the given container. Currently only supports reductions inside 323 /// WsLoopOp but can be easily extended. 324 static omp::ReductionDeclareOp findReductionDecl(omp::WsLoopOp container, 325 omp::ReductionOp reduction) { 326 SymbolRefAttr reductionSymbol; 327 for (unsigned i = 0, e = container.getNumReductionVars(); i < e; ++i) { 328 if (container.reduction_vars()[i] != reduction.accumulator()) 329 continue; 330 reductionSymbol = (*container.reductions())[i].cast<SymbolRefAttr>(); 331 break; 332 } 333 assert(reductionSymbol && 334 "reduction operation must be associated with a declaration"); 335 336 return SymbolTable::lookupNearestSymbolFrom<omp::ReductionDeclareOp>( 337 container, reductionSymbol); 338 } 339 340 /// Populates `reductions` with reduction declarations used in the given loop. 341 static void 342 collectReductionDecls(omp::WsLoopOp loop, 343 SmallVectorImpl<omp::ReductionDeclareOp> &reductions) { 344 Optional<ArrayAttr> attr = loop.reductions(); 345 if (!attr) 346 return; 347 348 reductions.reserve(reductions.size() + loop.getNumReductionVars()); 349 for (auto symbolRef : attr->getAsRange<SymbolRefAttr>()) { 350 reductions.push_back( 351 SymbolTable::lookupNearestSymbolFrom<omp::ReductionDeclareOp>( 352 loop, symbolRef)); 353 } 354 } 355 356 /// Translates the blocks contained in the given region and appends them to at 357 /// the current insertion point of `builder`. The operations of the entry block 358 /// are appended to the current insertion block, which is not expected to have a 359 /// terminator. If set, `continuationBlockArgs` is populated with translated 360 /// values that correspond to the values omp.yield'ed from the region. 361 static LogicalResult inlineConvertOmpRegions( 362 Region ®ion, StringRef blockName, llvm::IRBuilderBase &builder, 363 LLVM::ModuleTranslation &moduleTranslation, 364 SmallVectorImpl<llvm::Value *> *continuationBlockArgs = nullptr) { 365 if (region.empty()) 366 return success(); 367 368 // Special case for single-block regions that don't create additional blocks: 369 // insert operations without creating additional blocks. 370 if (llvm::hasSingleElement(region)) { 371 moduleTranslation.mapBlock(®ion.front(), builder.GetInsertBlock()); 372 if (failed(moduleTranslation.convertBlock( 373 region.front(), /*ignoreArguments=*/true, builder))) 374 return failure(); 375 376 // The continuation arguments are simply the translated terminator operands. 377 if (continuationBlockArgs) 378 llvm::append_range( 379 *continuationBlockArgs, 380 moduleTranslation.lookupValues(region.front().back().getOperands())); 381 382 // Drop the mapping that is no longer necessary so that the same region can 383 // be processed multiple times. 384 moduleTranslation.forgetMapping(region); 385 return success(); 386 } 387 388 // Create the continuation block manually instead of calling splitBlock 389 // because the current insertion block may not have a terminator. 390 llvm::BasicBlock *continuationBlock = 391 llvm::BasicBlock::Create(builder.getContext(), blockName + ".cont", 392 builder.GetInsertBlock()->getParent(), 393 builder.GetInsertBlock()->getNextNode()); 394 builder.CreateBr(continuationBlock); 395 396 LogicalResult bodyGenStatus = success(); 397 SmallVector<llvm::PHINode *> phis; 398 convertOmpOpRegions(region, blockName, *builder.GetInsertBlock(), 399 *continuationBlock, builder, moduleTranslation, 400 bodyGenStatus, &phis); 401 if (failed(bodyGenStatus)) 402 return failure(); 403 if (continuationBlockArgs) 404 llvm::append_range(*continuationBlockArgs, phis); 405 builder.SetInsertPoint(continuationBlock, 406 continuationBlock->getFirstInsertionPt()); 407 return success(); 408 } 409 410 namespace { 411 /// Owning equivalents of OpenMPIRBuilder::(Atomic)ReductionGen that are used to 412 /// store lambdas with capture. 413 using OwningReductionGen = std::function<llvm::OpenMPIRBuilder::InsertPointTy( 414 llvm::OpenMPIRBuilder::InsertPointTy, llvm::Value *, llvm::Value *, 415 llvm::Value *&)>; 416 using OwningAtomicReductionGen = 417 std::function<llvm::OpenMPIRBuilder::InsertPointTy( 418 llvm::OpenMPIRBuilder::InsertPointTy, llvm::Type *, llvm::Value *, 419 llvm::Value *)>; 420 } // namespace 421 422 /// Create an OpenMPIRBuilder-compatible reduction generator for the given 423 /// reduction declaration. The generator uses `builder` but ignores its 424 /// insertion point. 425 static OwningReductionGen 426 makeReductionGen(omp::ReductionDeclareOp decl, llvm::IRBuilderBase &builder, 427 LLVM::ModuleTranslation &moduleTranslation) { 428 // The lambda is mutable because we need access to non-const methods of decl 429 // (which aren't actually mutating it), and we must capture decl by-value to 430 // avoid the dangling reference after the parent function returns. 431 OwningReductionGen gen = 432 [&, decl](llvm::OpenMPIRBuilder::InsertPointTy insertPoint, 433 llvm::Value *lhs, llvm::Value *rhs, 434 llvm::Value *&result) mutable { 435 Region &reductionRegion = decl.reductionRegion(); 436 moduleTranslation.mapValue(reductionRegion.front().getArgument(0), lhs); 437 moduleTranslation.mapValue(reductionRegion.front().getArgument(1), rhs); 438 builder.restoreIP(insertPoint); 439 SmallVector<llvm::Value *> phis; 440 if (failed(inlineConvertOmpRegions(reductionRegion, 441 "omp.reduction.nonatomic.body", 442 builder, moduleTranslation, &phis))) 443 return llvm::OpenMPIRBuilder::InsertPointTy(); 444 assert(phis.size() == 1); 445 result = phis[0]; 446 return builder.saveIP(); 447 }; 448 return gen; 449 } 450 451 /// Create an OpenMPIRBuilder-compatible atomic reduction generator for the 452 /// given reduction declaration. The generator uses `builder` but ignores its 453 /// insertion point. Returns null if there is no atomic region available in the 454 /// reduction declaration. 455 static OwningAtomicReductionGen 456 makeAtomicReductionGen(omp::ReductionDeclareOp decl, 457 llvm::IRBuilderBase &builder, 458 LLVM::ModuleTranslation &moduleTranslation) { 459 if (decl.atomicReductionRegion().empty()) 460 return OwningAtomicReductionGen(); 461 462 // The lambda is mutable because we need access to non-const methods of decl 463 // (which aren't actually mutating it), and we must capture decl by-value to 464 // avoid the dangling reference after the parent function returns. 465 OwningAtomicReductionGen atomicGen = 466 [&, decl](llvm::OpenMPIRBuilder::InsertPointTy insertPoint, llvm::Type *, 467 llvm::Value *lhs, llvm::Value *rhs) mutable { 468 Region &atomicRegion = decl.atomicReductionRegion(); 469 moduleTranslation.mapValue(atomicRegion.front().getArgument(0), lhs); 470 moduleTranslation.mapValue(atomicRegion.front().getArgument(1), rhs); 471 builder.restoreIP(insertPoint); 472 SmallVector<llvm::Value *> phis; 473 if (failed(inlineConvertOmpRegions(atomicRegion, 474 "omp.reduction.atomic.body", builder, 475 moduleTranslation, &phis))) 476 return llvm::OpenMPIRBuilder::InsertPointTy(); 477 assert(phis.empty()); 478 return builder.saveIP(); 479 }; 480 return atomicGen; 481 } 482 483 /// Converts an OpenMP 'ordered' operation into LLVM IR using OpenMPIRBuilder. 484 static LogicalResult 485 convertOmpOrdered(Operation &opInst, llvm::IRBuilderBase &builder, 486 LLVM::ModuleTranslation &moduleTranslation) { 487 auto orderedOp = cast<omp::OrderedOp>(opInst); 488 489 omp::ClauseDepend dependType = 490 *omp::symbolizeClauseDepend(orderedOp.depend_type_valAttr().getValue()); 491 bool isDependSource = dependType == omp::ClauseDepend::dependsource; 492 unsigned numLoops = orderedOp.num_loops_val().getValue(); 493 SmallVector<llvm::Value *> vecValues = 494 moduleTranslation.lookupValues(orderedOp.depend_vec_vars()); 495 496 llvm::OpenMPIRBuilder::LocationDescription ompLoc( 497 builder.saveIP(), builder.getCurrentDebugLocation()); 498 size_t indexVecValues = 0; 499 while (indexVecValues < vecValues.size()) { 500 SmallVector<llvm::Value *> storeValues; 501 storeValues.reserve(numLoops); 502 for (unsigned i = 0; i < numLoops; i++) { 503 storeValues.push_back(vecValues[indexVecValues]); 504 indexVecValues++; 505 } 506 builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createOrderedDepend( 507 ompLoc, findAllocaInsertPoint(builder, moduleTranslation), numLoops, 508 storeValues, ".cnt.addr", isDependSource)); 509 } 510 return success(); 511 } 512 513 /// Converts an OpenMP 'ordered_region' operation into LLVM IR using 514 /// OpenMPIRBuilder. 515 static LogicalResult 516 convertOmpOrderedRegion(Operation &opInst, llvm::IRBuilderBase &builder, 517 LLVM::ModuleTranslation &moduleTranslation) { 518 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 519 auto orderedRegionOp = cast<omp::OrderedRegionOp>(opInst); 520 521 // TODO: The code generation for ordered simd directive is not supported yet. 522 if (orderedRegionOp.simd()) 523 return failure(); 524 525 // TODO: support error propagation in OpenMPIRBuilder and use it instead of 526 // relying on captured variables. 527 LogicalResult bodyGenStatus = success(); 528 529 auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP, 530 llvm::BasicBlock &continuationBlock) { 531 // OrderedOp has only one region associated with it. 532 auto ®ion = cast<omp::OrderedRegionOp>(opInst).getRegion(); 533 convertOmpOpRegions(region, "omp.ordered.region", *codeGenIP.getBlock(), 534 continuationBlock, builder, moduleTranslation, 535 bodyGenStatus); 536 }; 537 538 // TODO: Perform finalization actions for variables. This has to be 539 // called for variables which have destructors/finalizers. 540 auto finiCB = [&](InsertPointTy codeGenIP) {}; 541 542 llvm::OpenMPIRBuilder::LocationDescription ompLoc( 543 builder.saveIP(), builder.getCurrentDebugLocation()); 544 builder.restoreIP( 545 moduleTranslation.getOpenMPBuilder()->createOrderedThreadsSimd( 546 ompLoc, bodyGenCB, finiCB, !orderedRegionOp.simd())); 547 return bodyGenStatus; 548 } 549 550 /// Converts an OpenMP workshare loop into LLVM IR using OpenMPIRBuilder. 551 static LogicalResult 552 convertOmpWsLoop(Operation &opInst, llvm::IRBuilderBase &builder, 553 LLVM::ModuleTranslation &moduleTranslation) { 554 auto loop = cast<omp::WsLoopOp>(opInst); 555 // TODO: this should be in the op verifier instead. 556 if (loop.lowerBound().empty()) 557 return failure(); 558 559 // Static is the default. 560 omp::ClauseScheduleKind schedule = omp::ClauseScheduleKind::Static; 561 if (loop.schedule_val().hasValue()) 562 schedule = 563 *omp::symbolizeClauseScheduleKind(loop.schedule_val().getValue()); 564 565 // Find the loop configuration. 566 llvm::Value *step = moduleTranslation.lookupValue(loop.step()[0]); 567 llvm::Type *ivType = step->getType(); 568 llvm::Value *chunk = 569 loop.schedule_chunk_var() 570 ? moduleTranslation.lookupValue(loop.schedule_chunk_var()) 571 : llvm::ConstantInt::get(ivType, 1); 572 573 SmallVector<omp::ReductionDeclareOp> reductionDecls; 574 collectReductionDecls(loop, reductionDecls); 575 llvm::OpenMPIRBuilder::InsertPointTy allocaIP = 576 findAllocaInsertPoint(builder, moduleTranslation); 577 578 // Allocate space for privatized reduction variables. 579 SmallVector<llvm::Value *> privateReductionVariables; 580 DenseMap<Value, llvm::Value *> reductionVariableMap; 581 unsigned numReductions = loop.getNumReductionVars(); 582 privateReductionVariables.reserve(numReductions); 583 if (numReductions != 0) { 584 llvm::IRBuilderBase::InsertPointGuard guard(builder); 585 builder.restoreIP(allocaIP); 586 for (unsigned i = 0; i < numReductions; ++i) { 587 auto reductionType = 588 loop.reduction_vars()[i].getType().cast<LLVM::LLVMPointerType>(); 589 llvm::Value *var = builder.CreateAlloca( 590 moduleTranslation.convertType(reductionType.getElementType())); 591 privateReductionVariables.push_back(var); 592 reductionVariableMap.try_emplace(loop.reduction_vars()[i], var); 593 } 594 } 595 596 // Store the mapping between reduction variables and their private copies on 597 // ModuleTranslation stack. It can be then recovered when translating 598 // omp.reduce operations in a separate call. 599 LLVM::ModuleTranslation::SaveStack<OpenMPVarMappingStackFrame> mappingGuard( 600 moduleTranslation, reductionVariableMap); 601 602 // Before the loop, store the initial values of reductions into reduction 603 // variables. Although this could be done after allocas, we don't want to mess 604 // up with the alloca insertion point. 605 for (unsigned i = 0; i < numReductions; ++i) { 606 SmallVector<llvm::Value *> phis; 607 if (failed(inlineConvertOmpRegions(reductionDecls[i].initializerRegion(), 608 "omp.reduction.neutral", builder, 609 moduleTranslation, &phis))) 610 return failure(); 611 assert(phis.size() == 1 && "expected one value to be yielded from the " 612 "reduction neutral element declaration region"); 613 builder.CreateStore(phis[0], privateReductionVariables[i]); 614 } 615 616 // Set up the source location value for OpenMP runtime. 617 llvm::DISubprogram *subprogram = 618 builder.GetInsertBlock()->getParent()->getSubprogram(); 619 const llvm::DILocation *diLoc = 620 moduleTranslation.translateLoc(opInst.getLoc(), subprogram); 621 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder.saveIP(), 622 llvm::DebugLoc(diLoc)); 623 624 // Generator of the canonical loop body. 625 // TODO: support error propagation in OpenMPIRBuilder and use it instead of 626 // relying on captured variables. 627 SmallVector<llvm::CanonicalLoopInfo *> loopInfos; 628 SmallVector<llvm::OpenMPIRBuilder::InsertPointTy> bodyInsertPoints; 629 LogicalResult bodyGenStatus = success(); 630 auto bodyGen = [&](llvm::OpenMPIRBuilder::InsertPointTy ip, llvm::Value *iv) { 631 // Make sure further conversions know about the induction variable. 632 moduleTranslation.mapValue( 633 loop.getRegion().front().getArgument(loopInfos.size()), iv); 634 635 // Capture the body insertion point for use in nested loops. BodyIP of the 636 // CanonicalLoopInfo always points to the beginning of the entry block of 637 // the body. 638 bodyInsertPoints.push_back(ip); 639 640 if (loopInfos.size() != loop.getNumLoops() - 1) 641 return; 642 643 // Convert the body of the loop. 644 llvm::BasicBlock *entryBlock = ip.getBlock(); 645 llvm::BasicBlock *exitBlock = 646 entryBlock->splitBasicBlock(ip.getPoint(), "omp.wsloop.exit"); 647 convertOmpOpRegions(loop.region(), "omp.wsloop.region", *entryBlock, 648 *exitBlock, builder, moduleTranslation, bodyGenStatus); 649 }; 650 651 // Delegate actual loop construction to the OpenMP IRBuilder. 652 // TODO: this currently assumes WsLoop is semantically similar to SCF loop, 653 // i.e. it has a positive step, uses signed integer semantics. Reconsider 654 // this code when WsLoop clearly supports more cases. 655 llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder(); 656 for (unsigned i = 0, e = loop.getNumLoops(); i < e; ++i) { 657 llvm::Value *lowerBound = 658 moduleTranslation.lookupValue(loop.lowerBound()[i]); 659 llvm::Value *upperBound = 660 moduleTranslation.lookupValue(loop.upperBound()[i]); 661 llvm::Value *step = moduleTranslation.lookupValue(loop.step()[i]); 662 663 // Make sure loop trip count are emitted in the preheader of the outermost 664 // loop at the latest so that they are all available for the new collapsed 665 // loop will be created below. 666 llvm::OpenMPIRBuilder::LocationDescription loc = ompLoc; 667 llvm::OpenMPIRBuilder::InsertPointTy computeIP = ompLoc.IP; 668 if (i != 0) { 669 loc = llvm::OpenMPIRBuilder::LocationDescription(bodyInsertPoints.back(), 670 llvm::DebugLoc(diLoc)); 671 computeIP = loopInfos.front()->getPreheaderIP(); 672 } 673 loopInfos.push_back(ompBuilder->createCanonicalLoop( 674 loc, bodyGen, lowerBound, upperBound, step, 675 /*IsSigned=*/true, loop.inclusive(), computeIP)); 676 677 if (failed(bodyGenStatus)) 678 return failure(); 679 } 680 681 // Collapse loops. Store the insertion point because LoopInfos may get 682 // invalidated. 683 llvm::IRBuilderBase::InsertPoint afterIP = loopInfos.front()->getAfterIP(); 684 llvm::CanonicalLoopInfo *loopInfo = 685 ompBuilder->collapseLoops(diLoc, loopInfos, {}); 686 687 allocaIP = findAllocaInsertPoint(builder, moduleTranslation); 688 689 bool isSimd = loop.simd_modifier(); 690 691 if (schedule == omp::ClauseScheduleKind::Static) { 692 ompBuilder->applyStaticWorkshareLoop(ompLoc.DL, loopInfo, allocaIP, 693 !loop.nowait(), chunk); 694 } else { 695 llvm::omp::OMPScheduleType schedType; 696 switch (schedule) { 697 case omp::ClauseScheduleKind::Dynamic: 698 schedType = llvm::omp::OMPScheduleType::DynamicChunked; 699 break; 700 case omp::ClauseScheduleKind::Guided: 701 if (isSimd) 702 schedType = llvm::omp::OMPScheduleType::GuidedSimd; 703 else 704 schedType = llvm::omp::OMPScheduleType::GuidedChunked; 705 break; 706 case omp::ClauseScheduleKind::Auto: 707 schedType = llvm::omp::OMPScheduleType::Auto; 708 break; 709 case omp::ClauseScheduleKind::Runtime: 710 if (isSimd) 711 schedType = llvm::omp::OMPScheduleType::RuntimeSimd; 712 else 713 schedType = llvm::omp::OMPScheduleType::Runtime; 714 break; 715 default: 716 llvm_unreachable("Unknown schedule value"); 717 break; 718 } 719 720 if (loop.schedule_modifier().hasValue()) { 721 omp::ScheduleModifier modifier = 722 *omp::symbolizeScheduleModifier(loop.schedule_modifier().getValue()); 723 switch (modifier) { 724 case omp::ScheduleModifier::monotonic: 725 schedType |= llvm::omp::OMPScheduleType::ModifierMonotonic; 726 break; 727 case omp::ScheduleModifier::nonmonotonic: 728 schedType |= llvm::omp::OMPScheduleType::ModifierNonmonotonic; 729 break; 730 default: 731 // Nothing to do here. 732 break; 733 } 734 } 735 afterIP = ompBuilder->applyDynamicWorkshareLoop( 736 ompLoc.DL, loopInfo, allocaIP, schedType, !loop.nowait(), chunk); 737 } 738 739 // Continue building IR after the loop. Note that the LoopInfo returned by 740 // `collapseLoops` points inside the outermost loop and is intended for 741 // potential further loop transformations. Use the insertion point stored 742 // before collapsing loops instead. 743 builder.restoreIP(afterIP); 744 745 // Process the reductions if required. 746 if (numReductions == 0) 747 return success(); 748 749 // Create the reduction generators. We need to own them here because 750 // ReductionInfo only accepts references to the generators. 751 SmallVector<OwningReductionGen> owningReductionGens; 752 SmallVector<OwningAtomicReductionGen> owningAtomicReductionGens; 753 for (unsigned i = 0; i < numReductions; ++i) { 754 owningReductionGens.push_back( 755 makeReductionGen(reductionDecls[i], builder, moduleTranslation)); 756 owningAtomicReductionGens.push_back( 757 makeAtomicReductionGen(reductionDecls[i], builder, moduleTranslation)); 758 } 759 760 // Collect the reduction information. 761 SmallVector<llvm::OpenMPIRBuilder::ReductionInfo> reductionInfos; 762 reductionInfos.reserve(numReductions); 763 for (unsigned i = 0; i < numReductions; ++i) { 764 llvm::OpenMPIRBuilder::AtomicReductionGenTy atomicGen = nullptr; 765 if (owningAtomicReductionGens[i]) 766 atomicGen = owningAtomicReductionGens[i]; 767 llvm::Value *variable = 768 moduleTranslation.lookupValue(loop.reduction_vars()[i]); 769 reductionInfos.push_back({variable->getType()->getPointerElementType(), 770 variable, privateReductionVariables[i], 771 owningReductionGens[i], atomicGen}); 772 } 773 774 // The call to createReductions below expects the block to have a 775 // terminator. Create an unreachable instruction to serve as terminator 776 // and remove it later. 777 llvm::UnreachableInst *tempTerminator = builder.CreateUnreachable(); 778 builder.SetInsertPoint(tempTerminator); 779 llvm::OpenMPIRBuilder::InsertPointTy contInsertPoint = 780 ompBuilder->createReductions(builder.saveIP(), allocaIP, reductionInfos, 781 loop.nowait()); 782 if (!contInsertPoint.getBlock()) 783 return loop->emitOpError() << "failed to convert reductions"; 784 auto nextInsertionPoint = 785 ompBuilder->createBarrier(contInsertPoint, llvm::omp::OMPD_for); 786 tempTerminator->eraseFromParent(); 787 builder.restoreIP(nextInsertionPoint); 788 789 return success(); 790 } 791 792 // Convert an Atomic Ordering attribute to llvm::AtomicOrdering. 793 llvm::AtomicOrdering convertAtomicOrdering(Optional<StringRef> AOAttr) { 794 if (!AOAttr.hasValue()) 795 return llvm::AtomicOrdering::Monotonic; // Default Memory Ordering 796 797 return StringSwitch<llvm::AtomicOrdering>(AOAttr.getValue()) 798 .Case("seq_cst", llvm::AtomicOrdering::SequentiallyConsistent) 799 .Case("acq_rel", llvm::AtomicOrdering::AcquireRelease) 800 .Case("acquire", llvm::AtomicOrdering::Acquire) 801 .Case("release", llvm::AtomicOrdering::Release) 802 .Case("relaxed", llvm::AtomicOrdering::Monotonic) 803 .Default(llvm::AtomicOrdering::Monotonic); 804 } 805 806 // Convert omp.atomic.read operation to LLVM IR. 807 static LogicalResult 808 convertOmpAtomicRead(Operation &opInst, llvm::IRBuilderBase &builder, 809 LLVM::ModuleTranslation &moduleTranslation) { 810 811 auto readOp = cast<omp::AtomicReadOp>(opInst); 812 llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder(); 813 814 // Set up the source location value for OpenMP runtime. 815 llvm::DISubprogram *subprogram = 816 builder.GetInsertBlock()->getParent()->getSubprogram(); 817 const llvm::DILocation *diLoc = 818 moduleTranslation.translateLoc(opInst.getLoc(), subprogram); 819 llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder.saveIP(), 820 llvm::DebugLoc(diLoc)); 821 llvm::AtomicOrdering AO = convertAtomicOrdering(readOp.memory_order()); 822 llvm::Value *address = moduleTranslation.lookupValue(readOp.address()); 823 llvm::OpenMPIRBuilder::InsertPointTy currentIP = builder.saveIP(); 824 825 // Insert alloca for result. 826 llvm::OpenMPIRBuilder::InsertPointTy allocaIP = 827 findAllocaInsertPoint(builder, moduleTranslation); 828 builder.restoreIP(allocaIP); 829 llvm::Value *v = builder.CreateAlloca( 830 moduleTranslation.convertType(readOp.getResult().getType())); 831 moduleTranslation.mapValue(readOp.getResult(), v); 832 833 // Restore the IP and insert Atomic Read. 834 builder.restoreIP(currentIP); 835 llvm::OpenMPIRBuilder::AtomicOpValue V = {v, false, false}; 836 llvm::OpenMPIRBuilder::AtomicOpValue X = {address, false, false}; 837 builder.restoreIP(ompBuilder->createAtomicRead(ompLoc, X, V, AO)); 838 return success(); 839 } 840 841 /// Converts an OpenMP reduction operation using OpenMPIRBuilder. Expects the 842 /// mapping between reduction variables and their private equivalents to have 843 /// been stored on the ModuleTranslation stack. Currently only supports 844 /// reduction within WsLoopOp, but can be easily extended. 845 static LogicalResult 846 convertOmpReductionOp(omp::ReductionOp reductionOp, 847 llvm::IRBuilderBase &builder, 848 LLVM::ModuleTranslation &moduleTranslation) { 849 // Find the declaration that corresponds to the reduction op. 850 auto reductionContainer = reductionOp->getParentOfType<omp::WsLoopOp>(); 851 omp::ReductionDeclareOp declaration = 852 findReductionDecl(reductionContainer, reductionOp); 853 assert(declaration && "could not find reduction declaration"); 854 855 // Retrieve the mapping between reduction variables and their private 856 // equivalents. 857 const DenseMap<Value, llvm::Value *> *reductionVariableMap = nullptr; 858 moduleTranslation.stackWalk<OpenMPVarMappingStackFrame>( 859 [&](const OpenMPVarMappingStackFrame &frame) { 860 reductionVariableMap = &frame.mapping; 861 return WalkResult::interrupt(); 862 }); 863 assert(reductionVariableMap && "couldn't find private reduction variables"); 864 865 // Translate the reduction operation by emitting the body of the corresponding 866 // reduction declaration. 867 Region &reductionRegion = declaration.reductionRegion(); 868 llvm::Value *privateReductionVar = 869 reductionVariableMap->lookup(reductionOp.accumulator()); 870 llvm::Value *reductionVal = builder.CreateLoad( 871 moduleTranslation.convertType(reductionOp.operand().getType()), 872 privateReductionVar); 873 874 moduleTranslation.mapValue(reductionRegion.front().getArgument(0), 875 reductionVal); 876 moduleTranslation.mapValue( 877 reductionRegion.front().getArgument(1), 878 moduleTranslation.lookupValue(reductionOp.operand())); 879 880 SmallVector<llvm::Value *> phis; 881 if (failed(inlineConvertOmpRegions(reductionRegion, "omp.reduction.body", 882 builder, moduleTranslation, &phis))) 883 return failure(); 884 assert(phis.size() == 1 && "expected one value to be yielded from " 885 "the reduction body declaration region"); 886 builder.CreateStore(phis[0], privateReductionVar); 887 return success(); 888 } 889 890 namespace { 891 892 /// Implementation of the dialect interface that converts operations belonging 893 /// to the OpenMP dialect to LLVM IR. 894 class OpenMPDialectLLVMIRTranslationInterface 895 : public LLVMTranslationDialectInterface { 896 public: 897 using LLVMTranslationDialectInterface::LLVMTranslationDialectInterface; 898 899 /// Translates the given operation to LLVM IR using the provided IR builder 900 /// and saving the state in `moduleTranslation`. 901 LogicalResult 902 convertOperation(Operation *op, llvm::IRBuilderBase &builder, 903 LLVM::ModuleTranslation &moduleTranslation) const final; 904 }; 905 906 } // namespace 907 908 /// Given an OpenMP MLIR operation, create the corresponding LLVM IR 909 /// (including OpenMP runtime calls). 910 LogicalResult OpenMPDialectLLVMIRTranslationInterface::convertOperation( 911 Operation *op, llvm::IRBuilderBase &builder, 912 LLVM::ModuleTranslation &moduleTranslation) const { 913 914 llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder(); 915 916 return llvm::TypeSwitch<Operation *, LogicalResult>(op) 917 .Case([&](omp::BarrierOp) { 918 ompBuilder->createBarrier(builder.saveIP(), llvm::omp::OMPD_barrier); 919 return success(); 920 }) 921 .Case([&](omp::TaskwaitOp) { 922 ompBuilder->createTaskwait(builder.saveIP()); 923 return success(); 924 }) 925 .Case([&](omp::TaskyieldOp) { 926 ompBuilder->createTaskyield(builder.saveIP()); 927 return success(); 928 }) 929 .Case([&](omp::FlushOp) { 930 // No support in Openmp runtime function (__kmpc_flush) to accept 931 // the argument list. 932 // OpenMP standard states the following: 933 // "An implementation may implement a flush with a list by ignoring 934 // the list, and treating it the same as a flush without a list." 935 // 936 // The argument list is discarded so that, flush with a list is treated 937 // same as a flush without a list. 938 ompBuilder->createFlush(builder.saveIP()); 939 return success(); 940 }) 941 .Case([&](omp::ParallelOp) { 942 return convertOmpParallel(*op, builder, moduleTranslation); 943 }) 944 .Case([&](omp::ReductionOp reductionOp) { 945 return convertOmpReductionOp(reductionOp, builder, moduleTranslation); 946 }) 947 .Case([&](omp::MasterOp) { 948 return convertOmpMaster(*op, builder, moduleTranslation); 949 }) 950 .Case([&](omp::CriticalOp) { 951 return convertOmpCritical(*op, builder, moduleTranslation); 952 }) 953 .Case([&](omp::OrderedRegionOp) { 954 return convertOmpOrderedRegion(*op, builder, moduleTranslation); 955 }) 956 .Case([&](omp::OrderedOp) { 957 return convertOmpOrdered(*op, builder, moduleTranslation); 958 }) 959 .Case([&](omp::WsLoopOp) { 960 return convertOmpWsLoop(*op, builder, moduleTranslation); 961 }) 962 .Case([&](omp::AtomicReadOp) { 963 return convertOmpAtomicRead(*op, builder, moduleTranslation); 964 }) 965 .Case<omp::YieldOp, omp::TerminatorOp, omp::ReductionDeclareOp, 966 omp::CriticalDeclareOp>([](auto op) { 967 // `yield` and `terminator` can be just omitted. The block structure 968 // was created in the region that handles their parent operation. 969 // `reduction.declare` will be used by reductions and is not 970 // converted directly, skip it. 971 // `critical.declare` is only used to declare names of critical 972 // sections which will be used by `critical` ops and hence can be 973 // ignored for lowering. The OpenMP IRBuilder will create unique 974 // name for critical section names. 975 return success(); 976 }) 977 .Default([&](Operation *inst) { 978 return inst->emitError("unsupported OpenMP operation: ") 979 << inst->getName(); 980 }); 981 } 982 983 void mlir::registerOpenMPDialectTranslation(DialectRegistry ®istry) { 984 registry.insert<omp::OpenMPDialect>(); 985 registry.addDialectInterface<omp::OpenMPDialect, 986 OpenMPDialectLLVMIRTranslationInterface>(); 987 } 988 989 void mlir::registerOpenMPDialectTranslation(MLIRContext &context) { 990 DialectRegistry registry; 991 registerOpenMPDialectTranslation(registry); 992 context.appendDialectRegistry(registry); 993 } 994