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 single construct into LLVM IR using OpenMPIRBuilder.
641 static LogicalResult
642 convertOmpSingle(omp::SingleOp &singleOp, llvm::IRBuilderBase &builder,
643                  LLVM::ModuleTranslation &moduleTranslation) {
644   using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
645   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
646   LogicalResult bodyGenStatus = success();
647   auto bodyCB = [&](InsertPointTy allocaIP, InsertPointTy codegenIP,
648                     llvm::BasicBlock &continuationBB) {
649     convertOmpOpRegions(singleOp.region(), "omp.single.region",
650                         *codegenIP.getBlock(), continuationBB, builder,
651                         moduleTranslation, bodyGenStatus);
652   };
653   auto finiCB = [&](InsertPointTy codeGenIP) {};
654   builder.restoreIP(moduleTranslation.getOpenMPBuilder()->createSingle(
655       ompLoc, bodyCB, finiCB, singleOp.nowait(), /*DidIt=*/nullptr));
656   return bodyGenStatus;
657 }
658 
659 /// Converts an OpenMP workshare loop into LLVM IR using OpenMPIRBuilder.
660 static LogicalResult
661 convertOmpWsLoop(Operation &opInst, llvm::IRBuilderBase &builder,
662                  LLVM::ModuleTranslation &moduleTranslation) {
663   auto loop = cast<omp::WsLoopOp>(opInst);
664   // TODO: this should be in the op verifier instead.
665   if (loop.lowerBound().empty())
666     return failure();
667 
668   // Static is the default.
669   auto schedule =
670       loop.schedule_val().getValueOr(omp::ClauseScheduleKind::Static);
671 
672   // Find the loop configuration.
673   llvm::Value *step = moduleTranslation.lookupValue(loop.step()[0]);
674   llvm::Type *ivType = step->getType();
675   llvm::Value *chunk = nullptr;
676   if (loop.schedule_chunk_var()) {
677     llvm::Value *chunkVar =
678         moduleTranslation.lookupValue(loop.schedule_chunk_var());
679     llvm::Type *chunkVarType = chunkVar->getType();
680     assert(chunkVarType->isIntegerTy() &&
681            "chunk size must be one integer expression");
682     if (chunkVarType->getIntegerBitWidth() < ivType->getIntegerBitWidth())
683       chunk = builder.CreateSExt(chunkVar, ivType);
684     else if (chunkVarType->getIntegerBitWidth() > ivType->getIntegerBitWidth())
685       chunk = builder.CreateTrunc(chunkVar, ivType);
686     else
687       chunk = chunkVar;
688   }
689 
690   SmallVector<omp::ReductionDeclareOp> reductionDecls;
691   collectReductionDecls(loop, reductionDecls);
692   llvm::OpenMPIRBuilder::InsertPointTy allocaIP =
693       findAllocaInsertPoint(builder, moduleTranslation);
694 
695   // Allocate space for privatized reduction variables.
696   SmallVector<llvm::Value *> privateReductionVariables;
697   DenseMap<Value, llvm::Value *> reductionVariableMap;
698   unsigned numReductions = loop.getNumReductionVars();
699   privateReductionVariables.reserve(numReductions);
700   if (numReductions != 0) {
701     llvm::IRBuilderBase::InsertPointGuard guard(builder);
702     builder.restoreIP(allocaIP);
703     for (unsigned i = 0; i < numReductions; ++i) {
704       auto reductionType =
705           loop.reduction_vars()[i].getType().cast<LLVM::LLVMPointerType>();
706       llvm::Value *var = builder.CreateAlloca(
707           moduleTranslation.convertType(reductionType.getElementType()));
708       privateReductionVariables.push_back(var);
709       reductionVariableMap.try_emplace(loop.reduction_vars()[i], var);
710     }
711   }
712 
713   // Store the mapping between reduction variables and their private copies on
714   // ModuleTranslation stack. It can be then recovered when translating
715   // omp.reduce operations in a separate call.
716   LLVM::ModuleTranslation::SaveStack<OpenMPVarMappingStackFrame> mappingGuard(
717       moduleTranslation, reductionVariableMap);
718 
719   // Before the loop, store the initial values of reductions into reduction
720   // variables. Although this could be done after allocas, we don't want to mess
721   // up with the alloca insertion point.
722   for (unsigned i = 0; i < numReductions; ++i) {
723     SmallVector<llvm::Value *> phis;
724     if (failed(inlineConvertOmpRegions(reductionDecls[i].initializerRegion(),
725                                        "omp.reduction.neutral", builder,
726                                        moduleTranslation, &phis)))
727       return failure();
728     assert(phis.size() == 1 && "expected one value to be yielded from the "
729                                "reduction neutral element declaration region");
730     builder.CreateStore(phis[0], privateReductionVariables[i]);
731   }
732 
733   // Set up the source location value for OpenMP runtime.
734   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
735 
736   // Generator of the canonical loop body.
737   // TODO: support error propagation in OpenMPIRBuilder and use it instead of
738   // relying on captured variables.
739   SmallVector<llvm::CanonicalLoopInfo *> loopInfos;
740   SmallVector<llvm::OpenMPIRBuilder::InsertPointTy> bodyInsertPoints;
741   LogicalResult bodyGenStatus = success();
742   auto bodyGen = [&](llvm::OpenMPIRBuilder::InsertPointTy ip, llvm::Value *iv) {
743     // Make sure further conversions know about the induction variable.
744     moduleTranslation.mapValue(
745         loop.getRegion().front().getArgument(loopInfos.size()), iv);
746 
747     // Capture the body insertion point for use in nested loops. BodyIP of the
748     // CanonicalLoopInfo always points to the beginning of the entry block of
749     // the body.
750     bodyInsertPoints.push_back(ip);
751 
752     if (loopInfos.size() != loop.getNumLoops() - 1)
753       return;
754 
755     // Convert the body of the loop.
756     llvm::BasicBlock *entryBlock = ip.getBlock();
757     llvm::BasicBlock *exitBlock =
758         entryBlock->splitBasicBlock(ip.getPoint(), "omp.wsloop.exit");
759     convertOmpOpRegions(loop.region(), "omp.wsloop.region", *entryBlock,
760                         *exitBlock, builder, moduleTranslation, bodyGenStatus);
761   };
762 
763   // Delegate actual loop construction to the OpenMP IRBuilder.
764   // TODO: this currently assumes WsLoop is semantically similar to SCF loop,
765   // i.e. it has a positive step, uses signed integer semantics. Reconsider
766   // this code when WsLoop clearly supports more cases.
767   llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
768   for (unsigned i = 0, e = loop.getNumLoops(); i < e; ++i) {
769     llvm::Value *lowerBound =
770         moduleTranslation.lookupValue(loop.lowerBound()[i]);
771     llvm::Value *upperBound =
772         moduleTranslation.lookupValue(loop.upperBound()[i]);
773     llvm::Value *step = moduleTranslation.lookupValue(loop.step()[i]);
774 
775     // Make sure loop trip count are emitted in the preheader of the outermost
776     // loop at the latest so that they are all available for the new collapsed
777     // loop will be created below.
778     llvm::OpenMPIRBuilder::LocationDescription loc = ompLoc;
779     llvm::OpenMPIRBuilder::InsertPointTy computeIP = ompLoc.IP;
780     if (i != 0) {
781       loc = llvm::OpenMPIRBuilder::LocationDescription(bodyInsertPoints.back());
782       computeIP = loopInfos.front()->getPreheaderIP();
783     }
784     loopInfos.push_back(ompBuilder->createCanonicalLoop(
785         loc, bodyGen, lowerBound, upperBound, step,
786         /*IsSigned=*/true, loop.inclusive(), computeIP));
787 
788     if (failed(bodyGenStatus))
789       return failure();
790   }
791 
792   // Collapse loops. Store the insertion point because LoopInfos may get
793   // invalidated.
794   llvm::IRBuilderBase::InsertPoint afterIP = loopInfos.front()->getAfterIP();
795   llvm::CanonicalLoopInfo *loopInfo =
796       ompBuilder->collapseLoops(ompLoc.DL, loopInfos, {});
797 
798   allocaIP = findAllocaInsertPoint(builder, moduleTranslation);
799 
800   bool isSimd = loop.simd_modifier();
801 
802   // The orderedVal refers to the value obtained from the ordered[(n)] clause.
803   //   orderedVal == -1: No ordered[(n)] clause specified.
804   //   orderedVal == 0: The ordered clause specified without a parameter.
805   //   orderedVal > 0: The ordered clause specified with a parameter (n).
806   // TODO: Handle doacross loop init when orderedVal is greater than 0.
807   int64_t orderedVal =
808       loop.ordered_val().hasValue() ? loop.ordered_val().getValue() : -1;
809   if (schedule == omp::ClauseScheduleKind::Static && orderedVal != 0) {
810     ompBuilder->applyWorkshareLoop(ompLoc.DL, loopInfo, allocaIP,
811                                    !loop.nowait(),
812                                    llvm::omp::OMP_SCHEDULE_Static, chunk);
813   } else {
814     llvm::omp::OMPScheduleType schedType;
815     switch (schedule) {
816     case omp::ClauseScheduleKind::Static:
817       if (loop.schedule_chunk_var())
818         schedType = llvm::omp::OMPScheduleType::OrderedStaticChunked;
819       else
820         schedType = llvm::omp::OMPScheduleType::OrderedStatic;
821       break;
822     case omp::ClauseScheduleKind::Dynamic:
823       if (orderedVal == 0)
824         schedType = llvm::omp::OMPScheduleType::OrderedDynamicChunked;
825       else
826         schedType = llvm::omp::OMPScheduleType::DynamicChunked;
827       break;
828     case omp::ClauseScheduleKind::Guided:
829       if (orderedVal == 0) {
830         schedType = llvm::omp::OMPScheduleType::OrderedGuidedChunked;
831       } else {
832         if (isSimd)
833           schedType = llvm::omp::OMPScheduleType::GuidedSimd;
834         else
835           schedType = llvm::omp::OMPScheduleType::GuidedChunked;
836       }
837       break;
838     case omp::ClauseScheduleKind::Auto:
839       if (orderedVal == 0)
840         schedType = llvm::omp::OMPScheduleType::OrderedAuto;
841       else
842         schedType = llvm::omp::OMPScheduleType::Auto;
843       break;
844     case omp::ClauseScheduleKind::Runtime:
845       if (orderedVal == 0) {
846         schedType = llvm::omp::OMPScheduleType::OrderedRuntime;
847       } else {
848         if (isSimd)
849           schedType = llvm::omp::OMPScheduleType::RuntimeSimd;
850         else
851           schedType = llvm::omp::OMPScheduleType::Runtime;
852       }
853       break;
854     }
855 
856     if (Optional<omp::ScheduleModifier> modifier = loop.schedule_modifier()) {
857       switch (*modifier) {
858       case omp::ScheduleModifier::monotonic:
859         schedType |= llvm::omp::OMPScheduleType::ModifierMonotonic;
860         break;
861       case omp::ScheduleModifier::nonmonotonic:
862         schedType |= llvm::omp::OMPScheduleType::ModifierNonmonotonic;
863         break;
864       default:
865         // Nothing to do here.
866         break;
867       }
868     } else {
869       // OpenMP 5.1, 2.11.4 Worksharing-Loop Construct, Description.
870       // If the static schedule kind is specified or if the ordered clause is
871       // specified, and if the nonmonotonic modifier is not specified, the
872       // effect is as if the monotonic modifier is specified. Otherwise, unless
873       // the monotonic modifier is specified, the effect is as if the
874       // nonmonotonic modifier is specified.
875       // The monotonic is used by default in openmp runtime library, so no need
876       // to set it.
877       if (!(schedType == llvm::omp::OMPScheduleType::OrderedStatic ||
878             schedType == llvm::omp::OMPScheduleType::OrderedStaticChunked))
879         schedType |= llvm::omp::OMPScheduleType::ModifierNonmonotonic;
880     }
881 
882     ompBuilder->applyDynamicWorkshareLoop(ompLoc.DL, loopInfo, allocaIP,
883                                           schedType, !loop.nowait(), chunk,
884                                           /*ordered*/ orderedVal == 0);
885   }
886 
887   // Continue building IR after the loop. Note that the LoopInfo returned by
888   // `collapseLoops` points inside the outermost loop and is intended for
889   // potential further loop transformations. Use the insertion point stored
890   // before collapsing loops instead.
891   builder.restoreIP(afterIP);
892 
893   // Process the reductions if required.
894   if (numReductions == 0)
895     return success();
896 
897   // Create the reduction generators. We need to own them here because
898   // ReductionInfo only accepts references to the generators.
899   SmallVector<OwningReductionGen> owningReductionGens;
900   SmallVector<OwningAtomicReductionGen> owningAtomicReductionGens;
901   for (unsigned i = 0; i < numReductions; ++i) {
902     owningReductionGens.push_back(
903         makeReductionGen(reductionDecls[i], builder, moduleTranslation));
904     owningAtomicReductionGens.push_back(
905         makeAtomicReductionGen(reductionDecls[i], builder, moduleTranslation));
906   }
907 
908   // Collect the reduction information.
909   SmallVector<llvm::OpenMPIRBuilder::ReductionInfo> reductionInfos;
910   reductionInfos.reserve(numReductions);
911   for (unsigned i = 0; i < numReductions; ++i) {
912     llvm::OpenMPIRBuilder::AtomicReductionGenTy atomicGen = nullptr;
913     if (owningAtomicReductionGens[i])
914       atomicGen = owningAtomicReductionGens[i];
915     auto reductionType =
916         loop.reduction_vars()[i].getType().cast<LLVM::LLVMPointerType>();
917     llvm::Value *variable =
918         moduleTranslation.lookupValue(loop.reduction_vars()[i]);
919     reductionInfos.push_back(
920         {moduleTranslation.convertType(reductionType.getElementType()),
921          variable, privateReductionVariables[i], owningReductionGens[i],
922          atomicGen});
923   }
924 
925   // The call to createReductions below expects the block to have a
926   // terminator. Create an unreachable instruction to serve as terminator
927   // and remove it later.
928   llvm::UnreachableInst *tempTerminator = builder.CreateUnreachable();
929   builder.SetInsertPoint(tempTerminator);
930   llvm::OpenMPIRBuilder::InsertPointTy contInsertPoint =
931       ompBuilder->createReductions(builder.saveIP(), allocaIP, reductionInfos,
932                                    loop.nowait());
933   if (!contInsertPoint.getBlock())
934     return loop->emitOpError() << "failed to convert reductions";
935   auto nextInsertionPoint =
936       ompBuilder->createBarrier(contInsertPoint, llvm::omp::OMPD_for);
937   tempTerminator->eraseFromParent();
938   builder.restoreIP(nextInsertionPoint);
939 
940   return success();
941 }
942 
943 /// Converts an OpenMP simd loop into LLVM IR using OpenMPIRBuilder.
944 static LogicalResult
945 convertOmpSimdLoop(Operation &opInst, llvm::IRBuilderBase &builder,
946                    LLVM::ModuleTranslation &moduleTranslation) {
947   auto loop = cast<omp::SimdLoopOp>(opInst);
948 
949   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
950 
951   // Generator of the canonical loop body.
952   // TODO: support error propagation in OpenMPIRBuilder and use it instead of
953   // relying on captured variables.
954   SmallVector<llvm::CanonicalLoopInfo *> loopInfos;
955   SmallVector<llvm::OpenMPIRBuilder::InsertPointTy> bodyInsertPoints;
956   LogicalResult bodyGenStatus = success();
957   auto bodyGen = [&](llvm::OpenMPIRBuilder::InsertPointTy ip, llvm::Value *iv) {
958     // Make sure further conversions know about the induction variable.
959     moduleTranslation.mapValue(
960         loop.getRegion().front().getArgument(loopInfos.size()), iv);
961 
962     // Capture the body insertion point for use in nested loops. BodyIP of the
963     // CanonicalLoopInfo always points to the beginning of the entry block of
964     // the body.
965     bodyInsertPoints.push_back(ip);
966 
967     if (loopInfos.size() != loop.getNumLoops() - 1)
968       return;
969 
970     // Convert the body of the loop.
971     llvm::BasicBlock *entryBlock = ip.getBlock();
972     llvm::BasicBlock *exitBlock =
973         entryBlock->splitBasicBlock(ip.getPoint(), "omp.simdloop.exit");
974     convertOmpOpRegions(loop.region(), "omp.simdloop.region", *entryBlock,
975                         *exitBlock, builder, moduleTranslation, bodyGenStatus);
976   };
977 
978   // Delegate actual loop construction to the OpenMP IRBuilder.
979   // TODO: this currently assumes SimdLoop is semantically similar to SCF loop,
980   // i.e. it has a positive step, uses signed integer semantics. Reconsider
981   // this code when SimdLoop clearly supports more cases.
982   llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
983   for (unsigned i = 0, e = loop.getNumLoops(); i < e; ++i) {
984     llvm::Value *lowerBound =
985         moduleTranslation.lookupValue(loop.lowerBound()[i]);
986     llvm::Value *upperBound =
987         moduleTranslation.lookupValue(loop.upperBound()[i]);
988     llvm::Value *step = moduleTranslation.lookupValue(loop.step()[i]);
989 
990     // Make sure loop trip count are emitted in the preheader of the outermost
991     // loop at the latest so that they are all available for the new collapsed
992     // loop will be created below.
993     llvm::OpenMPIRBuilder::LocationDescription loc = ompLoc;
994     llvm::OpenMPIRBuilder::InsertPointTy computeIP = ompLoc.IP;
995     if (i != 0) {
996       loc = llvm::OpenMPIRBuilder::LocationDescription(bodyInsertPoints.back(),
997                                                        ompLoc.DL);
998       computeIP = loopInfos.front()->getPreheaderIP();
999     }
1000     loopInfos.push_back(ompBuilder->createCanonicalLoop(
1001         loc, bodyGen, lowerBound, upperBound, step,
1002         /*IsSigned=*/true, /*Inclusive=*/true, computeIP));
1003 
1004     if (failed(bodyGenStatus))
1005       return failure();
1006   }
1007 
1008   // Collapse loops.
1009   llvm::IRBuilderBase::InsertPoint afterIP = loopInfos.front()->getAfterIP();
1010   llvm::CanonicalLoopInfo *loopInfo =
1011       ompBuilder->collapseLoops(ompLoc.DL, loopInfos, {});
1012 
1013   ompBuilder->applySimd(ompLoc.DL, loopInfo);
1014 
1015   builder.restoreIP(afterIP);
1016   return success();
1017 }
1018 
1019 /// Convert an Atomic Ordering attribute to llvm::AtomicOrdering.
1020 llvm::AtomicOrdering
1021 convertAtomicOrdering(Optional<omp::ClauseMemoryOrderKind> ao) {
1022   if (!ao)
1023     return llvm::AtomicOrdering::Monotonic; // Default Memory Ordering
1024 
1025   switch (*ao) {
1026   case omp::ClauseMemoryOrderKind::Seq_cst:
1027     return llvm::AtomicOrdering::SequentiallyConsistent;
1028   case omp::ClauseMemoryOrderKind::Acq_rel:
1029     return llvm::AtomicOrdering::AcquireRelease;
1030   case omp::ClauseMemoryOrderKind::Acquire:
1031     return llvm::AtomicOrdering::Acquire;
1032   case omp::ClauseMemoryOrderKind::Release:
1033     return llvm::AtomicOrdering::Release;
1034   case omp::ClauseMemoryOrderKind::Relaxed:
1035     return llvm::AtomicOrdering::Monotonic;
1036   }
1037   llvm_unreachable("Unknown ClauseMemoryOrderKind kind");
1038 }
1039 
1040 /// Convert omp.atomic.read operation to LLVM IR.
1041 static LogicalResult
1042 convertOmpAtomicRead(Operation &opInst, llvm::IRBuilderBase &builder,
1043                      LLVM::ModuleTranslation &moduleTranslation) {
1044 
1045   auto readOp = cast<omp::AtomicReadOp>(opInst);
1046   llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
1047 
1048   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
1049 
1050   llvm::AtomicOrdering AO = convertAtomicOrdering(readOp.memory_order_val());
1051   llvm::Value *x = moduleTranslation.lookupValue(readOp.x());
1052   Type xTy = readOp.x().getType().cast<omp::PointerLikeType>().getElementType();
1053   llvm::Value *v = moduleTranslation.lookupValue(readOp.v());
1054   Type vTy = readOp.v().getType().cast<omp::PointerLikeType>().getElementType();
1055   llvm::OpenMPIRBuilder::AtomicOpValue V = {
1056       v, moduleTranslation.convertType(vTy), false, false};
1057   llvm::OpenMPIRBuilder::AtomicOpValue X = {
1058       x, moduleTranslation.convertType(xTy), false, false};
1059   builder.restoreIP(ompBuilder->createAtomicRead(ompLoc, X, V, AO));
1060   return success();
1061 }
1062 
1063 /// Converts an omp.atomic.write operation to LLVM IR.
1064 static LogicalResult
1065 convertOmpAtomicWrite(Operation &opInst, llvm::IRBuilderBase &builder,
1066                       LLVM::ModuleTranslation &moduleTranslation) {
1067   auto writeOp = cast<omp::AtomicWriteOp>(opInst);
1068   llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
1069 
1070   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
1071   llvm::AtomicOrdering ao = convertAtomicOrdering(writeOp.memory_order_val());
1072   llvm::Value *expr = moduleTranslation.lookupValue(writeOp.value());
1073   llvm::Value *dest = moduleTranslation.lookupValue(writeOp.address());
1074   llvm::Type *ty = moduleTranslation.convertType(writeOp.value().getType());
1075   llvm::OpenMPIRBuilder::AtomicOpValue x = {dest, ty, /*isSigned=*/false,
1076                                             /*isVolatile=*/false};
1077   builder.restoreIP(ompBuilder->createAtomicWrite(ompLoc, x, expr, ao));
1078   return success();
1079 }
1080 
1081 /// Converts an LLVM dialect binary operation to the corresponding enum value
1082 /// for `atomicrmw` supported binary operation.
1083 llvm::AtomicRMWInst::BinOp convertBinOpToAtomic(Operation &op) {
1084   return llvm::TypeSwitch<Operation *, llvm::AtomicRMWInst::BinOp>(&op)
1085       .Case([&](LLVM::AddOp) { return llvm::AtomicRMWInst::BinOp::Add; })
1086       .Case([&](LLVM::SubOp) { return llvm::AtomicRMWInst::BinOp::Sub; })
1087       .Case([&](LLVM::AndOp) { return llvm::AtomicRMWInst::BinOp::And; })
1088       .Case([&](LLVM::OrOp) { return llvm::AtomicRMWInst::BinOp::Or; })
1089       .Case([&](LLVM::XOrOp) { return llvm::AtomicRMWInst::BinOp::Xor; })
1090       .Case([&](LLVM::UMaxOp) { return llvm::AtomicRMWInst::BinOp::UMax; })
1091       .Case([&](LLVM::UMinOp) { return llvm::AtomicRMWInst::BinOp::UMin; })
1092       .Case([&](LLVM::FAddOp) { return llvm::AtomicRMWInst::BinOp::FAdd; })
1093       .Case([&](LLVM::FSubOp) { return llvm::AtomicRMWInst::BinOp::FSub; })
1094       .Default(llvm::AtomicRMWInst::BinOp::BAD_BINOP);
1095 }
1096 
1097 /// Converts an OpenMP atomic update operation using OpenMPIRBuilder.
1098 static LogicalResult
1099 convertOmpAtomicUpdate(omp::AtomicUpdateOp &opInst,
1100                        llvm::IRBuilderBase &builder,
1101                        LLVM::ModuleTranslation &moduleTranslation) {
1102   llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
1103   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
1104 
1105   // Convert values and types.
1106   auto &innerOpList = opInst.region().front().getOperations();
1107   if (innerOpList.size() != 2)
1108     return opInst.emitError("exactly two operations are allowed inside an "
1109                             "atomic update region while lowering to LLVM IR");
1110 
1111   Operation &innerUpdateOp = innerOpList.front();
1112 
1113   if (innerUpdateOp.getNumOperands() != 2 ||
1114       !llvm::is_contained(innerUpdateOp.getOperands(),
1115                           opInst.getRegion().getArgument(0)))
1116     return opInst.emitError(
1117         "the update operation inside the region must be a binary operation and "
1118         "that update operation must have the region argument as an operand");
1119 
1120   llvm::AtomicRMWInst::BinOp binop = convertBinOpToAtomic(innerUpdateOp);
1121 
1122   bool isXBinopExpr =
1123       innerUpdateOp.getNumOperands() > 0 &&
1124       innerUpdateOp.getOperand(0) == opInst.getRegion().getArgument(0);
1125 
1126   mlir::Value mlirExpr = (isXBinopExpr ? innerUpdateOp.getOperand(1)
1127                                        : innerUpdateOp.getOperand(0));
1128   llvm::Value *llvmExpr = moduleTranslation.lookupValue(mlirExpr);
1129   llvm::Value *llvmX = moduleTranslation.lookupValue(opInst.x());
1130   LLVM::LLVMPointerType mlirXType =
1131       opInst.x().getType().cast<LLVM::LLVMPointerType>();
1132   llvm::Type *llvmXElementType =
1133       moduleTranslation.convertType(mlirXType.getElementType());
1134   llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicX = {llvmX, llvmXElementType,
1135                                                       /*isSigned=*/false,
1136                                                       /*isVolatile=*/false};
1137 
1138   llvm::AtomicOrdering atomicOrdering =
1139       convertAtomicOrdering(opInst.memory_order_val());
1140 
1141   // Generate update code.
1142   LogicalResult updateGenStatus = success();
1143   auto updateFn = [&opInst, &moduleTranslation, &updateGenStatus](
1144                       llvm::Value *atomicx,
1145                       llvm::IRBuilder<> &builder) -> llvm::Value * {
1146     Block &bb = *opInst.region().begin();
1147     moduleTranslation.mapValue(*opInst.region().args_begin(), atomicx);
1148     moduleTranslation.mapBlock(&bb, builder.GetInsertBlock());
1149     if (failed(moduleTranslation.convertBlock(bb, true, builder))) {
1150       updateGenStatus = (opInst.emitError()
1151                          << "unable to convert update operation to llvm IR");
1152       return nullptr;
1153     }
1154     omp::YieldOp yieldop = dyn_cast<omp::YieldOp>(bb.getTerminator());
1155     assert(yieldop && yieldop.results().size() == 1 &&
1156            "terminator must be omp.yield op and it must have exactly one "
1157            "argument");
1158     return moduleTranslation.lookupValue(yieldop.results()[0]);
1159   };
1160 
1161   // Handle ambiguous alloca, if any.
1162   auto allocaIP = findAllocaInsertPoint(builder, moduleTranslation);
1163   if (allocaIP.getPoint() == ompLoc.IP.getPoint()) {
1164     // Same point => split basic block and make them unambigous.
1165     llvm::UnreachableInst *unreachableInst = builder.CreateUnreachable();
1166     builder.SetInsertPoint(builder.GetInsertBlock()->splitBasicBlock(
1167         unreachableInst, "alloca_split"));
1168     ompLoc.IP = builder.saveIP();
1169     unreachableInst->eraseFromParent();
1170   }
1171   builder.restoreIP(ompBuilder->createAtomicUpdate(
1172       ompLoc, findAllocaInsertPoint(builder, moduleTranslation), llvmAtomicX,
1173       llvmExpr, atomicOrdering, binop, updateFn, isXBinopExpr));
1174   return updateGenStatus;
1175 }
1176 
1177 static LogicalResult
1178 convertOmpAtomicCapture(omp::AtomicCaptureOp atomicCaptureOp,
1179                         llvm::IRBuilderBase &builder,
1180                         LLVM::ModuleTranslation &moduleTranslation) {
1181   llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
1182   llvm::OpenMPIRBuilder::LocationDescription ompLoc(builder);
1183   mlir::Value mlirExpr;
1184   bool isXBinopExpr = false, isPostfixUpdate = false;
1185   llvm::AtomicRMWInst::BinOp binop = llvm::AtomicRMWInst::BinOp::BAD_BINOP;
1186 
1187   omp::AtomicUpdateOp atomicUpdateOp = atomicCaptureOp.getAtomicUpdateOp();
1188   omp::AtomicWriteOp atomicWriteOp = atomicCaptureOp.getAtomicWriteOp();
1189 
1190   assert((atomicUpdateOp || atomicWriteOp) &&
1191          "internal op must be an atomic.update or atomic.write op");
1192 
1193   if (atomicWriteOp) {
1194     isPostfixUpdate = true;
1195     mlirExpr = atomicWriteOp.value();
1196   } else {
1197     isPostfixUpdate = atomicCaptureOp.getSecondOp() ==
1198                       atomicCaptureOp.getAtomicUpdateOp().getOperation();
1199     auto &innerOpList = atomicUpdateOp.region().front().getOperations();
1200     if (innerOpList.size() != 2)
1201       return atomicUpdateOp.emitError(
1202           "exactly two operations are allowed inside an "
1203           "atomic update region while lowering to LLVM IR");
1204     Operation *innerUpdateOp = atomicUpdateOp.getFirstOp();
1205     if (innerUpdateOp->getNumOperands() != 2 ||
1206         !llvm::is_contained(innerUpdateOp->getOperands(),
1207                             atomicUpdateOp.getRegion().getArgument(0)))
1208       return atomicUpdateOp.emitError(
1209           "the update operation inside the region must be a binary operation "
1210           "and that update operation must have the region argument as an "
1211           "operand");
1212     binop = convertBinOpToAtomic(*innerUpdateOp);
1213 
1214     isXBinopExpr = innerUpdateOp->getOperand(0) ==
1215                    atomicUpdateOp.getRegion().getArgument(0);
1216 
1217     mlirExpr = (isXBinopExpr ? innerUpdateOp->getOperand(1)
1218                              : innerUpdateOp->getOperand(0));
1219   }
1220 
1221   llvm::Value *llvmExpr = moduleTranslation.lookupValue(mlirExpr);
1222   llvm::Value *llvmX =
1223       moduleTranslation.lookupValue(atomicCaptureOp.getAtomicReadOp().x());
1224   llvm::Value *llvmV =
1225       moduleTranslation.lookupValue(atomicCaptureOp.getAtomicReadOp().v());
1226   auto mlirXType = atomicCaptureOp.getAtomicReadOp()
1227                        .x()
1228                        .getType()
1229                        .cast<LLVM::LLVMPointerType>();
1230   llvm::Type *llvmXElementType =
1231       moduleTranslation.convertType(mlirXType.getElementType());
1232   llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicX = {llvmX, llvmXElementType,
1233                                                       /*isSigned=*/false,
1234                                                       /*isVolatile=*/false};
1235   llvm::OpenMPIRBuilder::AtomicOpValue llvmAtomicV = {llvmV, llvmXElementType,
1236                                                       /*isSigned=*/false,
1237                                                       /*isVolatile=*/false};
1238 
1239   llvm::AtomicOrdering atomicOrdering =
1240       convertAtomicOrdering(atomicCaptureOp.memory_order_val());
1241 
1242   LogicalResult updateGenStatus = success();
1243   auto updateFn = [&](llvm::Value *atomicx,
1244                       llvm::IRBuilder<> &builder) -> llvm::Value * {
1245     if (atomicWriteOp)
1246       return moduleTranslation.lookupValue(atomicWriteOp.value());
1247     Block &bb = *atomicUpdateOp.region().begin();
1248     moduleTranslation.mapValue(*atomicUpdateOp.region().args_begin(), atomicx);
1249     moduleTranslation.mapBlock(&bb, builder.GetInsertBlock());
1250     if (failed(moduleTranslation.convertBlock(bb, true, builder))) {
1251       updateGenStatus = (atomicUpdateOp.emitError()
1252                          << "unable to convert update operation to llvm IR");
1253       return nullptr;
1254     }
1255     omp::YieldOp yieldop = dyn_cast<omp::YieldOp>(bb.getTerminator());
1256     assert(yieldop && yieldop.results().size() == 1 &&
1257            "terminator must be omp.yield op and it must have exactly one "
1258            "argument");
1259     return moduleTranslation.lookupValue(yieldop.results()[0]);
1260   };
1261   // Handle ambiguous alloca, if any.
1262   auto allocaIP = findAllocaInsertPoint(builder, moduleTranslation);
1263   if (allocaIP.getPoint() == ompLoc.IP.getPoint()) {
1264     // Same point => split basic block and make them unambigous.
1265     llvm::UnreachableInst *unreachableInst = builder.CreateUnreachable();
1266     builder.SetInsertPoint(builder.GetInsertBlock()->splitBasicBlock(
1267         unreachableInst, "alloca_split"));
1268     ompLoc.IP = builder.saveIP();
1269     unreachableInst->eraseFromParent();
1270   }
1271   builder.restoreIP(ompBuilder->createAtomicCapture(
1272       ompLoc, findAllocaInsertPoint(builder, moduleTranslation), llvmAtomicX,
1273       llvmAtomicV, llvmExpr, atomicOrdering, binop, updateFn, atomicUpdateOp,
1274       isPostfixUpdate, isXBinopExpr));
1275   return updateGenStatus;
1276 }
1277 
1278 /// Converts an OpenMP reduction operation using OpenMPIRBuilder. Expects the
1279 /// mapping between reduction variables and their private equivalents to have
1280 /// been stored on the ModuleTranslation stack. Currently only supports
1281 /// reduction within WsLoopOp, but can be easily extended.
1282 static LogicalResult
1283 convertOmpReductionOp(omp::ReductionOp reductionOp,
1284                       llvm::IRBuilderBase &builder,
1285                       LLVM::ModuleTranslation &moduleTranslation) {
1286   // Find the declaration that corresponds to the reduction op.
1287   auto reductionContainer = reductionOp->getParentOfType<omp::WsLoopOp>();
1288   omp::ReductionDeclareOp declaration =
1289       findReductionDecl(reductionContainer, reductionOp);
1290   assert(declaration && "could not find reduction declaration");
1291 
1292   // Retrieve the mapping between reduction variables and their private
1293   // equivalents.
1294   const DenseMap<Value, llvm::Value *> *reductionVariableMap = nullptr;
1295   moduleTranslation.stackWalk<OpenMPVarMappingStackFrame>(
1296       [&](const OpenMPVarMappingStackFrame &frame) {
1297         reductionVariableMap = &frame.mapping;
1298         return WalkResult::interrupt();
1299       });
1300   assert(reductionVariableMap && "couldn't find private reduction variables");
1301 
1302   // Translate the reduction operation by emitting the body of the corresponding
1303   // reduction declaration.
1304   Region &reductionRegion = declaration.reductionRegion();
1305   llvm::Value *privateReductionVar =
1306       reductionVariableMap->lookup(reductionOp.accumulator());
1307   llvm::Value *reductionVal = builder.CreateLoad(
1308       moduleTranslation.convertType(reductionOp.operand().getType()),
1309       privateReductionVar);
1310 
1311   moduleTranslation.mapValue(reductionRegion.front().getArgument(0),
1312                              reductionVal);
1313   moduleTranslation.mapValue(
1314       reductionRegion.front().getArgument(1),
1315       moduleTranslation.lookupValue(reductionOp.operand()));
1316 
1317   SmallVector<llvm::Value *> phis;
1318   if (failed(inlineConvertOmpRegions(reductionRegion, "omp.reduction.body",
1319                                      builder, moduleTranslation, &phis)))
1320     return failure();
1321   assert(phis.size() == 1 && "expected one value to be yielded from "
1322                              "the reduction body declaration region");
1323   builder.CreateStore(phis[0], privateReductionVar);
1324   return success();
1325 }
1326 
1327 namespace {
1328 
1329 /// Implementation of the dialect interface that converts operations belonging
1330 /// to the OpenMP dialect to LLVM IR.
1331 class OpenMPDialectLLVMIRTranslationInterface
1332     : public LLVMTranslationDialectInterface {
1333 public:
1334   using LLVMTranslationDialectInterface::LLVMTranslationDialectInterface;
1335 
1336   /// Translates the given operation to LLVM IR using the provided IR builder
1337   /// and saving the state in `moduleTranslation`.
1338   LogicalResult
1339   convertOperation(Operation *op, llvm::IRBuilderBase &builder,
1340                    LLVM::ModuleTranslation &moduleTranslation) const final;
1341 };
1342 
1343 } // namespace
1344 
1345 /// Given an OpenMP MLIR operation, create the corresponding LLVM IR
1346 /// (including OpenMP runtime calls).
1347 LogicalResult OpenMPDialectLLVMIRTranslationInterface::convertOperation(
1348     Operation *op, llvm::IRBuilderBase &builder,
1349     LLVM::ModuleTranslation &moduleTranslation) const {
1350 
1351   llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
1352 
1353   return llvm::TypeSwitch<Operation *, LogicalResult>(op)
1354       .Case([&](omp::BarrierOp) {
1355         ompBuilder->createBarrier(builder.saveIP(), llvm::omp::OMPD_barrier);
1356         return success();
1357       })
1358       .Case([&](omp::TaskwaitOp) {
1359         ompBuilder->createTaskwait(builder.saveIP());
1360         return success();
1361       })
1362       .Case([&](omp::TaskyieldOp) {
1363         ompBuilder->createTaskyield(builder.saveIP());
1364         return success();
1365       })
1366       .Case([&](omp::FlushOp) {
1367         // No support in Openmp runtime function (__kmpc_flush) to accept
1368         // the argument list.
1369         // OpenMP standard states the following:
1370         //  "An implementation may implement a flush with a list by ignoring
1371         //   the list, and treating it the same as a flush without a list."
1372         //
1373         // The argument list is discarded so that, flush with a list is treated
1374         // same as a flush without a list.
1375         ompBuilder->createFlush(builder.saveIP());
1376         return success();
1377       })
1378       .Case([&](omp::ParallelOp op) {
1379         return convertOmpParallel(op, builder, moduleTranslation);
1380       })
1381       .Case([&](omp::ReductionOp reductionOp) {
1382         return convertOmpReductionOp(reductionOp, builder, moduleTranslation);
1383       })
1384       .Case([&](omp::MasterOp) {
1385         return convertOmpMaster(*op, builder, moduleTranslation);
1386       })
1387       .Case([&](omp::CriticalOp) {
1388         return convertOmpCritical(*op, builder, moduleTranslation);
1389       })
1390       .Case([&](omp::OrderedRegionOp) {
1391         return convertOmpOrderedRegion(*op, builder, moduleTranslation);
1392       })
1393       .Case([&](omp::OrderedOp) {
1394         return convertOmpOrdered(*op, builder, moduleTranslation);
1395       })
1396       .Case([&](omp::WsLoopOp) {
1397         return convertOmpWsLoop(*op, builder, moduleTranslation);
1398       })
1399       .Case([&](omp::SimdLoopOp) {
1400         return convertOmpSimdLoop(*op, builder, moduleTranslation);
1401       })
1402       .Case([&](omp::AtomicReadOp) {
1403         return convertOmpAtomicRead(*op, builder, moduleTranslation);
1404       })
1405       .Case([&](omp::AtomicWriteOp) {
1406         return convertOmpAtomicWrite(*op, builder, moduleTranslation);
1407       })
1408       .Case([&](omp::AtomicUpdateOp op) {
1409         return convertOmpAtomicUpdate(op, builder, moduleTranslation);
1410       })
1411       .Case([&](omp::AtomicCaptureOp op) {
1412         return convertOmpAtomicCapture(op, builder, moduleTranslation);
1413       })
1414       .Case([&](omp::SectionsOp) {
1415         return convertOmpSections(*op, builder, moduleTranslation);
1416       })
1417       .Case([&](omp::SingleOp op) {
1418         return convertOmpSingle(op, builder, moduleTranslation);
1419       })
1420       .Case<omp::YieldOp, omp::TerminatorOp, omp::ReductionDeclareOp,
1421             omp::CriticalDeclareOp>([](auto op) {
1422         // `yield` and `terminator` can be just omitted. The block structure
1423         // was created in the region that handles their parent operation.
1424         // `reduction.declare` will be used by reductions and is not
1425         // converted directly, skip it.
1426         // `critical.declare` is only used to declare names of critical
1427         // sections which will be used by `critical` ops and hence can be
1428         // ignored for lowering. The OpenMP IRBuilder will create unique
1429         // name for critical section names.
1430         return success();
1431       })
1432       .Default([&](Operation *inst) {
1433         return inst->emitError("unsupported OpenMP operation: ")
1434                << inst->getName();
1435       });
1436 }
1437 
1438 void mlir::registerOpenMPDialectTranslation(DialectRegistry &registry) {
1439   registry.insert<omp::OpenMPDialect>();
1440   registry.addExtension(+[](MLIRContext *ctx, omp::OpenMPDialect *dialect) {
1441     dialect->addInterfaces<OpenMPDialectLLVMIRTranslationInterface>();
1442   });
1443 }
1444 
1445 void mlir::registerOpenMPDialectTranslation(MLIRContext &context) {
1446   DialectRegistry registry;
1447   registerOpenMPDialectTranslation(registry);
1448   context.appendDialectRegistry(registry);
1449 }
1450