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/PFTBuilder.h"
17 #include "flang/Lower/StatementContext.h"
18 #include "flang/Lower/Todo.h"
19 #include "flang/Optimizer/Builder/BoxValue.h"
20 #include "flang/Optimizer/Builder/FIRBuilder.h"
21 #include "flang/Parser/parse-tree.h"
22 #include "flang/Semantics/tools.h"
23 #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
24 #include "llvm/Frontend/OpenMP/OMPConstants.h"
25 
26 using namespace mlir;
27 
28 static const Fortran::parser::Name *
29 getDesignatorNameIfDataRef(const Fortran::parser::Designator &designator) {
30   const auto *dataRef = std::get_if<Fortran::parser::DataRef>(&designator.u);
31   return dataRef ? std::get_if<Fortran::parser::Name>(&dataRef->u) : nullptr;
32 }
33 
34 template <typename T>
35 static void createPrivateVarSyms(Fortran::lower::AbstractConverter &converter,
36                                  const T *clause) {
37   Fortran::semantics::Symbol *sym = nullptr;
38   const Fortran::parser::OmpObjectList &ompObjectList = clause->v;
39   for (const Fortran::parser::OmpObject &ompObject : ompObjectList.v) {
40     std::visit(
41         Fortran::common::visitors{
42             [&](const Fortran::parser::Designator &designator) {
43               if (const Fortran::parser::Name *name =
44                       getDesignatorNameIfDataRef(designator)) {
45                 sym = name->symbol;
46               }
47             },
48             [&](const Fortran::parser::Name &name) { sym = name.symbol; }},
49         ompObject.u);
50 
51     // Privatization for symbols which are pre-determined (like loop index
52     // variables) happen separately, for everything else privatize here
53     if constexpr (std::is_same_v<T, Fortran::parser::OmpClause::Firstprivate>) {
54       converter.copyHostAssociateVar(*sym);
55     } else {
56       bool success = converter.createHostAssociateVarClone(*sym);
57       (void)success;
58       assert(success && "Privatization failed due to existing binding");
59     }
60   }
61 }
62 
63 static void privatizeVars(Fortran::lower::AbstractConverter &converter,
64                           const Fortran::parser::OmpClauseList &opClauseList) {
65   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
66   auto insPt = firOpBuilder.saveInsertionPoint();
67   firOpBuilder.setInsertionPointToStart(firOpBuilder.getAllocaBlock());
68   for (const Fortran::parser::OmpClause &clause : opClauseList.v) {
69     if (const auto &privateClause =
70             std::get_if<Fortran::parser::OmpClause::Private>(&clause.u)) {
71       createPrivateVarSyms(converter, privateClause);
72     } else if (const auto &firstPrivateClause =
73                    std::get_if<Fortran::parser::OmpClause::Firstprivate>(
74                        &clause.u)) {
75       createPrivateVarSyms(converter, firstPrivateClause);
76     }
77   }
78   firOpBuilder.restoreInsertionPoint(insPt);
79 }
80 
81 static void genObjectList(const Fortran::parser::OmpObjectList &objectList,
82                           Fortran::lower::AbstractConverter &converter,
83                           llvm::SmallVectorImpl<Value> &operands) {
84   auto addOperands = [&](Fortran::lower::SymbolRef sym) {
85     const mlir::Value variable = converter.getSymbolAddress(sym);
86     if (variable) {
87       operands.push_back(variable);
88     } else {
89       if (const auto *details =
90               sym->detailsIf<Fortran::semantics::HostAssocDetails>()) {
91         operands.push_back(converter.getSymbolAddress(details->symbol()));
92         converter.copySymbolBinding(details->symbol(), sym);
93       }
94     }
95   };
96   for (const Fortran::parser::OmpObject &ompObject : objectList.v) {
97     std::visit(Fortran::common::visitors{
98                    [&](const Fortran::parser::Designator &designator) {
99                      if (const Fortran::parser::Name *name =
100                              getDesignatorNameIfDataRef(designator)) {
101                        addOperands(*name->symbol);
102                      }
103                    },
104                    [&](const Fortran::parser::Name &name) {
105                      addOperands(*name.symbol);
106                    }},
107                ompObject.u);
108   }
109 }
110 
111 template <typename Op>
112 static void
113 createBodyOfOp(Op &op, Fortran::lower::AbstractConverter &converter,
114                mlir::Location &loc,
115                const Fortran::parser::OmpClauseList *clauses = nullptr,
116                bool outerCombined = false) {
117   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
118   firOpBuilder.createBlock(&op.getRegion());
119   auto &block = op.getRegion().back();
120   firOpBuilder.setInsertionPointToStart(&block);
121   // Ensure the block is well-formed.
122   firOpBuilder.create<mlir::omp::TerminatorOp>(loc);
123   // Reset the insertion point to the start of the first block.
124   firOpBuilder.setInsertionPointToStart(&block);
125   // Handle privatization. Do not privatize if this is the outer operation.
126   if (clauses && !outerCombined)
127     privatizeVars(converter, *clauses);
128 }
129 
130 static void genOMP(Fortran::lower::AbstractConverter &converter,
131                    Fortran::lower::pft::Evaluation &eval,
132                    const Fortran::parser::OpenMPSimpleStandaloneConstruct
133                        &simpleStandaloneConstruct) {
134   const auto &directive =
135       std::get<Fortran::parser::OmpSimpleStandaloneDirective>(
136           simpleStandaloneConstruct.t);
137   switch (directive.v) {
138   default:
139     break;
140   case llvm::omp::Directive::OMPD_barrier:
141     converter.getFirOpBuilder().create<mlir::omp::BarrierOp>(
142         converter.getCurrentLocation());
143     break;
144   case llvm::omp::Directive::OMPD_taskwait:
145     converter.getFirOpBuilder().create<mlir::omp::TaskwaitOp>(
146         converter.getCurrentLocation());
147     break;
148   case llvm::omp::Directive::OMPD_taskyield:
149     converter.getFirOpBuilder().create<mlir::omp::TaskyieldOp>(
150         converter.getCurrentLocation());
151     break;
152   case llvm::omp::Directive::OMPD_target_enter_data:
153     TODO(converter.getCurrentLocation(), "OMPD_target_enter_data");
154   case llvm::omp::Directive::OMPD_target_exit_data:
155     TODO(converter.getCurrentLocation(), "OMPD_target_exit_data");
156   case llvm::omp::Directive::OMPD_target_update:
157     TODO(converter.getCurrentLocation(), "OMPD_target_update");
158   case llvm::omp::Directive::OMPD_ordered:
159     TODO(converter.getCurrentLocation(), "OMPD_ordered");
160   }
161 }
162 
163 static void
164 genAllocateClause(Fortran::lower::AbstractConverter &converter,
165                   const Fortran::parser::OmpAllocateClause &ompAllocateClause,
166                   SmallVector<Value> &allocatorOperands,
167                   SmallVector<Value> &allocateOperands) {
168   auto &firOpBuilder = converter.getFirOpBuilder();
169   auto currentLocation = converter.getCurrentLocation();
170   Fortran::lower::StatementContext stmtCtx;
171 
172   mlir::Value allocatorOperand;
173   const Fortran::parser::OmpObjectList &ompObjectList =
174       std::get<Fortran::parser::OmpObjectList>(ompAllocateClause.t);
175   const auto &allocatorValue =
176       std::get<std::optional<Fortran::parser::OmpAllocateClause::Allocator>>(
177           ompAllocateClause.t);
178   // Check if allocate clause has allocator specified. If so, add it
179   // to list of allocators, otherwise, add default allocator to
180   // list of allocators.
181   if (allocatorValue) {
182     allocatorOperand = fir::getBase(converter.genExprValue(
183         *Fortran::semantics::GetExpr(allocatorValue->v), stmtCtx));
184     allocatorOperands.insert(allocatorOperands.end(), ompObjectList.v.size(),
185                              allocatorOperand);
186   } else {
187     allocatorOperand = firOpBuilder.createIntegerConstant(
188         currentLocation, firOpBuilder.getI32Type(), 1);
189     allocatorOperands.insert(allocatorOperands.end(), ompObjectList.v.size(),
190                              allocatorOperand);
191   }
192   genObjectList(ompObjectList, converter, allocateOperands);
193 }
194 
195 static void
196 genOMP(Fortran::lower::AbstractConverter &converter,
197        Fortran::lower::pft::Evaluation &eval,
198        const Fortran::parser::OpenMPStandaloneConstruct &standaloneConstruct) {
199   std::visit(
200       Fortran::common::visitors{
201           [&](const Fortran::parser::OpenMPSimpleStandaloneConstruct
202                   &simpleStandaloneConstruct) {
203             genOMP(converter, eval, simpleStandaloneConstruct);
204           },
205           [&](const Fortran::parser::OpenMPFlushConstruct &flushConstruct) {
206             SmallVector<Value, 4> operandRange;
207             if (const auto &ompObjectList =
208                     std::get<std::optional<Fortran::parser::OmpObjectList>>(
209                         flushConstruct.t))
210               genObjectList(*ompObjectList, converter, operandRange);
211             const auto &memOrderClause = std::get<std::optional<
212                 std::list<Fortran::parser::OmpMemoryOrderClause>>>(
213                 flushConstruct.t);
214             if (memOrderClause.has_value() && memOrderClause->size() > 0)
215               TODO(converter.getCurrentLocation(),
216                    "Handle OmpMemoryOrderClause");
217             converter.getFirOpBuilder().create<mlir::omp::FlushOp>(
218                 converter.getCurrentLocation(), operandRange);
219           },
220           [&](const Fortran::parser::OpenMPCancelConstruct &cancelConstruct) {
221             TODO(converter.getCurrentLocation(), "OpenMPCancelConstruct");
222           },
223           [&](const Fortran::parser::OpenMPCancellationPointConstruct
224                   &cancellationPointConstruct) {
225             TODO(converter.getCurrentLocation(), "OpenMPCancelConstruct");
226           },
227       },
228       standaloneConstruct.u);
229 }
230 
231 static void
232 genOMP(Fortran::lower::AbstractConverter &converter,
233        Fortran::lower::pft::Evaluation &eval,
234        const Fortran::parser::OpenMPBlockConstruct &blockConstruct) {
235   const auto &beginBlockDirective =
236       std::get<Fortran::parser::OmpBeginBlockDirective>(blockConstruct.t);
237   const auto &blockDirective =
238       std::get<Fortran::parser::OmpBlockDirective>(beginBlockDirective.t);
239   const auto &endBlockDirective =
240       std::get<Fortran::parser::OmpEndBlockDirective>(blockConstruct.t);
241   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
242   mlir::Location currentLocation = converter.getCurrentLocation();
243 
244   Fortran::lower::StatementContext stmtCtx;
245   llvm::ArrayRef<mlir::Type> argTy;
246   mlir::Value ifClauseOperand, numThreadsClauseOperand;
247   mlir::omp::ClauseProcBindKindAttr procBindKindAttr;
248   SmallVector<Value> allocateOperands, allocatorOperands;
249   mlir::UnitAttr nowaitAttr;
250 
251   const auto &opClauseList =
252       std::get<Fortran::parser::OmpClauseList>(beginBlockDirective.t);
253   for (const auto &clause : opClauseList.v) {
254     if (const auto &ifClause =
255             std::get_if<Fortran::parser::OmpClause::If>(&clause.u)) {
256       auto &expr = std::get<Fortran::parser::ScalarLogicalExpr>(ifClause->v.t);
257       ifClauseOperand = fir::getBase(
258           converter.genExprValue(*Fortran::semantics::GetExpr(expr), stmtCtx));
259     } else if (const auto &numThreadsClause =
260                    std::get_if<Fortran::parser::OmpClause::NumThreads>(
261                        &clause.u)) {
262       // OMPIRBuilder expects `NUM_THREAD` clause as a `Value`.
263       numThreadsClauseOperand = fir::getBase(converter.genExprValue(
264           *Fortran::semantics::GetExpr(numThreadsClause->v), stmtCtx));
265     } else if (const auto &procBindClause =
266                    std::get_if<Fortran::parser::OmpClause::ProcBind>(
267                        &clause.u)) {
268       omp::ClauseProcBindKind pbKind;
269       switch (procBindClause->v.v) {
270       case Fortran::parser::OmpProcBindClause::Type::Master:
271         pbKind = omp::ClauseProcBindKind::Master;
272         break;
273       case Fortran::parser::OmpProcBindClause::Type::Close:
274         pbKind = omp::ClauseProcBindKind::Close;
275         break;
276       case Fortran::parser::OmpProcBindClause::Type::Spread:
277         pbKind = omp::ClauseProcBindKind::Spread;
278         break;
279       case Fortran::parser::OmpProcBindClause::Type::Primary:
280         pbKind = omp::ClauseProcBindKind::Primary;
281         break;
282       }
283       procBindKindAttr =
284           omp::ClauseProcBindKindAttr::get(firOpBuilder.getContext(), pbKind);
285     } else if (const auto &allocateClause =
286                    std::get_if<Fortran::parser::OmpClause::Allocate>(
287                        &clause.u)) {
288       genAllocateClause(converter, allocateClause->v, allocatorOperands,
289                         allocateOperands);
290     } else if (std::get_if<Fortran::parser::OmpClause::Private>(&clause.u) ||
291                std::get_if<Fortran::parser::OmpClause::Firstprivate>(
292                    &clause.u)) {
293       // Privatisation clauses are handled elsewhere.
294       continue;
295     } else {
296       TODO(currentLocation, "OpenMP Block construct clauses");
297     }
298   }
299 
300   for (const auto &clause :
301        std::get<Fortran::parser::OmpClauseList>(endBlockDirective.t).v) {
302     if (std::get_if<Fortran::parser::OmpClause::Nowait>(&clause.u))
303       nowaitAttr = firOpBuilder.getUnitAttr();
304   }
305 
306   if (blockDirective.v == llvm::omp::OMPD_parallel) {
307     // Create and insert the operation.
308     auto parallelOp = firOpBuilder.create<mlir::omp::ParallelOp>(
309         currentLocation, argTy, ifClauseOperand, numThreadsClauseOperand,
310         allocateOperands, allocatorOperands, /*reduction_vars=*/ValueRange(),
311         /*reductions=*/nullptr, procBindKindAttr);
312     createBodyOfOp<omp::ParallelOp>(parallelOp, converter, currentLocation,
313                                     &opClauseList, /*isCombined=*/false);
314   } else if (blockDirective.v == llvm::omp::OMPD_master) {
315     auto masterOp =
316         firOpBuilder.create<mlir::omp::MasterOp>(currentLocation, argTy);
317     createBodyOfOp<omp::MasterOp>(masterOp, converter, currentLocation);
318   } else if (blockDirective.v == llvm::omp::OMPD_single) {
319     auto singleOp = firOpBuilder.create<mlir::omp::SingleOp>(
320         currentLocation, allocateOperands, allocatorOperands, nowaitAttr);
321     createBodyOfOp<omp::SingleOp>(singleOp, converter, currentLocation);
322   } else {
323     TODO(converter.getCurrentLocation(), "Unhandled block directive");
324   }
325 }
326 
327 static void
328 genOMP(Fortran::lower::AbstractConverter &converter,
329        Fortran::lower::pft::Evaluation &eval,
330        const Fortran::parser::OpenMPCriticalConstruct &criticalConstruct) {
331   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
332   mlir::Location currentLocation = converter.getCurrentLocation();
333   std::string name;
334   const Fortran::parser::OmpCriticalDirective &cd =
335       std::get<Fortran::parser::OmpCriticalDirective>(criticalConstruct.t);
336   if (std::get<std::optional<Fortran::parser::Name>>(cd.t).has_value()) {
337     name =
338         std::get<std::optional<Fortran::parser::Name>>(cd.t).value().ToString();
339   }
340 
341   uint64_t hint = 0;
342   const auto &clauseList = std::get<Fortran::parser::OmpClauseList>(cd.t);
343   for (const Fortran::parser::OmpClause &clause : clauseList.v)
344     if (auto hintClause =
345             std::get_if<Fortran::parser::OmpClause::Hint>(&clause.u)) {
346       const auto *expr = Fortran::semantics::GetExpr(hintClause->v);
347       hint = *Fortran::evaluate::ToInt64(*expr);
348       break;
349     }
350 
351   mlir::omp::CriticalOp criticalOp = [&]() {
352     if (name.empty()) {
353       return firOpBuilder.create<mlir::omp::CriticalOp>(currentLocation,
354                                                         FlatSymbolRefAttr());
355     } else {
356       mlir::ModuleOp module = firOpBuilder.getModule();
357       mlir::OpBuilder modBuilder(module.getBodyRegion());
358       auto global = module.lookupSymbol<mlir::omp::CriticalDeclareOp>(name);
359       if (!global)
360         global = modBuilder.create<mlir::omp::CriticalDeclareOp>(
361             currentLocation, name, hint);
362       return firOpBuilder.create<mlir::omp::CriticalOp>(
363           currentLocation, mlir::FlatSymbolRefAttr::get(
364                                firOpBuilder.getContext(), global.sym_name()));
365     }
366   }();
367   createBodyOfOp<omp::CriticalOp>(criticalOp, converter, currentLocation);
368 }
369 
370 static void
371 genOMP(Fortran::lower::AbstractConverter &converter,
372        Fortran::lower::pft::Evaluation &eval,
373        const Fortran::parser::OpenMPSectionConstruct &sectionConstruct) {
374 
375   auto &firOpBuilder = converter.getFirOpBuilder();
376   auto currentLocation = converter.getCurrentLocation();
377   mlir::omp::SectionOp sectionOp =
378       firOpBuilder.create<mlir::omp::SectionOp>(currentLocation);
379   createBodyOfOp<omp::SectionOp>(sectionOp, converter, currentLocation);
380 }
381 
382 // TODO: Add support for reduction
383 static void
384 genOMP(Fortran::lower::AbstractConverter &converter,
385        Fortran::lower::pft::Evaluation &eval,
386        const Fortran::parser::OpenMPSectionsConstruct &sectionsConstruct) {
387   auto &firOpBuilder = converter.getFirOpBuilder();
388   auto currentLocation = converter.getCurrentLocation();
389   SmallVector<Value> reductionVars, allocateOperands, allocatorOperands;
390   mlir::UnitAttr noWaitClauseOperand;
391   const auto &sectionsClauseList = std::get<Fortran::parser::OmpClauseList>(
392       std::get<Fortran::parser::OmpBeginSectionsDirective>(sectionsConstruct.t)
393           .t);
394   for (const Fortran::parser::OmpClause &clause : sectionsClauseList.v) {
395 
396     // Reduction Clause
397     if (std::get_if<Fortran::parser::OmpClause::Reduction>(&clause.u)) {
398       TODO(currentLocation, "OMPC_Reduction");
399 
400       // Allocate clause
401     } else if (const auto &allocateClause =
402                    std::get_if<Fortran::parser::OmpClause::Allocate>(
403                        &clause.u)) {
404       genAllocateClause(converter, allocateClause->v, allocatorOperands,
405                         allocateOperands);
406     }
407   }
408   const auto &endSectionsClauseList =
409       std::get<Fortran::parser::OmpEndSectionsDirective>(sectionsConstruct.t);
410   const auto &clauseList =
411       std::get<Fortran::parser::OmpClauseList>(endSectionsClauseList.t);
412   for (const auto &clause : clauseList.v) {
413     // Nowait clause
414     if (std::get_if<Fortran::parser::OmpClause::Nowait>(&clause.u)) {
415       noWaitClauseOperand = firOpBuilder.getUnitAttr();
416     }
417   }
418 
419   llvm::omp::Directive dir =
420       std::get<Fortran::parser::OmpSectionsDirective>(
421           std::get<Fortran::parser::OmpBeginSectionsDirective>(
422               sectionsConstruct.t)
423               .t)
424           .v;
425 
426   // Parallel Sections Construct
427   if (dir == llvm::omp::Directive::OMPD_parallel_sections) {
428     auto parallelOp = firOpBuilder.create<mlir::omp::ParallelOp>(
429         currentLocation, /*if_expr_var*/ nullptr, /*num_threads_var*/ nullptr,
430         allocateOperands, allocatorOperands, /*reduction_vars=*/ValueRange(),
431         /*reductions=*/nullptr, /*proc_bind_val*/ nullptr);
432     createBodyOfOp(parallelOp, converter, currentLocation);
433     auto sectionsOp = firOpBuilder.create<mlir::omp::SectionsOp>(
434         currentLocation, /*reduction_vars*/ ValueRange(),
435         /*reductions=*/nullptr, /*allocate_vars*/ ValueRange(),
436         /*allocators_vars*/ ValueRange(), /*nowait=*/nullptr);
437     createBodyOfOp(sectionsOp, converter, currentLocation);
438 
439     // Sections Construct
440   } else if (dir == llvm::omp::Directive::OMPD_sections) {
441     auto sectionsOp = firOpBuilder.create<mlir::omp::SectionsOp>(
442         currentLocation, reductionVars, /*reductions = */ nullptr,
443         allocateOperands, allocatorOperands, noWaitClauseOperand);
444     createBodyOfOp<omp::SectionsOp>(sectionsOp, converter, currentLocation);
445   }
446 }
447 
448 void Fortran::lower::genOpenMPConstruct(
449     Fortran::lower::AbstractConverter &converter,
450     Fortran::lower::pft::Evaluation &eval,
451     const Fortran::parser::OpenMPConstruct &ompConstruct) {
452 
453   std::visit(
454       common::visitors{
455           [&](const Fortran::parser::OpenMPStandaloneConstruct
456                   &standaloneConstruct) {
457             genOMP(converter, eval, standaloneConstruct);
458           },
459           [&](const Fortran::parser::OpenMPSectionsConstruct
460                   &sectionsConstruct) {
461             genOMP(converter, eval, sectionsConstruct);
462           },
463           [&](const Fortran::parser::OpenMPSectionConstruct &sectionConstruct) {
464             genOMP(converter, eval, sectionConstruct);
465           },
466           [&](const Fortran::parser::OpenMPLoopConstruct &loopConstruct) {
467             TODO(converter.getCurrentLocation(), "OpenMPLoopConstruct");
468           },
469           [&](const Fortran::parser::OpenMPDeclarativeAllocate
470                   &execAllocConstruct) {
471             TODO(converter.getCurrentLocation(), "OpenMPDeclarativeAllocate");
472           },
473           [&](const Fortran::parser::OpenMPExecutableAllocate
474                   &execAllocConstruct) {
475             TODO(converter.getCurrentLocation(), "OpenMPExecutableAllocate");
476           },
477           [&](const Fortran::parser::OpenMPBlockConstruct &blockConstruct) {
478             genOMP(converter, eval, blockConstruct);
479           },
480           [&](const Fortran::parser::OpenMPAtomicConstruct &atomicConstruct) {
481             TODO(converter.getCurrentLocation(), "OpenMPAtomicConstruct");
482           },
483           [&](const Fortran::parser::OpenMPCriticalConstruct
484                   &criticalConstruct) {
485             genOMP(converter, eval, criticalConstruct);
486           },
487       },
488       ompConstruct.u);
489 }
490