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