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 &region, 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 &region = 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 &region = 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 &region, 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(&region.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 &region = 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.private_vars().empty() ||
584       !sectionsOp.firstprivate_vars().empty() ||
585       !sectionsOp.lastprivate_vars().empty() ||
586       !sectionsOp.reduction_vars().empty() || sectionsOp.reductions() ||
587       !sectionsOp.allocate_vars().empty() ||
588       !sectionsOp.allocators_vars().empty())
589     return emitError(sectionsOp.getLoc())
590            << "private, firstprivate, lastprivate, reduction and allocate "
591               "clauses are not supported for sections construct";
592 
593   LogicalResult bodyGenStatus = success();
594   SmallVector<StorableBodyGenCallbackTy> sectionCBs;
595 
596   for (Operation &op : *sectionsOp.region().begin()) {
597     auto sectionOp = dyn_cast<omp::SectionOp>(op);
598     if (!sectionOp) // omp.terminator
599       continue;
600 
601     Region &region = sectionOp.region();
602     auto sectionCB = [&region, &builder, &moduleTranslation, &bodyGenStatus](
603                          InsertPointTy allocaIP, InsertPointTy codeGenIP,
604                          llvm::BasicBlock &finiBB) {
605       builder.restoreIP(codeGenIP);
606       builder.CreateBr(&finiBB);
607       convertOmpOpRegions(region, "omp.section.region", *codeGenIP.getBlock(),
608                           finiBB, builder, moduleTranslation, bodyGenStatus);
609     };
610     sectionCBs.push_back(sectionCB);
611   }
612 
613   // No sections within omp.sections operation - skip generation. This situation
614   // is only possible if there is only a terminator operation inside the
615   // sections operation
616   if (sectionCBs.empty())
617     return success();
618 
619   assert(isa<omp::SectionOp>(*sectionsOp.region().op_begin()));
620 
621   // TODO: Perform appropriate actions according to the data-sharing
622   // attribute (shared, private, firstprivate, ...) of variables.
623   // Currently defaults to shared.
624   auto privCB = [&](InsertPointTy, InsertPointTy codeGenIP, llvm::Value &,
625                     llvm::Value &vPtr,
626                     llvm::Value *&replacementValue) -> InsertPointTy {
627     replacementValue = &vPtr;
628     return codeGenIP;
629   };
630 
631   // TODO: Perform finalization actions for variables. This has to be
632   // called for variables which have destructors/finalizers.
633   auto finiCB = [&](InsertPointTy codeGenIP) {};
634 
635   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
636   builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createSections(
637       ompLoc, findAllocaInsertPoint(builder, moduleTranslation), sectionCBs,
638       privCB, finiCB, false, sectionsOp.nowait()));
639   return bodyGenStatus;
640 }
641 
642 /// Converts an OpenMP workshare loop into LLVM IR using OpenMPIRBuilder.
643 static LogicalResult
644 convertOmpWsLoop(Operation &opInst, llvm::IRBuilderBase &builder,
645                  LLVM::ModuleTranslation &moduleTranslation) {
646   auto loop = cast<omp::WsLoopOp>(opInst);
647   // TODO: this should be in the op verifier instead.
648   if (loop.lowerBound().empty())
649     return failure();
650 
651   // Static is the default.
652   auto schedule =
653       loop.schedule_val().getValueOr(omp::ClauseScheduleKind::Static);
654 
655   // Find the loop configuration.
656   llvm::Value *step = moduleTranslation.lookupValue(loop.step()[0]);
657   llvm::Type *ivType = step->getType();
658   llvm::Value *chunk = nullptr;
659   if (loop.schedule_chunk_var()) {
660     llvm::Value *chunkVar =
661         moduleTranslation.lookupValue(loop.schedule_chunk_var());
662     llvm::Type *chunkVarType = chunkVar->getType();
663     assert(chunkVarType->isIntegerTy() &&
664            "chunk size must be one integer expression");
665     if (chunkVarType->getIntegerBitWidth() < ivType->getIntegerBitWidth())
666       chunk = builder.CreateSExt(chunkVar, ivType);
667     else if (chunkVarType->getIntegerBitWidth() > ivType->getIntegerBitWidth())
668       chunk = builder.CreateTrunc(chunkVar, ivType);
669     else
670       chunk = chunkVar;
671   }
672 
673   SmallVector<omp::ReductionDeclareOp> reductionDecls;
674   collectReductionDecls(loop, reductionDecls);
675   llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
676       findAllocaInsertPoint(builder, moduleTranslation);
677 
678   // Allocate space for privatized reduction variables.
679   SmallVector<llvm::Value *> privateReductionVariables;
680   DenseMap<Value, llvm::Value *> reductionVariableMap;
681   unsigned numReductions = loop.getNumReductionVars();
682   privateReductionVariables.reserve(numReductions);
683   if (numReductions != 0) {
684     llvm::IRBuilderBase::InsertPointGuard guard(builder);
685     builder.restoreIP(allocaIP);
686     for (unsigned i = 0; i < numReductions; ++i) {
687       auto reductionType =
688           loop.reduction_vars()[i].getType().cast<LLVM::LLVMPointerType>();
689       llvm::Value *var = builder.CreateAlloca(
690           moduleTranslation.convertType(reductionType.getElementType()));
691       privateReductionVariables.push_back(var);
692       reductionVariableMap.try_emplace(loop.reduction_vars()[i], var);
693     }
694   }
695 
696   // Store the mapping between reduction variables and their private copies on
697   // ModuleTranslation stack. It can be then recovered when translating
698   // omp.reduce operations in a separate call.
699   LLVM::ModuleTranslation::SaveStack<OpenMPVarMappingStackFrame> mappingGuard(
700       moduleTranslation, reductionVariableMap);
701 
702   // Before the loop, store the initial values of reductions into reduction
703   // variables. Although this could be done after allocas, we don't want to mess
704   // up with the alloca insertion point.
705   for (unsigned i = 0; i < numReductions; ++i) {
706     SmallVector<llvm::Value *> phis;
707     if (failed(inlineConvertOmpRegions(reductionDecls[i].initializerRegion(),
708                                        "omp.reduction.neutral", builder,
709                                        moduleTranslation, &phis)))
710       return failure();
711     assert(phis.size() == 1 && "expected one value to be yielded from the "
712                                "reduction neutral element declaration region");
713     builder.CreateStore(phis[0], privateReductionVariables[i]);
714   }
715 
716   // Set up the source location value for OpenMP runtime.
717   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
718 
719   // Generator of the canonical loop body.
720   // TODO: support error propagation in OpenMPIRBuilder and use it instead of
721   // relying on captured variables.
722   SmallVector<llvm::CanonicalLoopInfo *> loopInfos;
723   SmallVector<llvm::OpenMPIRBuilder::InsertPointTy> bodyInsertPoints;
724   LogicalResult bodyGenStatus = success();
725   auto bodyGen = [&](llvm::OpenMPIRBuilder::InsertPointTy ip, llvm::Value *iv) {
726     // Make sure further conversions know about the induction variable.
727     moduleTranslation.mapValue(
728         loop.getRegion().front().getArgument(loopInfos.size()), iv);
729 
730     // Capture the body insertion point for use in nested loops. BodyIP of the
731     // CanonicalLoopInfo always points to the beginning of the entry block of
732     // the body.
733     bodyInsertPoints.push_back(ip);
734 
735     if (loopInfos.size() != loop.getNumLoops() - 1)
736       return;
737 
738     // Convert the body of the loop.
739     llvm::BasicBlock *entryBlock = ip.getBlock();
740     llvm::BasicBlock *exitBlock =
741         entryBlock->splitBasicBlock(ip.getPoint(), "omp.wsloop.exit");
742     convertOmpOpRegions(loop.region(), "omp.wsloop.region", *entryBlock,
743                         *exitBlock, builder, moduleTranslation, bodyGenStatus);
744   };
745 
746   // Delegate actual loop construction to the OpenMP IRBuilder.
747   // TODO: this currently assumes WsLoop is semantically similar to SCF loop,
748   // i.e. it has a positive step, uses signed integer semantics. Reconsider
749   // this code when WsLoop clearly supports more cases.
750   llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
751   for (unsigned i = 0, e = loop.getNumLoops(); i < e; ++i) {
752     llvm::Value *lowerBound =
753         moduleTranslation.lookupValue(loop.lowerBound()[i]);
754     llvm::Value *upperBound =
755         moduleTranslation.lookupValue(loop.upperBound()[i]);
756     llvm::Value *step = moduleTranslation.lookupValue(loop.step()[i]);
757 
758     // Make sure loop trip count are emitted in the preheader of the outermost
759     // loop at the latest so that they are all available for the new collapsed
760     // loop will be created below.
761     llvm::OpenMPIRBuilder::LocationDescription loc = ompLoc;
762     llvm::OpenMPIRBuilder::InsertPointTy computeIP = ompLoc.IP;
763     if (i != 0) {
764       loc = llvm::OpenMPIRBuilder::LocationDescription(bodyInsertPoints.back());
765       computeIP = loopInfos.front()->getPreheaderIP();
766     }
767     loopInfos.push_back(ompBuilder->createCanonicalLoop(
768         loc, bodyGen, lowerBound, upperBound, step,
769         /*IsSigned=*/true, loop.inclusive(), computeIP));
770 
771     if (failed(bodyGenStatus))
772       return failure();
773   }
774 
775   // Collapse loops. Store the insertion point because LoopInfos may get
776   // invalidated.
777   llvm::IRBuilderBase::InsertPoint afterIP = loopInfos.front()->getAfterIP();
778   llvm::CanonicalLoopInfo *loopInfo =
779       ompBuilder->collapseLoops(ompLoc.DL, loopInfos, {});
780 
781   allocaIP = findAllocaInsertPoint(builder, moduleTranslation);
782 
783   bool isSimd = loop.simd_modifier();
784 
785   if (schedule == omp::ClauseScheduleKind::Static) {
786     ompBuilder->applyStaticWorkshareLoop(ompLoc.DL, loopInfo, allocaIP,
787                                          !loop.nowait(), chunk);
788   } else {
789     llvm::omp::OMPScheduleType schedType;
790     switch (schedule) {
791     case omp::ClauseScheduleKind::Dynamic:
792       schedType = llvm::omp::OMPScheduleType::DynamicChunked;
793       break;
794     case omp::ClauseScheduleKind::Guided:
795       if (isSimd)
796         schedType = llvm::omp::OMPScheduleType::GuidedSimd;
797       else
798         schedType = llvm::omp::OMPScheduleType::GuidedChunked;
799       break;
800     case omp::ClauseScheduleKind::Auto:
801       schedType = llvm::omp::OMPScheduleType::Auto;
802       break;
803     case omp::ClauseScheduleKind::Runtime:
804       if (isSimd)
805         schedType = llvm::omp::OMPScheduleType::RuntimeSimd;
806       else
807         schedType = llvm::omp::OMPScheduleType::Runtime;
808       break;
809     default:
810       llvm_unreachable("Unknown schedule value");
811       break;
812     }
813 
814     if (Optional<omp::ScheduleModifier> modifier = loop.schedule_modifier()) {
815       switch (*modifier) {
816       case omp::ScheduleModifier::monotonic:
817         schedType |= llvm::omp::OMPScheduleType::ModifierMonotonic;
818         break;
819       case omp::ScheduleModifier::nonmonotonic:
820         schedType |= llvm::omp::OMPScheduleType::ModifierNonmonotonic;
821         break;
822       default:
823         // Nothing to do here.
824         break;
825       }
826     }
827     afterIP = ompBuilder->applyDynamicWorkshareLoop(
828         ompLoc.DL, loopInfo, allocaIP, schedType, !loop.nowait(), chunk);
829   }
830 
831   // Continue building IR after the loop. Note that the LoopInfo returned by
832   // `collapseLoops` points inside the outermost loop and is intended for
833   // potential further loop transformations. Use the insertion point stored
834   // before collapsing loops instead.
835   builder.restoreIP(afterIP);
836 
837   // Process the reductions if required.
838   if (numReductions == 0)
839     return success();
840 
841   // Create the reduction generators. We need to own them here because
842   // ReductionInfo only accepts references to the generators.
843   SmallVector<OwningReductionGen> owningReductionGens;
844   SmallVector<OwningAtomicReductionGen> owningAtomicReductionGens;
845   for (unsigned i = 0; i < numReductions; ++i) {
846     owningReductionGens.push_back(
847         makeReductionGen(reductionDecls[i], builder, moduleTranslation));
848     owningAtomicReductionGens.push_back(
849         makeAtomicReductionGen(reductionDecls[i], builder, moduleTranslation));
850   }
851 
852   // Collect the reduction information.
853   SmallVector<llvm::OpenMPIRBuilder::ReductionInfo> reductionInfos;
854   reductionInfos.reserve(numReductions);
855   for (unsigned i = 0; i < numReductions; ++i) {
856     llvm::OpenMPIRBuilder::AtomicReductionGenTy atomicGen = nullptr;
857     if (owningAtomicReductionGens[i])
858       atomicGen = owningAtomicReductionGens[i];
859     llvm::Value *variable =
860         moduleTranslation.lookupValue(loop.reduction_vars()[i]);
861     reductionInfos.push_back({variable->getType()->getPointerElementType(),
862                               variable, privateReductionVariables[i],
863                               owningReductionGens[i], atomicGen});
864   }
865 
866   // The call to createReductions below expects the block to have a
867   // terminator. Create an unreachable instruction to serve as terminator
868   // and remove it later.
869   llvm::UnreachableInst *tempTerminator = builder.CreateUnreachable();
870   builder.SetInsertPoint(tempTerminator);
871   llvm::OpenMPIRBuilder::InsertPointTy contInsertPoint =
872       ompBuilder->createReductions(builder.saveIP(), allocaIP, reductionInfos,
873                                    loop.nowait());
874   if (!contInsertPoint.getBlock())
875     return loop->emitOpError() << "failed to convert reductions";
876   auto nextInsertionPoint =
877       ompBuilder->createBarrier(contInsertPoint, llvm::omp::OMPD_for);
878   tempTerminator->eraseFromParent();
879   builder.restoreIP(nextInsertionPoint);
880 
881   return success();
882 }
883 
884 /// Convert an Atomic Ordering attribute to llvm::AtomicOrdering.
885 llvm::AtomicOrdering
886 convertAtomicOrdering(Optional<omp::ClauseMemoryOrderKind> ao) {
887   if (!ao)
888     return llvm::AtomicOrdering::Monotonic; // Default Memory Ordering
889 
890   switch (*ao) {
891   case omp::ClauseMemoryOrderKind::seq_cst:
892     return llvm::AtomicOrdering::SequentiallyConsistent;
893   case omp::ClauseMemoryOrderKind::acq_rel:
894     return llvm::AtomicOrdering::AcquireRelease;
895   case omp::ClauseMemoryOrderKind::acquire:
896     return llvm::AtomicOrdering::Acquire;
897   case omp::ClauseMemoryOrderKind::release:
898     return llvm::AtomicOrdering::Release;
899   case omp::ClauseMemoryOrderKind::relaxed:
900     return llvm::AtomicOrdering::Monotonic;
901   }
902   llvm_unreachable("Unknown ClauseMemoryOrderKind kind");
903 }
904 
905 /// Convert omp.atomic.read operation to LLVM IR.
906 static LogicalResult
907 convertOmpAtomicRead(Operation &opInst, llvm::IRBuilderBase &builder,
908                      LLVM::ModuleTranslation &moduleTranslation) {
909 
910   auto readOp = cast<omp::AtomicReadOp>(opInst);
911   llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
912 
913   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
914 
915   llvm::AtomicOrdering AO = convertAtomicOrdering(readOp.memory_order());
916   llvm::Value *x = moduleTranslation.lookupValue(readOp.x());
917   Type xTy = readOp.x().getType().cast<omp::PointerLikeType>().getElementType();
918   llvm::Value *v = moduleTranslation.lookupValue(readOp.v());
919   Type vTy = readOp.v().getType().cast<omp::PointerLikeType>().getElementType();
920   llvm::OpenMPIRBuilder::AtomicOpValue V = {
921       v, moduleTranslation.convertType(vTy), false, false};
922   llvm::OpenMPIRBuilder::AtomicOpValue X = {
923       x, moduleTranslation.convertType(xTy), false, false};
924   builder.restoreIP(ompBuilder->createAtomicRead(ompLoc, X, V, AO));
925   return success();
926 }
927 
928 /// Converts an omp.atomic.write operation to LLVM IR.
929 static LogicalResult
930 convertOmpAtomicWrite(Operation &opInst, llvm::IRBuilderBase &builder,
931                       LLVM::ModuleTranslation &moduleTranslation) {
932   auto writeOp = cast<omp::AtomicWriteOp>(opInst);
933   llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
934 
935   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
936   llvm::AtomicOrdering ao = convertAtomicOrdering(writeOp.memory_order());
937   llvm::Value *expr = moduleTranslation.lookupValue(writeOp.value());
938   llvm::Value *dest = moduleTranslation.lookupValue(writeOp.address());
939   llvm::Type *ty = moduleTranslation.convertType(writeOp.value().getType());
940   llvm::OpenMPIRBuilder::AtomicOpValue x = {dest, ty, /*isSigned=*/false,
941                                             /*isVolatile=*/false};
942   builder.restoreIP(ompBuilder->createAtomicWrite(ompLoc, x, expr, ao));
943   return success();
944 }
945 
946 /// Converts an OpenMP reduction operation using OpenMPIRBuilder. Expects the
947 /// mapping between reduction variables and their private equivalents to have
948 /// been stored on the ModuleTranslation stack. Currently only supports
949 /// reduction within WsLoopOp, but can be easily extended.
950 static LogicalResult
951 convertOmpReductionOp(omp::ReductionOp reductionOp,
952                       llvm::IRBuilderBase &builder,
953                       LLVM::ModuleTranslation &moduleTranslation) {
954   // Find the declaration that corresponds to the reduction op.
955   auto reductionContainer = reductionOp->getParentOfType<omp::WsLoopOp>();
956   omp::ReductionDeclareOp declaration =
957       findReductionDecl(reductionContainer, reductionOp);
958   assert(declaration && "could not find reduction declaration");
959 
960   // Retrieve the mapping between reduction variables and their private
961   // equivalents.
962   const DenseMap<Value, llvm::Value *> *reductionVariableMap = nullptr;
963   moduleTranslation.stackWalk<OpenMPVarMappingStackFrame>(
964       [&](const OpenMPVarMappingStackFrame &frame) {
965         reductionVariableMap = &frame.mapping;
966         return WalkResult::interrupt();
967       });
968   assert(reductionVariableMap && "couldn't find private reduction variables");
969 
970   // Translate the reduction operation by emitting the body of the corresponding
971   // reduction declaration.
972   Region &reductionRegion = declaration.reductionRegion();
973   llvm::Value *privateReductionVar =
974       reductionVariableMap->lookup(reductionOp.accumulator());
975   llvm::Value *reductionVal = builder.CreateLoad(
976       moduleTranslation.convertType(reductionOp.operand().getType()),
977       privateReductionVar);
978 
979   moduleTranslation.mapValue(reductionRegion.front().getArgument(0),
980                              reductionVal);
981   moduleTranslation.mapValue(
982       reductionRegion.front().getArgument(1),
983       moduleTranslation.lookupValue(reductionOp.operand()));
984 
985   SmallVector<llvm::Value *> phis;
986   if (failed(inlineConvertOmpRegions(reductionRegion, "omp.reduction.body",
987                                      builder, moduleTranslation, &phis)))
988     return failure();
989   assert(phis.size() == 1 && "expected one value to be yielded from "
990                              "the reduction body declaration region");
991   builder.CreateStore(phis[0], privateReductionVar);
992   return success();
993 }
994 
995 namespace {
996 
997 /// Implementation of the dialect interface that converts operations belonging
998 /// to the OpenMP dialect to LLVM IR.
999 class OpenMPDialectLLVMIRTranslationInterface
1000     : public LLVMTranslationDialectInterface {
1001 public:
1002   using LLVMTranslationDialectInterface::LLVMTranslationDialectInterface;
1003 
1004   /// Translates the given operation to LLVM IR using the provided IR builder
1005   /// and saving the state in `moduleTranslation`.
1006   LogicalResult
1007   convertOperation(Operation *op, llvm::IRBuilderBase &builder,
1008                    LLVM::ModuleTranslation &moduleTranslation) const final;
1009 };
1010 
1011 } // namespace
1012 
1013 /// Given an OpenMP MLIR operation, create the corresponding LLVM IR
1014 /// (including OpenMP runtime calls).
1015 LogicalResult OpenMPDialectLLVMIRTranslationInterface::convertOperation(
1016     Operation *op, llvm::IRBuilderBase &builder,
1017     LLVM::ModuleTranslation &moduleTranslation) const {
1018 
1019   llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
1020 
1021   return llvm::TypeSwitch<Operation *, LogicalResult>(op)
1022       .Case([&](omp::BarrierOp) {
1023         ompBuilder->createBarrier(builder.saveIP(), llvm::omp::OMPD_barrier);
1024         return success();
1025       })
1026       .Case([&](omp::TaskwaitOp) {
1027         ompBuilder->createTaskwait(builder.saveIP());
1028         return success();
1029       })
1030       .Case([&](omp::TaskyieldOp) {
1031         ompBuilder->createTaskyield(builder.saveIP());
1032         return success();
1033       })
1034       .Case([&](omp::FlushOp) {
1035         // No support in Openmp runtime function (__kmpc_flush) to accept
1036         // the argument list.
1037         // OpenMP standard states the following:
1038         //  "An implementation may implement a flush with a list by ignoring
1039         //   the list, and treating it the same as a flush without a list."
1040         //
1041         // The argument list is discarded so that, flush with a list is treated
1042         // same as a flush without a list.
1043         ompBuilder->createFlush(builder.saveIP());
1044         return success();
1045       })
1046       .Case([&](omp::ParallelOp op) {
1047         return convertOmpParallel(op, builder, moduleTranslation);
1048       })
1049       .Case([&](omp::ReductionOp reductionOp) {
1050         return convertOmpReductionOp(reductionOp, builder, moduleTranslation);
1051       })
1052       .Case([&](omp::MasterOp) {
1053         return convertOmpMaster(*op, builder, moduleTranslation);
1054       })
1055       .Case([&](omp::CriticalOp) {
1056         return convertOmpCritical(*op, builder, moduleTranslation);
1057       })
1058       .Case([&](omp::OrderedRegionOp) {
1059         return convertOmpOrderedRegion(*op, builder, moduleTranslation);
1060       })
1061       .Case([&](omp::OrderedOp) {
1062         return convertOmpOrdered(*op, builder, moduleTranslation);
1063       })
1064       .Case([&](omp::WsLoopOp) {
1065         return convertOmpWsLoop(*op, builder, moduleTranslation);
1066       })
1067       .Case([&](omp::AtomicReadOp) {
1068         return convertOmpAtomicRead(*op, builder, moduleTranslation);
1069       })
1070       .Case([&](omp::AtomicWriteOp) {
1071         return convertOmpAtomicWrite(*op, builder, moduleTranslation);
1072       })
1073       .Case([&](omp::SectionsOp) {
1074         return convertOmpSections(*op, builder, moduleTranslation);
1075       })
1076       .Case<omp::YieldOp, omp::TerminatorOp, omp::ReductionDeclareOp,
1077             omp::CriticalDeclareOp>([](auto op) {
1078         // `yield` and `terminator` can be just omitted. The block structure
1079         // was created in the region that handles their parent operation.
1080         // `reduction.declare` will be used by reductions and is not
1081         // converted directly, skip it.
1082         // `critical.declare` is only used to declare names of critical
1083         // sections which will be used by `critical` ops and hence can be
1084         // ignored for lowering. The OpenMP IRBuilder will create unique
1085         // name for critical section names.
1086         return success();
1087       })
1088       .Default([&](Operation *inst) {
1089         return inst->emitError("unsupported OpenMP operation: ")
1090                << inst->getName();
1091       });
1092 }
1093 
1094 void mlir::registerOpenMPDialectTranslation(DialectRegistry &registry) {
1095   registry.insert<omp::OpenMPDialect>();
1096   registry.addDialectInterface<omp::OpenMPDialect,
1097                                OpenMPDialectLLVMIRTranslationInterface>();
1098 }
1099 
1100 void mlir::registerOpenMPDialectTranslation(MLIRContext &context) {
1101   DialectRegistry registry;
1102   registerOpenMPDialectTranslation(registry);
1103   context.appendDialectRegistry(registry);
1104 }
1105