1 //===-- OpenMP.cpp -- Open MP directive lowering --------------------------===//
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 // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "flang/Lower/OpenMP.h"
14 #include "flang/Common/idioms.h"
15 #include "flang/Lower/Bridge.h"
16 #include "flang/Lower/ConvertExpr.h"
17 #include "flang/Lower/PFTBuilder.h"
18 #include "flang/Lower/StatementContext.h"
19 #include "flang/Optimizer/Builder/BoxValue.h"
20 #include "flang/Optimizer/Builder/FIRBuilder.h"
21 #include "flang/Optimizer/Builder/Todo.h"
22 #include "flang/Parser/parse-tree.h"
23 #include "flang/Semantics/tools.h"
24 #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
25 #include "llvm/Frontend/OpenMP/OMPConstants.h"
26 
27 using namespace mlir;
28 
29 int64_t Fortran::lower::getCollapseValue(
30     const Fortran::parser::OmpClauseList &clauseList) {
31   for (const auto &clause : clauseList.v) {
32     if (const auto &collapseClause =
33             std::get_if<Fortran::parser::OmpClause::Collapse>(&clause.u)) {
34       const auto *expr = Fortran::semantics::GetExpr(collapseClause->v);
35       return Fortran::evaluate::ToInt64(*expr).value();
36     }
37   }
38   return 1;
39 }
40 
41 static const Fortran::parser::Name *
42 getDesignatorNameIfDataRef(const Fortran::parser::Designator &designator) {
43   const auto *dataRef = std::get_if<Fortran::parser::DataRef>(&designator.u);
44   return dataRef ? std::get_if<Fortran::parser::Name>(&dataRef->u) : nullptr;
45 }
46 
47 static Fortran::semantics::Symbol *
48 getOmpObjectSymbol(const Fortran::parser::OmpObject &ompObject) {
49   Fortran::semantics::Symbol *sym = nullptr;
50   std::visit(Fortran::common::visitors{
51                  [&](const Fortran::parser::Designator &designator) {
52                    if (const Fortran::parser::Name *name =
53                            getDesignatorNameIfDataRef(designator)) {
54                      sym = name->symbol;
55                    }
56                  },
57                  [&](const Fortran::parser::Name &name) { sym = name.symbol; }},
58              ompObject.u);
59   return sym;
60 }
61 
62 template <typename T>
63 static void createPrivateVarSyms(Fortran::lower::AbstractConverter &converter,
64                                  const T *clause) {
65   const Fortran::parser::OmpObjectList &ompObjectList = clause->v;
66   for (const Fortran::parser::OmpObject &ompObject : ompObjectList.v) {
67     Fortran::semantics::Symbol *sym = getOmpObjectSymbol(ompObject);
68     // Privatization for symbols which are pre-determined (like loop index
69     // variables) happen separately, for everything else privatize here.
70     if (sym->test(Fortran::semantics::Symbol::Flag::OmpPreDetermined))
71       continue;
72     bool success = converter.createHostAssociateVarClone(*sym);
73     (void)success;
74     assert(success && "Privatization failed due to existing binding");
75     if constexpr (std::is_same_v<T, Fortran::parser::OmpClause::Firstprivate>) {
76       converter.copyHostAssociateVar(*sym);
77     }
78   }
79 }
80 
81 static void privatizeVars(Fortran::lower::AbstractConverter &converter,
82                           const Fortran::parser::OmpClauseList &opClauseList) {
83   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
84   auto insPt = firOpBuilder.saveInsertionPoint();
85   firOpBuilder.setInsertionPointToStart(firOpBuilder.getAllocaBlock());
86   bool hasFirstPrivateOp = false;
87   for (const Fortran::parser::OmpClause &clause : opClauseList.v) {
88     if (const auto &privateClause =
89             std::get_if<Fortran::parser::OmpClause::Private>(&clause.u)) {
90       createPrivateVarSyms(converter, privateClause);
91     } else if (const auto &firstPrivateClause =
92                    std::get_if<Fortran::parser::OmpClause::Firstprivate>(
93                        &clause.u)) {
94       createPrivateVarSyms(converter, firstPrivateClause);
95       hasFirstPrivateOp = true;
96     }
97   }
98   if (hasFirstPrivateOp)
99     firOpBuilder.create<mlir::omp::BarrierOp>(converter.getCurrentLocation());
100   firOpBuilder.restoreInsertionPoint(insPt);
101 }
102 
103 /// The COMMON block is a global structure. \p commonValue is the base address
104 /// of the the COMMON block. As the offset from the symbol \p sym, generate the
105 /// COMMON block member value (commonValue + offset) for the symbol.
106 /// FIXME: Share the code with `instantiateCommon` in ConvertVariable.cpp.
107 static mlir::Value
108 genCommonBlockMember(Fortran::lower::AbstractConverter &converter,
109                      const Fortran::semantics::Symbol &sym,
110                      mlir::Value commonValue) {
111   auto &firOpBuilder = converter.getFirOpBuilder();
112   mlir::Location currentLocation = converter.getCurrentLocation();
113   mlir::IntegerType i8Ty = firOpBuilder.getIntegerType(8);
114   mlir::Type i8Ptr = firOpBuilder.getRefType(i8Ty);
115   mlir::Type seqTy = firOpBuilder.getRefType(firOpBuilder.getVarLenSeqTy(i8Ty));
116   mlir::Value base =
117       firOpBuilder.createConvert(currentLocation, seqTy, commonValue);
118   std::size_t byteOffset = sym.GetUltimate().offset();
119   mlir::Value offs = firOpBuilder.createIntegerConstant(
120       currentLocation, firOpBuilder.getIndexType(), byteOffset);
121   mlir::Value varAddr = firOpBuilder.create<fir::CoordinateOp>(
122       currentLocation, i8Ptr, base, mlir::ValueRange{offs});
123   mlir::Type symType = converter.genType(sym);
124   return firOpBuilder.createConvert(currentLocation,
125                                     firOpBuilder.getRefType(symType), varAddr);
126 }
127 
128 // Get the extended value for \p val by extracting additional variable
129 // information from \p base.
130 static fir::ExtendedValue getExtendedValue(fir::ExtendedValue base,
131                                            mlir::Value val) {
132   return base.match(
133       [&](const fir::MutableBoxValue &box) -> fir::ExtendedValue {
134         return fir::MutableBoxValue(val, box.nonDeferredLenParams(), {});
135       },
136       [&](const auto &) -> fir::ExtendedValue {
137         return fir::substBase(base, val);
138       });
139 }
140 
141 static void threadPrivatizeVars(Fortran::lower::AbstractConverter &converter,
142                                 Fortran::lower::pft::Evaluation &eval) {
143   auto &firOpBuilder = converter.getFirOpBuilder();
144   mlir::Location currentLocation = converter.getCurrentLocation();
145   auto insPt = firOpBuilder.saveInsertionPoint();
146   firOpBuilder.setInsertionPointToStart(firOpBuilder.getAllocaBlock());
147 
148   // Get the original ThreadprivateOp corresponding to the symbol and use the
149   // symbol value from that opeartion to create one ThreadprivateOp copy
150   // operation inside the parallel region.
151   auto genThreadprivateOp = [&](Fortran::lower::SymbolRef sym) -> mlir::Value {
152     mlir::Value symOriThreadprivateValue = converter.getSymbolAddress(sym);
153     mlir::Operation *op = symOriThreadprivateValue.getDefiningOp();
154     assert(mlir::isa<mlir::omp::ThreadprivateOp>(op) &&
155            "The threadprivate operation not created");
156     mlir::Value symValue =
157         mlir::dyn_cast<mlir::omp::ThreadprivateOp>(op).sym_addr();
158     return firOpBuilder.create<mlir::omp::ThreadprivateOp>(
159         currentLocation, symValue.getType(), symValue);
160   };
161 
162   llvm::SetVector<const Fortran::semantics::Symbol *> threadprivateSyms;
163   converter.collectSymbolSet(eval, threadprivateSyms,
164                              Fortran::semantics::Symbol::Flag::OmpThreadprivate,
165                              /*isUltimateSymbol=*/false);
166   std::set<Fortran::semantics::SourceName> threadprivateSymNames;
167 
168   // For a COMMON block, the ThreadprivateOp is generated for itself instead of
169   // its members, so only bind the value of the new copied ThreadprivateOp
170   // inside the parallel region to the common block symbol only once for
171   // multiple members in one COMMON block.
172   llvm::SetVector<const Fortran::semantics::Symbol *> commonSyms;
173   for (std::size_t i = 0; i < threadprivateSyms.size(); i++) {
174     auto sym = threadprivateSyms[i];
175     mlir::Value symThreadprivateValue;
176     // The variable may be used more than once, and each reference has one
177     // symbol with the same name. Only do once for references of one variable.
178     if (threadprivateSymNames.find(sym->name()) != threadprivateSymNames.end())
179       continue;
180     threadprivateSymNames.insert(sym->name());
181     if (const Fortran::semantics::Symbol *common =
182             Fortran::semantics::FindCommonBlockContaining(sym->GetUltimate())) {
183       mlir::Value commonThreadprivateValue;
184       if (commonSyms.contains(common)) {
185         commonThreadprivateValue = converter.getSymbolAddress(*common);
186       } else {
187         commonThreadprivateValue = genThreadprivateOp(*common);
188         converter.bindSymbol(*common, commonThreadprivateValue);
189         commonSyms.insert(common);
190       }
191       symThreadprivateValue =
192           genCommonBlockMember(converter, *sym, commonThreadprivateValue);
193     } else {
194       symThreadprivateValue = genThreadprivateOp(*sym);
195     }
196 
197     fir::ExtendedValue sexv = converter.getSymbolExtendedValue(*sym);
198     fir::ExtendedValue symThreadprivateExv =
199         getExtendedValue(sexv, symThreadprivateValue);
200     converter.bindSymbol(*sym, symThreadprivateExv);
201   }
202 
203   firOpBuilder.restoreInsertionPoint(insPt);
204 }
205 
206 static void
207 genCopyinClause(Fortran::lower::AbstractConverter &converter,
208                 const Fortran::parser::OmpClauseList &opClauseList) {
209   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
210   mlir::OpBuilder::InsertPoint insPt = firOpBuilder.saveInsertionPoint();
211   firOpBuilder.setInsertionPointToStart(firOpBuilder.getAllocaBlock());
212   bool hasCopyin = false;
213   for (const Fortran::parser::OmpClause &clause : opClauseList.v) {
214     if (const auto &copyinClause =
215             std::get_if<Fortran::parser::OmpClause::Copyin>(&clause.u)) {
216       hasCopyin = true;
217       const Fortran::parser::OmpObjectList &ompObjectList = copyinClause->v;
218       for (const Fortran::parser::OmpObject &ompObject : ompObjectList.v) {
219         Fortran::semantics::Symbol *sym = getOmpObjectSymbol(ompObject);
220         if (sym->has<Fortran::semantics::CommonBlockDetails>())
221           TODO(converter.getCurrentLocation(), "common block in Copyin clause");
222         if (Fortran::semantics::IsAllocatableOrPointer(sym->GetUltimate()))
223           TODO(converter.getCurrentLocation(),
224                "pointer or allocatable variables in Copyin clause");
225         assert(sym->has<Fortran::semantics::HostAssocDetails>() &&
226                "No host-association found");
227         converter.copyHostAssociateVar(*sym);
228       }
229     }
230   }
231   if (hasCopyin)
232     firOpBuilder.create<mlir::omp::BarrierOp>(converter.getCurrentLocation());
233   firOpBuilder.restoreInsertionPoint(insPt);
234 }
235 
236 static void genObjectList(const Fortran::parser::OmpObjectList &objectList,
237                           Fortran::lower::AbstractConverter &converter,
238                           llvm::SmallVectorImpl<Value> &operands) {
239   auto addOperands = [&](Fortran::lower::SymbolRef sym) {
240     const mlir::Value variable = converter.getSymbolAddress(sym);
241     if (variable) {
242       operands.push_back(variable);
243     } else {
244       if (const auto *details =
245               sym->detailsIf<Fortran::semantics::HostAssocDetails>()) {
246         operands.push_back(converter.getSymbolAddress(details->symbol()));
247         converter.copySymbolBinding(details->symbol(), sym);
248       }
249     }
250   };
251   for (const Fortran::parser::OmpObject &ompObject : objectList.v) {
252     Fortran::semantics::Symbol *sym = getOmpObjectSymbol(ompObject);
253     addOperands(*sym);
254   }
255 }
256 
257 static mlir::Type getLoopVarType(Fortran::lower::AbstractConverter &converter,
258                                  std::size_t loopVarTypeSize) {
259   // OpenMP runtime requires 32-bit or 64-bit loop variables.
260   loopVarTypeSize = loopVarTypeSize * 8;
261   if (loopVarTypeSize < 32) {
262     loopVarTypeSize = 32;
263   } else if (loopVarTypeSize > 64) {
264     loopVarTypeSize = 64;
265     mlir::emitWarning(converter.getCurrentLocation(),
266                       "OpenMP loop iteration variable cannot have more than 64 "
267                       "bits size and will be narrowed into 64 bits.");
268   }
269   assert((loopVarTypeSize == 32 || loopVarTypeSize == 64) &&
270          "OpenMP loop iteration variable size must be transformed into 32-bit "
271          "or 64-bit");
272   return converter.getFirOpBuilder().getIntegerType(loopVarTypeSize);
273 }
274 
275 /// Create empty blocks for the current region.
276 /// These blocks replace blocks parented to an enclosing region.
277 void createEmptyRegionBlocks(
278     fir::FirOpBuilder &firOpBuilder,
279     std::list<Fortran::lower::pft::Evaluation> &evaluationList) {
280   auto *region = &firOpBuilder.getRegion();
281   for (auto &eval : evaluationList) {
282     if (eval.block) {
283       if (eval.block->empty()) {
284         eval.block->erase();
285         eval.block = firOpBuilder.createBlock(region);
286       } else {
287         [[maybe_unused]] auto &terminatorOp = eval.block->back();
288         assert((mlir::isa<mlir::omp::TerminatorOp>(terminatorOp) ||
289                 mlir::isa<mlir::omp::YieldOp>(terminatorOp)) &&
290                "expected terminator op");
291       }
292     }
293     if (!eval.isDirective() && eval.hasNestedEvaluations())
294       createEmptyRegionBlocks(firOpBuilder, eval.getNestedEvaluations());
295   }
296 }
297 
298 /// Create the body (block) for an OpenMP Operation.
299 ///
300 /// \param [in]    op - the operation the body belongs to.
301 /// \param [inout] converter - converter to use for the clauses.
302 /// \param [in]    loc - location in source code.
303 /// \param [in]    eval - current PFT node/evaluation.
304 /// \oaran [in]    clauses - list of clauses to process.
305 /// \param [in]    args - block arguments (induction variable[s]) for the
306 ////                      region.
307 /// \param [in]    outerCombined - is this an outer operation - prevents
308 ///                                privatization.
309 template <typename Op>
310 static void
311 createBodyOfOp(Op &op, Fortran::lower::AbstractConverter &converter,
312                mlir::Location &loc, Fortran::lower::pft::Evaluation &eval,
313                const Fortran::parser::OmpClauseList *clauses = nullptr,
314                const SmallVector<const Fortran::semantics::Symbol *> &args = {},
315                bool outerCombined = false) {
316   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
317   // If an argument for the region is provided then create the block with that
318   // argument. Also update the symbol's address with the mlir argument value.
319   // e.g. For loops the argument is the induction variable. And all further
320   // uses of the induction variable should use this mlir value.
321   mlir::Operation *storeOp = nullptr;
322   if (args.size()) {
323     std::size_t loopVarTypeSize = 0;
324     for (const Fortran::semantics::Symbol *arg : args)
325       loopVarTypeSize = std::max(loopVarTypeSize, arg->GetUltimate().size());
326     mlir::Type loopVarType = getLoopVarType(converter, loopVarTypeSize);
327     SmallVector<Type> tiv;
328     SmallVector<Location> locs;
329     for (int i = 0; i < (int)args.size(); i++) {
330       tiv.push_back(loopVarType);
331       locs.push_back(loc);
332     }
333     firOpBuilder.createBlock(&op.getRegion(), {}, tiv, locs);
334     int argIndex = 0;
335     // The argument is not currently in memory, so make a temporary for the
336     // argument, and store it there, then bind that location to the argument.
337     for (const Fortran::semantics::Symbol *arg : args) {
338       mlir::Value val =
339           fir::getBase(op.getRegion().front().getArgument(argIndex));
340       mlir::Value temp = firOpBuilder.createTemporary(
341           loc, loopVarType,
342           llvm::ArrayRef<mlir::NamedAttribute>{
343               Fortran::lower::getAdaptToByRefAttr(firOpBuilder)});
344       storeOp = firOpBuilder.create<fir::StoreOp>(loc, val, temp);
345       converter.bindSymbol(*arg, temp);
346       argIndex++;
347     }
348   } else {
349     firOpBuilder.createBlock(&op.getRegion());
350   }
351   // Set the insert for the terminator operation to go at the end of the
352   // block - this is either empty or the block with the stores above,
353   // the end of the block works for both.
354   mlir::Block &block = op.getRegion().back();
355   firOpBuilder.setInsertionPointToEnd(&block);
356 
357   // If it is an unstructured region and is not the outer region of a combined
358   // construct, create empty blocks for all evaluations.
359   if (eval.lowerAsUnstructured() && !outerCombined)
360     createEmptyRegionBlocks(firOpBuilder, eval.getNestedEvaluations());
361 
362   // Insert the terminator.
363   if constexpr (std::is_same_v<Op, omp::WsLoopOp> ||
364                 std::is_same_v<Op, omp::SimdLoopOp>) {
365     mlir::ValueRange results;
366     firOpBuilder.create<mlir::omp::YieldOp>(loc, results);
367   } else {
368     firOpBuilder.create<mlir::omp::TerminatorOp>(loc);
369   }
370 
371   // Reset the insert point to before the terminator.
372   if (storeOp)
373     firOpBuilder.setInsertionPointAfter(storeOp);
374   else
375     firOpBuilder.setInsertionPointToStart(&block);
376 
377   // Handle privatization. Do not privatize if this is the outer operation.
378   if (clauses && !outerCombined)
379     privatizeVars(converter, *clauses);
380 
381   if constexpr (std::is_same_v<Op, omp::ParallelOp>) {
382     threadPrivatizeVars(converter, eval);
383     if (clauses)
384       genCopyinClause(converter, *clauses);
385   }
386 }
387 
388 static void genOMP(Fortran::lower::AbstractConverter &converter,
389                    Fortran::lower::pft::Evaluation &eval,
390                    const Fortran::parser::OpenMPSimpleStandaloneConstruct
391                        &simpleStandaloneConstruct) {
392   const auto &directive =
393       std::get<Fortran::parser::OmpSimpleStandaloneDirective>(
394           simpleStandaloneConstruct.t);
395   switch (directive.v) {
396   default:
397     break;
398   case llvm::omp::Directive::OMPD_barrier:
399     converter.getFirOpBuilder().create<mlir::omp::BarrierOp>(
400         converter.getCurrentLocation());
401     break;
402   case llvm::omp::Directive::OMPD_taskwait:
403     converter.getFirOpBuilder().create<mlir::omp::TaskwaitOp>(
404         converter.getCurrentLocation());
405     break;
406   case llvm::omp::Directive::OMPD_taskyield:
407     converter.getFirOpBuilder().create<mlir::omp::TaskyieldOp>(
408         converter.getCurrentLocation());
409     break;
410   case llvm::omp::Directive::OMPD_target_enter_data:
411     TODO(converter.getCurrentLocation(), "OMPD_target_enter_data");
412   case llvm::omp::Directive::OMPD_target_exit_data:
413     TODO(converter.getCurrentLocation(), "OMPD_target_exit_data");
414   case llvm::omp::Directive::OMPD_target_update:
415     TODO(converter.getCurrentLocation(), "OMPD_target_update");
416   case llvm::omp::Directive::OMPD_ordered:
417     TODO(converter.getCurrentLocation(), "OMPD_ordered");
418   }
419 }
420 
421 static void
422 genAllocateClause(Fortran::lower::AbstractConverter &converter,
423                   const Fortran::parser::OmpAllocateClause &ompAllocateClause,
424                   SmallVector<Value> &allocatorOperands,
425                   SmallVector<Value> &allocateOperands) {
426   auto &firOpBuilder = converter.getFirOpBuilder();
427   auto currentLocation = converter.getCurrentLocation();
428   Fortran::lower::StatementContext stmtCtx;
429 
430   mlir::Value allocatorOperand;
431   const Fortran::parser::OmpObjectList &ompObjectList =
432       std::get<Fortran::parser::OmpObjectList>(ompAllocateClause.t);
433   const auto &allocatorValue =
434       std::get<std::optional<Fortran::parser::OmpAllocateClause::Allocator>>(
435           ompAllocateClause.t);
436   // Check if allocate clause has allocator specified. If so, add it
437   // to list of allocators, otherwise, add default allocator to
438   // list of allocators.
439   if (allocatorValue) {
440     allocatorOperand = fir::getBase(converter.genExprValue(
441         *Fortran::semantics::GetExpr(allocatorValue->v), stmtCtx));
442     allocatorOperands.insert(allocatorOperands.end(), ompObjectList.v.size(),
443                              allocatorOperand);
444   } else {
445     allocatorOperand = firOpBuilder.createIntegerConstant(
446         currentLocation, firOpBuilder.getI32Type(), 1);
447     allocatorOperands.insert(allocatorOperands.end(), ompObjectList.v.size(),
448                              allocatorOperand);
449   }
450   genObjectList(ompObjectList, converter, allocateOperands);
451 }
452 
453 static void
454 genOMP(Fortran::lower::AbstractConverter &converter,
455        Fortran::lower::pft::Evaluation &eval,
456        const Fortran::parser::OpenMPStandaloneConstruct &standaloneConstruct) {
457   std::visit(
458       Fortran::common::visitors{
459           [&](const Fortran::parser::OpenMPSimpleStandaloneConstruct
460                   &simpleStandaloneConstruct) {
461             genOMP(converter, eval, simpleStandaloneConstruct);
462           },
463           [&](const Fortran::parser::OpenMPFlushConstruct &flushConstruct) {
464             SmallVector<Value, 4> operandRange;
465             if (const auto &ompObjectList =
466                     std::get<std::optional<Fortran::parser::OmpObjectList>>(
467                         flushConstruct.t))
468               genObjectList(*ompObjectList, converter, operandRange);
469             const auto &memOrderClause = std::get<std::optional<
470                 std::list<Fortran::parser::OmpMemoryOrderClause>>>(
471                 flushConstruct.t);
472             if (memOrderClause.has_value() && memOrderClause->size() > 0)
473               TODO(converter.getCurrentLocation(),
474                    "Handle OmpMemoryOrderClause");
475             converter.getFirOpBuilder().create<mlir::omp::FlushOp>(
476                 converter.getCurrentLocation(), operandRange);
477           },
478           [&](const Fortran::parser::OpenMPCancelConstruct &cancelConstruct) {
479             TODO(converter.getCurrentLocation(), "OpenMPCancelConstruct");
480           },
481           [&](const Fortran::parser::OpenMPCancellationPointConstruct
482                   &cancellationPointConstruct) {
483             TODO(converter.getCurrentLocation(), "OpenMPCancelConstruct");
484           },
485       },
486       standaloneConstruct.u);
487 }
488 
489 static omp::ClauseProcBindKindAttr genProcBindKindAttr(
490     fir::FirOpBuilder &firOpBuilder,
491     const Fortran::parser::OmpClause::ProcBind *procBindClause) {
492   omp::ClauseProcBindKind pbKind;
493   switch (procBindClause->v.v) {
494   case Fortran::parser::OmpProcBindClause::Type::Master:
495     pbKind = omp::ClauseProcBindKind::Master;
496     break;
497   case Fortran::parser::OmpProcBindClause::Type::Close:
498     pbKind = omp::ClauseProcBindKind::Close;
499     break;
500   case Fortran::parser::OmpProcBindClause::Type::Spread:
501     pbKind = omp::ClauseProcBindKind::Spread;
502     break;
503   case Fortran::parser::OmpProcBindClause::Type::Primary:
504     pbKind = omp::ClauseProcBindKind::Primary;
505     break;
506   }
507   return omp::ClauseProcBindKindAttr::get(firOpBuilder.getContext(), pbKind);
508 }
509 
510 /* When parallel is used in a combined construct, then use this function to
511  * create the parallel operation. It handles the parallel specific clauses
512  * and leaves the rest for handling at the inner operations.
513  * TODO: Refactor clause handling
514  */
515 template <typename Directive>
516 static void
517 createCombinedParallelOp(Fortran::lower::AbstractConverter &converter,
518                          Fortran::lower::pft::Evaluation &eval,
519                          const Directive &directive) {
520   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
521   mlir::Location currentLocation = converter.getCurrentLocation();
522   Fortran::lower::StatementContext stmtCtx;
523   llvm::ArrayRef<mlir::Type> argTy;
524   mlir::Value ifClauseOperand, numThreadsClauseOperand;
525   SmallVector<Value> allocatorOperands, allocateOperands;
526   mlir::omp::ClauseProcBindKindAttr procBindKindAttr;
527   const auto &opClauseList =
528       std::get<Fortran::parser::OmpClauseList>(directive.t);
529   // TODO: Handle the following clauses
530   // 1. default
531   // Note: rest of the clauses are handled when the inner operation is created
532   for (const Fortran::parser::OmpClause &clause : opClauseList.v) {
533     if (const auto &ifClause =
534             std::get_if<Fortran::parser::OmpClause::If>(&clause.u)) {
535       auto &expr = std::get<Fortran::parser::ScalarLogicalExpr>(ifClause->v.t);
536       mlir::Value ifVal = fir::getBase(
537           converter.genExprValue(*Fortran::semantics::GetExpr(expr), stmtCtx));
538       ifClauseOperand = firOpBuilder.createConvert(
539           currentLocation, firOpBuilder.getI1Type(), ifVal);
540     } else if (const auto &numThreadsClause =
541                    std::get_if<Fortran::parser::OmpClause::NumThreads>(
542                        &clause.u)) {
543       numThreadsClauseOperand = fir::getBase(converter.genExprValue(
544           *Fortran::semantics::GetExpr(numThreadsClause->v), stmtCtx));
545     } else if (const auto &procBindClause =
546                    std::get_if<Fortran::parser::OmpClause::ProcBind>(
547                        &clause.u)) {
548       procBindKindAttr = genProcBindKindAttr(firOpBuilder, procBindClause);
549     }
550   }
551   // Create and insert the operation.
552   auto parallelOp = firOpBuilder.create<mlir::omp::ParallelOp>(
553       currentLocation, argTy, ifClauseOperand, numThreadsClauseOperand,
554       allocateOperands, allocatorOperands, /*reduction_vars=*/ValueRange(),
555       /*reductions=*/nullptr, procBindKindAttr);
556 
557   createBodyOfOp<omp::ParallelOp>(parallelOp, converter, currentLocation, eval,
558                                   &opClauseList, /*iv=*/{},
559                                   /*isCombined=*/true);
560 }
561 
562 static void
563 genOMP(Fortran::lower::AbstractConverter &converter,
564        Fortran::lower::pft::Evaluation &eval,
565        const Fortran::parser::OpenMPBlockConstruct &blockConstruct) {
566   const auto &beginBlockDirective =
567       std::get<Fortran::parser::OmpBeginBlockDirective>(blockConstruct.t);
568   const auto &blockDirective =
569       std::get<Fortran::parser::OmpBlockDirective>(beginBlockDirective.t);
570   const auto &endBlockDirective =
571       std::get<Fortran::parser::OmpEndBlockDirective>(blockConstruct.t);
572   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
573   mlir::Location currentLocation = converter.getCurrentLocation();
574 
575   Fortran::lower::StatementContext stmtCtx;
576   llvm::ArrayRef<mlir::Type> argTy;
577   mlir::Value ifClauseOperand, numThreadsClauseOperand, finalClauseOperand,
578       priorityClauseOperand;
579   mlir::omp::ClauseProcBindKindAttr procBindKindAttr;
580   SmallVector<Value> allocateOperands, allocatorOperands;
581   mlir::UnitAttr nowaitAttr, untiedAttr, mergeableAttr;
582 
583   const auto &opClauseList =
584       std::get<Fortran::parser::OmpClauseList>(beginBlockDirective.t);
585   for (const auto &clause : opClauseList.v) {
586     if (const auto &ifClause =
587             std::get_if<Fortran::parser::OmpClause::If>(&clause.u)) {
588       auto &expr = std::get<Fortran::parser::ScalarLogicalExpr>(ifClause->v.t);
589       mlir::Value ifVal = fir::getBase(
590           converter.genExprValue(*Fortran::semantics::GetExpr(expr), stmtCtx));
591       ifClauseOperand = firOpBuilder.createConvert(
592           currentLocation, firOpBuilder.getI1Type(), ifVal);
593     } else if (const auto &numThreadsClause =
594                    std::get_if<Fortran::parser::OmpClause::NumThreads>(
595                        &clause.u)) {
596       // OMPIRBuilder expects `NUM_THREAD` clause as a `Value`.
597       numThreadsClauseOperand = fir::getBase(converter.genExprValue(
598           *Fortran::semantics::GetExpr(numThreadsClause->v), stmtCtx));
599     } else if (const auto &procBindClause =
600                    std::get_if<Fortran::parser::OmpClause::ProcBind>(
601                        &clause.u)) {
602       procBindKindAttr = genProcBindKindAttr(firOpBuilder, procBindClause);
603     } else if (const auto &allocateClause =
604                    std::get_if<Fortran::parser::OmpClause::Allocate>(
605                        &clause.u)) {
606       genAllocateClause(converter, allocateClause->v, allocatorOperands,
607                         allocateOperands);
608     } else if (std::get_if<Fortran::parser::OmpClause::Private>(&clause.u) ||
609                std::get_if<Fortran::parser::OmpClause::Firstprivate>(
610                    &clause.u) ||
611                std::get_if<Fortran::parser::OmpClause::Copyin>(&clause.u)) {
612       // Privatisation and copyin clauses are handled elsewhere.
613       continue;
614     } else if (std::get_if<Fortran::parser::OmpClause::Shared>(&clause.u)) {
615       // Shared is the default behavior in the IR, so no handling is required.
616       continue;
617     } else if (const auto &defaultClause =
618                    std::get_if<Fortran::parser::OmpClause::Default>(
619                        &clause.u)) {
620       if ((defaultClause->v.v ==
621            Fortran::parser::OmpDefaultClause::Type::Shared) ||
622           (defaultClause->v.v ==
623            Fortran::parser::OmpDefaultClause::Type::None)) {
624         // Default clause with shared or none do not require any handling since
625         // Shared is the default behavior in the IR and None is only required
626         // for semantic checks.
627         continue;
628       }
629     } else if (std::get_if<Fortran::parser::OmpClause::Threads>(&clause.u)) {
630       // Nothing needs to be done for threads clause.
631       continue;
632     } else if (const auto &finalClause =
633                    std::get_if<Fortran::parser::OmpClause::Final>(&clause.u)) {
634       mlir::Value finalVal = fir::getBase(converter.genExprValue(
635           *Fortran::semantics::GetExpr(finalClause->v), stmtCtx));
636       finalClauseOperand = firOpBuilder.createConvert(
637           currentLocation, firOpBuilder.getI1Type(), finalVal);
638     } else if (std::get_if<Fortran::parser::OmpClause::Untied>(&clause.u)) {
639       untiedAttr = firOpBuilder.getUnitAttr();
640     } else if (std::get_if<Fortran::parser::OmpClause::Mergeable>(&clause.u)) {
641       mergeableAttr = firOpBuilder.getUnitAttr();
642     } else if (const auto &priorityClause =
643                    std::get_if<Fortran::parser::OmpClause::Priority>(
644                        &clause.u)) {
645       priorityClauseOperand = fir::getBase(converter.genExprValue(
646           *Fortran::semantics::GetExpr(priorityClause->v), stmtCtx));
647     } else {
648       TODO(currentLocation, "OpenMP Block construct clauses");
649     }
650   }
651 
652   for (const auto &clause :
653        std::get<Fortran::parser::OmpClauseList>(endBlockDirective.t).v) {
654     if (std::get_if<Fortran::parser::OmpClause::Nowait>(&clause.u))
655       nowaitAttr = firOpBuilder.getUnitAttr();
656   }
657 
658   if (blockDirective.v == llvm::omp::OMPD_parallel) {
659     // Create and insert the operation.
660     auto parallelOp = firOpBuilder.create<mlir::omp::ParallelOp>(
661         currentLocation, argTy, ifClauseOperand, numThreadsClauseOperand,
662         allocateOperands, allocatorOperands, /*reduction_vars=*/ValueRange(),
663         /*reductions=*/nullptr, procBindKindAttr);
664     createBodyOfOp<omp::ParallelOp>(parallelOp, converter, currentLocation,
665                                     eval, &opClauseList);
666   } else if (blockDirective.v == llvm::omp::OMPD_master) {
667     auto masterOp =
668         firOpBuilder.create<mlir::omp::MasterOp>(currentLocation, argTy);
669     createBodyOfOp<omp::MasterOp>(masterOp, converter, currentLocation, eval);
670   } else if (blockDirective.v == llvm::omp::OMPD_single) {
671     auto singleOp = firOpBuilder.create<mlir::omp::SingleOp>(
672         currentLocation, allocateOperands, allocatorOperands, nowaitAttr);
673     createBodyOfOp<omp::SingleOp>(singleOp, converter, currentLocation, eval);
674   } else if (blockDirective.v == llvm::omp::OMPD_ordered) {
675     auto orderedOp = firOpBuilder.create<mlir::omp::OrderedRegionOp>(
676         currentLocation, /*simd=*/nullptr);
677     createBodyOfOp<omp::OrderedRegionOp>(orderedOp, converter, currentLocation,
678                                          eval);
679   } else if (blockDirective.v == llvm::omp::OMPD_task) {
680     auto taskOp = firOpBuilder.create<mlir::omp::TaskOp>(
681         currentLocation, ifClauseOperand, finalClauseOperand, untiedAttr,
682         mergeableAttr, /*in_reduction_vars=*/ValueRange(),
683         /*in_reductions=*/nullptr, priorityClauseOperand, allocateOperands,
684         allocatorOperands);
685     createBodyOfOp(taskOp, converter, currentLocation, eval, &opClauseList);
686   } else {
687     TODO(converter.getCurrentLocation(), "Unhandled block directive");
688   }
689 }
690 
691 static mlir::omp::ScheduleModifier
692 translateModifier(const Fortran::parser::OmpScheduleModifierType &m) {
693   switch (m.v) {
694   case Fortran::parser::OmpScheduleModifierType::ModType::Monotonic:
695     return mlir::omp::ScheduleModifier::monotonic;
696   case Fortran::parser::OmpScheduleModifierType::ModType::Nonmonotonic:
697     return mlir::omp::ScheduleModifier::nonmonotonic;
698   case Fortran::parser::OmpScheduleModifierType::ModType::Simd:
699     return mlir::omp::ScheduleModifier::simd;
700   }
701   return mlir::omp::ScheduleModifier::none;
702 }
703 
704 static mlir::omp::ScheduleModifier
705 getScheduleModifier(const Fortran::parser::OmpScheduleClause &x) {
706   const auto &modifier =
707       std::get<std::optional<Fortran::parser::OmpScheduleModifier>>(x.t);
708   // The input may have the modifier any order, so we look for one that isn't
709   // SIMD. If modifier is not set at all, fall down to the bottom and return
710   // "none".
711   if (modifier) {
712     const auto &modType1 =
713         std::get<Fortran::parser::OmpScheduleModifier::Modifier1>(modifier->t);
714     if (modType1.v.v ==
715         Fortran::parser::OmpScheduleModifierType::ModType::Simd) {
716       const auto &modType2 = std::get<
717           std::optional<Fortran::parser::OmpScheduleModifier::Modifier2>>(
718           modifier->t);
719       if (modType2 &&
720           modType2->v.v !=
721               Fortran::parser::OmpScheduleModifierType::ModType::Simd)
722         return translateModifier(modType2->v);
723 
724       return mlir::omp::ScheduleModifier::none;
725     }
726 
727     return translateModifier(modType1.v);
728   }
729   return mlir::omp::ScheduleModifier::none;
730 }
731 
732 static mlir::omp::ScheduleModifier
733 getSIMDModifier(const Fortran::parser::OmpScheduleClause &x) {
734   const auto &modifier =
735       std::get<std::optional<Fortran::parser::OmpScheduleModifier>>(x.t);
736   // Either of the two possible modifiers in the input can be the SIMD modifier,
737   // so look in either one, and return simd if we find one. Not found = return
738   // "none".
739   if (modifier) {
740     const auto &modType1 =
741         std::get<Fortran::parser::OmpScheduleModifier::Modifier1>(modifier->t);
742     if (modType1.v.v == Fortran::parser::OmpScheduleModifierType::ModType::Simd)
743       return mlir::omp::ScheduleModifier::simd;
744 
745     const auto &modType2 = std::get<
746         std::optional<Fortran::parser::OmpScheduleModifier::Modifier2>>(
747         modifier->t);
748     if (modType2 && modType2->v.v ==
749                         Fortran::parser::OmpScheduleModifierType::ModType::Simd)
750       return mlir::omp::ScheduleModifier::simd;
751   }
752   return mlir::omp::ScheduleModifier::none;
753 }
754 
755 static void genOMP(Fortran::lower::AbstractConverter &converter,
756                    Fortran::lower::pft::Evaluation &eval,
757                    const Fortran::parser::OpenMPLoopConstruct &loopConstruct) {
758 
759   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
760   mlir::Location currentLocation = converter.getCurrentLocation();
761   llvm::SmallVector<mlir::Value> lowerBound, upperBound, step, linearVars,
762       linearStepVars, reductionVars;
763   mlir::Value scheduleChunkClauseOperand;
764   mlir::Attribute scheduleClauseOperand, noWaitClauseOperand,
765       orderedClauseOperand, orderClauseOperand;
766   const auto &loopOpClauseList = std::get<Fortran::parser::OmpClauseList>(
767       std::get<Fortran::parser::OmpBeginLoopDirective>(loopConstruct.t).t);
768 
769   const auto ompDirective =
770       std::get<Fortran::parser::OmpLoopDirective>(
771           std::get<Fortran::parser::OmpBeginLoopDirective>(loopConstruct.t).t)
772           .v;
773   if (llvm::omp::OMPD_parallel_do == ompDirective) {
774     createCombinedParallelOp<Fortran::parser::OmpBeginLoopDirective>(
775         converter, eval,
776         std::get<Fortran::parser::OmpBeginLoopDirective>(loopConstruct.t));
777   } else if (llvm::omp::OMPD_do != ompDirective &&
778              llvm::omp::OMPD_simd != ompDirective) {
779     TODO(converter.getCurrentLocation(), "Construct enclosing do loop");
780   }
781 
782   // Collect the loops to collapse.
783   auto *doConstructEval = &eval.getFirstNestedEvaluation();
784 
785   std::int64_t collapseValue =
786       Fortran::lower::getCollapseValue(loopOpClauseList);
787   std::size_t loopVarTypeSize = 0;
788   SmallVector<const Fortran::semantics::Symbol *> iv;
789   do {
790     auto *doLoop = &doConstructEval->getFirstNestedEvaluation();
791     auto *doStmt = doLoop->getIf<Fortran::parser::NonLabelDoStmt>();
792     assert(doStmt && "Expected do loop to be in the nested evaluation");
793     const auto &loopControl =
794         std::get<std::optional<Fortran::parser::LoopControl>>(doStmt->t);
795     const Fortran::parser::LoopControl::Bounds *bounds =
796         std::get_if<Fortran::parser::LoopControl::Bounds>(&loopControl->u);
797     assert(bounds && "Expected bounds for worksharing do loop");
798     Fortran::lower::StatementContext stmtCtx;
799     lowerBound.push_back(fir::getBase(converter.genExprValue(
800         *Fortran::semantics::GetExpr(bounds->lower), stmtCtx)));
801     upperBound.push_back(fir::getBase(converter.genExprValue(
802         *Fortran::semantics::GetExpr(bounds->upper), stmtCtx)));
803     if (bounds->step) {
804       step.push_back(fir::getBase(converter.genExprValue(
805           *Fortran::semantics::GetExpr(bounds->step), stmtCtx)));
806     } else { // If `step` is not present, assume it as `1`.
807       step.push_back(firOpBuilder.createIntegerConstant(
808           currentLocation, firOpBuilder.getIntegerType(32), 1));
809     }
810     iv.push_back(bounds->name.thing.symbol);
811     loopVarTypeSize = std::max(loopVarTypeSize,
812                                bounds->name.thing.symbol->GetUltimate().size());
813 
814     collapseValue--;
815     doConstructEval =
816         &*std::next(doConstructEval->getNestedEvaluations().begin());
817   } while (collapseValue > 0);
818 
819   for (const auto &clause : loopOpClauseList.v) {
820     if (const auto &scheduleClause =
821             std::get_if<Fortran::parser::OmpClause::Schedule>(&clause.u)) {
822       if (const auto &chunkExpr =
823               std::get<std::optional<Fortran::parser::ScalarIntExpr>>(
824                   scheduleClause->v.t)) {
825         if (const auto *expr = Fortran::semantics::GetExpr(*chunkExpr)) {
826           Fortran::lower::StatementContext stmtCtx;
827           scheduleChunkClauseOperand =
828               fir::getBase(converter.genExprValue(*expr, stmtCtx));
829         }
830       }
831     }
832   }
833 
834   // The types of lower bound, upper bound, and step are converted into the
835   // type of the loop variable if necessary.
836   mlir::Type loopVarType = getLoopVarType(converter, loopVarTypeSize);
837   for (unsigned it = 0; it < (unsigned)lowerBound.size(); it++) {
838     lowerBound[it] = firOpBuilder.createConvert(currentLocation, loopVarType,
839                                                 lowerBound[it]);
840     upperBound[it] = firOpBuilder.createConvert(currentLocation, loopVarType,
841                                                 upperBound[it]);
842     step[it] =
843         firOpBuilder.createConvert(currentLocation, loopVarType, step[it]);
844   }
845 
846   // 2.9.3.1 SIMD construct
847   // TODO: Support all the clauses
848   if (llvm::omp::OMPD_simd == ompDirective) {
849     TypeRange resultType;
850     auto SimdLoopOp = firOpBuilder.create<mlir::omp::SimdLoopOp>(
851         currentLocation, resultType, lowerBound, upperBound, step);
852     createBodyOfOp<omp::SimdLoopOp>(SimdLoopOp, converter, currentLocation,
853                                     eval, &loopOpClauseList, iv);
854     return;
855   }
856 
857   // FIXME: Add support for following clauses:
858   // 1. linear
859   // 2. order
860   auto wsLoopOp = firOpBuilder.create<mlir::omp::WsLoopOp>(
861       currentLocation, lowerBound, upperBound, step, linearVars, linearStepVars,
862       reductionVars, /*reductions=*/nullptr,
863       scheduleClauseOperand.dyn_cast_or_null<omp::ClauseScheduleKindAttr>(),
864       scheduleChunkClauseOperand, /*schedule_modifiers=*/nullptr,
865       /*simd_modifier=*/nullptr,
866       noWaitClauseOperand.dyn_cast_or_null<UnitAttr>(),
867       orderedClauseOperand.dyn_cast_or_null<IntegerAttr>(),
868       orderClauseOperand.dyn_cast_or_null<omp::ClauseOrderKindAttr>(),
869       /*inclusive=*/firOpBuilder.getUnitAttr());
870 
871   // Handle attribute based clauses.
872   for (const Fortran::parser::OmpClause &clause : loopOpClauseList.v) {
873     if (const auto &orderedClause =
874             std::get_if<Fortran::parser::OmpClause::Ordered>(&clause.u)) {
875       if (orderedClause->v.has_value()) {
876         const auto *expr = Fortran::semantics::GetExpr(orderedClause->v);
877         const std::optional<std::int64_t> orderedClauseValue =
878             Fortran::evaluate::ToInt64(*expr);
879         wsLoopOp.ordered_valAttr(
880             firOpBuilder.getI64IntegerAttr(*orderedClauseValue));
881       } else {
882         wsLoopOp.ordered_valAttr(firOpBuilder.getI64IntegerAttr(0));
883       }
884     } else if (const auto &scheduleClause =
885                    std::get_if<Fortran::parser::OmpClause::Schedule>(
886                        &clause.u)) {
887       mlir::MLIRContext *context = firOpBuilder.getContext();
888       const auto &scheduleType = scheduleClause->v;
889       const auto &scheduleKind =
890           std::get<Fortran::parser::OmpScheduleClause::ScheduleType>(
891               scheduleType.t);
892       switch (scheduleKind) {
893       case Fortran::parser::OmpScheduleClause::ScheduleType::Static:
894         wsLoopOp.schedule_valAttr(omp::ClauseScheduleKindAttr::get(
895             context, omp::ClauseScheduleKind::Static));
896         break;
897       case Fortran::parser::OmpScheduleClause::ScheduleType::Dynamic:
898         wsLoopOp.schedule_valAttr(omp::ClauseScheduleKindAttr::get(
899             context, omp::ClauseScheduleKind::Dynamic));
900         break;
901       case Fortran::parser::OmpScheduleClause::ScheduleType::Guided:
902         wsLoopOp.schedule_valAttr(omp::ClauseScheduleKindAttr::get(
903             context, omp::ClauseScheduleKind::Guided));
904         break;
905       case Fortran::parser::OmpScheduleClause::ScheduleType::Auto:
906         wsLoopOp.schedule_valAttr(omp::ClauseScheduleKindAttr::get(
907             context, omp::ClauseScheduleKind::Auto));
908         break;
909       case Fortran::parser::OmpScheduleClause::ScheduleType::Runtime:
910         wsLoopOp.schedule_valAttr(omp::ClauseScheduleKindAttr::get(
911             context, omp::ClauseScheduleKind::Runtime));
912         break;
913       }
914       mlir::omp::ScheduleModifier scheduleModifier =
915           getScheduleModifier(scheduleClause->v);
916       if (scheduleModifier != mlir::omp::ScheduleModifier::none)
917         wsLoopOp.schedule_modifierAttr(
918             omp::ScheduleModifierAttr::get(context, scheduleModifier));
919       if (getSIMDModifier(scheduleClause->v) !=
920           mlir::omp::ScheduleModifier::none)
921         wsLoopOp.simd_modifierAttr(firOpBuilder.getUnitAttr());
922     }
923   }
924   // In FORTRAN `nowait` clause occur at the end of `omp do` directive.
925   // i.e
926   // !$omp do
927   // <...>
928   // !$omp end do nowait
929   if (const auto &endClauseList =
930           std::get<std::optional<Fortran::parser::OmpEndLoopDirective>>(
931               loopConstruct.t)) {
932     const auto &clauseList =
933         std::get<Fortran::parser::OmpClauseList>((*endClauseList).t);
934     for (const Fortran::parser::OmpClause &clause : clauseList.v)
935       if (std::get_if<Fortran::parser::OmpClause::Nowait>(&clause.u))
936         wsLoopOp.nowaitAttr(firOpBuilder.getUnitAttr());
937   }
938 
939   createBodyOfOp<omp::WsLoopOp>(wsLoopOp, converter, currentLocation, eval,
940                                 &loopOpClauseList, iv);
941 }
942 
943 static void
944 genOMP(Fortran::lower::AbstractConverter &converter,
945        Fortran::lower::pft::Evaluation &eval,
946        const Fortran::parser::OpenMPCriticalConstruct &criticalConstruct) {
947   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
948   mlir::Location currentLocation = converter.getCurrentLocation();
949   std::string name;
950   const Fortran::parser::OmpCriticalDirective &cd =
951       std::get<Fortran::parser::OmpCriticalDirective>(criticalConstruct.t);
952   if (std::get<std::optional<Fortran::parser::Name>>(cd.t).has_value()) {
953     name =
954         std::get<std::optional<Fortran::parser::Name>>(cd.t).value().ToString();
955   }
956 
957   uint64_t hint = 0;
958   const auto &clauseList = std::get<Fortran::parser::OmpClauseList>(cd.t);
959   for (const Fortran::parser::OmpClause &clause : clauseList.v)
960     if (auto hintClause =
961             std::get_if<Fortran::parser::OmpClause::Hint>(&clause.u)) {
962       const auto *expr = Fortran::semantics::GetExpr(hintClause->v);
963       hint = *Fortran::evaluate::ToInt64(*expr);
964       break;
965     }
966 
967   mlir::omp::CriticalOp criticalOp = [&]() {
968     if (name.empty()) {
969       return firOpBuilder.create<mlir::omp::CriticalOp>(currentLocation,
970                                                         FlatSymbolRefAttr());
971     } else {
972       mlir::ModuleOp module = firOpBuilder.getModule();
973       mlir::OpBuilder modBuilder(module.getBodyRegion());
974       auto global = module.lookupSymbol<mlir::omp::CriticalDeclareOp>(name);
975       if (!global)
976         global = modBuilder.create<mlir::omp::CriticalDeclareOp>(
977             currentLocation, name, hint);
978       return firOpBuilder.create<mlir::omp::CriticalOp>(
979           currentLocation, mlir::FlatSymbolRefAttr::get(
980                                firOpBuilder.getContext(), global.sym_name()));
981     }
982   }();
983   createBodyOfOp<omp::CriticalOp>(criticalOp, converter, currentLocation, eval);
984 }
985 
986 static void
987 genOMP(Fortran::lower::AbstractConverter &converter,
988        Fortran::lower::pft::Evaluation &eval,
989        const Fortran::parser::OpenMPSectionConstruct &sectionConstruct) {
990 
991   auto &firOpBuilder = converter.getFirOpBuilder();
992   auto currentLocation = converter.getCurrentLocation();
993   mlir::omp::SectionOp sectionOp =
994       firOpBuilder.create<mlir::omp::SectionOp>(currentLocation);
995   createBodyOfOp<omp::SectionOp>(sectionOp, converter, currentLocation, eval);
996 }
997 
998 // TODO: Add support for reduction
999 static void
1000 genOMP(Fortran::lower::AbstractConverter &converter,
1001        Fortran::lower::pft::Evaluation &eval,
1002        const Fortran::parser::OpenMPSectionsConstruct &sectionsConstruct) {
1003   auto &firOpBuilder = converter.getFirOpBuilder();
1004   auto currentLocation = converter.getCurrentLocation();
1005   SmallVector<Value> reductionVars, allocateOperands, allocatorOperands;
1006   mlir::UnitAttr noWaitClauseOperand;
1007   const auto &sectionsClauseList = std::get<Fortran::parser::OmpClauseList>(
1008       std::get<Fortran::parser::OmpBeginSectionsDirective>(sectionsConstruct.t)
1009           .t);
1010   for (const Fortran::parser::OmpClause &clause : sectionsClauseList.v) {
1011 
1012     // Reduction Clause
1013     if (std::get_if<Fortran::parser::OmpClause::Reduction>(&clause.u)) {
1014       TODO(currentLocation, "OMPC_Reduction");
1015 
1016       // Allocate clause
1017     } else if (const auto &allocateClause =
1018                    std::get_if<Fortran::parser::OmpClause::Allocate>(
1019                        &clause.u)) {
1020       genAllocateClause(converter, allocateClause->v, allocatorOperands,
1021                         allocateOperands);
1022     }
1023   }
1024   const auto &endSectionsClauseList =
1025       std::get<Fortran::parser::OmpEndSectionsDirective>(sectionsConstruct.t);
1026   const auto &clauseList =
1027       std::get<Fortran::parser::OmpClauseList>(endSectionsClauseList.t);
1028   for (const auto &clause : clauseList.v) {
1029     // Nowait clause
1030     if (std::get_if<Fortran::parser::OmpClause::Nowait>(&clause.u)) {
1031       noWaitClauseOperand = firOpBuilder.getUnitAttr();
1032     }
1033   }
1034 
1035   llvm::omp::Directive dir =
1036       std::get<Fortran::parser::OmpSectionsDirective>(
1037           std::get<Fortran::parser::OmpBeginSectionsDirective>(
1038               sectionsConstruct.t)
1039               .t)
1040           .v;
1041 
1042   // Parallel Sections Construct
1043   if (dir == llvm::omp::Directive::OMPD_parallel_sections) {
1044     createCombinedParallelOp<Fortran::parser::OmpBeginSectionsDirective>(
1045         converter, eval,
1046         std::get<Fortran::parser::OmpBeginSectionsDirective>(
1047             sectionsConstruct.t));
1048     auto sectionsOp = firOpBuilder.create<mlir::omp::SectionsOp>(
1049         currentLocation, /*reduction_vars*/ ValueRange(),
1050         /*reductions=*/nullptr, allocateOperands, allocatorOperands,
1051         /*nowait=*/nullptr);
1052     createBodyOfOp(sectionsOp, converter, currentLocation, eval);
1053 
1054     // Sections Construct
1055   } else if (dir == llvm::omp::Directive::OMPD_sections) {
1056     auto sectionsOp = firOpBuilder.create<mlir::omp::SectionsOp>(
1057         currentLocation, reductionVars, /*reductions = */ nullptr,
1058         allocateOperands, allocatorOperands, noWaitClauseOperand);
1059     createBodyOfOp<omp::SectionsOp>(sectionsOp, converter, currentLocation,
1060                                     eval);
1061   }
1062 }
1063 
1064 static void genOmpAtomicHintAndMemoryOrderClauses(
1065     Fortran::lower::AbstractConverter &converter,
1066     const Fortran::parser::OmpAtomicClauseList &clauseList,
1067     mlir::IntegerAttr &hint,
1068     mlir::omp::ClauseMemoryOrderKindAttr &memory_order) {
1069   auto &firOpBuilder = converter.getFirOpBuilder();
1070   for (const auto &clause : clauseList.v) {
1071     if (auto ompClause = std::get_if<Fortran::parser::OmpClause>(&clause.u)) {
1072       if (auto hintClause =
1073               std::get_if<Fortran::parser::OmpClause::Hint>(&ompClause->u)) {
1074         const auto *expr = Fortran::semantics::GetExpr(hintClause->v);
1075         uint64_t hintExprValue = *Fortran::evaluate::ToInt64(*expr);
1076         hint = firOpBuilder.getI64IntegerAttr(hintExprValue);
1077       }
1078     } else if (auto ompMemoryOrderClause =
1079                    std::get_if<Fortran::parser::OmpMemoryOrderClause>(
1080                        &clause.u)) {
1081       if (std::get_if<Fortran::parser::OmpClause::Acquire>(
1082               &ompMemoryOrderClause->v.u)) {
1083         memory_order = mlir::omp::ClauseMemoryOrderKindAttr::get(
1084             firOpBuilder.getContext(), omp::ClauseMemoryOrderKind::Acquire);
1085       } else if (std::get_if<Fortran::parser::OmpClause::Relaxed>(
1086                      &ompMemoryOrderClause->v.u)) {
1087         memory_order = mlir::omp::ClauseMemoryOrderKindAttr::get(
1088             firOpBuilder.getContext(), omp::ClauseMemoryOrderKind::Relaxed);
1089       } else if (std::get_if<Fortran::parser::OmpClause::SeqCst>(
1090                      &ompMemoryOrderClause->v.u)) {
1091         memory_order = mlir::omp::ClauseMemoryOrderKindAttr::get(
1092             firOpBuilder.getContext(), omp::ClauseMemoryOrderKind::Seq_cst);
1093       } else if (std::get_if<Fortran::parser::OmpClause::Release>(
1094                      &ompMemoryOrderClause->v.u)) {
1095         memory_order = mlir::omp::ClauseMemoryOrderKindAttr::get(
1096             firOpBuilder.getContext(), omp::ClauseMemoryOrderKind::Release);
1097       }
1098     }
1099   }
1100 }
1101 
1102 static void
1103 genOmpAtomicWrite(Fortran::lower::AbstractConverter &converter,
1104                   Fortran::lower::pft::Evaluation &eval,
1105                   const Fortran::parser::OmpAtomicWrite &atomicWrite) {
1106   auto &firOpBuilder = converter.getFirOpBuilder();
1107   auto currentLocation = converter.getCurrentLocation();
1108   // Get the value and address of atomic write operands.
1109   const Fortran::parser::OmpAtomicClauseList &rightHandClauseList =
1110       std::get<2>(atomicWrite.t);
1111   const Fortran::parser::OmpAtomicClauseList &leftHandClauseList =
1112       std::get<0>(atomicWrite.t);
1113   const auto &assignmentStmtExpr =
1114       std::get<Fortran::parser::Expr>(std::get<3>(atomicWrite.t).statement.t);
1115   const auto &assignmentStmtVariable = std::get<Fortran::parser::Variable>(
1116       std::get<3>(atomicWrite.t).statement.t);
1117   Fortran::lower::StatementContext stmtCtx;
1118   mlir::Value value = fir::getBase(converter.genExprValue(
1119       *Fortran::semantics::GetExpr(assignmentStmtExpr), stmtCtx));
1120   mlir::Value address = fir::getBase(converter.genExprAddr(
1121       *Fortran::semantics::GetExpr(assignmentStmtVariable), stmtCtx));
1122   // If no hint clause is specified, the effect is as if
1123   // hint(omp_sync_hint_none) had been specified.
1124   mlir::IntegerAttr hint = nullptr;
1125   mlir::omp::ClauseMemoryOrderKindAttr memory_order = nullptr;
1126   genOmpAtomicHintAndMemoryOrderClauses(converter, leftHandClauseList, hint,
1127                                         memory_order);
1128   genOmpAtomicHintAndMemoryOrderClauses(converter, rightHandClauseList, hint,
1129                                         memory_order);
1130   firOpBuilder.create<mlir::omp::AtomicWriteOp>(currentLocation, address, value,
1131                                                 hint, memory_order);
1132 }
1133 
1134 static void genOmpAtomicRead(Fortran::lower::AbstractConverter &converter,
1135                              Fortran::lower::pft::Evaluation &eval,
1136                              const Fortran::parser::OmpAtomicRead &atomicRead) {
1137   auto &firOpBuilder = converter.getFirOpBuilder();
1138   auto currentLocation = converter.getCurrentLocation();
1139   // Get the address of atomic read operands.
1140   const Fortran::parser::OmpAtomicClauseList &rightHandClauseList =
1141       std::get<2>(atomicRead.t);
1142   const Fortran::parser::OmpAtomicClauseList &leftHandClauseList =
1143       std::get<0>(atomicRead.t);
1144   const auto &assignmentStmtExpr =
1145       std::get<Fortran::parser::Expr>(std::get<3>(atomicRead.t).statement.t);
1146   const auto &assignmentStmtVariable = std::get<Fortran::parser::Variable>(
1147       std::get<3>(atomicRead.t).statement.t);
1148   Fortran::lower::StatementContext stmtCtx;
1149   mlir::Value from_address = fir::getBase(converter.genExprAddr(
1150       *Fortran::semantics::GetExpr(assignmentStmtExpr), stmtCtx));
1151   mlir::Value to_address = fir::getBase(converter.genExprAddr(
1152       *Fortran::semantics::GetExpr(assignmentStmtVariable), stmtCtx));
1153   // If no hint clause is specified, the effect is as if
1154   // hint(omp_sync_hint_none) had been specified.
1155   mlir::IntegerAttr hint = nullptr;
1156   mlir::omp::ClauseMemoryOrderKindAttr memory_order = nullptr;
1157   genOmpAtomicHintAndMemoryOrderClauses(converter, leftHandClauseList, hint,
1158                                         memory_order);
1159   genOmpAtomicHintAndMemoryOrderClauses(converter, rightHandClauseList, hint,
1160                                         memory_order);
1161   firOpBuilder.create<mlir::omp::AtomicReadOp>(currentLocation, from_address,
1162                                                to_address, hint, memory_order);
1163 }
1164 
1165 static void
1166 genOMP(Fortran::lower::AbstractConverter &converter,
1167        Fortran::lower::pft::Evaluation &eval,
1168        const Fortran::parser::OpenMPAtomicConstruct &atomicConstruct) {
1169   std::visit(Fortran::common::visitors{
1170                  [&](const Fortran::parser::OmpAtomicRead &atomicRead) {
1171                    genOmpAtomicRead(converter, eval, atomicRead);
1172                  },
1173                  [&](const Fortran::parser::OmpAtomicWrite &atomicWrite) {
1174                    genOmpAtomicWrite(converter, eval, atomicWrite);
1175                  },
1176                  [&](const auto &) {
1177                    TODO(converter.getCurrentLocation(),
1178                         "Atomic update & capture");
1179                  },
1180              },
1181              atomicConstruct.u);
1182 }
1183 
1184 void Fortran::lower::genOpenMPConstruct(
1185     Fortran::lower::AbstractConverter &converter,
1186     Fortran::lower::pft::Evaluation &eval,
1187     const Fortran::parser::OpenMPConstruct &ompConstruct) {
1188 
1189   std::visit(
1190       common::visitors{
1191           [&](const Fortran::parser::OpenMPStandaloneConstruct
1192                   &standaloneConstruct) {
1193             genOMP(converter, eval, standaloneConstruct);
1194           },
1195           [&](const Fortran::parser::OpenMPSectionsConstruct
1196                   &sectionsConstruct) {
1197             genOMP(converter, eval, sectionsConstruct);
1198           },
1199           [&](const Fortran::parser::OpenMPSectionConstruct &sectionConstruct) {
1200             genOMP(converter, eval, sectionConstruct);
1201           },
1202           [&](const Fortran::parser::OpenMPLoopConstruct &loopConstruct) {
1203             genOMP(converter, eval, loopConstruct);
1204           },
1205           [&](const Fortran::parser::OpenMPDeclarativeAllocate
1206                   &execAllocConstruct) {
1207             TODO(converter.getCurrentLocation(), "OpenMPDeclarativeAllocate");
1208           },
1209           [&](const Fortran::parser::OpenMPExecutableAllocate
1210                   &execAllocConstruct) {
1211             TODO(converter.getCurrentLocation(), "OpenMPExecutableAllocate");
1212           },
1213           [&](const Fortran::parser::OpenMPBlockConstruct &blockConstruct) {
1214             genOMP(converter, eval, blockConstruct);
1215           },
1216           [&](const Fortran::parser::OpenMPAtomicConstruct &atomicConstruct) {
1217             genOMP(converter, eval, atomicConstruct);
1218           },
1219           [&](const Fortran::parser::OpenMPCriticalConstruct
1220                   &criticalConstruct) {
1221             genOMP(converter, eval, criticalConstruct);
1222           },
1223       },
1224       ompConstruct.u);
1225 }
1226 
1227 void Fortran::lower::genThreadprivateOp(
1228     Fortran::lower::AbstractConverter &converter,
1229     const Fortran::lower::pft::Variable &var) {
1230   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
1231   mlir::Location currentLocation = converter.getCurrentLocation();
1232 
1233   const Fortran::semantics::Symbol &sym = var.getSymbol();
1234   mlir::Value symThreadprivateValue;
1235   if (const Fortran::semantics::Symbol *common =
1236           Fortran::semantics::FindCommonBlockContaining(sym.GetUltimate())) {
1237     mlir::Value commonValue = converter.getSymbolAddress(*common);
1238     if (mlir::isa<mlir::omp::ThreadprivateOp>(commonValue.getDefiningOp())) {
1239       // Generate ThreadprivateOp for a common block instead of its members and
1240       // only do it once for a common block.
1241       return;
1242     }
1243     // Generate ThreadprivateOp and rebind the common block.
1244     mlir::Value commonThreadprivateValue =
1245         firOpBuilder.create<mlir::omp::ThreadprivateOp>(
1246             currentLocation, commonValue.getType(), commonValue);
1247     converter.bindSymbol(*common, commonThreadprivateValue);
1248     // Generate the threadprivate value for the common block member.
1249     symThreadprivateValue =
1250         genCommonBlockMember(converter, sym, commonThreadprivateValue);
1251   } else {
1252     mlir::Value symValue = converter.getSymbolAddress(sym);
1253     symThreadprivateValue = firOpBuilder.create<mlir::omp::ThreadprivateOp>(
1254         currentLocation, symValue.getType(), symValue);
1255   }
1256 
1257   fir::ExtendedValue sexv = converter.getSymbolExtendedValue(sym);
1258   fir::ExtendedValue symThreadprivateExv =
1259       getExtendedValue(sexv, symThreadprivateValue);
1260   converter.bindSymbol(sym, symThreadprivateExv);
1261 }
1262 
1263 void Fortran::lower::genOpenMPDeclarativeConstruct(
1264     Fortran::lower::AbstractConverter &converter,
1265     Fortran::lower::pft::Evaluation &eval,
1266     const Fortran::parser::OpenMPDeclarativeConstruct &ompDeclConstruct) {
1267 
1268   std::visit(
1269       common::visitors{
1270           [&](const Fortran::parser::OpenMPDeclarativeAllocate
1271                   &declarativeAllocate) {
1272             TODO(converter.getCurrentLocation(), "OpenMPDeclarativeAllocate");
1273           },
1274           [&](const Fortran::parser::OpenMPDeclareReductionConstruct
1275                   &declareReductionConstruct) {
1276             TODO(converter.getCurrentLocation(),
1277                  "OpenMPDeclareReductionConstruct");
1278           },
1279           [&](const Fortran::parser::OpenMPDeclareSimdConstruct
1280                   &declareSimdConstruct) {
1281             TODO(converter.getCurrentLocation(), "OpenMPDeclareSimdConstruct");
1282           },
1283           [&](const Fortran::parser::OpenMPDeclareTargetConstruct
1284                   &declareTargetConstruct) {
1285             TODO(converter.getCurrentLocation(),
1286                  "OpenMPDeclareTargetConstruct");
1287           },
1288           [&](const Fortran::parser::OpenMPThreadprivate &threadprivate) {
1289             // The directive is lowered when instantiating the variable to
1290             // support the case of threadprivate variable declared in module.
1291           },
1292       },
1293       ompDeclConstruct.u);
1294 }
1295