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 =
339         llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvmContext),
340                                static_cast<int>(criticalDeclareOp.hint_val()));
341   }
342   builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createCritical(
343       ompLoc, bodyGenCB, finiCB, criticalOp.name().getValueOr(""), hint));
344   return success();
345 }
346 
347 /// Returns a reduction declaration that corresponds to the given reduction
348 /// operation in the given container. Currently only supports reductions inside
349 /// WsLoopOp but can be easily extended.
350 static omp::ReductionDeclareOp findReductionDecl(omp::WsLoopOp container,
351                                                  omp::ReductionOp reduction) {
352   SymbolRefAttr reductionSymbol;
353   for (unsigned i = 0, e = container.getNumReductionVars(); i < e; ++i) {
354     if (container.reduction_vars()[i] != reduction.accumulator())
355       continue;
356     reductionSymbol = (*container.reductions())[i].cast<SymbolRefAttr>();
357     break;
358   }
359   assert(reductionSymbol &&
360          "reduction operation must be associated with a declaration");
361 
362   return SymbolTable::lookupNearestSymbolFrom<omp::ReductionDeclareOp>(
363       container, reductionSymbol);
364 }
365 
366 /// Populates `reductions` with reduction declarations used in the given loop.
367 static void
368 collectReductionDecls(omp::WsLoopOp loop,
369                       SmallVectorImpl<omp::ReductionDeclareOp> &reductions) {
370   Optional<ArrayAttr> attr = loop.reductions();
371   if (!attr)
372     return;
373 
374   reductions.reserve(reductions.size() + loop.getNumReductionVars());
375   for (auto symbolRef : attr->getAsRange<SymbolRefAttr>()) {
376     reductions.push_back(
377         SymbolTable::lookupNearestSymbolFrom<omp::ReductionDeclareOp>(
378             loop, symbolRef));
379   }
380 }
381 
382 /// Translates the blocks contained in the given region and appends them to at
383 /// the current insertion point of `builder`. The operations of the entry block
384 /// are appended to the current insertion block, which is not expected to have a
385 /// terminator. If set, `continuationBlockArgs` is populated with translated
386 /// values that correspond to the values omp.yield'ed from the region.
387 static LogicalResult inlineConvertOmpRegions(
388     Region &region, StringRef blockName, llvm::IRBuilderBase &builder,
389     LLVM::ModuleTranslation &moduleTranslation,
390     SmallVectorImpl<llvm::Value *> *continuationBlockArgs = nullptr) {
391   if (region.empty())
392     return success();
393 
394   // Special case for single-block regions that don't create additional blocks:
395   // insert operations without creating additional blocks.
396   if (llvm::hasSingleElement(region)) {
397     moduleTranslation.mapBlock(&region.front(), builder.GetInsertBlock());
398     if (failed(moduleTranslation.convertBlock(
399             region.front(), /*ignoreArguments=*/true, builder)))
400       return failure();
401 
402     // The continuation arguments are simply the translated terminator operands.
403     if (continuationBlockArgs)
404       llvm::append_range(
405           *continuationBlockArgs,
406           moduleTranslation.lookupValues(region.front().back().getOperands()));
407 
408     // Drop the mapping that is no longer necessary so that the same region can
409     // be processed multiple times.
410     moduleTranslation.forgetMapping(region);
411     return success();
412   }
413 
414   // Create the continuation block manually instead of calling splitBlock
415   // because the current insertion block may not have a terminator.
416   llvm::BasicBlock *continuationBlock =
417       llvm::BasicBlock::Create(builder.getContext(), blockName + ".cont",
418                                builder.GetInsertBlock()->getParent(),
419                                builder.GetInsertBlock()->getNextNode());
420   builder.CreateBr(continuationBlock);
421 
422   LogicalResult bodyGenStatus = success();
423   SmallVector<llvm::PHINode *> phis;
424   convertOmpOpRegions(region, blockName, *builder.GetInsertBlock(),
425                       *continuationBlock, builder, moduleTranslation,
426                       bodyGenStatus, &phis);
427   if (failed(bodyGenStatus))
428     return failure();
429   if (continuationBlockArgs)
430     llvm::append_range(*continuationBlockArgs, phis);
431   builder.SetInsertPoint(continuationBlock,
432                          continuationBlock->getFirstInsertionPt());
433   return success();
434 }
435 
436 namespace {
437 /// Owning equivalents of OpenMPIRBuilder::(Atomic)ReductionGen that are used to
438 /// store lambdas with capture.
439 using OwningReductionGen = std::function<llvm::OpenMPIRBuilder::InsertPointTy(
440     llvm::OpenMPIRBuilder::InsertPointTy, llvm::Value *, llvm::Value *,
441     llvm::Value *&)>;
442 using OwningAtomicReductionGen =
443     std::function<llvm::OpenMPIRBuilder::InsertPointTy(
444         llvm::OpenMPIRBuilder::InsertPointTy, llvm::Type *, llvm::Value *,
445         llvm::Value *)>;
446 } // namespace
447 
448 /// Create an OpenMPIRBuilder-compatible reduction generator for the given
449 /// reduction declaration. The generator uses `builder` but ignores its
450 /// insertion point.
451 static OwningReductionGen
452 makeReductionGen(omp::ReductionDeclareOp decl, llvm::IRBuilderBase &builder,
453                  LLVM::ModuleTranslation &moduleTranslation) {
454   // The lambda is mutable because we need access to non-const methods of decl
455   // (which aren't actually mutating it), and we must capture decl by-value to
456   // avoid the dangling reference after the parent function returns.
457   OwningReductionGen gen =
458       [&, decl](llvm::OpenMPIRBuilder::InsertPointTy insertPoint,
459                 llvm::Value *lhs, llvm::Value *rhs,
460                 llvm::Value *&result) mutable {
461         Region &reductionRegion = decl.reductionRegion();
462         moduleTranslation.mapValue(reductionRegion.front().getArgument(0), lhs);
463         moduleTranslation.mapValue(reductionRegion.front().getArgument(1), rhs);
464         builder.restoreIP(insertPoint);
465         SmallVector<llvm::Value *> phis;
466         if (failed(inlineConvertOmpRegions(reductionRegion,
467                                            "omp.reduction.nonatomic.body",
468                                            builder, moduleTranslation, &phis)))
469           return llvm::OpenMPIRBuilder::InsertPointTy();
470         assert(phis.size() == 1);
471         result = phis[0];
472         return builder.saveIP();
473       };
474   return gen;
475 }
476 
477 /// Create an OpenMPIRBuilder-compatible atomic reduction generator for the
478 /// given reduction declaration. The generator uses `builder` but ignores its
479 /// insertion point. Returns null if there is no atomic region available in the
480 /// reduction declaration.
481 static OwningAtomicReductionGen
482 makeAtomicReductionGen(omp::ReductionDeclareOp decl,
483                        llvm::IRBuilderBase &builder,
484                        LLVM::ModuleTranslation &moduleTranslation) {
485   if (decl.atomicReductionRegion().empty())
486     return OwningAtomicReductionGen();
487 
488   // The lambda is mutable because we need access to non-const methods of decl
489   // (which aren't actually mutating it), and we must capture decl by-value to
490   // avoid the dangling reference after the parent function returns.
491   OwningAtomicReductionGen atomicGen =
492       [&, decl](llvm::OpenMPIRBuilder::InsertPointTy insertPoint, llvm::Type *,
493                 llvm::Value *lhs, llvm::Value *rhs) mutable {
494         Region &atomicRegion = decl.atomicReductionRegion();
495         moduleTranslation.mapValue(atomicRegion.front().getArgument(0), lhs);
496         moduleTranslation.mapValue(atomicRegion.front().getArgument(1), rhs);
497         builder.restoreIP(insertPoint);
498         SmallVector<llvm::Value *> phis;
499         if (failed(inlineConvertOmpRegions(atomicRegion,
500                                            "omp.reduction.atomic.body", builder,
501                                            moduleTranslation, &phis)))
502           return llvm::OpenMPIRBuilder::InsertPointTy();
503         assert(phis.empty());
504         return builder.saveIP();
505       };
506   return atomicGen;
507 }
508 
509 /// Converts an OpenMP 'ordered' operation into LLVM IR using OpenMPIRBuilder.
510 static LogicalResult
511 convertOmpOrdered(Operation &opInst, llvm::IRBuilderBase &builder,
512                   LLVM::ModuleTranslation &moduleTranslation) {
513   auto orderedOp = cast<omp::OrderedOp>(opInst);
514 
515   omp::ClauseDepend dependType = *orderedOp.depend_type_val();
516   bool isDependSource = dependType == omp::ClauseDepend::dependsource;
517   unsigned numLoops = orderedOp.num_loops_val().getValue();
518   SmallVector<llvm::Value *> vecValues =
519       moduleTranslation.lookupValues(orderedOp.depend_vec_vars());
520 
521   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
522   size_t indexVecValues = 0;
523   while (indexVecValues < vecValues.size()) {
524     SmallVector<llvm::Value *> storeValues;
525     storeValues.reserve(numLoops);
526     for (unsigned i = 0; i < numLoops; i++) {
527       storeValues.push_back(vecValues[indexVecValues]);
528       indexVecValues++;
529     }
530     builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createOrderedDepend(
531         ompLoc, findAllocaInsertPoint(builder, moduleTranslation), numLoops,
532         storeValues, ".cnt.addr", isDependSource));
533   }
534   return success();
535 }
536 
537 /// Converts an OpenMP 'ordered_region' operation into LLVM IR using
538 /// OpenMPIRBuilder.
539 static LogicalResult
540 convertOmpOrderedRegion(Operation &opInst, llvm::IRBuilderBase &builder,
541                         LLVM::ModuleTranslation &moduleTranslation) {
542   using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
543   auto orderedRegionOp = cast<omp::OrderedRegionOp>(opInst);
544 
545   // TODO: The code generation for ordered simd directive is not supported yet.
546   if (orderedRegionOp.simd())
547     return failure();
548 
549   // TODO: support error propagation in OpenMPIRBuilder and use it instead of
550   // relying on captured variables.
551   LogicalResult bodyGenStatus = success();
552 
553   auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
554                        llvm::BasicBlock &continuationBlock) {
555     // OrderedOp has only one region associated with it.
556     auto &region = cast<omp::OrderedRegionOp>(opInst).getRegion();
557     convertOmpOpRegions(region, "omp.ordered.region", *codeGenIP.getBlock(),
558                         continuationBlock, builder, moduleTranslation,
559                         bodyGenStatus);
560   };
561 
562   // TODO: Perform finalization actions for variables. This has to be
563   // called for variables which have destructors/finalizers.
564   auto finiCB = [&](InsertPointTy codeGenIP) {};
565 
566   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
567   builder.restoreIP(
568       moduleTranslation.getOpenMPBuilder()->createOrderedThreadsSimd(
569           ompLoc, bodyGenCB, finiCB, !orderedRegionOp.simd()));
570   return bodyGenStatus;
571 }
572 
573 static LogicalResult
574 convertOmpSections(Operation &opInst, llvm::IRBuilderBase &builder,
575                    LLVM::ModuleTranslation &moduleTranslation) {
576   using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
577   using StorableBodyGenCallbackTy =
578       llvm::OpenMPIRBuilder::StorableBodyGenCallbackTy;
579 
580   auto sectionsOp = cast<omp::SectionsOp>(opInst);
581 
582   // TODO: Support the following clauses: private, firstprivate, lastprivate,
583   // reduction, allocate
584   if (!sectionsOp.reduction_vars().empty() || sectionsOp.reductions() ||
585       !sectionsOp.allocate_vars().empty() ||
586       !sectionsOp.allocators_vars().empty())
587     return emitError(sectionsOp.getLoc())
588            << "reduction and allocate clauses are not supported for sections "
589               "construct";
590 
591   LogicalResult bodyGenStatus = success();
592   SmallVector<StorableBodyGenCallbackTy> sectionCBs;
593 
594   for (Operation &op : *sectionsOp.region().begin()) {
595     auto sectionOp = dyn_cast<omp::SectionOp>(op);
596     if (!sectionOp) // omp.terminator
597       continue;
598 
599     Region &region = sectionOp.region();
600     auto sectionCB = [&region, &builder, &moduleTranslation, &bodyGenStatus](
601                          InsertPointTy allocaIP, InsertPointTy codeGenIP,
602                          llvm::BasicBlock &finiBB) {
603       builder.restoreIP(codeGenIP);
604       builder.CreateBr(&finiBB);
605       convertOmpOpRegions(region, "omp.section.region", *codeGenIP.getBlock(),
606                           finiBB, builder, moduleTranslation, bodyGenStatus);
607     };
608     sectionCBs.push_back(sectionCB);
609   }
610 
611   // No sections within omp.sections operation - skip generation. This situation
612   // is only possible if there is only a terminator operation inside the
613   // sections operation
614   if (sectionCBs.empty())
615     return success();
616 
617   assert(isa<omp::SectionOp>(*sectionsOp.region().op_begin()));
618 
619   // TODO: Perform appropriate actions according to the data-sharing
620   // attribute (shared, private, firstprivate, ...) of variables.
621   // Currently defaults to shared.
622   auto privCB = [&](InsertPointTy, InsertPointTy codeGenIP, llvm::Value &,
623                     llvm::Value &vPtr,
624                     llvm::Value *&replacementValue) -> InsertPointTy {
625     replacementValue = &vPtr;
626     return codeGenIP;
627   };
628 
629   // TODO: Perform finalization actions for variables. This has to be
630   // called for variables which have destructors/finalizers.
631   auto finiCB = [&](InsertPointTy codeGenIP) {};
632 
633   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
634   builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createSections(
635       ompLoc, findAllocaInsertPoint(builder, moduleTranslation), sectionCBs,
636       privCB, finiCB, false, sectionsOp.nowait()));
637   return bodyGenStatus;
638 }
639 
640 /// Converts an OpenMP workshare loop into LLVM IR using OpenMPIRBuilder.
641 static LogicalResult
642 convertOmpWsLoop(Operation &opInst, llvm::IRBuilderBase &builder,
643                  LLVM::ModuleTranslation &moduleTranslation) {
644   auto loop = cast<omp::WsLoopOp>(opInst);
645   // TODO: this should be in the op verifier instead.
646   if (loop.lowerBound().empty())
647     return failure();
648 
649   // Static is the default.
650   auto schedule =
651       loop.schedule_val().getValueOr(omp::ClauseScheduleKind::Static);
652 
653   // Find the loop configuration.
654   llvm::Value *step = moduleTranslation.lookupValue(loop.step()[0]);
655   llvm::Type *ivType = step->getType();
656   llvm::Value *chunk = nullptr;
657   if (loop.schedule_chunk_var()) {
658     llvm::Value *chunkVar =
659         moduleTranslation.lookupValue(loop.schedule_chunk_var());
660     llvm::Type *chunkVarType = chunkVar->getType();
661     assert(chunkVarType->isIntegerTy() &&
662            "chunk size must be one integer expression");
663     if (chunkVarType->getIntegerBitWidth() < ivType->getIntegerBitWidth())
664       chunk = builder.CreateSExt(chunkVar, ivType);
665     else if (chunkVarType->getIntegerBitWidth() > ivType->getIntegerBitWidth())
666       chunk = builder.CreateTrunc(chunkVar, ivType);
667     else
668       chunk = chunkVar;
669   }
670 
671   SmallVector<omp::ReductionDeclareOp> reductionDecls;
672   collectReductionDecls(loop, reductionDecls);
673   llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
674       findAllocaInsertPoint(builder, moduleTranslation);
675 
676   // Allocate space for privatized reduction variables.
677   SmallVector<llvm::Value *> privateReductionVariables;
678   DenseMap<Value, llvm::Value *> reductionVariableMap;
679   unsigned numReductions = loop.getNumReductionVars();
680   privateReductionVariables.reserve(numReductions);
681   if (numReductions != 0) {
682     llvm::IRBuilderBase::InsertPointGuard guard(builder);
683     builder.restoreIP(allocaIP);
684     for (unsigned i = 0; i < numReductions; ++i) {
685       auto reductionType =
686           loop.reduction_vars()[i].getType().cast<LLVM::LLVMPointerType>();
687       llvm::Value *var = builder.CreateAlloca(
688           moduleTranslation.convertType(reductionType.getElementType()));
689       privateReductionVariables.push_back(var);
690       reductionVariableMap.try_emplace(loop.reduction_vars()[i], var);
691     }
692   }
693 
694   // Store the mapping between reduction variables and their private copies on
695   // ModuleTranslation stack. It can be then recovered when translating
696   // omp.reduce operations in a separate call.
697   LLVM::ModuleTranslation::SaveStack<OpenMPVarMappingStackFrame> mappingGuard(
698       moduleTranslation, reductionVariableMap);
699 
700   // Before the loop, store the initial values of reductions into reduction
701   // variables. Although this could be done after allocas, we don't want to mess
702   // up with the alloca insertion point.
703   for (unsigned i = 0; i < numReductions; ++i) {
704     SmallVector<llvm::Value *> phis;
705     if (failed(inlineConvertOmpRegions(reductionDecls[i].initializerRegion(),
706                                        "omp.reduction.neutral", builder,
707                                        moduleTranslation, &phis)))
708       return failure();
709     assert(phis.size() == 1 && "expected one value to be yielded from the "
710                                "reduction neutral element declaration region");
711     builder.CreateStore(phis[0], privateReductionVariables[i]);
712   }
713 
714   // Set up the source location value for OpenMP runtime.
715   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
716 
717   // Generator of the canonical loop body.
718   // TODO: support error propagation in OpenMPIRBuilder and use it instead of
719   // relying on captured variables.
720   SmallVector<llvm::CanonicalLoopInfo *> loopInfos;
721   SmallVector<llvm::OpenMPIRBuilder::InsertPointTy> bodyInsertPoints;
722   LogicalResult bodyGenStatus = success();
723   auto bodyGen = [&](llvm::OpenMPIRBuilder::InsertPointTy ip, llvm::Value *iv) {
724     // Make sure further conversions know about the induction variable.
725     moduleTranslation.mapValue(
726         loop.getRegion().front().getArgument(loopInfos.size()), iv);
727 
728     // Capture the body insertion point for use in nested loops. BodyIP of the
729     // CanonicalLoopInfo always points to the beginning of the entry block of
730     // the body.
731     bodyInsertPoints.push_back(ip);
732 
733     if (loopInfos.size() != loop.getNumLoops() - 1)
734       return;
735 
736     // Convert the body of the loop.
737     llvm::BasicBlock *entryBlock = ip.getBlock();
738     llvm::BasicBlock *exitBlock =
739         entryBlock->splitBasicBlock(ip.getPoint(), "omp.wsloop.exit");
740     convertOmpOpRegions(loop.region(), "omp.wsloop.region", *entryBlock,
741                         *exitBlock, builder, moduleTranslation, bodyGenStatus);
742   };
743 
744   // Delegate actual loop construction to the OpenMP IRBuilder.
745   // TODO: this currently assumes WsLoop is semantically similar to SCF loop,
746   // i.e. it has a positive step, uses signed integer semantics. Reconsider
747   // this code when WsLoop clearly supports more cases.
748   llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
749   for (unsigned i = 0, e = loop.getNumLoops(); i < e; ++i) {
750     llvm::Value *lowerBound =
751         moduleTranslation.lookupValue(loop.lowerBound()[i]);
752     llvm::Value *upperBound =
753         moduleTranslation.lookupValue(loop.upperBound()[i]);
754     llvm::Value *step = moduleTranslation.lookupValue(loop.step()[i]);
755 
756     // Make sure loop trip count are emitted in the preheader of the outermost
757     // loop at the latest so that they are all available for the new collapsed
758     // loop will be created below.
759     llvm::OpenMPIRBuilder::LocationDescription loc = ompLoc;
760     llvm::OpenMPIRBuilder::InsertPointTy computeIP = ompLoc.IP;
761     if (i != 0) {
762       loc = llvm::OpenMPIRBuilder::LocationDescription(bodyInsertPoints.back());
763       computeIP = loopInfos.front()->getPreheaderIP();
764     }
765     loopInfos.push_back(ompBuilder->createCanonicalLoop(
766         loc, bodyGen, lowerBound, upperBound, step,
767         /*IsSigned=*/true, loop.inclusive(), computeIP));
768 
769     if (failed(bodyGenStatus))
770       return failure();
771   }
772 
773   // Collapse loops. Store the insertion point because LoopInfos may get
774   // invalidated.
775   llvm::IRBuilderBase::InsertPoint afterIP = loopInfos.front()->getAfterIP();
776   llvm::CanonicalLoopInfo *loopInfo =
777       ompBuilder->collapseLoops(ompLoc.DL, loopInfos, {});
778 
779   allocaIP = findAllocaInsertPoint(builder, moduleTranslation);
780 
781   bool isSimd = loop.simd_modifier();
782 
783   if (schedule == omp::ClauseScheduleKind::Static) {
784     ompBuilder->applyWorkshareLoop(ompLoc.DL, loopInfo, allocaIP,
785                                    !loop.nowait(),
786                                    llvm::omp::OMP_SCHEDULE_Static, chunk);
787   } else {
788     llvm::omp::OMPScheduleType schedType;
789     switch (schedule) {
790     case omp::ClauseScheduleKind::Dynamic:
791       schedType = llvm::omp::OMPScheduleType::DynamicChunked;
792       break;
793     case omp::ClauseScheduleKind::Guided:
794       if (isSimd)
795         schedType = llvm::omp::OMPScheduleType::GuidedSimd;
796       else
797         schedType = llvm::omp::OMPScheduleType::GuidedChunked;
798       break;
799     case omp::ClauseScheduleKind::Auto:
800       schedType = llvm::omp::OMPScheduleType::Auto;
801       break;
802     case omp::ClauseScheduleKind::Runtime:
803       if (isSimd)
804         schedType = llvm::omp::OMPScheduleType::RuntimeSimd;
805       else
806         schedType = llvm::omp::OMPScheduleType::Runtime;
807       break;
808     default:
809       llvm_unreachable("Unknown schedule value");
810       break;
811     }
812 
813     if (Optional<omp::ScheduleModifier> modifier = loop.schedule_modifier()) {
814       switch (*modifier) {
815       case omp::ScheduleModifier::monotonic:
816         schedType |= llvm::omp::OMPScheduleType::ModifierMonotonic;
817         break;
818       case omp::ScheduleModifier::nonmonotonic:
819         schedType |= llvm::omp::OMPScheduleType::ModifierNonmonotonic;
820         break;
821       default:
822         // Nothing to do here.
823         break;
824       }
825     }
826     ompBuilder->applyDynamicWorkshareLoop(ompLoc.DL, loopInfo, allocaIP,
827                                           schedType, !loop.nowait(), chunk);
828   }
829 
830   // Continue building IR after the loop. Note that the LoopInfo returned by
831   // `collapseLoops` points inside the outermost loop and is intended for
832   // potential further loop transformations. Use the insertion point stored
833   // before collapsing loops instead.
834   builder.restoreIP(afterIP);
835 
836   // Process the reductions if required.
837   if (numReductions == 0)
838     return success();
839 
840   // Create the reduction generators. We need to own them here because
841   // ReductionInfo only accepts references to the generators.
842   SmallVector<OwningReductionGen> owningReductionGens;
843   SmallVector<OwningAtomicReductionGen> owningAtomicReductionGens;
844   for (unsigned i = 0; i < numReductions; ++i) {
845     owningReductionGens.push_back(
846         makeReductionGen(reductionDecls[i], builder, moduleTranslation));
847     owningAtomicReductionGens.push_back(
848         makeAtomicReductionGen(reductionDecls[i], builder, moduleTranslation));
849   }
850 
851   // Collect the reduction information.
852   SmallVector<llvm::OpenMPIRBuilder::ReductionInfo> reductionInfos;
853   reductionInfos.reserve(numReductions);
854   for (unsigned i = 0; i < numReductions; ++i) {
855     llvm::OpenMPIRBuilder::AtomicReductionGenTy atomicGen = nullptr;
856     if (owningAtomicReductionGens[i])
857       atomicGen = owningAtomicReductionGens[i];
858     llvm::Value *variable =
859         moduleTranslation.lookupValue(loop.reduction_vars()[i]);
860     reductionInfos.push_back({variable->getType()->getPointerElementType(),
861                               variable, privateReductionVariables[i],
862                               owningReductionGens[i], atomicGen});
863   }
864 
865   // The call to createReductions below expects the block to have a
866   // terminator. Create an unreachable instruction to serve as terminator
867   // and remove it later.
868   llvm::UnreachableInst *tempTerminator = builder.CreateUnreachable();
869   builder.SetInsertPoint(tempTerminator);
870   llvm::OpenMPIRBuilder::InsertPointTy contInsertPoint =
871       ompBuilder->createReductions(builder.saveIP(), allocaIP, reductionInfos,
872                                    loop.nowait());
873   if (!contInsertPoint.getBlock())
874     return loop->emitOpError() << "failed to convert reductions";
875   auto nextInsertionPoint =
876       ompBuilder->createBarrier(contInsertPoint, llvm::omp::OMPD_for);
877   tempTerminator->eraseFromParent();
878   builder.restoreIP(nextInsertionPoint);
879 
880   return success();
881 }
882 
883 /// Convert an Atomic Ordering attribute to llvm::AtomicOrdering.
884 llvm::AtomicOrdering
885 convertAtomicOrdering(Optional<omp::ClauseMemoryOrderKind> ao) {
886   if (!ao)
887     return llvm::AtomicOrdering::Monotonic; // Default Memory Ordering
888 
889   switch (*ao) {
890   case omp::ClauseMemoryOrderKind::Seq_cst:
891     return llvm::AtomicOrdering::SequentiallyConsistent;
892   case omp::ClauseMemoryOrderKind::Acq_rel:
893     return llvm::AtomicOrdering::AcquireRelease;
894   case omp::ClauseMemoryOrderKind::Acquire:
895     return llvm::AtomicOrdering::Acquire;
896   case omp::ClauseMemoryOrderKind::Release:
897     return llvm::AtomicOrdering::Release;
898   case omp::ClauseMemoryOrderKind::Relaxed:
899     return llvm::AtomicOrdering::Monotonic;
900   }
901   llvm_unreachable("Unknown ClauseMemoryOrderKind kind");
902 }
903 
904 /// Convert omp.atomic.read operation to LLVM IR.
905 static LogicalResult
906 convertOmpAtomicRead(Operation &opInst, llvm::IRBuilderBase &builder,
907                      LLVM::ModuleTranslation &moduleTranslation) {
908 
909   auto readOp = cast<omp::AtomicReadOp>(opInst);
910   llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
911 
912   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
913 
914   llvm::AtomicOrdering AO = convertAtomicOrdering(readOp.memory_order_val());
915   llvm::Value *x = moduleTranslation.lookupValue(readOp.x());
916   Type xTy = readOp.x().getType().cast<omp::PointerLikeType>().getElementType();
917   llvm::Value *v = moduleTranslation.lookupValue(readOp.v());
918   Type vTy = readOp.v().getType().cast<omp::PointerLikeType>().getElementType();
919   llvm::OpenMPIRBuilder::AtomicOpValue V = {
920       v, moduleTranslation.convertType(vTy), false, false};
921   llvm::OpenMPIRBuilder::AtomicOpValue X = {
922       x, moduleTranslation.convertType(xTy), false, false};
923   builder.restoreIP(ompBuilder->createAtomicRead(ompLoc, X, V, AO));
924   return success();
925 }
926 
927 /// Converts an omp.atomic.write operation to LLVM IR.
928 static LogicalResult
929 convertOmpAtomicWrite(Operation &opInst, llvm::IRBuilderBase &builder,
930                       LLVM::ModuleTranslation &moduleTranslation) {
931   auto writeOp = cast<omp::AtomicWriteOp>(opInst);
932   llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
933 
934   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
935   llvm::AtomicOrdering ao = convertAtomicOrdering(writeOp.memory_order_val());
936   llvm::Value *expr = moduleTranslation.lookupValue(writeOp.value());
937   llvm::Value *dest = moduleTranslation.lookupValue(writeOp.address());
938   llvm::Type *ty = moduleTranslation.convertType(writeOp.value().getType());
939   llvm::OpenMPIRBuilder::AtomicOpValue x = {dest, ty, /*isSigned=*/false,
940                                             /*isVolatile=*/false};
941   builder.restoreIP(ompBuilder->createAtomicWrite(ompLoc, x, expr, ao));
942   return success();
943 }
944 
945 /// Converts an LLVM dialect binary operation to the corresponding enum value
946 /// for `atomicrmw` supported binary operation.
947 llvm::AtomicRMWInst::BinOp convertBinOpToAtomic(Operation &op) {
948   return llvm::TypeSwitch<Operation *, llvm::AtomicRMWInst::BinOp>(&op)
949       .Case([&](LLVM::AddOp) { return llvm::AtomicRMWInst::BinOp::Add; })
950       .Case([&](LLVM::SubOp) { return llvm::AtomicRMWInst::BinOp::Sub; })
951       .Case([&](LLVM::AndOp) { return llvm::AtomicRMWInst::BinOp::And; })
952       .Case([&](LLVM::OrOp) { return llvm::AtomicRMWInst::BinOp::Or; })
953       .Case([&](LLVM::XOrOp) { return llvm::AtomicRMWInst::BinOp::Xor; })
954       .Case([&](LLVM::UMaxOp) { return llvm::AtomicRMWInst::BinOp::UMax; })
955       .Case([&](LLVM::UMinOp) { return llvm::AtomicRMWInst::BinOp::UMin; })
956       .Case([&](LLVM::FAddOp) { return llvm::AtomicRMWInst::BinOp::FAdd; })
957       .Case([&](LLVM::FSubOp) { return llvm::AtomicRMWInst::BinOp::FSub; })
958       .Default(llvm::AtomicRMWInst::BinOp::BAD_BINOP);
959 }
960 
961 /// Converts an OpenMP atomic update operation using OpenMPIRBuilder.
962 static LogicalResult
963 convertOmpAtomicUpdate(omp::AtomicUpdateOp &opInst,
964                        llvm::IRBuilderBase &builder,
965                        LLVM::ModuleTranslation &moduleTranslation) {
966   llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
967   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
968 
969   // Convert values and types.
970   auto &innerOpList = opInst.region().front().getOperations();
971   if (innerOpList.size() != 2)
972     return opInst.emitError("exactly two operations are allowed inside an "
973                             "atomic update region while lowering to LLVM IR");
974 
975   Operation &innerUpdateOp = innerOpList.front();
976 
977   if (innerUpdateOp.getNumOperands() != 2 ||
978       !llvm::is_contained(innerUpdateOp.getOperands(),
979                           opInst.getRegion().getArgument(0)))
980     return opInst.emitError(
981         "the update operation inside the region must be a binary operation and "
982         "that update operation must have the region argument as an operand");
983 
984   llvm::AtomicRMWInst::BinOp binop = convertBinOpToAtomic(innerUpdateOp);
985 
986   bool isXBinopExpr =
987       innerUpdateOp.getNumOperands() > 0 &&
988       innerUpdateOp.getOperand(0) == opInst.getRegion().getArgument(0);
989 
990   mlir::Value mlirExpr = (isXBinopExpr ? innerUpdateOp.getOperand(1)
991                                        : innerUpdateOp.getOperand(0));
992   llvm::Value *llvmExpr = moduleTranslation.lookupValue(mlirExpr);
993   llvm::Value *llvmX = moduleTranslation.lookupValue(opInst.x());
994   LLVM::LLVMPointerType mlirXType =
995       opInst.x().getType().cast<LLVM::LLVMPointerType>();
996   llvm::Type *llvmXElementType =
997       moduleTranslation.convertType(mlirXType.getElementType());
998   llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicX = {llvmX, llvmXElementType,
999                                                       /*isSigned=*/false,
1000                                                       /*isVolatile=*/false};
1001 
1002   llvm::AtomicOrdering atomicOrdering =
1003       convertAtomicOrdering(opInst.memory_order_val());
1004 
1005   // Generate update code.
1006   LogicalResult updateGenStatus = success();
1007   auto updateFn = [&opInst, &moduleTranslation, &updateGenStatus](
1008                       llvm::Value *atomicx,
1009                       llvm::IRBuilder<> &builder) -> llvm::Value * {
1010     Block &bb = *opInst.region().begin();
1011     moduleTranslation.mapValue(*opInst.region().args_begin(), atomicx);
1012     moduleTranslation.mapBlock(&bb, builder.GetInsertBlock());
1013     if (failed(moduleTranslation.convertBlock(bb, true, builder))) {
1014       updateGenStatus = (opInst.emitError()
1015                          << "unable to convert update operation to llvm IR");
1016       return nullptr;
1017     }
1018     omp::YieldOp yieldop = dyn_cast<omp::YieldOp>(bb.getTerminator());
1019     assert(yieldop && yieldop.results().size() == 1 &&
1020            "terminator must be omp.yield op and it must have exactly one "
1021            "argument");
1022     return moduleTranslation.lookupValue(yieldop.results()[0]);
1023   };
1024 
1025   // Handle ambiguous alloca, if any.
1026   auto allocaIP = findAllocaInsertPoint(builder, moduleTranslation);
1027   llvm::UnreachableInst *unreachableInst;
1028   if (allocaIP.getPoint() == ompLoc.IP.getPoint()) {
1029     // Same point => split basic block and make them unambigous.
1030     unreachableInst = builder.CreateUnreachable();
1031     builder.SetInsertPoint(builder.GetInsertBlock()->splitBasicBlock(
1032         unreachableInst, "alloca_split"));
1033     ompLoc.IP = builder.saveIP();
1034     unreachableInst->removeFromParent();
1035   }
1036   builder.restoreIP(ompBuilder->createAtomicUpdate(
1037       ompLoc, findAllocaInsertPoint(builder, moduleTranslation), llvmAtomicX,
1038       llvmExpr, atomicOrdering, binop, updateFn, isXBinopExpr));
1039   return updateGenStatus;
1040 }
1041 
1042 /// Converts an OpenMP reduction operation using OpenMPIRBuilder. Expects the
1043 /// mapping between reduction variables and their private equivalents to have
1044 /// been stored on the ModuleTranslation stack. Currently only supports
1045 /// reduction within WsLoopOp, but can be easily extended.
1046 static LogicalResult
1047 convertOmpReductionOp(omp::ReductionOp reductionOp,
1048                       llvm::IRBuilderBase &builder,
1049                       LLVM::ModuleTranslation &moduleTranslation) {
1050   // Find the declaration that corresponds to the reduction op.
1051   auto reductionContainer = reductionOp->getParentOfType<omp::WsLoopOp>();
1052   omp::ReductionDeclareOp declaration =
1053       findReductionDecl(reductionContainer, reductionOp);
1054   assert(declaration && "could not find reduction declaration");
1055 
1056   // Retrieve the mapping between reduction variables and their private
1057   // equivalents.
1058   const DenseMap<Value, llvm::Value *> *reductionVariableMap = nullptr;
1059   moduleTranslation.stackWalk<OpenMPVarMappingStackFrame>(
1060       [&](const OpenMPVarMappingStackFrame &frame) {
1061         reductionVariableMap = &frame.mapping;
1062         return WalkResult::interrupt();
1063       });
1064   assert(reductionVariableMap && "couldn't find private reduction variables");
1065 
1066   // Translate the reduction operation by emitting the body of the corresponding
1067   // reduction declaration.
1068   Region &reductionRegion = declaration.reductionRegion();
1069   llvm::Value *privateReductionVar =
1070       reductionVariableMap->lookup(reductionOp.accumulator());
1071   llvm::Value *reductionVal = builder.CreateLoad(
1072       moduleTranslation.convertType(reductionOp.operand().getType()),
1073       privateReductionVar);
1074 
1075   moduleTranslation.mapValue(reductionRegion.front().getArgument(0),
1076                              reductionVal);
1077   moduleTranslation.mapValue(
1078       reductionRegion.front().getArgument(1),
1079       moduleTranslation.lookupValue(reductionOp.operand()));
1080 
1081   SmallVector<llvm::Value *> phis;
1082   if (failed(inlineConvertOmpRegions(reductionRegion, "omp.reduction.body",
1083                                      builder, moduleTranslation, &phis)))
1084     return failure();
1085   assert(phis.size() == 1 && "expected one value to be yielded from "
1086                              "the reduction body declaration region");
1087   builder.CreateStore(phis[0], privateReductionVar);
1088   return success();
1089 }
1090 
1091 namespace {
1092 
1093 /// Implementation of the dialect interface that converts operations belonging
1094 /// to the OpenMP dialect to LLVM IR.
1095 class OpenMPDialectLLVMIRTranslationInterface
1096     : public LLVMTranslationDialectInterface {
1097 public:
1098   using LLVMTranslationDialectInterface::LLVMTranslationDialectInterface;
1099 
1100   /// Translates the given operation to LLVM IR using the provided IR builder
1101   /// and saving the state in `moduleTranslation`.
1102   LogicalResult
1103   convertOperation(Operation *op, llvm::IRBuilderBase &builder,
1104                    LLVM::ModuleTranslation &moduleTranslation) const final;
1105 };
1106 
1107 } // namespace
1108 
1109 /// Given an OpenMP MLIR operation, create the corresponding LLVM IR
1110 /// (including OpenMP runtime calls).
1111 LogicalResult OpenMPDialectLLVMIRTranslationInterface::convertOperation(
1112     Operation *op, llvm::IRBuilderBase &builder,
1113     LLVM::ModuleTranslation &moduleTranslation) const {
1114 
1115   llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
1116 
1117   return llvm::TypeSwitch<Operation *, LogicalResult>(op)
1118       .Case([&](omp::BarrierOp) {
1119         ompBuilder->createBarrier(builder.saveIP(), llvm::omp::OMPD_barrier);
1120         return success();
1121       })
1122       .Case([&](omp::TaskwaitOp) {
1123         ompBuilder->createTaskwait(builder.saveIP());
1124         return success();
1125       })
1126       .Case([&](omp::TaskyieldOp) {
1127         ompBuilder->createTaskyield(builder.saveIP());
1128         return success();
1129       })
1130       .Case([&](omp::FlushOp) {
1131         // No support in Openmp runtime function (__kmpc_flush) to accept
1132         // the argument list.
1133         // OpenMP standard states the following:
1134         //  "An implementation may implement a flush with a list by ignoring
1135         //   the list, and treating it the same as a flush without a list."
1136         //
1137         // The argument list is discarded so that, flush with a list is treated
1138         // same as a flush without a list.
1139         ompBuilder->createFlush(builder.saveIP());
1140         return success();
1141       })
1142       .Case([&](omp::ParallelOp op) {
1143         return convertOmpParallel(op, builder, moduleTranslation);
1144       })
1145       .Case([&](omp::ReductionOp reductionOp) {
1146         return convertOmpReductionOp(reductionOp, builder, moduleTranslation);
1147       })
1148       .Case([&](omp::MasterOp) {
1149         return convertOmpMaster(*op, builder, moduleTranslation);
1150       })
1151       .Case([&](omp::CriticalOp) {
1152         return convertOmpCritical(*op, builder, moduleTranslation);
1153       })
1154       .Case([&](omp::OrderedRegionOp) {
1155         return convertOmpOrderedRegion(*op, builder, moduleTranslation);
1156       })
1157       .Case([&](omp::OrderedOp) {
1158         return convertOmpOrdered(*op, builder, moduleTranslation);
1159       })
1160       .Case([&](omp::WsLoopOp) {
1161         return convertOmpWsLoop(*op, builder, moduleTranslation);
1162       })
1163       .Case([&](omp::AtomicReadOp) {
1164         return convertOmpAtomicRead(*op, builder, moduleTranslation);
1165       })
1166       .Case([&](omp::AtomicWriteOp) {
1167         return convertOmpAtomicWrite(*op, builder, moduleTranslation);
1168       })
1169       .Case([&](omp::AtomicUpdateOp op) {
1170         return convertOmpAtomicUpdate(op, builder, moduleTranslation);
1171       })
1172       .Case([&](omp::SectionsOp) {
1173         return convertOmpSections(*op, builder, moduleTranslation);
1174       })
1175       .Case<omp::YieldOp, omp::TerminatorOp, omp::ReductionDeclareOp,
1176             omp::CriticalDeclareOp>([](auto op) {
1177         // `yield` and `terminator` can be just omitted. The block structure
1178         // was created in the region that handles their parent operation.
1179         // `reduction.declare` will be used by reductions and is not
1180         // converted directly, skip it.
1181         // `critical.declare` is only used to declare names of critical
1182         // sections which will be used by `critical` ops and hence can be
1183         // ignored for lowering. The OpenMP IRBuilder will create unique
1184         // name for critical section names.
1185         return success();
1186       })
1187       .Default([&](Operation *inst) {
1188         return inst->emitError("unsupported OpenMP operation: ")
1189                << inst->getName();
1190       });
1191 }
1192 
1193 void mlir::registerOpenMPDialectTranslation(DialectRegistry &registry) {
1194   registry.insert<omp::OpenMPDialect>();
1195   registry.addDialectInterface<omp::OpenMPDialect,
1196                                OpenMPDialectLLVMIRTranslationInterface>();
1197 }
1198 
1199 void mlir::registerOpenMPDialectTranslation(MLIRContext &context) {
1200   DialectRegistry registry;
1201   registerOpenMPDialectTranslation(registry);
1202   context.appendDialectRegistry(registry);
1203 }
1204