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