Debian Codegraph @

flang/lib/Lower/OpenMP/OpenMP.cpp

raw
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
15 #include "ClauseProcessor.h"
16 #include "Clauses.h"
17 #include "DataSharingProcessor.h"
18 #include "Decomposer.h"
19 #include "DirectivesCommon.h"
20 #include "ReductionProcessor.h"
21 #include "Utils.h"
22 #include "flang/Common/idioms.h"
23 #include "flang/Lower/Bridge.h"
24 #include "flang/Lower/ConvertExpr.h"
25 #include "flang/Lower/ConvertVariable.h"
26 #include "flang/Lower/StatementContext.h"
27 #include "flang/Lower/SymbolMap.h"
28 #include "flang/Optimizer/Builder/BoxValue.h"
29 #include "flang/Optimizer/Builder/FIRBuilder.h"
30 #include "flang/Optimizer/Builder/Todo.h"
31 #include "flang/Optimizer/Dialect/FIRType.h"
32 #include "flang/Optimizer/HLFIR/HLFIROps.h"
33 #include "flang/Parser/parse-tree.h"
34 #include "flang/Semantics/openmp-directive-sets.h"
35 #include "flang/Semantics/tools.h"
36 #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
37 #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
38 #include "mlir/Transforms/RegionUtils.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/Frontend/OpenMP/OMPConstants.h"
41
42 using namespace Fortran::lower::omp;
43
44 //===----------------------------------------------------------------------===//
45 // Code generation helper functions
46 //===----------------------------------------------------------------------===//
47
48 static void genOMPDispatch(lower::AbstractConverter &converter,
49 lower::SymMap &symTable,
50 semantics::SemanticsContext &semaCtx,
51 lower::pft::Evaluation &eval, mlir::Location loc,
52 const ConstructQueue &queue,
53 ConstructQueue::iterator item);
54
55 static lower::pft::Evaluation *
56 getCollapsedLoopEval(lower::pft::Evaluation &eval, int collapseValue) {
57 // Return the Evaluation of the innermost collapsed loop, or the current one
58 // if there was no COLLAPSE.
59 if (collapseValue == 0)
60 return &eval;
61
62 lower::pft::Evaluation *curEval = &eval.getFirstNestedEvaluation();
63 for (int i = 1; i < collapseValue; i++) {
64 // The nested evaluations should be DoConstructs (i.e. they should form
65 // a loop nest). Each DoConstruct is a tuple <NonLabelDoStmt, Block,
66 // EndDoStmt>.
67 assert(curEval->isA<parser::DoConstruct>());
68 curEval = &*std::next(curEval->getNestedEvaluations().begin());
69 }
70 return curEval;
71 }
72
73 static void genNestedEvaluations(lower::AbstractConverter &converter,
74 lower::pft::Evaluation &eval,
75 int collapseValue = 0) {
76 lower::pft::Evaluation *curEval = getCollapsedLoopEval(eval, collapseValue);
77
78 for (lower::pft::Evaluation &e : curEval->getNestedEvaluations())
79 converter.genEval(e);
80 }
81
82 static fir::GlobalOp globalInitialization(lower::AbstractConverter &converter,
83 fir::FirOpBuilder &firOpBuilder,
84 const semantics::Symbol &sym,
85 const lower::pft::Variable &var,
86 mlir::Location currentLocation) {
87 mlir::Type ty = converter.genType(sym);
88 std::string globalName = converter.mangleName(sym);
89 mlir::StringAttr linkage = firOpBuilder.createInternalLinkage();
90 fir::GlobalOp global =
91 firOpBuilder.createGlobal(currentLocation, ty, globalName, linkage);
92
93 // Create default initialization for non-character scalar.
94 if (semantics::IsAllocatableOrObjectPointer(&sym)) {
95 mlir::Type baseAddrType = mlir::dyn_cast<fir::BoxType>(ty).getEleTy();
96 lower::createGlobalInitialization(
97 firOpBuilder, global, [&](fir::FirOpBuilder &b) {
98 mlir::Value nullAddr =
99 b.createNullConstant(currentLocation, baseAddrType);
100 mlir::Value box =
101 b.create<fir::EmboxOp>(currentLocation, ty, nullAddr);
102 b.create<fir::HasValueOp>(currentLocation, box);
103 });
104 } else {
105 lower::createGlobalInitialization(
106 firOpBuilder, global, [&](fir::FirOpBuilder &b) {
107 mlir::Value undef = b.create<fir::UndefOp>(currentLocation, ty);
108 b.create<fir::HasValueOp>(currentLocation, undef);
109 });
110 }
111
112 return global;
113 }
114
115 // Get the extended value for \p val by extracting additional variable
116 // information from \p base.
117 static fir::ExtendedValue getExtendedValue(fir::ExtendedValue base,
118 mlir::Value val) {
119 return base.match(
120 [&](const fir::MutableBoxValue &box) -> fir::ExtendedValue {
121 return fir::MutableBoxValue(val, box.nonDeferredLenParams(), {});
122 },
123 [&](const auto &) -> fir::ExtendedValue {
124 return fir::substBase(base, val);
125 });
126 }
127
128 #ifndef NDEBUG
129 static bool isThreadPrivate(lower::SymbolRef sym) {
130 if (const auto *details = sym->detailsIf<semantics::CommonBlockDetails>()) {
131 for (const auto &obj : details->objects())
132 if (!obj->test(semantics::Symbol::Flag::OmpThreadprivate))
133 return false;
134 return true;
135 }
136 return sym->test(semantics::Symbol::Flag::OmpThreadprivate);
137 }
138 #endif
139
140 static void threadPrivatizeVars(lower::AbstractConverter &converter,
141 lower::pft::Evaluation &eval) {
142 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
143 mlir::Location currentLocation = converter.getCurrentLocation();
144 mlir::OpBuilder::InsertionGuard guard(firOpBuilder);
145 firOpBuilder.setInsertionPointToStart(firOpBuilder.getAllocaBlock());
146
147 // If the symbol corresponds to the original ThreadprivateOp, use the symbol
148 // value from that operation to create one ThreadprivateOp copy operation
149 // inside the parallel region.
150 // In some cases, however, the symbol will correspond to the original,
151 // non-threadprivate variable. This can happen, for instance, with a common
152 // block, declared in a separate module, used by a parent procedure and
153 // privatized in its child procedure.
154 auto genThreadprivateOp = [&](lower::SymbolRef sym) -> mlir::Value {
155 assert(isThreadPrivate(sym));
156 mlir::Value symValue = converter.getSymbolAddress(sym);
157 mlir::Operation *op = symValue.getDefiningOp();
158 if (auto declOp = mlir::dyn_cast<hlfir::DeclareOp>(op))
159 op = declOp.getMemref().getDefiningOp();
160 if (mlir::isa<mlir::omp::ThreadprivateOp>(op))
161 symValue = mlir::dyn_cast<mlir::omp::ThreadprivateOp>(op).getSymAddr();
162 return firOpBuilder.create<mlir::omp::ThreadprivateOp>(
163 currentLocation, symValue.getType(), symValue);
164 };
165
166 llvm::SetVector<const semantics::Symbol *> threadprivateSyms;
167 converter.collectSymbolSet(eval, threadprivateSyms,
168 semantics::Symbol::Flag::OmpThreadprivate,
169 /*collectSymbols=*/true,
170 /*collectHostAssociatedSymbols=*/true);
171 std::set<semantics::SourceName> threadprivateSymNames;
172
173 // For a COMMON block, the ThreadprivateOp is generated for itself instead of
174 // its members, so only bind the value of the new copied ThreadprivateOp
175 // inside the parallel region to the common block symbol only once for
176 // multiple members in one COMMON block.
177 llvm::SetVector<const semantics::Symbol *> commonSyms;
178 for (std::size_t i = 0; i < threadprivateSyms.size(); i++) {
179 const semantics::Symbol *sym = threadprivateSyms[i];
180 mlir::Value symThreadprivateValue;
181 // The variable may be used more than once, and each reference has one
182 // symbol with the same name. Only do once for references of one variable.
183 if (threadprivateSymNames.find(sym->name()) != threadprivateSymNames.end())
184 continue;
185 threadprivateSymNames.insert(sym->name());
186 if (const semantics::Symbol *common =
187 semantics::FindCommonBlockContaining(sym->GetUltimate())) {
188 mlir::Value commonThreadprivateValue;
189 if (commonSyms.contains(common)) {
190 commonThreadprivateValue = converter.getSymbolAddress(*common);
191 } else {
192 commonThreadprivateValue = genThreadprivateOp(*common);
193 converter.bindSymbol(*common, commonThreadprivateValue);
194 commonSyms.insert(common);
195 }
196 symThreadprivateValue = lower::genCommonBlockMember(
197 converter, currentLocation, *sym, commonThreadprivateValue);
198 } else {
199 symThreadprivateValue = genThreadprivateOp(*sym);
200 }
201
202 fir::ExtendedValue sexv = converter.getSymbolExtendedValue(*sym);
203 fir::ExtendedValue symThreadprivateExv =
204 getExtendedValue(sexv, symThreadprivateValue);
205 converter.bindSymbol(*sym, symThreadprivateExv);
206 }
207 }
208
209 static mlir::Operation *
210 createAndSetPrivatizedLoopVar(lower::AbstractConverter &converter,
211 mlir::Location loc, mlir::Value indexVal,
212 const semantics::Symbol *sym) {
213 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
214 mlir::OpBuilder::InsertPoint insPt = firOpBuilder.saveInsertionPoint();
215 firOpBuilder.setInsertionPointToStart(firOpBuilder.getAllocaBlock());
216
217 mlir::Type tempTy = converter.genType(*sym);
218
219 assert(converter.isPresentShallowLookup(*sym) &&
220 "Expected symbol to be in symbol table.");
221
222 firOpBuilder.restoreInsertionPoint(insPt);
223 mlir::Value cvtVal = firOpBuilder.createConvert(loc, tempTy, indexVal);
224 mlir::Operation *storeOp = firOpBuilder.create<fir::StoreOp>(
225 loc, cvtVal, converter.getSymbolAddress(*sym));
226 return storeOp;
227 }
228
229 // This helper function implements the functionality of "promoting"
230 // non-CPTR arguments of use_device_ptr to use_device_addr
231 // arguments (automagic conversion of use_device_ptr ->
232 // use_device_addr in these cases). The way we do so currently is
233 // through the shuffling of operands from the devicePtrOperands to
234 // deviceAddrOperands where neccesary and re-organizing the types,
235 // locations and symbols to maintain the correct ordering of ptr/addr
236 // input -> BlockArg.
237 //
238 // This effectively implements some deprecated OpenMP functionality
239 // that some legacy applications unfortunately depend on
240 // (deprecated in specification version 5.2):
241 //
242 // "If a list item in a use_device_ptr clause is not of type C_PTR,
243 // the behavior is as if the list item appeared in a use_device_addr
244 // clause. Support for such list items in a use_device_ptr clause
245 // is deprecated."
246 static void promoteNonCPtrUseDevicePtrArgsToUseDeviceAddr(
247 llvm::SmallVectorImpl<mlir::Value> &useDeviceAddrVars,
248 llvm::SmallVectorImpl<mlir::Value> &useDevicePtrVars,
249 llvm::SmallVectorImpl<mlir::Type> &useDeviceTypes,
250 llvm::SmallVectorImpl<mlir::Location> &useDeviceLocs,
251 llvm::SmallVectorImpl<const semantics::Symbol *> &useDeviceSymbols) {
252 auto moveElementToBack = [](size_t idx, auto &vector) {
253 auto *iter = std::next(vector.begin(), idx);
254 vector.push_back(*iter);
255 vector.erase(iter);
256 };
257
258 // Iterate over our use_device_ptr list and shift all non-cptr arguments into
259 // use_device_addr.
260 for (auto *it = useDevicePtrVars.begin(); it != useDevicePtrVars.end();) {
261 if (!fir::isa_builtin_cptr_type(fir::unwrapRefType(it->getType()))) {
262 useDeviceAddrVars.push_back(*it);
263 // We have to shuffle the symbols around as well, to maintain
264 // the correct Input -> BlockArg for use_device_ptr/use_device_addr.
265 // NOTE: However, as map's do not seem to be included currently
266 // this isn't as pertinent, but we must try to maintain for
267 // future alterations. I believe the reason they are not currently
268 // is that the BlockArg assign/lowering needs to be extended
269 // to a greater set of types.
270 auto idx = std::distance(useDevicePtrVars.begin(), it);
271 moveElementToBack(idx, useDeviceTypes);
272 moveElementToBack(idx, useDeviceLocs);
273 moveElementToBack(idx, useDeviceSymbols);
274 it = useDevicePtrVars.erase(it);
275 continue;
276 }
277 ++it;
278 }
279 }
280
281 /// Extract the list of function and variable symbols affected by the given
282 /// 'declare target' directive and return the intended device type for them.
283 static void getDeclareTargetInfo(
284 lower::AbstractConverter &converter, semantics::SemanticsContext &semaCtx,
285 lower::pft::Evaluation &eval,
286 const parser::OpenMPDeclareTargetConstruct &declareTargetConstruct,
287 mlir::omp::DeclareTargetClauseOps &clauseOps,
288 llvm::SmallVectorImpl<DeclareTargetCapturePair> &symbolAndClause) {
289 const auto &spec =
290 std::get<parser::OmpDeclareTargetSpecifier>(declareTargetConstruct.t);
291 if (const auto *objectList{parser::Unwrap<parser::OmpObjectList>(spec.u)}) {
292 ObjectList objects{makeObjects(*objectList, semaCtx)};
293 // Case: declare target(func, var1, var2)
294 gatherFuncAndVarSyms(objects, mlir::omp::DeclareTargetCaptureClause::to,
295 symbolAndClause);
296 } else if (const auto *clauseList{
297 parser::Unwrap<parser::OmpClauseList>(spec.u)}) {
298 List<Clause> clauses = makeClauses(*clauseList, semaCtx);
299 if (clauses.empty() &&
300 (!eval.getOwningProcedure()->isMainProgram() ||
301 eval.getOwningProcedure()->getMainProgramSymbol())) {
302 // Case: declare target, implicit capture of function
303 symbolAndClause.emplace_back(
304 mlir::omp::DeclareTargetCaptureClause::to,
305 eval.getOwningProcedure()->getSubprogramSymbol());
306 }
307
308 ClauseProcessor cp(converter, semaCtx, clauses);
309 cp.processDeviceType(clauseOps);
310 cp.processEnter(symbolAndClause);
311 cp.processLink(symbolAndClause);
312 cp.processTo(symbolAndClause);
313
314 cp.processTODO<clause::Indirect>(converter.getCurrentLocation(),
315 llvm::omp::Directive::OMPD_declare_target);
316 }
317 }
318
319 static void collectDeferredDeclareTargets(
320 lower::AbstractConverter &converter, semantics::SemanticsContext &semaCtx,
321 lower::pft::Evaluation &eval,
322 const parser::OpenMPDeclareTargetConstruct &declareTargetConstruct,
323 llvm::SmallVectorImpl<lower::OMPDeferredDeclareTargetInfo>
324 &deferredDeclareTarget) {
325 mlir::omp::DeclareTargetClauseOps clauseOps;
326 llvm::SmallVector<DeclareTargetCapturePair> symbolAndClause;
327 getDeclareTargetInfo(converter, semaCtx, eval, declareTargetConstruct,
328 clauseOps, symbolAndClause);
329 // Return the device type only if at least one of the targets for the
330 // directive is a function or subroutine
331 mlir::ModuleOp mod = converter.getFirOpBuilder().getModule();
332
333 for (const DeclareTargetCapturePair &symClause : symbolAndClause) {
334 mlir::Operation *op = mod.lookupSymbol(
335 converter.mangleName(std::get<const semantics::Symbol &>(symClause)));
336
337 if (!op) {
338 deferredDeclareTarget.push_back({std::get<0>(symClause),
339 clauseOps.deviceType,
340 std::get<1>(symClause)});
341 }
342 }
343 }
344
345 static std::optional<mlir::omp::DeclareTargetDeviceType>
346 getDeclareTargetFunctionDevice(
347 lower::AbstractConverter &converter, semantics::SemanticsContext &semaCtx,
348 lower::pft::Evaluation &eval,
349 const parser::OpenMPDeclareTargetConstruct &declareTargetConstruct) {
350 mlir::omp::DeclareTargetClauseOps clauseOps;
351 llvm::SmallVector<DeclareTargetCapturePair> symbolAndClause;
352 getDeclareTargetInfo(converter, semaCtx, eval, declareTargetConstruct,
353 clauseOps, symbolAndClause);
354
355 // Return the device type only if at least one of the targets for the
356 // directive is a function or subroutine
357 mlir::ModuleOp mod = converter.getFirOpBuilder().getModule();
358 for (const DeclareTargetCapturePair &symClause : symbolAndClause) {
359 mlir::Operation *op = mod.lookupSymbol(
360 converter.mangleName(std::get<const semantics::Symbol &>(symClause)));
361
362 if (mlir::isa_and_nonnull<mlir::func::FuncOp>(op))
363 return clauseOps.deviceType;
364 }
365
366 return std::nullopt;
367 }
368
369 /// Set up the entry block of the given `omp.loop_nest` operation, adding a
370 /// block argument for each loop induction variable and allocating and
371 /// initializing a private value to hold each of them.
372 ///
373 /// This function can also bind the symbols of any variables that should match
374 /// block arguments on parent loop wrapper operations attached to the same
375 /// loop. This allows the introduction of any necessary `hlfir.declare`
376 /// operations inside of the entry block of the `omp.loop_nest` operation and
377 /// not directly under any of the wrappers, which would invalidate them.
378 ///
379 /// \param [in] op - the loop nest operation.
380 /// \param [in] converter - PFT to MLIR conversion interface.
381 /// \param [in] loc - location.
382 /// \param [in] args - symbols of induction variables.
383 /// \param [in] wrapperSyms - symbols of variables to be mapped to loop wrapper
384 /// entry block arguments.
385 /// \param [in] wrapperArgs - entry block arguments of parent loop wrappers.
386 static void
387 genLoopVars(mlir::Operation *op, lower::AbstractConverter &converter,
388 mlir::Location &loc, llvm::ArrayRef<const semantics::Symbol *> args,
389 llvm::ArrayRef<const semantics::Symbol *> wrapperSyms = {},
390 llvm::ArrayRef<mlir::BlockArgument> wrapperArgs = {}) {
391 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
392 auto &region = op->getRegion(0);
393
394 std::size_t loopVarTypeSize = 0;
395 for (const semantics::Symbol *arg : args)
396 loopVarTypeSize = std::max(loopVarTypeSize, arg->GetUltimate().size());
397 mlir::Type loopVarType = getLoopVarType(converter, loopVarTypeSize);
398 llvm::SmallVector<mlir::Type> tiv(args.size(), loopVarType);
399 llvm::SmallVector<mlir::Location> locs(args.size(), loc);
400 firOpBuilder.createBlock(&region, {}, tiv, locs);
401
402 // Bind the entry block arguments of parent wrappers to the corresponding
403 // symbols.
404 for (auto [arg, prv] : llvm::zip_equal(wrapperSyms, wrapperArgs))
405 converter.bindSymbol(*arg, prv);
406
407 // The argument is not currently in memory, so make a temporary for the
408 // argument, and store it there, then bind that location to the argument.
409 mlir::Operation *storeOp = nullptr;
410 for (auto [argIndex, argSymbol] : llvm::enumerate(args)) {
411 mlir::Value indexVal = fir::getBase(region.front().getArgument(argIndex));
412 storeOp =
413 createAndSetPrivatizedLoopVar(converter, loc, indexVal, argSymbol);
414 }
415 firOpBuilder.setInsertionPointAfter(storeOp);
416 }
417
418 static void
419 genReductionVars(mlir::Operation *op, lower::AbstractConverter &converter,
420 mlir::Location &loc,
421 llvm::ArrayRef<const semantics::Symbol *> reductionArgs,
422 llvm::ArrayRef<mlir::Type> reductionTypes) {
423 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
424 llvm::SmallVector<mlir::Location> blockArgLocs(reductionArgs.size(), loc);
425
426 mlir::Block *entryBlock = firOpBuilder.createBlock(
427 &op->getRegion(0), {}, reductionTypes, blockArgLocs);
428
429 // Bind the reduction arguments to their block arguments.
430 for (auto [arg, prv] :
431 llvm::zip_equal(reductionArgs, entryBlock->getArguments())) {
432 converter.bindSymbol(*arg, prv);
433 }
434 }
435
436 static void
437 markDeclareTarget(mlir::Operation *op, lower::AbstractConverter &converter,
438 mlir::omp::DeclareTargetCaptureClause captureClause,
439 mlir::omp::DeclareTargetDeviceType deviceType) {
440 // TODO: Add support for program local variables with declare target applied
441 auto declareTargetOp = llvm::dyn_cast<mlir::omp::DeclareTargetInterface>(op);
442 if (!declareTargetOp)
443 fir::emitFatalError(
444 converter.getCurrentLocation(),
445 "Attempt to apply declare target on unsupported operation");
446
447 // The function or global already has a declare target applied to it, very
448 // likely through implicit capture (usage in another declare target
449 // function/subroutine). It should be marked as any if it has been assigned
450 // both host and nohost, else we skip, as there is no change
451 if (declareTargetOp.isDeclareTarget()) {
452 if (declareTargetOp.getDeclareTargetDeviceType() != deviceType)
453 declareTargetOp.setDeclareTarget(mlir::omp::DeclareTargetDeviceType::any,
454 captureClause);
455 return;
456 }
457
458 declareTargetOp.setDeclareTarget(deviceType, captureClause);
459 }
460
461 /// For an operation that takes `omp.private` values as region args, this util
462 /// merges the private vars info into the region arguments list.
463 ///
464 /// \tparam OMPOP - the OpenMP op that takes `omp.private` inputs.
465 /// \tparam InfoTy - the type of private info we want to merge; e.g. mlir::Type
466 /// or mlir::Location fields of the private var list.
467 ///
468 /// \param [in] op - the op accepting `omp.private` inputs.
469 /// \param [in] currentList - the current list of region info that we
470 /// want to merge private info with. For example this could be the list of types
471 /// or locations of previous arguments to \op's region.
472 /// \param [in] infoAccessor - for a private variable, this returns the
473 /// data we want to merge: type or location.
474 /// \param [out] allRegionArgsInfo - the merged list of region info.
475 template <typename OMPOp, typename InfoTy>
476 static void
477 mergePrivateVarsInfo(OMPOp op, llvm::ArrayRef<InfoTy> currentList,
478 llvm::function_ref<InfoTy(mlir::Value)> infoAccessor,
479 llvm::SmallVectorImpl<InfoTy> &allRegionArgsInfo) {
480 mlir::OperandRange privateVars = op.getPrivateVars();
481
482 llvm::transform(currentList, std::back_inserter(allRegionArgsInfo),
483 [](InfoTy i) { return i; });
484 llvm::transform(privateVars, std::back_inserter(allRegionArgsInfo),
485 infoAccessor);
486 }
487
488 //===----------------------------------------------------------------------===//
489 // Op body generation helper structures and functions
490 //===----------------------------------------------------------------------===//
491
492 struct OpWithBodyGenInfo {
493 /// A type for a code-gen callback function. This takes as argument the op for
494 /// which the code is being generated and returns the arguments of the op's
495 /// region.
496 using GenOMPRegionEntryCBFn =
497 std::function<llvm::SmallVector<const semantics::Symbol *>(
498 mlir::Operation *)>;
499
500 OpWithBodyGenInfo(lower::AbstractConverter &converter,
501 lower::SymMap &symTable,
502 semantics::SemanticsContext &semaCtx, mlir::Location loc,
503 lower::pft::Evaluation &eval, llvm::omp::Directive dir)
504 : converter(converter), symTable(symTable), semaCtx(semaCtx), loc(loc),
505 eval(eval), dir(dir) {}
506
507 OpWithBodyGenInfo &setClauses(const List<Clause> *value) {
508 clauses = value;
509 return *this;
510 }
511
512 OpWithBodyGenInfo &setDataSharingProcessor(DataSharingProcessor *value) {
513 dsp = value;
514 return *this;
515 }
516
517 OpWithBodyGenInfo &setGenRegionEntryCb(GenOMPRegionEntryCBFn value) {
518 genRegionEntryCB = value;
519 return *this;
520 }
521
522 /// [inout] converter to use for the clauses.
523 lower::AbstractConverter &converter;
524 /// [in] Symbol table
525 lower::SymMap &symTable;
526 /// [in] Semantics context
527 semantics::SemanticsContext &semaCtx;
528 /// [in] location in source code.
529 mlir::Location loc;
530 /// [in] current PFT node/evaluation.
531 lower::pft::Evaluation &eval;
532 /// [in] leaf directive for which to generate the op body.
533 llvm::omp::Directive dir;
534 /// [in] list of clauses to process.
535 const List<Clause> *clauses = nullptr;
536 /// [in] if provided, processes the construct's data-sharing attributes.
537 DataSharingProcessor *dsp = nullptr;
538 /// [in] if provided, emits the op's region entry. Otherwise, an emtpy block
539 /// is created in the region.
540 GenOMPRegionEntryCBFn genRegionEntryCB = nullptr;
541 };
542
543 /// Create the body (block) for an OpenMP Operation.
544 ///
545 /// \param [in] op - the operation the body belongs to.
546 /// \param [in] info - options controlling code-gen for the construction.
547 /// \param [in] queue - work queue with nested constructs.
548 /// \param [in] item - item in the queue to generate body for.
549 static void createBodyOfOp(mlir::Operation &op, const OpWithBodyGenInfo &info,
550 const ConstructQueue &queue,
551 ConstructQueue::iterator item) {
552 fir::FirOpBuilder &firOpBuilder = info.converter.getFirOpBuilder();
553
554 auto insertMarker = [](fir::FirOpBuilder &builder) {
555 mlir::Value undef = builder.create<fir::UndefOp>(builder.getUnknownLoc(),
556 builder.getIndexType());
557 return undef.getDefiningOp();
558 };
559
560 // If an argument for the region is provided then create the block with that
561 // argument. Also update the symbol's address with the mlir argument value.
562 // e.g. For loops the argument is the induction variable. And all further
563 // uses of the induction variable should use this mlir value.
564 auto regionArgs = [&]() -> llvm::SmallVector<const semantics::Symbol *> {
565 if (info.genRegionEntryCB != nullptr) {
566 return info.genRegionEntryCB(&op);
567 }
568
569 firOpBuilder.createBlock(&op.getRegion(0));
570 return {};
571 }();
572 // Mark the earliest insertion point.
573 mlir::Operation *marker = insertMarker(firOpBuilder);
574
575 // If it is an unstructured region, create empty blocks for all evaluations.
576 if (info.eval.lowerAsUnstructured())
577 lower::createEmptyRegionBlocks<mlir::omp::TerminatorOp, mlir::omp::YieldOp>(
578 firOpBuilder, info.eval.getNestedEvaluations());
579
580 // Start with privatization, so that the lowering of the nested
581 // code will use the right symbols.
582 bool isLoop = llvm::omp::getDirectiveAssociation(info.dir) ==
583 llvm::omp::Association::Loop;
584 bool privatize = info.clauses;
585
586 firOpBuilder.setInsertionPoint(marker);
587 std::optional<DataSharingProcessor> tempDsp;
588 if (privatize && !info.dsp) {
589 tempDsp.emplace(info.converter, info.semaCtx, *info.clauses, info.eval,
590 Fortran::lower::omp::isLastItemInQueue(item, queue));
591 tempDsp->processStep1();
592 }
593
594 if (info.dir == llvm::omp::Directive::OMPD_parallel) {
595 threadPrivatizeVars(info.converter, info.eval);
596 if (info.clauses) {
597 firOpBuilder.setInsertionPoint(marker);
598 ClauseProcessor(info.converter, info.semaCtx, *info.clauses)
599 .processCopyin();
600 }
601 }
602
603 if (ConstructQueue::iterator next = std::next(item); next != queue.end()) {
604 genOMPDispatch(info.converter, info.symTable, info.semaCtx, info.eval,
605 info.loc, queue, next);
606 } else {
607 // genFIR(Evaluation&) tries to patch up unterminated blocks, causing
608 // a lot of complications for our approach if the terminator generation
609 // is delayed past this point. Insert a temporary terminator here, then
610 // delete it.
611 firOpBuilder.setInsertionPointToEnd(&op.getRegion(0).back());
612 auto *temp = lower::genOpenMPTerminator(firOpBuilder, &op, info.loc);
613 firOpBuilder.setInsertionPointAfter(marker);
614 genNestedEvaluations(info.converter, info.eval);
615 temp->erase();
616 }
617
618 // Get or create a unique exiting block from the given region, or
619 // return nullptr if there is no exiting block.
620 auto getUniqueExit = [&](mlir::Region &region) -> mlir::Block * {
621 // Find the blocks where the OMP terminator should go. In simple cases
622 // it is the single block in the operation's region. When the region
623 // is more complicated, especially with unstructured control flow, there
624 // may be multiple blocks, and some of them may have non-OMP terminators
625 // resulting from lowering of the code contained within the operation.
626 // All the remaining blocks are potential exit points from the op's region.
627 //
628 // Explicit control flow cannot exit any OpenMP region (other than via
629 // STOP), and that is enforced by semantic checks prior to lowering. STOP
630 // statements are lowered to a function call.
631
632 // Collect unterminated blocks.
633 llvm::SmallVector<mlir::Block *> exits;
634 for (mlir::Block &b : region) {
635 if (b.empty() || !b.back().hasTrait<mlir::OpTrait::IsTerminator>())
636 exits.push_back(&b);
637 }
638
639 if (exits.empty())
640 return nullptr;
641 // If there already is a unique exiting block, do not create another one.
642 // Additionally, some ops (e.g. omp.sections) require only 1 block in
643 // its region.
644 if (exits.size() == 1)
645 return exits[0];
646 mlir::Block *exit = firOpBuilder.createBlock(&region);
647 for (mlir::Block *b : exits) {
648 firOpBuilder.setInsertionPointToEnd(b);
649 firOpBuilder.create<mlir::cf::BranchOp>(info.loc, exit);
650 }
651 return exit;
652 };
653
654 if (auto *exitBlock = getUniqueExit(op.getRegion(0))) {
655 firOpBuilder.setInsertionPointToEnd(exitBlock);
656 auto *term = lower::genOpenMPTerminator(firOpBuilder, &op, info.loc);
657 // Only insert lastprivate code when there actually is an exit block.
658 // Such a block may not exist if the nested code produced an infinite
659 // loop (this may not make sense in production code, but a user could
660 // write that and we should handle it).
661 firOpBuilder.setInsertionPoint(term);
662 if (privatize) {
663 // DataSharingProcessor::processStep2() may create operations before/after
664 // the one passed as argument. We need to treat loop wrappers and their
665 // nested loop as a unit, so we need to pass the top level wrapper (if
666 // present). Otherwise, these operations will be inserted within a
667 // wrapper region.
668 mlir::Operation *privatizationTopLevelOp = &op;
669 if (auto loopNest = llvm::dyn_cast<mlir::omp::LoopNestOp>(op)) {
670 llvm::SmallVector<mlir::omp::LoopWrapperInterface> wrappers;
671 loopNest.gatherWrappers(wrappers);
672 if (!wrappers.empty())
673 privatizationTopLevelOp = &*wrappers.back();
674 }
675
676 if (!info.dsp) {
677 assert(tempDsp.has_value());
678 tempDsp->processStep2(privatizationTopLevelOp, isLoop);
679 } else {
680 if (isLoop && regionArgs.size() > 0) {
681 for (const auto &regionArg : regionArgs) {
682 info.dsp->pushLoopIV(info.converter.getSymbolAddress(*regionArg));
683 }
684 }
685 info.dsp->processStep2(privatizationTopLevelOp, isLoop);
686 }
687 }
688 }
689
690 firOpBuilder.setInsertionPointAfter(marker);
691 marker->erase();
692 }
693
694 static void genBodyOfTargetDataOp(
695 lower::AbstractConverter &converter, lower::SymMap &symTable,
696 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
697 mlir::omp::TargetDataOp &dataOp, llvm::ArrayRef<mlir::Type> useDeviceTypes,
698 llvm::ArrayRef<mlir::Location> useDeviceLocs,
699 llvm::ArrayRef<const semantics::Symbol *> useDeviceSymbols,
700 const mlir::Location &currentLocation, const ConstructQueue &queue,
701 ConstructQueue::iterator item) {
702 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
703 mlir::Region &region = dataOp.getRegion();
704
705 firOpBuilder.createBlock(&region, {}, useDeviceTypes, useDeviceLocs);
706
707 for (auto [argIndex, argSymbol] : llvm::enumerate(useDeviceSymbols)) {
708 const mlir::BlockArgument &arg = region.front().getArgument(argIndex);
709 fir::ExtendedValue extVal = converter.getSymbolExtendedValue(*argSymbol);
710 if (auto refType = mlir::dyn_cast<fir::ReferenceType>(arg.getType())) {
711 if (fir::isa_builtin_cptr_type(refType.getElementType())) {
712 converter.bindSymbol(*argSymbol, arg);
713 } else {
714 // Avoid capture of a reference to a structured binding.
715 const semantics::Symbol *sym = argSymbol;
716 extVal.match(
717 [&](const fir::MutableBoxValue &mbv) {
718 converter.bindSymbol(
719 *sym,
720 fir::MutableBoxValue(
721 arg, fir::factory::getNonDeferredLenParams(extVal), {}));
722 },
723 [&](const auto &) {
724 TODO(converter.getCurrentLocation(),
725 "use_device clause operand unsupported type");
726 });
727 }
728 } else {
729 TODO(converter.getCurrentLocation(),
730 "use_device clause operand unsupported type");
731 }
732 }
733
734 // Insert dummy instruction to remember the insertion position. The
735 // marker will be deleted by clean up passes since there are no uses.
736 // Remembering the position for further insertion is important since
737 // there are hlfir.declares inserted above while setting block arguments
738 // and new code from the body should be inserted after that.
739 mlir::Value undefMarker = firOpBuilder.create<fir::UndefOp>(
740 dataOp.getOperation()->getLoc(), firOpBuilder.getIndexType());
741
742 // Create blocks for unstructured regions. This has to be done since
743 // blocks are initially allocated with the function as the parent region.
744 if (eval.lowerAsUnstructured()) {
745 lower::createEmptyRegionBlocks<mlir::omp::TerminatorOp, mlir::omp::YieldOp>(
746 firOpBuilder, eval.getNestedEvaluations());
747 }
748
749 firOpBuilder.create<mlir::omp::TerminatorOp>(currentLocation);
750
751 // Set the insertion point after the marker.
752 firOpBuilder.setInsertionPointAfter(undefMarker.getDefiningOp());
753
754 if (ConstructQueue::iterator next = std::next(item); next != queue.end()) {
755 genOMPDispatch(converter, symTable, semaCtx, eval, currentLocation, queue,
756 next);
757 } else {
758 genNestedEvaluations(converter, eval);
759 }
760 }
761
762 // This generates intermediate common block member accesses within a region
763 // and then rebinds the members symbol to the intermediate accessors we have
764 // generated so that subsequent code generation will utilise these instead.
765 //
766 // When the scope changes, the bindings to the intermediate accessors should
767 // be dropped in place of the original symbol bindings.
768 //
769 // This is for utilisation with TargetOp.
770 static void genIntermediateCommonBlockAccessors(
771 Fortran::lower::AbstractConverter &converter,
772 const mlir::Location &currentLocation, mlir::Region &region,
773 llvm::ArrayRef<const Fortran::semantics::Symbol *> mapSyms) {
774 for (auto [argIndex, argSymbol] : llvm::enumerate(mapSyms)) {
775 if (auto *details =
776 argSymbol->detailsIf<Fortran::semantics::CommonBlockDetails>()) {
777 for (auto obj : details->objects()) {
778 auto targetCBMemberBind = Fortran::lower::genCommonBlockMember(
779 converter, currentLocation, *obj, region.getArgument(argIndex));
780 fir::ExtendedValue sexv = converter.getSymbolExtendedValue(*obj);
781 fir::ExtendedValue targetCBExv =
782 getExtendedValue(sexv, targetCBMemberBind);
783 converter.bindSymbol(*obj, targetCBExv);
784 }
785 }
786 }
787 }
788
789 // This functions creates a block for the body of the targetOp's region. It adds
790 // all the symbols present in mapSymbols as block arguments to this block.
791 static void
792 genBodyOfTargetOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
793 semantics::SemanticsContext &semaCtx,
794 lower::pft::Evaluation &eval, mlir::omp::TargetOp &targetOp,
795 llvm::ArrayRef<const semantics::Symbol *> mapSyms,
796 llvm::ArrayRef<mlir::Location> mapSymLocs,
797 llvm::ArrayRef<mlir::Type> mapSymTypes,
798 DataSharingProcessor &dsp,
799 const mlir::Location &currentLocation,
800 const ConstructQueue &queue, ConstructQueue::iterator item) {
801 assert(mapSymTypes.size() == mapSymLocs.size());
802
803 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
804 mlir::Region &region = targetOp.getRegion();
805
806 llvm::SmallVector<mlir::Type> allRegionArgTypes;
807 mergePrivateVarsInfo(targetOp, mapSymTypes,
808 llvm::function_ref<mlir::Type(mlir::Value)>{
809 [](mlir::Value v) { return v.getType(); }},
810 allRegionArgTypes);
811
812 llvm::SmallVector<mlir::Location> allRegionArgLocs;
813 mergePrivateVarsInfo(targetOp, mapSymLocs,
814 llvm::function_ref<mlir::Location(mlir::Value)>{
815 [](mlir::Value v) { return v.getLoc(); }},
816 allRegionArgLocs);
817
818 auto *regionBlock = firOpBuilder.createBlock(&region, {}, allRegionArgTypes,
819 allRegionArgLocs);
820
821 // Clones the `bounds` placing them inside the target region and returns them.
822 auto cloneBound = [&](mlir::Value bound) {
823 if (mlir::isMemoryEffectFree(bound.getDefiningOp())) {
824 mlir::Operation *clonedOp = bound.getDefiningOp()->clone();
825 regionBlock->push_back(clonedOp);
826 return clonedOp->getResult(0);
827 }
828 TODO(converter.getCurrentLocation(),
829 "target map clause operand unsupported bound type");
830 };
831
832 auto cloneBounds = [cloneBound](llvm::ArrayRef<mlir::Value> bounds) {
833 llvm::SmallVector<mlir::Value> clonedBounds;
834 for (mlir::Value bound : bounds)
835 clonedBounds.emplace_back(cloneBound(bound));
836 return clonedBounds;
837 };
838
839 // Bind the symbols to their corresponding block arguments.
840 for (auto [argIndex, argSymbol] : llvm::enumerate(mapSyms)) {
841 const mlir::BlockArgument &arg = region.getArgument(argIndex);
842 // Avoid capture of a reference to a structured binding.
843 const semantics::Symbol *sym = argSymbol;
844 // Structure component symbols don't have bindings.
845 if (sym->owner().IsDerivedType())
846 continue;
847 fir::ExtendedValue extVal = converter.getSymbolExtendedValue(*sym);
848 extVal.match(
849 [&](const fir::BoxValue &v) {
850 converter.bindSymbol(*sym,
851 fir::BoxValue(arg, cloneBounds(v.getLBounds()),
852 v.getExplicitParameters(),
853 v.getExplicitExtents()));
854 },
855 [&](const fir::MutableBoxValue &v) {
856 converter.bindSymbol(
857 *sym, fir::MutableBoxValue(arg, cloneBounds(v.getLBounds()),
858 v.getMutableProperties()));
859 },
860 [&](const fir::ArrayBoxValue &v) {
861 converter.bindSymbol(
862 *sym, fir::ArrayBoxValue(arg, cloneBounds(v.getExtents()),
863 cloneBounds(v.getLBounds()),
864 v.getSourceBox()));
865 },
866 [&](const fir::CharArrayBoxValue &v) {
867 converter.bindSymbol(
868 *sym, fir::CharArrayBoxValue(arg, cloneBound(v.getLen()),
869 cloneBounds(v.getExtents()),
870 cloneBounds(v.getLBounds())));
871 },
872 [&](const fir::CharBoxValue &v) {
873 converter.bindSymbol(*sym,
874 fir::CharBoxValue(arg, cloneBound(v.getLen())));
875 },
876 [&](const fir::UnboxedValue &v) { converter.bindSymbol(*sym, arg); },
877 [&](const auto &) {
878 TODO(converter.getCurrentLocation(),
879 "target map clause operand unsupported type");
880 });
881 }
882
883 for (auto [argIndex, argSymbol] :
884 llvm::enumerate(dsp.getAllSymbolsToPrivatize())) {
885 argIndex = mapSyms.size() + argIndex;
886
887 const mlir::BlockArgument &arg = region.getArgument(argIndex);
888 converter.bindSymbol(*argSymbol,
889 hlfir::translateToExtendedValue(
890 currentLocation, firOpBuilder, hlfir::Entity{arg},
891 /*contiguousHint=*/
892 evaluate::IsSimplyContiguous(
893 *argSymbol, converter.getFoldingContext()))
894 .first);
895 }
896
897 // Check if cloning the bounds introduced any dependency on the outer region.
898 // If so, then either clone them as well if they are MemoryEffectFree, or else
899 // copy them to a new temporary and add them to the map and block_argument
900 // lists and replace their uses with the new temporary.
901 llvm::SetVector<mlir::Value> valuesDefinedAbove;
902 mlir::getUsedValuesDefinedAbove(region, valuesDefinedAbove);
903 while (!valuesDefinedAbove.empty()) {
904 for (mlir::Value val : valuesDefinedAbove) {
905 mlir::Operation *valOp = val.getDefiningOp();
906 if (mlir::isMemoryEffectFree(valOp)) {
907 mlir::Operation *clonedOp = valOp->clone();
908 regionBlock->push_front(clonedOp);
909 val.replaceUsesWithIf(
910 clonedOp->getResult(0), [regionBlock](mlir::OpOperand &use) {
911 return use.getOwner()->getBlock() == regionBlock;
912 });
913 } else {
914 auto savedIP = firOpBuilder.getInsertionPoint();
915 firOpBuilder.setInsertionPointAfter(valOp);
916 auto copyVal =
917 firOpBuilder.createTemporary(val.getLoc(), val.getType());
918 firOpBuilder.createStoreWithConvert(copyVal.getLoc(), val, copyVal);
919
920 llvm::SmallVector<mlir::Value> bounds;
921 std::stringstream name;
922 firOpBuilder.setInsertionPoint(targetOp);
923 mlir::Value mapOp = createMapInfoOp(
924 firOpBuilder, copyVal.getLoc(), copyVal,
925 /*varPtrPtr=*/mlir::Value{}, name.str(), bounds,
926 /*members=*/llvm::SmallVector<mlir::Value>{},
927 /*membersIndex=*/mlir::DenseIntElementsAttr{},
928 static_cast<
929 std::underlying_type_t<llvm::omp::OpenMPOffloadMappingFlags>>(
930 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_IMPLICIT),
931 mlir::omp::VariableCaptureKind::ByCopy, copyVal.getType());
932 targetOp.getMapOperandsMutable().append(mapOp);
933 mlir::Value clonedValArg =
934 region.addArgument(copyVal.getType(), copyVal.getLoc());
935 firOpBuilder.setInsertionPointToStart(regionBlock);
936 auto loadOp = firOpBuilder.create<fir::LoadOp>(clonedValArg.getLoc(),
937 clonedValArg);
938 val.replaceUsesWithIf(
939 loadOp->getResult(0), [regionBlock](mlir::OpOperand &use) {
940 return use.getOwner()->getBlock() == regionBlock;
941 });
942 firOpBuilder.setInsertionPoint(regionBlock, savedIP);
943 }
944 }
945 valuesDefinedAbove.clear();
946 mlir::getUsedValuesDefinedAbove(region, valuesDefinedAbove);
947 }
948
949 // Insert dummy instruction to remember the insertion position. The
950 // marker will be deleted since there are not uses.
951 // In the HLFIR flow there are hlfir.declares inserted above while
952 // setting block arguments.
953 mlir::Value undefMarker = firOpBuilder.create<fir::UndefOp>(
954 targetOp.getOperation()->getLoc(), firOpBuilder.getIndexType());
955
956 // Create blocks for unstructured regions. This has to be done since
957 // blocks are initially allocated with the function as the parent region.
958 if (eval.lowerAsUnstructured()) {
959 lower::createEmptyRegionBlocks<mlir::omp::TerminatorOp, mlir::omp::YieldOp>(
960 firOpBuilder, eval.getNestedEvaluations());
961 }
962
963 firOpBuilder.create<mlir::omp::TerminatorOp>(currentLocation);
964
965 // Create the insertion point after the marker.
966 firOpBuilder.setInsertionPointAfter(undefMarker.getDefiningOp());
967
968 // If we map a common block using it's symbol e.g. map(tofrom: /common_block/)
969 // and accessing it's members within the target region, there is a large
970 // chance we will end up with uses external to the region accessing the common
971 // resolve these, we do so by generating new common block member accesses
972 // within the region, binding them to the member symbol for the scope of the
973 // region so that subsequent code generation within the region will utilise
974 // our new member accesses we have created.
975 genIntermediateCommonBlockAccessors(converter, currentLocation, region,
976 mapSyms);
977
978 if (ConstructQueue::iterator next = std::next(item); next != queue.end()) {
979 genOMPDispatch(converter, symTable, semaCtx, eval, currentLocation, queue,
980 next);
981 } else {
982 genNestedEvaluations(converter, eval);
983 }
984
985 dsp.processStep2(targetOp, /*isLoop=*/false);
986 }
987
988 template <typename OpTy, typename... Args>
989 static OpTy genOpWithBody(const OpWithBodyGenInfo &info,
990 const ConstructQueue &queue,
991 ConstructQueue::iterator item, Args &&...args) {
992 auto op = info.converter.getFirOpBuilder().create<OpTy>(
993 info.loc, std::forward<Args>(args)...);
994 createBodyOfOp(*op, info, queue, item);
995 return op;
996 }
997
998 template <typename OpTy, typename ClauseOpsTy>
999 static OpTy genWrapperOp(lower::AbstractConverter &converter,
1000 mlir::Location loc, const ClauseOpsTy &clauseOps,
1001 llvm::ArrayRef<mlir::Type> blockArgTypes) {
1002 static_assert(
1003 OpTy::template hasTrait<mlir::omp::LoopWrapperInterface::Trait>(),
1004 "expected a loop wrapper");
1005 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
1006
1007 // Create wrapper.
1008 auto op = firOpBuilder.create<OpTy>(loc, clauseOps);
1009
1010 // Create entry block with arguments.
1011 llvm::SmallVector<mlir::Location> locs(blockArgTypes.size(), loc);
1012 firOpBuilder.createBlock(&op.getRegion(), /*insertPt=*/{}, blockArgTypes,
1013 locs);
1014
1015 firOpBuilder.setInsertionPoint(
1016 lower::genOpenMPTerminator(firOpBuilder, op, loc));
1017
1018 return op;
1019 }
1020
1021 //===----------------------------------------------------------------------===//
1022 // Code generation functions for clauses
1023 //===----------------------------------------------------------------------===//
1024
1025 static void genCriticalDeclareClauses(lower::AbstractConverter &converter,
1026 semantics::SemanticsContext &semaCtx,
1027 const List<Clause> &clauses,
1028 mlir::Location loc,
1029 mlir::omp::CriticalClauseOps &clauseOps,
1030 llvm::StringRef name) {
1031 ClauseProcessor cp(converter, semaCtx, clauses);
1032 cp.processHint(clauseOps);
1033 clauseOps.criticalNameAttr =
1034 mlir::StringAttr::get(converter.getFirOpBuilder().getContext(), name);
1035 }
1036
1037 static void genDistributeClauses(lower::AbstractConverter &converter,
1038 semantics::SemanticsContext &semaCtx,
1039 lower::StatementContext &stmtCtx,
1040 const List<Clause> &clauses,
1041 mlir::Location loc,
1042 mlir::omp::DistributeClauseOps &clauseOps) {
1043 ClauseProcessor cp(converter, semaCtx, clauses);
1044 cp.processAllocate(clauseOps);
1045 cp.processDistSchedule(stmtCtx, clauseOps);
1046 cp.processOrder(clauseOps);
1047 // TODO Support delayed privatization.
1048 }
1049
1050 static void genFlushClauses(lower::AbstractConverter &converter,
1051 semantics::SemanticsContext &semaCtx,
1052 const ObjectList &objects,
1053 const List<Clause> &clauses, mlir::Location loc,
1054 llvm::SmallVectorImpl<mlir::Value> &operandRange) {
1055 if (!objects.empty())
1056 genObjectList(objects, converter, operandRange);
1057
1058 if (!clauses.empty())
1059 TODO(converter.getCurrentLocation(), "Handle OmpMemoryOrderClause");
1060 }
1061
1062 static void
1063 genLoopNestClauses(lower::AbstractConverter &converter,
1064 semantics::SemanticsContext &semaCtx,
1065 lower::pft::Evaluation &eval, const List<Clause> &clauses,
1066 mlir::Location loc, mlir::omp::LoopNestClauseOps &clauseOps,
1067 llvm::SmallVectorImpl<const semantics::Symbol *> &iv) {
1068 ClauseProcessor cp(converter, semaCtx, clauses);
1069 cp.processCollapse(loc, eval, clauseOps, iv);
1070 clauseOps.loopInclusiveAttr = converter.getFirOpBuilder().getUnitAttr();
1071 }
1072
1073 static void genMaskedClauses(lower::AbstractConverter &converter,
1074 semantics::SemanticsContext &semaCtx,
1075 lower::StatementContext &stmtCtx,
1076 const List<Clause> &clauses, mlir::Location loc,
1077 mlir::omp::MaskedClauseOps &clauseOps) {
1078 ClauseProcessor cp(converter, semaCtx, clauses);
1079 cp.processFilter(stmtCtx, clauseOps);
1080 }
1081
1082 static void
1083 genOrderedRegionClauses(lower::AbstractConverter &converter,
1084 semantics::SemanticsContext &semaCtx,
1085 const List<Clause> &clauses, mlir::Location loc,
1086 mlir::omp::OrderedRegionClauseOps &clauseOps) {
1087 ClauseProcessor cp(converter, semaCtx, clauses);
1088 cp.processTODO<clause::Simd>(loc, llvm::omp::Directive::OMPD_ordered);
1089 }
1090
1091 static void genParallelClauses(
1092 lower::AbstractConverter &converter, semantics::SemanticsContext &semaCtx,
1093 lower::StatementContext &stmtCtx, const List<Clause> &clauses,
1094 mlir::Location loc, mlir::omp::ParallelClauseOps &clauseOps,
1095 llvm::SmallVectorImpl<mlir::Type> &reductionTypes,
1096 llvm::SmallVectorImpl<const semantics::Symbol *> &reductionSyms) {
1097 ClauseProcessor cp(converter, semaCtx, clauses);
1098 cp.processAllocate(clauseOps);
1099 cp.processDefault();
1100 cp.processIf(llvm::omp::Directive::OMPD_parallel, clauseOps);
1101 cp.processNumThreads(stmtCtx, clauseOps);
1102 cp.processProcBind(clauseOps);
1103 cp.processReduction(loc, clauseOps, &reductionTypes, &reductionSyms);
1104 }
1105
1106 static void genSectionsClauses(
1107 lower::AbstractConverter &converter, semantics::SemanticsContext &semaCtx,
1108 const List<Clause> &clauses, mlir::Location loc,
1109 mlir::omp::SectionsClauseOps &clauseOps,
1110 llvm::SmallVectorImpl<mlir::Type> &reductionTypes,
1111 llvm::SmallVectorImpl<const semantics::Symbol *> &reductionSyms) {
1112 ClauseProcessor cp(converter, semaCtx, clauses);
1113 cp.processAllocate(clauseOps);
1114 cp.processNowait(clauseOps);
1115 cp.processReduction(loc, clauseOps, &reductionTypes, &reductionSyms);
1116 // TODO Support delayed privatization.
1117 }
1118
1119 static void genSimdClauses(lower::AbstractConverter &converter,
1120 semantics::SemanticsContext &semaCtx,
1121 const List<Clause> &clauses, mlir::Location loc,
1122 mlir::omp::SimdClauseOps &clauseOps) {
1123 ClauseProcessor cp(converter, semaCtx, clauses);
1124 cp.processAligned(clauseOps);
1125 cp.processIf(llvm::omp::Directive::OMPD_simd, clauseOps);
1126 cp.processOrder(clauseOps);
1127 cp.processReduction(loc, clauseOps);
1128 cp.processSafelen(clauseOps);
1129 cp.processSimdlen(clauseOps);
1130
1131 // TODO Support delayed privatization.
1132 cp.processTODO<clause::Allocate, clause::Linear, clause::Nontemporal>(
1133 loc, llvm::omp::Directive::OMPD_simd);
1134 }
1135
1136 static void genSingleClauses(lower::AbstractConverter &converter,
1137 semantics::SemanticsContext &semaCtx,
1138 const List<Clause> &clauses, mlir::Location loc,
1139 mlir::omp::SingleClauseOps &clauseOps) {
1140 ClauseProcessor cp(converter, semaCtx, clauses);
1141 cp.processAllocate(clauseOps);
1142 cp.processCopyprivate(loc, clauseOps);
1143 cp.processNowait(clauseOps);
1144 // TODO Support delayed privatization.
1145 }
1146
1147 static void genTargetClauses(
1148 lower::AbstractConverter &converter, semantics::SemanticsContext &semaCtx,
1149 lower::StatementContext &stmtCtx, const List<Clause> &clauses,
1150 mlir::Location loc, bool processHostOnlyClauses,
1151 mlir::omp::TargetClauseOps &clauseOps,
1152 llvm::SmallVectorImpl<const semantics::Symbol *> &mapSyms,
1153 llvm::SmallVectorImpl<mlir::Location> &mapLocs,
1154 llvm::SmallVectorImpl<mlir::Type> &mapTypes,
1155 llvm::SmallVectorImpl<const semantics::Symbol *> &deviceAddrSyms,
1156 llvm::SmallVectorImpl<mlir::Location> &deviceAddrLocs,
1157 llvm::SmallVectorImpl<mlir::Type> &deviceAddrTypes,
1158 llvm::SmallVectorImpl<const semantics::Symbol *> &devicePtrSyms,
1159 llvm::SmallVectorImpl<mlir::Location> &devicePtrLocs,
1160 llvm::SmallVectorImpl<mlir::Type> &devicePtrTypes) {
1161 ClauseProcessor cp(converter, semaCtx, clauses);
1162 cp.processDepend(clauseOps);
1163 cp.processDevice(stmtCtx, clauseOps);
1164 cp.processHasDeviceAddr(clauseOps, deviceAddrTypes, deviceAddrLocs,
1165 deviceAddrSyms);
1166 cp.processIf(llvm::omp::Directive::OMPD_target, clauseOps);
1167 cp.processIsDevicePtr(clauseOps, devicePtrTypes, devicePtrLocs,
1168 devicePtrSyms);
1169 cp.processMap(loc, stmtCtx, clauseOps, &mapSyms, &mapLocs, &mapTypes);
1170 cp.processThreadLimit(stmtCtx, clauseOps);
1171
1172 if (processHostOnlyClauses)
1173 cp.processNowait(clauseOps);
1174
1175 cp.processTODO<clause::Allocate, clause::Defaultmap, clause::Firstprivate,
1176 clause::InReduction, clause::Reduction,
1177 clause::UsesAllocators>(loc,
1178 llvm::omp::Directive::OMPD_target);
1179
1180 // `target private(..)` is only supported in delayed privatization mode.
1181 if (!enableDelayedPrivatizationStaging)
1182 cp.processTODO<clause::Private>(loc, llvm::omp::Directive::OMPD_target);
1183 }
1184
1185 static void genTargetDataClauses(
1186 lower::AbstractConverter &converter, semantics::SemanticsContext &semaCtx,
1187 lower::StatementContext &stmtCtx, const List<Clause> &clauses,
1188 mlir::Location loc, mlir::omp::TargetDataClauseOps &clauseOps,
1189 llvm::SmallVectorImpl<mlir::Type> &useDeviceTypes,
1190 llvm::SmallVectorImpl<mlir::Location> &useDeviceLocs,
1191 llvm::SmallVectorImpl<const semantics::Symbol *> &useDeviceSyms) {
1192 ClauseProcessor cp(converter, semaCtx, clauses);
1193 cp.processDevice(stmtCtx, clauseOps);
1194 cp.processIf(llvm::omp::Directive::OMPD_target_data, clauseOps);
1195 cp.processMap(loc, stmtCtx, clauseOps);
1196 cp.processUseDeviceAddr(clauseOps, useDeviceTypes, useDeviceLocs,
1197 useDeviceSyms);
1198 cp.processUseDevicePtr(clauseOps, useDeviceTypes, useDeviceLocs,
1199 useDeviceSyms);
1200
1201 // This function implements the deprecated functionality of use_device_ptr
1202 // that allows users to provide non-CPTR arguments to it with the caveat
1203 // that the compiler will treat them as use_device_addr. A lot of legacy
1204 // code may still depend on this functionality, so we should support it
1205 // in some manner. We do so currently by simply shifting non-cptr operands
1206 // from the use_device_ptr list into the front of the use_device_addr list
1207 // whilst maintaining the ordering of useDeviceLocs, useDeviceSyms and
1208 // useDeviceTypes to use_device_ptr/use_device_addr input for BlockArg
1209 // ordering.
1210 // TODO: Perhaps create a user provideable compiler option that will
1211 // re-introduce a hard-error rather than a warning in these cases.
1212 promoteNonCPtrUseDevicePtrArgsToUseDeviceAddr(
1213 clauseOps.useDeviceAddrVars, clauseOps.useDevicePtrVars, useDeviceTypes,
1214 useDeviceLocs, useDeviceSyms);
1215 }
1216
1217 static void genTargetEnterExitUpdateDataClauses(
1218 lower::AbstractConverter &converter, semantics::SemanticsContext &semaCtx,
1219 lower::StatementContext &stmtCtx, const List<Clause> &clauses,
1220 mlir::Location loc, llvm::omp::Directive directive,
1221 mlir::omp::TargetEnterExitUpdateDataClauseOps &clauseOps) {
1222 ClauseProcessor cp(converter, semaCtx, clauses);
1223 cp.processDepend(clauseOps);
1224 cp.processDevice(stmtCtx, clauseOps);
1225 cp.processIf(directive, clauseOps);
1226 cp.processNowait(clauseOps);
1227
1228 if (directive == llvm::omp::Directive::OMPD_target_update) {
1229 cp.processMotionClauses<clause::To>(stmtCtx, clauseOps);
1230 cp.processMotionClauses<clause::From>(stmtCtx, clauseOps);
1231 } else {
1232 cp.processMap(loc, stmtCtx, clauseOps);
1233 }
1234 }
1235
1236 static void genTaskClauses(lower::AbstractConverter &converter,
1237 semantics::SemanticsContext &semaCtx,
1238 lower::StatementContext &stmtCtx,
1239 const List<Clause> &clauses, mlir::Location loc,
1240 mlir::omp::TaskClauseOps &clauseOps) {
1241 ClauseProcessor cp(converter, semaCtx, clauses);
1242 cp.processAllocate(clauseOps);
1243 cp.processDefault();
1244 cp.processDepend(clauseOps);
1245 cp.processFinal(stmtCtx, clauseOps);
1246 cp.processIf(llvm::omp::Directive::OMPD_task, clauseOps);
1247 cp.processMergeable(clauseOps);
1248 cp.processPriority(stmtCtx, clauseOps);
1249 cp.processUntied(clauseOps);
1250 // TODO Support delayed privatization.
1251
1252 cp.processTODO<clause::Affinity, clause::Detach, clause::InReduction>(
1253 loc, llvm::omp::Directive::OMPD_task);
1254 }
1255
1256 static void genTaskgroupClauses(lower::AbstractConverter &converter,
1257 semantics::SemanticsContext &semaCtx,
1258 const List<Clause> &clauses, mlir::Location loc,
1259 mlir::omp::TaskgroupClauseOps &clauseOps) {
1260 ClauseProcessor cp(converter, semaCtx, clauses);
1261 cp.processAllocate(clauseOps);
1262 cp.processTODO<clause::TaskReduction>(loc,
1263 llvm::omp::Directive::OMPD_taskgroup);
1264 }
1265
1266 static void genTaskwaitClauses(lower::AbstractConverter &converter,
1267 semantics::SemanticsContext &semaCtx,
1268 const List<Clause> &clauses, mlir::Location loc,
1269 mlir::omp::TaskwaitClauseOps &clauseOps) {
1270 ClauseProcessor cp(converter, semaCtx, clauses);
1271 cp.processTODO<clause::Depend, clause::Nowait>(
1272 loc, llvm::omp::Directive::OMPD_taskwait);
1273 }
1274
1275 static void genTeamsClauses(lower::AbstractConverter &converter,
1276 semantics::SemanticsContext &semaCtx,
1277 lower::StatementContext &stmtCtx,
1278 const List<Clause> &clauses, mlir::Location loc,
1279 mlir::omp::TeamsClauseOps &clauseOps) {
1280 ClauseProcessor cp(converter, semaCtx, clauses);
1281 cp.processAllocate(clauseOps);
1282 cp.processDefault();
1283 cp.processIf(llvm::omp::Directive::OMPD_teams, clauseOps);
1284 cp.processNumTeams(stmtCtx, clauseOps);
1285 cp.processThreadLimit(stmtCtx, clauseOps);
1286 // TODO Support delayed privatization.
1287
1288 cp.processTODO<clause::Reduction>(loc, llvm::omp::Directive::OMPD_teams);
1289 }
1290
1291 static void genWsloopClauses(
1292 lower::AbstractConverter &converter, semantics::SemanticsContext &semaCtx,
1293 lower::StatementContext &stmtCtx, const List<Clause> &clauses,
1294 mlir::Location loc, mlir::omp::WsloopClauseOps &clauseOps,
1295 llvm::SmallVectorImpl<mlir::Type> &reductionTypes,
1296 llvm::SmallVectorImpl<const semantics::Symbol *> &reductionSyms) {
1297 ClauseProcessor cp(converter, semaCtx, clauses);
1298 cp.processNowait(clauseOps);
1299 cp.processOrder(clauseOps);
1300 cp.processOrdered(clauseOps);
1301 cp.processReduction(loc, clauseOps, &reductionTypes, &reductionSyms);
1302 cp.processSchedule(stmtCtx, clauseOps);
1303 // TODO Support delayed privatization.
1304
1305 cp.processTODO<clause::Allocate, clause::Linear>(
1306 loc, llvm::omp::Directive::OMPD_do);
1307 }
1308
1309 //===----------------------------------------------------------------------===//
1310 // Code generation functions for leaf constructs
1311 //===----------------------------------------------------------------------===//
1312
1313 static mlir::omp::BarrierOp
1314 genBarrierOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1315 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
1316 mlir::Location loc, const ConstructQueue &queue,
1317 ConstructQueue::iterator item) {
1318 return converter.getFirOpBuilder().create<mlir::omp::BarrierOp>(loc);
1319 }
1320
1321 static mlir::omp::CriticalOp
1322 genCriticalOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1323 semantics::SemanticsContext &semaCtx,
1324 lower::pft::Evaluation &eval, mlir::Location loc,
1325 const ConstructQueue &queue, ConstructQueue::iterator item,
1326 const std::optional<parser::Name> &name) {
1327 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
1328 mlir::FlatSymbolRefAttr nameAttr;
1329
1330 if (name) {
1331 std::string nameStr = name->ToString();
1332 mlir::ModuleOp mod = firOpBuilder.getModule();
1333 auto global = mod.lookupSymbol<mlir::omp::CriticalDeclareOp>(nameStr);
1334 if (!global) {
1335 mlir::omp::CriticalClauseOps clauseOps;
1336 genCriticalDeclareClauses(converter, semaCtx, item->clauses, loc,
1337 clauseOps, nameStr);
1338
1339 mlir::OpBuilder modBuilder(mod.getBodyRegion());
1340 global = modBuilder.create<mlir::omp::CriticalDeclareOp>(loc, clauseOps);
1341 }
1342 nameAttr = mlir::FlatSymbolRefAttr::get(firOpBuilder.getContext(),
1343 global.getSymName());
1344 }
1345
1346 return genOpWithBody<mlir::omp::CriticalOp>(
1347 OpWithBodyGenInfo(converter, symTable, semaCtx, loc, eval,
1348 llvm::omp::Directive::OMPD_critical),
1349 queue, item, nameAttr);
1350 }
1351
1352 static mlir::omp::FlushOp
1353 genFlushOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1354 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
1355 mlir::Location loc, const ObjectList &objects,
1356 const ConstructQueue &queue, ConstructQueue::iterator item) {
1357 llvm::SmallVector<mlir::Value> operandRange;
1358 genFlushClauses(converter, semaCtx, objects, item->clauses, loc,
1359 operandRange);
1360
1361 return converter.getFirOpBuilder().create<mlir::omp::FlushOp>(
1362 converter.getCurrentLocation(), operandRange);
1363 }
1364
1365 static mlir::omp::LoopNestOp
1366 genLoopNestOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1367 semantics::SemanticsContext &semaCtx,
1368 lower::pft::Evaluation &eval, mlir::Location loc,
1369 const ConstructQueue &queue, ConstructQueue::iterator item,
1370 mlir::omp::LoopNestClauseOps &clauseOps,
1371 llvm::ArrayRef<const semantics::Symbol *> iv,
1372 llvm::ArrayRef<const semantics::Symbol *> wrapperSyms,
1373 llvm::ArrayRef<mlir::BlockArgument> wrapperArgs,
1374 llvm::omp::Directive directive, DataSharingProcessor &dsp) {
1375 auto ivCallback = [&](mlir::Operation *op) {
1376 genLoopVars(op, converter, loc, iv, wrapperSyms, wrapperArgs);
1377 return llvm::SmallVector<const semantics::Symbol *>(iv);
1378 };
1379
1380 auto *nestedEval =
1381 getCollapsedLoopEval(eval, getCollapseValue(item->clauses));
1382
1383 return genOpWithBody<mlir::omp::LoopNestOp>(
1384 OpWithBodyGenInfo(converter, symTable, semaCtx, loc, *nestedEval,
1385 directive)
1386 .setClauses(&item->clauses)
1387 .setDataSharingProcessor(&dsp)
1388 .setGenRegionEntryCb(ivCallback),
1389 queue, item, clauseOps);
1390 }
1391
1392 static mlir::omp::MaskedOp
1393 genMaskedOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1394 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
1395 mlir::Location loc, const ConstructQueue &queue,
1396 ConstructQueue::iterator item) {
1397 lower::StatementContext stmtCtx;
1398 mlir::omp::MaskedClauseOps clauseOps;
1399 genMaskedClauses(converter, semaCtx, stmtCtx, item->clauses, loc, clauseOps);
1400
1401 return genOpWithBody<mlir::omp::MaskedOp>(
1402 OpWithBodyGenInfo(converter, symTable, semaCtx, loc, eval,
1403 llvm::omp::Directive::OMPD_masked),
1404 queue, item, clauseOps);
1405 }
1406
1407 static mlir::omp::MasterOp
1408 genMasterOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1409 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
1410 mlir::Location loc, const ConstructQueue &queue,
1411 ConstructQueue::iterator item) {
1412 return genOpWithBody<mlir::omp::MasterOp>(
1413 OpWithBodyGenInfo(converter, symTable, semaCtx, loc, eval,
1414 llvm::omp::Directive::OMPD_master),
1415 queue, item);
1416 }
1417
1418 static mlir::omp::OrderedOp
1419 genOrderedOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1420 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
1421 mlir::Location loc, const ConstructQueue &queue,
1422 ConstructQueue::iterator item) {
1423 TODO(loc, "OMPD_ordered");
1424 return nullptr;
1425 }
1426
1427 static mlir::omp::OrderedRegionOp
1428 genOrderedRegionOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1429 semantics::SemanticsContext &semaCtx,
1430 lower::pft::Evaluation &eval, mlir::Location loc,
1431 const ConstructQueue &queue, ConstructQueue::iterator item) {
1432 mlir::omp::OrderedRegionClauseOps clauseOps;
1433 genOrderedRegionClauses(converter, semaCtx, item->clauses, loc, clauseOps);
1434
1435 return genOpWithBody<mlir::omp::OrderedRegionOp>(
1436 OpWithBodyGenInfo(converter, symTable, semaCtx, loc, eval,
1437 llvm::omp::Directive::OMPD_ordered),
1438 queue, item, clauseOps);
1439 }
1440
1441 static mlir::omp::ParallelOp
1442 genParallelOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1443 semantics::SemanticsContext &semaCtx,
1444 lower::pft::Evaluation &eval, mlir::Location loc,
1445 const ConstructQueue &queue, ConstructQueue::iterator item,
1446 mlir::omp::ParallelClauseOps &clauseOps,
1447 llvm::ArrayRef<const semantics::Symbol *> reductionSyms,
1448 llvm::ArrayRef<mlir::Type> reductionTypes) {
1449 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
1450
1451 auto reductionCallback = [&](mlir::Operation *op) {
1452 genReductionVars(op, converter, loc, reductionSyms, reductionTypes);
1453 return llvm::SmallVector<const semantics::Symbol *>(reductionSyms);
1454 };
1455
1456 OpWithBodyGenInfo genInfo =
1457 OpWithBodyGenInfo(converter, symTable, semaCtx, loc, eval,
1458 llvm::omp::Directive::OMPD_parallel)
1459 .setClauses(&item->clauses)
1460 .setGenRegionEntryCb(reductionCallback);
1461
1462 if (!enableDelayedPrivatization)
1463 return genOpWithBody<mlir::omp::ParallelOp>(genInfo, queue, item,
1464 clauseOps);
1465
1466 DataSharingProcessor dsp(converter, semaCtx, item->clauses, eval,
1467 lower::omp::isLastItemInQueue(item, queue),
1468 /*useDelayedPrivatization=*/true, &symTable);
1469 dsp.processStep1(&clauseOps);
1470
1471 auto genRegionEntryCB = [&](mlir::Operation *op) {
1472 auto parallelOp = llvm::cast<mlir::omp::ParallelOp>(op);
1473
1474 llvm::SmallVector<mlir::Location> reductionLocs(
1475 clauseOps.reductionVars.size(), loc);
1476
1477 llvm::SmallVector<mlir::Type> allRegionArgTypes;
1478 mergePrivateVarsInfo(parallelOp, reductionTypes,
1479 llvm::function_ref<mlir::Type(mlir::Value)>{
1480 [](mlir::Value v) { return v.getType(); }},
1481 allRegionArgTypes);
1482
1483 llvm::SmallVector<mlir::Location> allRegionArgLocs;
1484 mergePrivateVarsInfo(parallelOp, llvm::ArrayRef(reductionLocs),
1485 llvm::function_ref<mlir::Location(mlir::Value)>{
1486 [](mlir::Value v) { return v.getLoc(); }},
1487 allRegionArgLocs);
1488
1489 mlir::Region &region = parallelOp.getRegion();
1490 firOpBuilder.createBlock(&region, /*insertPt=*/{}, allRegionArgTypes,
1491 allRegionArgLocs);
1492
1493 llvm::SmallVector<const semantics::Symbol *> allSymbols(reductionSyms);
1494 allSymbols.append(dsp.getAllSymbolsToPrivatize().begin(),
1495 dsp.getAllSymbolsToPrivatize().end());
1496
1497 for (auto [arg, prv] : llvm::zip_equal(allSymbols, region.getArguments())) {
1498 converter.bindSymbol(*arg, hlfir::translateToExtendedValue(
1499 loc, firOpBuilder, hlfir::Entity{prv},
1500 /*contiguousHint=*/
1501 evaluate::IsSimplyContiguous(
1502 *arg, converter.getFoldingContext()))
1503 .first);
1504 }
1505
1506 return allSymbols;
1507 };
1508
1509 genInfo.setGenRegionEntryCb(genRegionEntryCB).setDataSharingProcessor(&dsp);
1510 return genOpWithBody<mlir::omp::ParallelOp>(genInfo, queue, item, clauseOps);
1511 }
1512
1513 /// This breaks the normal prototype of the gen*Op functions: adding the
1514 /// sectionBlocks argument so that the enclosed section constructs can be
1515 /// lowered here with correct reduction symbol remapping.
1516 static mlir::omp::SectionsOp
1517 genSectionsOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1518 semantics::SemanticsContext &semaCtx,
1519 lower::pft::Evaluation &eval, mlir::Location loc,
1520 const ConstructQueue &queue, ConstructQueue::iterator item,
1521 const parser::OmpSectionBlocks &sectionBlocks) {
1522 llvm::SmallVector<mlir::Type> reductionTypes;
1523 llvm::SmallVector<const semantics::Symbol *> reductionSyms;
1524 mlir::omp::SectionsClauseOps clauseOps;
1525 genSectionsClauses(converter, semaCtx, item->clauses, loc, clauseOps,
1526 reductionTypes, reductionSyms);
1527
1528 auto &builder = converter.getFirOpBuilder();
1529
1530 // Insert privatizations before SECTIONS
1531 symTable.pushScope();
1532 DataSharingProcessor dsp(converter, semaCtx, item->clauses, eval,
1533 lower::omp::isLastItemInQueue(item, queue));
1534 dsp.processStep1();
1535
1536 List<Clause> nonDsaClauses;
1537 List<const clause::Lastprivate *> lastprivates;
1538
1539 for (const Clause &clause : item->clauses) {
1540 if (clause.id == llvm::omp::Clause::OMPC_lastprivate) {
1541 lastprivates.push_back(&std::get<clause::Lastprivate>(clause.u));
1542 } else {
1543 switch (clause.id) {
1544 case llvm::omp::Clause::OMPC_firstprivate:
1545 case llvm::omp::Clause::OMPC_private:
1546 case llvm::omp::Clause::OMPC_shared:
1547 break;
1548 default:
1549 nonDsaClauses.push_back(clause);
1550 }
1551 }
1552 }
1553
1554 // SECTIONS construct.
1555 auto sectionsOp = builder.create<mlir::omp::SectionsOp>(loc, clauseOps);
1556
1557 // create entry block with reduction variables as arguments
1558 llvm::SmallVector<mlir::Location> blockArgLocs(reductionSyms.size(), loc);
1559 builder.createBlock(&sectionsOp->getRegion(0), {}, reductionTypes,
1560 blockArgLocs);
1561 mlir::Operation *terminator =
1562 lower::genOpenMPTerminator(builder, sectionsOp, loc);
1563
1564 auto reductionCallback = [&](mlir::Operation *op) {
1565 genReductionVars(op, converter, loc, reductionSyms, reductionTypes);
1566 return reductionSyms;
1567 };
1568
1569 // Generate nested SECTION constructs.
1570 // This is done here rather than in genOMP([...], OpenMPSectionConstruct )
1571 // because we need to run genReductionVars on each omp.section so that the
1572 // reduction variable gets mapped to the private version
1573 for (auto [construct, nestedEval] :
1574 llvm::zip(sectionBlocks.v, eval.getNestedEvaluations())) {
1575 const auto *sectionConstruct =
1576 std::get_if<parser::OpenMPSectionConstruct>(&construct.u);
1577 if (!sectionConstruct) {
1578 assert(false &&
1579 "unexpected construct nested inside of SECTIONS construct");
1580 continue;
1581 }
1582
1583 ConstructQueue sectionQueue{buildConstructQueue(
1584 converter.getFirOpBuilder().getModule(), semaCtx, nestedEval,
1585 sectionConstruct->source, llvm::omp::Directive::OMPD_section, {})};
1586
1587 builder.setInsertionPoint(terminator);
1588 genOpWithBody<mlir::omp::SectionOp>(
1589 OpWithBodyGenInfo(converter, symTable, semaCtx, loc, nestedEval,
1590 llvm::omp::Directive::OMPD_section)
1591 .setClauses(&sectionQueue.begin()->clauses)
1592 .setGenRegionEntryCb(reductionCallback),
1593 sectionQueue, sectionQueue.begin());
1594 }
1595
1596 if (!lastprivates.empty()) {
1597 mlir::Region &sectionsBody = sectionsOp.getRegion();
1598 assert(sectionsBody.hasOneBlock());
1599 mlir::Block &body = sectionsBody.front();
1600
1601 auto lastSectionOp = llvm::find_if(
1602 llvm::reverse(body.getOperations()), [](const mlir::Operation &op) {
1603 return llvm::isa<mlir::omp::SectionOp>(op);
1604 });
1605 assert(lastSectionOp != body.rend());
1606
1607 for (const clause::Lastprivate *lastp : lastprivates) {
1608 builder.setInsertionPoint(
1609 lastSectionOp->getRegion(0).back().getTerminator());
1610 mlir::OpBuilder::InsertPoint insp = builder.saveInsertionPoint();
1611 const auto &objList = std::get<ObjectList>(lastp->t);
1612 for (const Object &object : objList) {
1613 semantics::Symbol *sym = object.sym();
1614 converter.copyHostAssociateVar(*sym, &insp);
1615 }
1616 }
1617 }
1618
1619 // Perform DataSharingProcessor's step2 out of SECTIONS
1620 builder.setInsertionPointAfter(sectionsOp.getOperation());
1621 dsp.processStep2(sectionsOp, false);
1622 // Emit implicit barrier to synchronize threads and avoid data
1623 // races on post-update of lastprivate variables when `nowait`
1624 // clause is present.
1625 if (clauseOps.nowaitAttr && !lastprivates.empty())
1626 builder.create<mlir::omp::BarrierOp>(loc);
1627
1628 symTable.popScope();
1629 return sectionsOp;
1630 }
1631
1632 static mlir::omp::SingleOp
1633 genSingleOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1634 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
1635 mlir::Location loc, const ConstructQueue &queue,
1636 ConstructQueue::iterator item) {
1637 mlir::omp::SingleClauseOps clauseOps;
1638 genSingleClauses(converter, semaCtx, item->clauses, loc, clauseOps);
1639
1640 return genOpWithBody<mlir::omp::SingleOp>(
1641 OpWithBodyGenInfo(converter, symTable, semaCtx, loc, eval,
1642 llvm::omp::Directive::OMPD_single)
1643 .setClauses(&item->clauses),
1644 queue, item, clauseOps);
1645 }
1646
1647 static mlir::omp::TargetOp
1648 genTargetOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1649 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
1650 mlir::Location loc, const ConstructQueue &queue,
1651 ConstructQueue::iterator item) {
1652 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
1653 lower::StatementContext stmtCtx;
1654
1655 bool processHostOnlyClauses =
1656 !llvm::cast<mlir::omp::OffloadModuleInterface>(*converter.getModuleOp())
1657 .getIsTargetDevice();
1658
1659 mlir::omp::TargetClauseOps clauseOps;
1660 llvm::SmallVector<const semantics::Symbol *> mapSyms, devicePtrSyms,
1661 deviceAddrSyms;
1662 llvm::SmallVector<mlir::Location> mapLocs, devicePtrLocs, deviceAddrLocs;
1663 llvm::SmallVector<mlir::Type> mapTypes, devicePtrTypes, deviceAddrTypes;
1664 genTargetClauses(converter, semaCtx, stmtCtx, item->clauses, loc,
1665 processHostOnlyClauses, clauseOps, mapSyms, mapLocs,
1666 mapTypes, deviceAddrSyms, deviceAddrLocs, deviceAddrTypes,
1667 devicePtrSyms, devicePtrLocs, devicePtrTypes);
1668
1669 llvm::SmallVector<const semantics::Symbol *> privateSyms;
1670 DataSharingProcessor dsp(converter, semaCtx, item->clauses, eval,
1671 /*shouldCollectPreDeterminedSymbols=*/
1672 lower::omp::isLastItemInQueue(item, queue),
1673 /*useDelayedPrivatization=*/true, &symTable);
1674 dsp.processStep1(&clauseOps);
1675
1676 // 5.8.1 Implicit Data-Mapping Attribute Rules
1677 // The following code follows the implicit data-mapping rules to map all the
1678 // symbols used inside the region that do not have explicit data-environment
1679 // attribute clauses (neither data-sharing; e.g. `private`, nor `map`
1680 // clauses).
1681 auto captureImplicitMap = [&](const semantics::Symbol &sym) {
1682 if (dsp.getAllSymbolsToPrivatize().contains(&sym))
1683 return;
1684
1685 // if the symbol is part of an already mapped common block, do not make a
1686 // map for it.
1687 if (const Fortran::semantics::Symbol *common =
1688 Fortran::semantics::FindCommonBlockContaining(sym.GetUltimate()))
1689 if (llvm::find(mapSyms, common) != mapSyms.end())
1690 return;
1691
1692 if (llvm::find(mapSyms, &sym) == mapSyms.end()) {
1693 mlir::Value baseOp = converter.getSymbolAddress(sym);
1694 if (!baseOp)
1695 if (const auto *details =
1696 sym.template detailsIf<semantics::HostAssocDetails>()) {
1697 baseOp = converter.getSymbolAddress(details->symbol());
1698 converter.copySymbolBinding(details->symbol(), sym);
1699 }
1700
1701 if (baseOp) {
1702 llvm::SmallVector<mlir::Value> bounds;
1703 std::stringstream name;
1704 fir::ExtendedValue dataExv = converter.getSymbolExtendedValue(sym);
1705 name << sym.name().ToString();
1706
1707 lower::AddrAndBoundsInfo info = getDataOperandBaseAddr(
1708 converter, firOpBuilder, sym, converter.getCurrentLocation());
1709 if (mlir::isa<fir::BaseBoxType>(
1710 fir::unwrapRefType(info.addr.getType())))
1711 bounds = lower::genBoundsOpsFromBox<mlir::omp::MapBoundsOp,
1712 mlir::omp::MapBoundsType>(
1713 firOpBuilder, converter.getCurrentLocation(), dataExv, info);
1714 if (mlir::isa<fir::SequenceType>(
1715 fir::unwrapRefType(info.addr.getType()))) {
1716 bool dataExvIsAssumedSize =
1717 semantics::IsAssumedSizeArray(sym.GetUltimate());
1718 bounds = lower::genBaseBoundsOps<mlir::omp::MapBoundsOp,
1719 mlir::omp::MapBoundsType>(
1720 firOpBuilder, converter.getCurrentLocation(), dataExv,
1721 dataExvIsAssumedSize);
1722 }
1723
1724 llvm::omp::OpenMPOffloadMappingFlags mapFlag =
1725 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_IMPLICIT;
1726 mlir::omp::VariableCaptureKind captureKind =
1727 mlir::omp::VariableCaptureKind::ByRef;
1728
1729 mlir::Type eleType = baseOp.getType();
1730 if (auto refType = mlir::dyn_cast<fir::ReferenceType>(baseOp.getType()))
1731 eleType = refType.getElementType();
1732
1733 // If a variable is specified in declare target link and if device
1734 // type is not specified as `nohost`, it needs to be mapped tofrom
1735 mlir::ModuleOp mod = firOpBuilder.getModule();
1736 mlir::Operation *op = mod.lookupSymbol(converter.mangleName(sym));
1737 auto declareTargetOp =
1738 llvm::dyn_cast_if_present<mlir::omp::DeclareTargetInterface>(op);
1739 if (declareTargetOp && declareTargetOp.isDeclareTarget()) {
1740 if (declareTargetOp.getDeclareTargetCaptureClause() ==
1741 mlir::omp::DeclareTargetCaptureClause::link &&
1742 declareTargetOp.getDeclareTargetDeviceType() !=
1743 mlir::omp::DeclareTargetDeviceType::nohost) {
1744 mapFlag |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TO;
1745 mapFlag |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_FROM;
1746 }
1747 } else if (fir::isa_trivial(eleType) || fir::isa_char(eleType)) {
1748 captureKind = mlir::omp::VariableCaptureKind::ByCopy;
1749 } else if (!fir::isa_builtin_cptr_type(eleType)) {
1750 mapFlag |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_TO;
1751 mapFlag |= llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_FROM;
1752 }
1753 auto location =
1754 mlir::NameLoc::get(mlir::StringAttr::get(firOpBuilder.getContext(),
1755 sym.name().ToString()),
1756 baseOp.getLoc());
1757 mlir::Value mapOp = createMapInfoOp(
1758 firOpBuilder, location, baseOp, /*varPtrPtr=*/mlir::Value{},
1759 name.str(), bounds, /*members=*/{},
1760 /*membersIndex=*/mlir::DenseIntElementsAttr{},
1761 static_cast<
1762 std::underlying_type_t<llvm::omp::OpenMPOffloadMappingFlags>>(
1763 mapFlag),
1764 captureKind, baseOp.getType());
1765
1766 clauseOps.mapVars.push_back(mapOp);
1767 mapSyms.push_back(&sym);
1768 mapLocs.push_back(baseOp.getLoc());
1769 mapTypes.push_back(baseOp.getType());
1770 }
1771 }
1772 };
1773 lower::pft::visitAllSymbols(eval, captureImplicitMap);
1774
1775 auto targetOp = firOpBuilder.create<mlir::omp::TargetOp>(loc, clauseOps);
1776 genBodyOfTargetOp(converter, symTable, semaCtx, eval, targetOp, mapSyms,
1777 mapLocs, mapTypes, dsp, loc, queue, item);
1778 return targetOp;
1779 }
1780
1781 static mlir::omp::TargetDataOp
1782 genTargetDataOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1783 semantics::SemanticsContext &semaCtx,
1784 lower::pft::Evaluation &eval, mlir::Location loc,
1785 const ConstructQueue &queue, ConstructQueue::iterator item) {
1786 lower::StatementContext stmtCtx;
1787 mlir::omp::TargetDataClauseOps clauseOps;
1788 llvm::SmallVector<mlir::Type> useDeviceTypes;
1789 llvm::SmallVector<mlir::Location> useDeviceLocs;
1790 llvm::SmallVector<const semantics::Symbol *> useDeviceSyms;
1791 genTargetDataClauses(converter, semaCtx, stmtCtx, item->clauses, loc,
1792 clauseOps, useDeviceTypes, useDeviceLocs, useDeviceSyms);
1793
1794 auto targetDataOp =
1795 converter.getFirOpBuilder().create<mlir::omp::TargetDataOp>(loc,
1796 clauseOps);
1797 genBodyOfTargetDataOp(converter, symTable, semaCtx, eval, targetDataOp,
1798 useDeviceTypes, useDeviceLocs, useDeviceSyms, loc,
1799 queue, item);
1800 return targetDataOp;
1801 }
1802
1803 template <typename OpTy>
1804 static OpTy genTargetEnterExitUpdateDataOp(lower::AbstractConverter &converter,
1805 lower::SymMap &symTable,
1806 semantics::SemanticsContext &semaCtx,
1807 mlir::Location loc,
1808 const ConstructQueue &queue,
1809 ConstructQueue::iterator item) {
1810 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
1811 lower::StatementContext stmtCtx;
1812
1813 // GCC 9.3.0 emits a (probably) bogus warning about an unused variable.
1814 [[maybe_unused]] llvm::omp::Directive directive;
1815 if constexpr (std::is_same_v<OpTy, mlir::omp::TargetEnterDataOp>) {
1816 directive = llvm::omp::Directive::OMPD_target_enter_data;
1817 } else if constexpr (std::is_same_v<OpTy, mlir::omp::TargetExitDataOp>) {
1818 directive = llvm::omp::Directive::OMPD_target_exit_data;
1819 } else if constexpr (std::is_same_v<OpTy, mlir::omp::TargetUpdateOp>) {
1820 directive = llvm::omp::Directive::OMPD_target_update;
1821 } else {
1822 llvm_unreachable("Unexpected TARGET DATA construct");
1823 }
1824
1825 mlir::omp::TargetEnterExitUpdateDataClauseOps clauseOps;
1826 genTargetEnterExitUpdateDataClauses(converter, semaCtx, stmtCtx,
1827 item->clauses, loc, directive, clauseOps);
1828
1829 return firOpBuilder.create<OpTy>(loc, clauseOps);
1830 }
1831
1832 static mlir::omp::TaskOp
1833 genTaskOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1834 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
1835 mlir::Location loc, const ConstructQueue &queue,
1836 ConstructQueue::iterator item) {
1837 lower::StatementContext stmtCtx;
1838 mlir::omp::TaskClauseOps clauseOps;
1839 genTaskClauses(converter, semaCtx, stmtCtx, item->clauses, loc, clauseOps);
1840
1841 return genOpWithBody<mlir::omp::TaskOp>(
1842 OpWithBodyGenInfo(converter, symTable, semaCtx, loc, eval,
1843 llvm::omp::Directive::OMPD_task)
1844 .setClauses(&item->clauses),
1845 queue, item, clauseOps);
1846 }
1847
1848 static mlir::omp::TaskgroupOp
1849 genTaskgroupOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1850 semantics::SemanticsContext &semaCtx,
1851 lower::pft::Evaluation &eval, mlir::Location loc,
1852 const ConstructQueue &queue, ConstructQueue::iterator item) {
1853 mlir::omp::TaskgroupClauseOps clauseOps;
1854 genTaskgroupClauses(converter, semaCtx, item->clauses, loc, clauseOps);
1855
1856 return genOpWithBody<mlir::omp::TaskgroupOp>(
1857 OpWithBodyGenInfo(converter, symTable, semaCtx, loc, eval,
1858 llvm::omp::Directive::OMPD_taskgroup)
1859 .setClauses(&item->clauses),
1860 queue, item, clauseOps);
1861 }
1862
1863 static mlir::omp::TaskwaitOp
1864 genTaskwaitOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1865 semantics::SemanticsContext &semaCtx,
1866 lower::pft::Evaluation &eval, mlir::Location loc,
1867 const ConstructQueue &queue, ConstructQueue::iterator item) {
1868 mlir::omp::TaskwaitClauseOps clauseOps;
1869 genTaskwaitClauses(converter, semaCtx, item->clauses, loc, clauseOps);
1870 return converter.getFirOpBuilder().create<mlir::omp::TaskwaitOp>(loc,
1871 clauseOps);
1872 }
1873
1874 static mlir::omp::TaskyieldOp
1875 genTaskyieldOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1876 semantics::SemanticsContext &semaCtx,
1877 lower::pft::Evaluation &eval, mlir::Location loc,
1878 const ConstructQueue &queue, ConstructQueue::iterator item) {
1879 return converter.getFirOpBuilder().create<mlir::omp::TaskyieldOp>(loc);
1880 }
1881
1882 static mlir::omp::TeamsOp
1883 genTeamsOp(lower::AbstractConverter &converter, lower::SymMap &symTable,
1884 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
1885 mlir::Location loc, const ConstructQueue &queue,
1886 ConstructQueue::iterator item) {
1887 lower::StatementContext stmtCtx;
1888 mlir::omp::TeamsClauseOps clauseOps;
1889 genTeamsClauses(converter, semaCtx, stmtCtx, item->clauses, loc, clauseOps);
1890
1891 return genOpWithBody<mlir::omp::TeamsOp>(
1892 OpWithBodyGenInfo(converter, symTable, semaCtx, loc, eval,
1893 llvm::omp::Directive::OMPD_teams)
1894 .setClauses(&item->clauses),
1895 queue, item, clauseOps);
1896 }
1897
1898 //===----------------------------------------------------------------------===//
1899 // Code generation functions for the standalone version of constructs that can
1900 // also be a leaf of a composite construct
1901 //===----------------------------------------------------------------------===//
1902
1903 static void genStandaloneDistribute(
1904 lower::AbstractConverter &converter, lower::SymMap &symTable,
1905 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
1906 mlir::Location loc, const ConstructQueue &queue,
1907 ConstructQueue::iterator item, DataSharingProcessor &dsp) {
1908 lower::StatementContext stmtCtx;
1909
1910 mlir::omp::DistributeClauseOps distributeClauseOps;
1911 genDistributeClauses(converter, semaCtx, stmtCtx, item->clauses, loc,
1912 distributeClauseOps);
1913
1914 mlir::omp::LoopNestClauseOps loopNestClauseOps;
1915 llvm::SmallVector<const semantics::Symbol *> iv;
1916 genLoopNestClauses(converter, semaCtx, eval, item->clauses, loc,
1917 loopNestClauseOps, iv);
1918
1919 // TODO: Populate entry block arguments with private variables.
1920 auto distributeOp = genWrapperOp<mlir::omp::DistributeOp>(
1921 converter, loc, distributeClauseOps, /*blockArgTypes=*/{});
1922
1923 genLoopNestOp(converter, symTable, semaCtx, eval, loc, queue, item,
1924 loopNestClauseOps, iv,
1925 /*wrapperSyms=*/{}, distributeOp.getRegion().getArguments(),
1926 llvm::omp::Directive::OMPD_distribute, dsp);
1927 }
1928
1929 static void genStandaloneDo(lower::AbstractConverter &converter,
1930 lower::SymMap &symTable,
1931 semantics::SemanticsContext &semaCtx,
1932 lower::pft::Evaluation &eval, mlir::Location loc,
1933 const ConstructQueue &queue,
1934 ConstructQueue::iterator item,
1935 DataSharingProcessor &dsp) {
1936 lower::StatementContext stmtCtx;
1937
1938 mlir::omp::WsloopClauseOps wsloopClauseOps;
1939 llvm::SmallVector<const semantics::Symbol *> reductionSyms;
1940 llvm::SmallVector<mlir::Type> reductionTypes;
1941 genWsloopClauses(converter, semaCtx, stmtCtx, item->clauses, loc,
1942 wsloopClauseOps, reductionTypes, reductionSyms);
1943
1944 mlir::omp::LoopNestClauseOps loopNestClauseOps;
1945 llvm::SmallVector<const semantics::Symbol *> iv;
1946 genLoopNestClauses(converter, semaCtx, eval, item->clauses, loc,
1947 loopNestClauseOps, iv);
1948
1949 // TODO: Add private variables to entry block arguments.
1950 auto wsloopOp = genWrapperOp<mlir::omp::WsloopOp>(
1951 converter, loc, wsloopClauseOps, reductionTypes);
1952
1953 genLoopNestOp(converter, symTable, semaCtx, eval, loc, queue, item,
1954 loopNestClauseOps, iv, reductionSyms,
1955 wsloopOp.getRegion().getArguments(),
1956 llvm::omp::Directive::OMPD_do, dsp);
1957 }
1958
1959 static void genStandaloneParallel(lower::AbstractConverter &converter,
1960 lower::SymMap &symTable,
1961 semantics::SemanticsContext &semaCtx,
1962 lower::pft::Evaluation &eval,
1963 mlir::Location loc,
1964 const ConstructQueue &queue,
1965 ConstructQueue::iterator item) {
1966 lower::StatementContext stmtCtx;
1967
1968 mlir::omp::ParallelClauseOps clauseOps;
1969 llvm::SmallVector<const semantics::Symbol *> reductionSyms;
1970 llvm::SmallVector<mlir::Type> reductionTypes;
1971 genParallelClauses(converter, semaCtx, stmtCtx, item->clauses, loc, clauseOps,
1972 reductionTypes, reductionSyms);
1973
1974 genParallelOp(converter, symTable, semaCtx, eval, loc, queue, item, clauseOps,
1975 reductionSyms, reductionTypes);
1976 }
1977
1978 static void genStandaloneSimd(lower::AbstractConverter &converter,
1979 lower::SymMap &symTable,
1980 semantics::SemanticsContext &semaCtx,
1981 lower::pft::Evaluation &eval, mlir::Location loc,
1982 const ConstructQueue &queue,
1983 ConstructQueue::iterator item,
1984 DataSharingProcessor &dsp) {
1985 mlir::omp::SimdClauseOps simdClauseOps;
1986 genSimdClauses(converter, semaCtx, item->clauses, loc, simdClauseOps);
1987
1988 mlir::omp::LoopNestClauseOps loopNestClauseOps;
1989 llvm::SmallVector<const semantics::Symbol *> iv;
1990 genLoopNestClauses(converter, semaCtx, eval, item->clauses, loc,
1991 loopNestClauseOps, iv);
1992
1993 // TODO: Populate entry block arguments with reduction and private variables.
1994 auto simdOp = genWrapperOp<mlir::omp::SimdOp>(converter, loc, simdClauseOps,
1995 /*blockArgTypes=*/{});
1996
1997 genLoopNestOp(converter, symTable, semaCtx, eval, loc, queue, item,
1998 loopNestClauseOps, iv,
1999 /*wrapperSyms=*/{}, simdOp.getRegion().getArguments(),
2000 llvm::omp::Directive::OMPD_simd, dsp);
2001 }
2002
2003 static void genStandaloneTaskloop(
2004 lower::AbstractConverter &converter, lower::SymMap &symTable,
2005 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
2006 mlir::Location loc, const ConstructQueue &queue,
2007 ConstructQueue::iterator item, DataSharingProcessor &dsp) {
2008 TODO(loc, "Taskloop construct");
2009 }
2010
2011 //===----------------------------------------------------------------------===//
2012 // Code generation functions for composite constructs
2013 //===----------------------------------------------------------------------===//
2014
2015 static void genCompositeDistributeParallelDo(
2016 lower::AbstractConverter &converter, lower::SymMap &symTable,
2017 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
2018 mlir::Location loc, const ConstructQueue &queue,
2019 ConstructQueue::iterator item, DataSharingProcessor &dsp) {
2020 TODO(loc, "Composite DISTRIBUTE PARALLEL DO");
2021 }
2022
2023 static void genCompositeDistributeParallelDoSimd(
2024 lower::AbstractConverter &converter, lower::SymMap &symTable,
2025 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
2026 mlir::Location loc, const ConstructQueue &queue,
2027 ConstructQueue::iterator item, DataSharingProcessor &dsp) {
2028 TODO(loc, "Composite DISTRIBUTE PARALLEL DO SIMD");
2029 }
2030
2031 static void genCompositeDistributeSimd(
2032 lower::AbstractConverter &converter, lower::SymMap &symTable,
2033 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
2034 mlir::Location loc, const ConstructQueue &queue,
2035 ConstructQueue::iterator item, DataSharingProcessor &dsp) {
2036 lower::StatementContext stmtCtx;
2037
2038 // Clause processing.
2039 mlir::omp::DistributeClauseOps distributeClauseOps;
2040 genDistributeClauses(converter, semaCtx, stmtCtx, item->clauses, loc,
2041 distributeClauseOps);
2042
2043 mlir::omp::SimdClauseOps simdClauseOps;
2044 genSimdClauses(converter, semaCtx, item->clauses, loc, simdClauseOps);
2045
2046 mlir::omp::LoopNestClauseOps loopNestClauseOps;
2047 llvm::SmallVector<const semantics::Symbol *> iv;
2048 genLoopNestClauses(converter, semaCtx, eval, item->clauses, loc,
2049 loopNestClauseOps, iv);
2050
2051 // Operation creation.
2052 // TODO: Populate entry block arguments with private variables.
2053 auto distributeOp = genWrapperOp<mlir::omp::DistributeOp>(
2054 converter, loc, distributeClauseOps, /*blockArgTypes=*/{});
2055
2056 // TODO: Populate entry block arguments with reduction and private variables.
2057 auto simdOp = genWrapperOp<mlir::omp::SimdOp>(converter, loc, simdClauseOps,
2058 /*blockArgTypes=*/{});
2059
2060 // Construct wrapper entry block list and associated symbols. It is important
2061 // that the symbol order and the block argument order match, so that the
2062 // symbol-value bindings created are correct.
2063 // TODO: Add omp.distribute private and omp.simd private and reduction args.
2064 auto wrapperArgs = llvm::to_vector(
2065 llvm::concat<mlir::BlockArgument>(distributeOp.getRegion().getArguments(),
2066 simdOp.getRegion().getArguments()));
2067
2068 assert(wrapperArgs.empty() &&
2069 "Block args for omp.simd and omp.distribute currently not expected");
2070 genLoopNestOp(converter, symTable, semaCtx, eval, loc, queue, item,
2071 loopNestClauseOps, iv, /*wrapperSyms=*/{}, wrapperArgs,
2072 llvm::omp::Directive::OMPD_distribute_simd, dsp);
2073 }
2074
2075 static void genCompositeDoSimd(lower::AbstractConverter &converter,
2076 lower::SymMap &symTable,
2077 semantics::SemanticsContext &semaCtx,
2078 lower::pft::Evaluation &eval, mlir::Location loc,
2079 const ConstructQueue &queue,
2080 ConstructQueue::iterator item,
2081 DataSharingProcessor &dsp) {
2082 lower::StatementContext stmtCtx;
2083
2084 // Clause processing.
2085 mlir::omp::WsloopClauseOps wsloopClauseOps;
2086 llvm::SmallVector<const semantics::Symbol *> wsloopReductionSyms;
2087 llvm::SmallVector<mlir::Type> wsloopReductionTypes;
2088 genWsloopClauses(converter, semaCtx, stmtCtx, item->clauses, loc,
2089 wsloopClauseOps, wsloopReductionTypes, wsloopReductionSyms);
2090
2091 mlir::omp::SimdClauseOps simdClauseOps;
2092 genSimdClauses(converter, semaCtx, item->clauses, loc, simdClauseOps);
2093
2094 mlir::omp::LoopNestClauseOps loopNestClauseOps;
2095 llvm::SmallVector<const semantics::Symbol *> iv;
2096 genLoopNestClauses(converter, semaCtx, eval, item->clauses, loc,
2097 loopNestClauseOps, iv);
2098
2099 // Operation creation.
2100 // TODO: Add private variables to entry block arguments.
2101 auto wsloopOp = genWrapperOp<mlir::omp::WsloopOp>(
2102 converter, loc, wsloopClauseOps, wsloopReductionTypes);
2103
2104 // TODO: Populate entry block arguments with reduction and private variables.
2105 auto simdOp = genWrapperOp<mlir::omp::SimdOp>(converter, loc, simdClauseOps,
2106 /*blockArgTypes=*/{});
2107
2108 // Construct wrapper entry block list and associated symbols. It is important
2109 // that the symbol and block argument order match, so that the symbol-value
2110 // bindings created are correct.
2111 // TODO: Add omp.wsloop private and omp.simd private and reduction args.
2112 auto wrapperArgs = llvm::to_vector(llvm::concat<mlir::BlockArgument>(
2113 wsloopOp.getRegion().getArguments(), simdOp.getRegion().getArguments()));
2114
2115 assert(wsloopReductionSyms.size() == wrapperArgs.size() &&
2116 "Number of symbols and wrapper block arguments must match");
2117 genLoopNestOp(converter, symTable, semaCtx, eval, loc, queue, item,
2118 loopNestClauseOps, iv, wsloopReductionSyms, wrapperArgs,
2119 llvm::omp::Directive::OMPD_do_simd, dsp);
2120 }
2121
2122 static void genCompositeTaskloopSimd(
2123 lower::AbstractConverter &converter, lower::SymMap &symTable,
2124 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
2125 mlir::Location loc, const ConstructQueue &queue,
2126 ConstructQueue::iterator item, DataSharingProcessor &dsp) {
2127 TODO(loc, "Composite TASKLOOP SIMD");
2128 }
2129
2130 //===----------------------------------------------------------------------===//
2131 // Dispatch
2132 //===----------------------------------------------------------------------===//
2133
2134 static void genOMPDispatch(lower::AbstractConverter &converter,
2135 lower::SymMap &symTable,
2136 semantics::SemanticsContext &semaCtx,
2137 lower::pft::Evaluation &eval, mlir::Location loc,
2138 const ConstructQueue &queue,
2139 ConstructQueue::iterator item) {
2140 assert(item != queue.end());
2141
2142 std::optional<DataSharingProcessor> loopDsp;
2143 bool loopLeaf = llvm::omp::getDirectiveAssociation(item->id) ==
2144 llvm::omp::Association::Loop;
2145 if (loopLeaf) {
2146 symTable.pushScope();
2147 loopDsp.emplace(converter, semaCtx, item->clauses, eval,
2148 /*shouldCollectPreDeterminedSymbols=*/true,
2149 enableDelayedPrivatization, &symTable);
2150 loopDsp->processStep1();
2151 }
2152
2153 switch (llvm::omp::Directive dir = item->id) {
2154 case llvm::omp::Directive::OMPD_barrier:
2155 genBarrierOp(converter, symTable, semaCtx, eval, loc, queue, item);
2156 break;
2157 case llvm::omp::Directive::OMPD_distribute:
2158 genStandaloneDistribute(converter, symTable, semaCtx, eval, loc, queue,
2159 item, *loopDsp);
2160 break;
2161 case llvm::omp::Directive::OMPD_do:
2162 genStandaloneDo(converter, symTable, semaCtx, eval, loc, queue, item,
2163 *loopDsp);
2164 break;
2165 case llvm::omp::Directive::OMPD_loop:
2166 TODO(loc, "Unhandled directive " + llvm::omp::getOpenMPDirectiveName(dir));
2167 break;
2168 case llvm::omp::Directive::OMPD_masked:
2169 genMaskedOp(converter, symTable, semaCtx, eval, loc, queue, item);
2170 break;
2171 case llvm::omp::Directive::OMPD_master:
2172 genMasterOp(converter, symTable, semaCtx, eval, loc, queue, item);
2173 break;
2174 case llvm::omp::Directive::OMPD_ordered:
2175 // Block-associated "ordered" construct.
2176 genOrderedRegionOp(converter, symTable, semaCtx, eval, loc, queue, item);
2177 break;
2178 case llvm::omp::Directive::OMPD_parallel:
2179 genStandaloneParallel(converter, symTable, semaCtx, eval, loc, queue, item);
2180 break;
2181 case llvm::omp::Directive::OMPD_section:
2182 llvm_unreachable("genOMPDispatch: OMPD_section");
2183 // Lowered in the enclosing genSectionsOp.
2184 break;
2185 case llvm::omp::Directive::OMPD_sections:
2186 // Called directly from genOMP([...], OpenMPSectionsConstruct) because it
2187 // has a different prototype.
2188 // This code path is still taken when iterating through the construct queue
2189 // in genBodyOfOp
2190 break;
2191 case llvm::omp::Directive::OMPD_simd:
2192 genStandaloneSimd(converter, symTable, semaCtx, eval, loc, queue, item,
2193 *loopDsp);
2194 break;
2195 case llvm::omp::Directive::OMPD_single:
2196 genSingleOp(converter, symTable, semaCtx, eval, loc, queue, item);
2197 break;
2198 case llvm::omp::Directive::OMPD_target:
2199 genTargetOp(converter, symTable, semaCtx, eval, loc, queue, item);
2200 break;
2201 case llvm::omp::Directive::OMPD_target_data:
2202 genTargetDataOp(converter, symTable, semaCtx, eval, loc, queue, item);
2203 break;
2204 case llvm::omp::Directive::OMPD_target_enter_data:
2205 genTargetEnterExitUpdateDataOp<mlir::omp::TargetEnterDataOp>(
2206 converter, symTable, semaCtx, loc, queue, item);
2207 break;
2208 case llvm::omp::Directive::OMPD_target_exit_data:
2209 genTargetEnterExitUpdateDataOp<mlir::omp::TargetExitDataOp>(
2210 converter, symTable, semaCtx, loc, queue, item);
2211 break;
2212 case llvm::omp::Directive::OMPD_target_update:
2213 genTargetEnterExitUpdateDataOp<mlir::omp::TargetUpdateOp>(
2214 converter, symTable, semaCtx, loc, queue, item);
2215 break;
2216 case llvm::omp::Directive::OMPD_task:
2217 genTaskOp(converter, symTable, semaCtx, eval, loc, queue, item);
2218 break;
2219 case llvm::omp::Directive::OMPD_taskgroup:
2220 genTaskgroupOp(converter, symTable, semaCtx, eval, loc, queue, item);
2221 break;
2222 case llvm::omp::Directive::OMPD_taskloop:
2223 genStandaloneTaskloop(converter, symTable, semaCtx, eval, loc, queue, item,
2224 *loopDsp);
2225 break;
2226 case llvm::omp::Directive::OMPD_taskwait:
2227 genTaskwaitOp(converter, symTable, semaCtx, eval, loc, queue, item);
2228 break;
2229 case llvm::omp::Directive::OMPD_taskyield:
2230 genTaskyieldOp(converter, symTable, semaCtx, eval, loc, queue, item);
2231 break;
2232 case llvm::omp::Directive::OMPD_teams:
2233 genTeamsOp(converter, symTable, semaCtx, eval, loc, queue, item);
2234 break;
2235 case llvm::omp::Directive::OMPD_tile:
2236 case llvm::omp::Directive::OMPD_unroll:
2237 TODO(loc, "Unhandled loop directive (" +
2238 llvm::omp::getOpenMPDirectiveName(dir) + ")");
2239 // case llvm::omp::Directive::OMPD_workdistribute:
2240 case llvm::omp::Directive::OMPD_workshare:
2241 // FIXME: Workshare is not a commonly used OpenMP construct, an
2242 // implementation for this feature will come later. For the codes
2243 // that use this construct, add a single construct for now.
2244 genSingleOp(converter, symTable, semaCtx, eval, loc, queue, item);
2245 break;
2246
2247 // Composite constructs
2248 case llvm::omp::Directive::OMPD_distribute_parallel_do:
2249 genCompositeDistributeParallelDo(converter, symTable, semaCtx, eval, loc,
2250 queue, item, *loopDsp);
2251 break;
2252 case llvm::omp::Directive::OMPD_distribute_parallel_do_simd:
2253 genCompositeDistributeParallelDoSimd(converter, symTable, semaCtx, eval,
2254 loc, queue, item, *loopDsp);
2255 break;
2256 case llvm::omp::Directive::OMPD_distribute_simd:
2257 genCompositeDistributeSimd(converter, symTable, semaCtx, eval, loc, queue,
2258 item, *loopDsp);
2259 break;
2260 case llvm::omp::Directive::OMPD_do_simd:
2261 genCompositeDoSimd(converter, symTable, semaCtx, eval, loc, queue, item,
2262 *loopDsp);
2263 break;
2264 case llvm::omp::Directive::OMPD_taskloop_simd:
2265 genCompositeTaskloopSimd(converter, symTable, semaCtx, eval, loc, queue,
2266 item, *loopDsp);
2267 break;
2268 default:
2269 break;
2270 }
2271
2272 if (loopLeaf)
2273 symTable.popScope();
2274 }
2275
2276 //===----------------------------------------------------------------------===//
2277 // OpenMPDeclarativeConstruct visitors
2278 //===----------------------------------------------------------------------===//
2279
2280 static void
2281 genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2282 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
2283 const parser::OpenMPDeclarativeAllocate &declarativeAllocate) {
2284 TODO(converter.getCurrentLocation(), "OpenMPDeclarativeAllocate");
2285 }
2286
2287 static void genOMP(
2288 lower::AbstractConverter &converter, lower::SymMap &symTable,
2289 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
2290 const parser::OpenMPDeclareReductionConstruct &declareReductionConstruct) {
2291 TODO(converter.getCurrentLocation(), "OpenMPDeclareReductionConstruct");
2292 }
2293
2294 static void
2295 genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2296 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
2297 const parser::OpenMPDeclareSimdConstruct &declareSimdConstruct) {
2298 TODO(converter.getCurrentLocation(), "OpenMPDeclareSimdConstruct");
2299 }
2300
2301 static void
2302 genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2303 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
2304 const parser::OpenMPDeclareTargetConstruct &declareTargetConstruct) {
2305 mlir::omp::DeclareTargetClauseOps clauseOps;
2306 llvm::SmallVector<DeclareTargetCapturePair> symbolAndClause;
2307 mlir::ModuleOp mod = converter.getFirOpBuilder().getModule();
2308 getDeclareTargetInfo(converter, semaCtx, eval, declareTargetConstruct,
2309 clauseOps, symbolAndClause);
2310
2311 for (const DeclareTargetCapturePair &symClause : symbolAndClause) {
2312 mlir::Operation *op = mod.lookupSymbol(
2313 converter.mangleName(std::get<const semantics::Symbol &>(symClause)));
2314
2315 // Some symbols are deferred until later in the module, these are handled
2316 // upon finalization of the module for OpenMP inside of Bridge, so we simply
2317 // skip for now.
2318 if (!op)
2319 continue;
2320
2321 markDeclareTarget(
2322 op, converter,
2323 std::get<mlir::omp::DeclareTargetCaptureClause>(symClause),
2324 clauseOps.deviceType);
2325 }
2326 }
2327
2328 static void genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2329 semantics::SemanticsContext &semaCtx,
2330 lower::pft::Evaluation &eval,
2331 const parser::OpenMPRequiresConstruct &requiresConstruct) {
2332 // Requires directives are gathered and processed in semantics and
2333 // then combined in the lowering bridge before triggering codegen
2334 // just once. Hence, there is no need to lower each individual
2335 // occurrence here.
2336 }
2337
2338 static void genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2339 semantics::SemanticsContext &semaCtx,
2340 lower::pft::Evaluation &eval,
2341 const parser::OpenMPThreadprivate &threadprivate) {
2342 // The directive is lowered when instantiating the variable to
2343 // support the case of threadprivate variable declared in module.
2344 }
2345
2346 static void genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2347 semantics::SemanticsContext &semaCtx,
2348 lower::pft::Evaluation &eval,
2349 const parser::OpenMPDeclarativeConstruct &ompDeclConstruct) {
2350 Fortran::common::visit(
2351 [&](auto &&s) { return genOMP(converter, symTable, semaCtx, eval, s); },
2352 ompDeclConstruct.u);
2353 }
2354
2355 //===----------------------------------------------------------------------===//
2356 // OpenMPStandaloneConstruct visitors
2357 //===----------------------------------------------------------------------===//
2358
2359 static void genOMP(
2360 lower::AbstractConverter &converter, lower::SymMap &symTable,
2361 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
2362 const parser::OpenMPSimpleStandaloneConstruct &simpleStandaloneConstruct) {
2363 const auto &directive = std::get<parser::OmpSimpleStandaloneDirective>(
2364 simpleStandaloneConstruct.t);
2365 List<Clause> clauses = makeClauses(
2366 std::get<parser::OmpClauseList>(simpleStandaloneConstruct.t), semaCtx);
2367 mlir::Location currentLocation = converter.genLocation(directive.source);
2368
2369 ConstructQueue queue{
2370 buildConstructQueue(converter.getFirOpBuilder().getModule(), semaCtx,
2371 eval, directive.source, directive.v, clauses)};
2372 if (directive.v == llvm::omp::Directive::OMPD_ordered) {
2373 // Standalone "ordered" directive.
2374 genOrderedOp(converter, symTable, semaCtx, eval, currentLocation, queue,
2375 queue.begin());
2376 } else {
2377 // Dispatch handles the "block-associated" variant of "ordered".
2378 genOMPDispatch(converter, symTable, semaCtx, eval, currentLocation, queue,
2379 queue.begin());
2380 }
2381 }
2382
2383 static void genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2384 semantics::SemanticsContext &semaCtx,
2385 lower::pft::Evaluation &eval,
2386 const parser::OpenMPFlushConstruct &flushConstruct) {
2387 const auto &verbatim = std::get<parser::Verbatim>(flushConstruct.t);
2388 const auto &objectList =
2389 std::get<std::optional<parser::OmpObjectList>>(flushConstruct.t);
2390 const auto &clauseList =
2391 std::get<std::optional<std::list<parser::OmpMemoryOrderClause>>>(
2392 flushConstruct.t);
2393 ObjectList objects =
2394 objectList ? makeObjects(*objectList, semaCtx) : ObjectList{};
2395 List<Clause> clauses =
2396 clauseList ? makeList(*clauseList,
2397 [&](auto &&s) { return makeClause(s.v, semaCtx); })
2398 : List<Clause>{};
2399 mlir::Location currentLocation = converter.genLocation(verbatim.source);
2400
2401 ConstructQueue queue{buildConstructQueue(
2402 converter.getFirOpBuilder().getModule(), semaCtx, eval, verbatim.source,
2403 llvm::omp::Directive::OMPD_flush, clauses)};
2404 genFlushOp(converter, symTable, semaCtx, eval, currentLocation, objects,
2405 queue, queue.begin());
2406 }
2407
2408 static void genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2409 semantics::SemanticsContext &semaCtx,
2410 lower::pft::Evaluation &eval,
2411 const parser::OpenMPCancelConstruct &cancelConstruct) {
2412 TODO(converter.getCurrentLocation(), "OpenMPCancelConstruct");
2413 }
2414
2415 static void genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2416 semantics::SemanticsContext &semaCtx,
2417 lower::pft::Evaluation &eval,
2418 const parser::OpenMPCancellationPointConstruct
2419 &cancellationPointConstruct) {
2420 TODO(converter.getCurrentLocation(), "OpenMPCancelConstruct");
2421 }
2422
2423 static void
2424 genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2425 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
2426 const parser::OpenMPStandaloneConstruct &standaloneConstruct) {
2427 Fortran::common::visit(
2428 [&](auto &&s) { return genOMP(converter, symTable, semaCtx, eval, s); },
2429 standaloneConstruct.u);
2430 }
2431
2432 //===----------------------------------------------------------------------===//
2433 // OpenMPConstruct visitors
2434 //===----------------------------------------------------------------------===//
2435
2436 static void genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2437 semantics::SemanticsContext &semaCtx,
2438 lower::pft::Evaluation &eval,
2439 const parser::OpenMPAllocatorsConstruct &allocsConstruct) {
2440 TODO(converter.getCurrentLocation(), "OpenMPAllocatorsConstruct");
2441 }
2442
2443 static void genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2444 semantics::SemanticsContext &semaCtx,
2445 lower::pft::Evaluation &eval,
2446 const parser::OpenMPAtomicConstruct &atomicConstruct) {
2447 Fortran::common::visit(
2448 common::visitors{
2449 [&](const parser::OmpAtomicRead &atomicRead) {
2450 mlir::Location loc = converter.genLocation(atomicRead.source);
2451 lower::genOmpAccAtomicRead<parser::OmpAtomicRead,
2452 parser::OmpAtomicClauseList>(
2453 converter, atomicRead, loc);
2454 },
2455 [&](const parser::OmpAtomicWrite &atomicWrite) {
2456 mlir::Location loc = converter.genLocation(atomicWrite.source);
2457 lower::genOmpAccAtomicWrite<parser::OmpAtomicWrite,
2458 parser::OmpAtomicClauseList>(
2459 converter, atomicWrite, loc);
2460 },
2461 [&](const parser::OmpAtomic &atomicConstruct) {
2462 mlir::Location loc = converter.genLocation(atomicConstruct.source);
2463 lower::genOmpAtomic<parser::OmpAtomic, parser::OmpAtomicClauseList>(
2464 converter, atomicConstruct, loc);
2465 },
2466 [&](const parser::OmpAtomicUpdate &atomicUpdate) {
2467 mlir::Location loc = converter.genLocation(atomicUpdate.source);
2468 lower::genOmpAccAtomicUpdate<parser::OmpAtomicUpdate,
2469 parser::OmpAtomicClauseList>(
2470 converter, atomicUpdate, loc);
2471 },
2472 [&](const parser::OmpAtomicCapture &atomicCapture) {
2473 mlir::Location loc = converter.genLocation(atomicCapture.source);
2474 lower::genOmpAccAtomicCapture<parser::OmpAtomicCapture,
2475 parser::OmpAtomicClauseList>(
2476 converter, atomicCapture, loc);
2477 },
2478 },
2479 atomicConstruct.u);
2480 }
2481
2482 static void genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2483 semantics::SemanticsContext &semaCtx,
2484 lower::pft::Evaluation &eval,
2485 const parser::OpenMPBlockConstruct &blockConstruct) {
2486 const auto &beginBlockDirective =
2487 std::get<parser::OmpBeginBlockDirective>(blockConstruct.t);
2488 const auto &endBlockDirective =
2489 std::get<parser::OmpEndBlockDirective>(blockConstruct.t);
2490 mlir::Location currentLocation =
2491 converter.genLocation(beginBlockDirective.source);
2492 const auto origDirective =
2493 std::get<parser::OmpBlockDirective>(beginBlockDirective.t).v;
2494 List<Clause> clauses = makeClauses(
2495 std::get<parser::OmpClauseList>(beginBlockDirective.t), semaCtx);
2496 clauses.append(makeClauses(
2497 std::get<parser::OmpClauseList>(endBlockDirective.t), semaCtx));
2498
2499 assert(llvm::omp::blockConstructSet.test(origDirective) &&
2500 "Expected block construct");
2501 (void)origDirective;
2502
2503 for (const Clause &clause : clauses) {
2504 mlir::Location clauseLocation = converter.genLocation(clause.source);
2505 if (!std::holds_alternative<clause::Allocate>(clause.u) &&
2506 !std::holds_alternative<clause::Copyin>(clause.u) &&
2507 !std::holds_alternative<clause::Copyprivate>(clause.u) &&
2508 !std::holds_alternative<clause::Default>(clause.u) &&
2509 !std::holds_alternative<clause::Depend>(clause.u) &&
2510 !std::holds_alternative<clause::Filter>(clause.u) &&
2511 !std::holds_alternative<clause::Final>(clause.u) &&
2512 !std::holds_alternative<clause::Firstprivate>(clause.u) &&
2513 !std::holds_alternative<clause::HasDeviceAddr>(clause.u) &&
2514 !std::holds_alternative<clause::If>(clause.u) &&
2515 !std::holds_alternative<clause::IsDevicePtr>(clause.u) &&
2516 !std::holds_alternative<clause::Map>(clause.u) &&
2517 !std::holds_alternative<clause::Nowait>(clause.u) &&
2518 !std::holds_alternative<clause::NumTeams>(clause.u) &&
2519 !std::holds_alternative<clause::NumThreads>(clause.u) &&
2520 !std::holds_alternative<clause::Priority>(clause.u) &&
2521 !std::holds_alternative<clause::Private>(clause.u) &&
2522 !std::holds_alternative<clause::ProcBind>(clause.u) &&
2523 !std::holds_alternative<clause::Reduction>(clause.u) &&
2524 !std::holds_alternative<clause::Shared>(clause.u) &&
2525 !std::holds_alternative<clause::Simd>(clause.u) &&
2526 !std::holds_alternative<clause::ThreadLimit>(clause.u) &&
2527 !std::holds_alternative<clause::Threads>(clause.u) &&
2528 !std::holds_alternative<clause::UseDeviceAddr>(clause.u) &&
2529 !std::holds_alternative<clause::UseDevicePtr>(clause.u)) {
2530 TODO(clauseLocation, "OpenMP Block construct clause");
2531 }
2532 }
2533
2534 llvm::omp::Directive directive =
2535 std::get<parser::OmpBlockDirective>(beginBlockDirective.t).v;
2536 const parser::CharBlock &source =
2537 std::get<parser::OmpBlockDirective>(beginBlockDirective.t).source;
2538 ConstructQueue queue{
2539 buildConstructQueue(converter.getFirOpBuilder().getModule(), semaCtx,
2540 eval, source, directive, clauses)};
2541 genOMPDispatch(converter, symTable, semaCtx, eval, currentLocation, queue,
2542 queue.begin());
2543 }
2544
2545 static void genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2546 semantics::SemanticsContext &semaCtx,
2547 lower::pft::Evaluation &eval,
2548 const parser::OpenMPCriticalConstruct &criticalConstruct) {
2549 const auto &cd = std::get<parser::OmpCriticalDirective>(criticalConstruct.t);
2550 List<Clause> clauses =
2551 makeClauses(std::get<parser::OmpClauseList>(cd.t), semaCtx);
2552
2553 ConstructQueue queue{buildConstructQueue(
2554 converter.getFirOpBuilder().getModule(), semaCtx, eval, cd.source,
2555 llvm::omp::Directive::OMPD_critical, clauses)};
2556
2557 const auto &name = std::get<std::optional<parser::Name>>(cd.t);
2558 mlir::Location currentLocation = converter.getCurrentLocation();
2559 genCriticalOp(converter, symTable, semaCtx, eval, currentLocation, queue,
2560 queue.begin(), name);
2561 }
2562
2563 static void genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2564 semantics::SemanticsContext &semaCtx,
2565 lower::pft::Evaluation &eval,
2566 const parser::OpenMPExecutableAllocate &execAllocConstruct) {
2567 TODO(converter.getCurrentLocation(), "OpenMPExecutableAllocate");
2568 }
2569
2570 static void genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2571 semantics::SemanticsContext &semaCtx,
2572 lower::pft::Evaluation &eval,
2573 const parser::OpenMPLoopConstruct &loopConstruct) {
2574 const auto &beginLoopDirective =
2575 std::get<parser::OmpBeginLoopDirective>(loopConstruct.t);
2576 List<Clause> clauses = makeClauses(
2577 std::get<parser::OmpClauseList>(beginLoopDirective.t), semaCtx);
2578 if (auto &endLoopDirective =
2579 std::get<std::optional<parser::OmpEndLoopDirective>>(
2580 loopConstruct.t)) {
2581 clauses.append(makeClauses(
2582 std::get<parser::OmpClauseList>(endLoopDirective->t), semaCtx));
2583 }
2584
2585 mlir::Location currentLocation =
2586 converter.genLocation(beginLoopDirective.source);
2587
2588 llvm::omp::Directive directive =
2589 std::get<parser::OmpLoopDirective>(beginLoopDirective.t).v;
2590 const parser::CharBlock &source =
2591 std::get<parser::OmpLoopDirective>(beginLoopDirective.t).source;
2592 ConstructQueue queue{
2593 buildConstructQueue(converter.getFirOpBuilder().getModule(), semaCtx,
2594 eval, source, directive, clauses)};
2595 genOMPDispatch(converter, symTable, semaCtx, eval, currentLocation, queue,
2596 queue.begin());
2597 }
2598
2599 static void genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2600 semantics::SemanticsContext &semaCtx,
2601 lower::pft::Evaluation &eval,
2602 const parser::OpenMPSectionConstruct &sectionConstruct) {
2603 // Do nothing here. SECTION is lowered inside of the lowering for Sections
2604 }
2605
2606 static void genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2607 semantics::SemanticsContext &semaCtx,
2608 lower::pft::Evaluation &eval,
2609 const parser::OpenMPSectionsConstruct &sectionsConstruct) {
2610 const auto &beginSectionsDirective =
2611 std::get<parser::OmpBeginSectionsDirective>(sectionsConstruct.t);
2612 List<Clause> clauses = makeClauses(
2613 std::get<parser::OmpClauseList>(beginSectionsDirective.t), semaCtx);
2614 const auto &endSectionsDirective =
2615 std::get<parser::OmpEndSectionsDirective>(sectionsConstruct.t);
2616 const auto &sectionBlocks =
2617 std::get<parser::OmpSectionBlocks>(sectionsConstruct.t);
2618 clauses.append(makeClauses(
2619 std::get<parser::OmpClauseList>(endSectionsDirective.t), semaCtx));
2620 mlir::Location currentLocation = converter.getCurrentLocation();
2621
2622 llvm::omp::Directive directive =
2623 std::get<parser::OmpSectionsDirective>(beginSectionsDirective.t).v;
2624 const parser::CharBlock &source =
2625 std::get<parser::OmpSectionsDirective>(beginSectionsDirective.t).source;
2626 ConstructQueue queue{
2627 buildConstructQueue(converter.getFirOpBuilder().getModule(), semaCtx,
2628 eval, source, directive, clauses)};
2629 ConstructQueue::iterator next = queue.begin();
2630 // Generate constructs that come first e.g. Parallel
2631 while (next != queue.end() &&
2632 next->id != llvm::omp::Directive::OMPD_sections) {
2633 genOMPDispatch(converter, symTable, semaCtx, eval, currentLocation, queue,
2634 next);
2635 next = std::next(next);
2636 }
2637
2638 // call genSectionsOp directly (not via genOMPDispatch) so that we can add the
2639 // sectionBlocks argument
2640 assert(next != queue.end());
2641 assert(next->id == llvm::omp::Directive::OMPD_sections);
2642 genSectionsOp(converter, symTable, semaCtx, eval, currentLocation, queue,
2643 next, sectionBlocks);
2644 assert(std::next(next) == queue.end());
2645 }
2646
2647 static void genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
2648 semantics::SemanticsContext &semaCtx,
2649 lower::pft::Evaluation &eval,
2650 const parser::OpenMPConstruct &ompConstruct) {
2651 Fortran::common::visit(
2652 [&](auto &&s) { return genOMP(converter, symTable, semaCtx, eval, s); },
2653 ompConstruct.u);
2654 }
2655
2656 //===----------------------------------------------------------------------===//
2657 // Public functions
2658 //===----------------------------------------------------------------------===//
2659
2660 mlir::Operation *Fortran::lower::genOpenMPTerminator(fir::FirOpBuilder &builder,
2661 mlir::Operation *op,
2662 mlir::Location loc) {
2663 if (mlir::isa<mlir::omp::AtomicUpdateOp, mlir::omp::DeclareReductionOp,
2664 mlir::omp::LoopNestOp>(op))
2665 return builder.create<mlir::omp::YieldOp>(loc);
2666 return builder.create<mlir::omp::TerminatorOp>(loc);
2667 }
2668
2669 void Fortran::lower::genOpenMPConstruct(lower::AbstractConverter &converter,
2670 lower::SymMap &symTable,
2671 semantics::SemanticsContext &semaCtx,
2672 lower::pft::Evaluation &eval,
2673 const parser::OpenMPConstruct &omp) {
2674 symTable.pushScope();
2675 genOMP(converter, symTable, semaCtx, eval, omp);
2676 symTable.popScope();
2677 }
2678
2679 void Fortran::lower::genOpenMPDeclarativeConstruct(
2680 lower::AbstractConverter &converter, lower::SymMap &symTable,
2681 semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
2682 const parser::OpenMPDeclarativeConstruct &omp) {
2683 genOMP(converter, symTable, semaCtx, eval, omp);
2684 genNestedEvaluations(converter, eval);
2685 }
2686
2687 void Fortran::lower::genOpenMPSymbolProperties(
2688 lower::AbstractConverter &converter, const lower::pft::Variable &var) {
2689 assert(var.hasSymbol() && "Expecting Symbol");
2690 const semantics::Symbol &sym = var.getSymbol();
2691
2692 if (sym.test(semantics::Symbol::Flag::OmpThreadprivate))
2693 lower::genThreadprivateOp(converter, var);
2694
2695 if (sym.test(semantics::Symbol::Flag::OmpDeclareTarget))
2696 lower::genDeclareTargetIntGlobal(converter, var);
2697 }
2698
2699 int64_t
2700 Fortran::lower::getCollapseValue(const parser::OmpClauseList &clauseList) {
2701 for (const parser::OmpClause &clause : clauseList.v) {
2702 if (const auto &collapseClause =
2703 std::get_if<parser::OmpClause::Collapse>(&clause.u)) {
2704 const auto *expr = semantics::GetExpr(collapseClause->v);
2705 return evaluate::ToInt64(*expr).value();
2706 }
2707 }
2708 return 1;
2709 }
2710
2711 void Fortran::lower::genThreadprivateOp(lower::AbstractConverter &converter,
2712 const lower::pft::Variable &var) {
2713 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
2714 mlir::Location currentLocation = converter.getCurrentLocation();
2715
2716 const semantics::Symbol &sym = var.getSymbol();
2717 mlir::Value symThreadprivateValue;
2718 if (const semantics::Symbol *common =
2719 semantics::FindCommonBlockContaining(sym.GetUltimate())) {
2720 mlir::Value commonValue = converter.getSymbolAddress(*common);
2721 if (mlir::isa<mlir::omp::ThreadprivateOp>(commonValue.getDefiningOp())) {
2722 // Generate ThreadprivateOp for a common block instead of its members and
2723 // only do it once for a common block.
2724 return;
2725 }
2726 // Generate ThreadprivateOp and rebind the common block.
2727 mlir::Value commonThreadprivateValue =
2728 firOpBuilder.create<mlir::omp::ThreadprivateOp>(
2729 currentLocation, commonValue.getType(), commonValue);
2730 converter.bindSymbol(*common, commonThreadprivateValue);
2731 // Generate the threadprivate value for the common block member.
2732 symThreadprivateValue = genCommonBlockMember(converter, currentLocation,
2733 sym, commonThreadprivateValue);
2734 } else if (!var.isGlobal()) {
2735 // Non-global variable which can be in threadprivate directive must be one
2736 // variable in main program, and it has implicit SAVE attribute. Take it as
2737 // with SAVE attribute, so to create GlobalOp for it to simplify the
2738 // translation to LLVM IR.
2739 // Avoids performing multiple globalInitializations.
2740 fir::GlobalOp global;
2741 auto module = converter.getModuleOp();
2742 std::string globalName = converter.mangleName(sym);
2743 if (module.lookupSymbol<fir::GlobalOp>(globalName))
2744 global = module.lookupSymbol<fir::GlobalOp>(globalName);
2745 else
2746 global = globalInitialization(converter, firOpBuilder, sym, var,
2747 currentLocation);
2748
2749 mlir::Value symValue = firOpBuilder.create<fir::AddrOfOp>(
2750 currentLocation, global.resultType(), global.getSymbol());
2751 symThreadprivateValue = firOpBuilder.create<mlir::omp::ThreadprivateOp>(
2752 currentLocation, symValue.getType(), symValue);
2753 } else {
2754 mlir::Value symValue = converter.getSymbolAddress(sym);
2755
2756 // The symbol may be use-associated multiple times, and nothing needs to be
2757 // done after the original symbol is mapped to the threadprivatized value
2758 // for the first time. Use the threadprivatized value directly.
2759 mlir::Operation *op;
2760 if (auto declOp = symValue.getDefiningOp<hlfir::DeclareOp>())
2761 op = declOp.getMemref().getDefiningOp();
2762 else
2763 op = symValue.getDefiningOp();
2764 if (mlir::isa<mlir::omp::ThreadprivateOp>(op))
2765 return;
2766
2767 symThreadprivateValue = firOpBuilder.create<mlir::omp::ThreadprivateOp>(
2768 currentLocation, symValue.getType(), symValue);
2769 }
2770
2771 fir::ExtendedValue sexv = converter.getSymbolExtendedValue(sym);
2772 fir::ExtendedValue symThreadprivateExv =
2773 getExtendedValue(sexv, symThreadprivateValue);
2774 converter.bindSymbol(sym, symThreadprivateExv);
2775 }
2776
2777 // This function replicates threadprivate's behaviour of generating
2778 // an internal fir.GlobalOp for non-global variables in the main program
2779 // that have the implicit SAVE attribute, to simplifiy LLVM-IR and MLIR
2780 // generation.
2781 void Fortran::lower::genDeclareTargetIntGlobal(
2782 lower::AbstractConverter &converter, const lower::pft::Variable &var) {
2783 if (!var.isGlobal()) {
2784 // A non-global variable which can be in a declare target directive must
2785 // be a variable in the main program, and it has the implicit SAVE
2786 // attribute. We create a GlobalOp for it to simplify the translation to
2787 // LLVM IR.
2788 globalInitialization(converter, converter.getFirOpBuilder(),
2789 var.getSymbol(), var, converter.getCurrentLocation());
2790 }
2791 }
2792
2793 bool Fortran::lower::isOpenMPTargetConstruct(
2794 const parser::OpenMPConstruct &omp) {
2795 llvm::omp::Directive dir = llvm::omp::Directive::OMPD_unknown;
2796 if (const auto *block = std::get_if<parser::OpenMPBlockConstruct>(&omp.u)) {
2797 const auto &begin = std::get<parser::OmpBeginBlockDirective>(block->t);
2798 dir = std::get<parser::OmpBlockDirective>(begin.t).v;
2799 } else if (const auto *loop =
2800 std::get_if<parser::OpenMPLoopConstruct>(&omp.u)) {
2801 const auto &begin = std::get<parser::OmpBeginLoopDirective>(loop->t);
2802 dir = std::get<parser::OmpLoopDirective>(begin.t).v;
2803 }
2804 return llvm::omp::allTargetSet.test(dir);
2805 }
2806
2807 void Fortran::lower::gatherOpenMPDeferredDeclareTargets(
2808 lower::AbstractConverter &converter, semantics::SemanticsContext &semaCtx,
2809 lower::pft::Evaluation &eval,
2810 const parser::OpenMPDeclarativeConstruct &ompDecl,
2811 llvm::SmallVectorImpl<OMPDeferredDeclareTargetInfo>
2812 &deferredDeclareTarget) {
2813 Fortran::common::visit(
2814 common::visitors{
2815 [&](const parser::OpenMPDeclareTargetConstruct &ompReq) {
2816 collectDeferredDeclareTargets(converter, semaCtx, eval, ompReq,
2817 deferredDeclareTarget);
2818 },
2819 [&](const auto &) {},
2820 },
2821 ompDecl.u);
2822 }
2823
2824 bool Fortran::lower::isOpenMPDeviceDeclareTarget(
2825 lower::AbstractConverter &converter, semantics::SemanticsContext &semaCtx,
2826 lower::pft::Evaluation &eval,
2827 const parser::OpenMPDeclarativeConstruct &ompDecl) {
2828 return Fortran::common::visit(
2829 common::visitors{
2830 [&](const parser::OpenMPDeclareTargetConstruct &ompReq) {
2831 mlir::omp::DeclareTargetDeviceType targetType =
2832 getDeclareTargetFunctionDevice(converter, semaCtx, eval, ompReq)
2833 .value_or(mlir::omp::DeclareTargetDeviceType::host);
2834 return targetType != mlir::omp::DeclareTargetDeviceType::host;
2835 },
2836 [&](const auto &) { return false; },
2837 },
2838 ompDecl.u);
2839 }
2840
2841 // In certain cases such as subroutine or function interfaces which declare
2842 // but do not define or directly call the subroutine or function in the same
2843 // module, their lowering is delayed until after the declare target construct
2844 // itself is processed, so there symbol is not within the table.
2845 //
2846 // This function will also return true if we encounter any device declare
2847 // target cases, to satisfy checking if we require the requires attributes
2848 // on the module.
2849 bool Fortran::lower::markOpenMPDeferredDeclareTargetFunctions(
2850 mlir::Operation *mod,
2851 llvm::SmallVectorImpl<OMPDeferredDeclareTargetInfo> &deferredDeclareTargets,
2852 AbstractConverter &converter) {
2853 bool deviceCodeFound = false;
2854 auto modOp = llvm::cast<mlir::ModuleOp>(mod);
2855 for (auto declTar : deferredDeclareTargets) {
2856 mlir::Operation *op = modOp.lookupSymbol(converter.mangleName(declTar.sym));
2857
2858 // Due to interfaces being optionally emitted on usage in a module,
2859 // not finding an operation at this point cannot be a hard error, we
2860 // simply ignore it for now.
2861 // TODO: Add semantic checks for detecting cases where an erronous
2862 // (undefined) symbol has been supplied to a declare target clause
2863 if (!op)
2864 continue;
2865
2866 auto devType = declTar.declareTargetDeviceType;
2867 if (!deviceCodeFound && devType != mlir::omp::DeclareTargetDeviceType::host)
2868 deviceCodeFound = true;
2869
2870 markDeclareTarget(op, converter, declTar.declareTargetCaptureClause,
2871 devType);
2872 }
2873
2874 return deviceCodeFound;
2875 }
2876
2877 void Fortran::lower::genOpenMPRequires(mlir::Operation *mod,
2878 const semantics::Symbol *symbol) {
2879 using MlirRequires = mlir::omp::ClauseRequires;
2880 using SemaRequires = semantics::WithOmpDeclarative::RequiresFlag;
2881
2882 if (auto offloadMod =
2883 llvm::dyn_cast<mlir::omp::OffloadModuleInterface>(mod)) {
2884 semantics::WithOmpDeclarative::RequiresFlags semaFlags;
2885 if (symbol) {
2886 common::visit(
2887 [&](const auto &details) {
2888 if constexpr (std::is_base_of_v<semantics::WithOmpDeclarative,
2889 std::decay_t<decltype(details)>>) {
2890 if (details.has_ompRequires())
2891 semaFlags = *details.ompRequires();
2892 }
2893 },
2894 symbol->details());
2895 }
2896
2897 // Use pre-populated omp.requires module attribute if it was set, so that
2898 // the "-fopenmp-force-usm" compiler option is honored.
2899 MlirRequires mlirFlags = offloadMod.getRequires();
2900 if (semaFlags.test(SemaRequires::ReverseOffload))
2901 mlirFlags = mlirFlags | MlirRequires::reverse_offload;
2902 if (semaFlags.test(SemaRequires::UnifiedAddress))
2903 mlirFlags = mlirFlags | MlirRequires::unified_address;
2904 if (semaFlags.test(SemaRequires::UnifiedSharedMemory))
2905 mlirFlags = mlirFlags | MlirRequires::unified_shared_memory;
2906 if (semaFlags.test(SemaRequires::DynamicAllocators))
2907 mlirFlags = mlirFlags | MlirRequires::dynamic_allocators;
2908
2909 offloadMod.setRequires(mlirFlags);
2910 }
2911 }