Debian Codegraph @

flang/lib/Semantics/check-omp-structure.cpp

raw
1 //===-- lib/Semantics/check-omp-structure.cpp -----------------------------===//
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 #include "check-omp-structure.h"
10 #include "definable.h"
11 #include "flang/Parser/parse-tree.h"
12 #include "flang/Semantics/tools.h"
13
14 namespace Fortran::semantics {
15
16 // Use when clause falls under 'struct OmpClause' in 'parse-tree.h'.
17 #define CHECK_SIMPLE_CLAUSE(X, Y) \
18 void OmpStructureChecker::Enter(const parser::OmpClause::X &) { \
19 CheckAllowed(llvm::omp::Clause::Y); \
20 }
21
22 #define CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(X, Y) \
23 void OmpStructureChecker::Enter(const parser::OmpClause::X &c) { \
24 CheckAllowed(llvm::omp::Clause::Y); \
25 RequiresConstantPositiveParameter(llvm::omp::Clause::Y, c.v); \
26 }
27
28 #define CHECK_REQ_SCALAR_INT_CLAUSE(X, Y) \
29 void OmpStructureChecker::Enter(const parser::OmpClause::X &c) { \
30 CheckAllowed(llvm::omp::Clause::Y); \
31 RequiresPositiveParameter(llvm::omp::Clause::Y, c.v); \
32 }
33
34 // Use when clause don't falls under 'struct OmpClause' in 'parse-tree.h'.
35 #define CHECK_SIMPLE_PARSER_CLAUSE(X, Y) \
36 void OmpStructureChecker::Enter(const parser::X &) { \
37 CheckAllowed(llvm::omp::Y); \
38 }
39
40 // 'OmpWorkshareBlockChecker' is used to check the validity of the assignment
41 // statements and the expressions enclosed in an OpenMP Workshare construct
42 class OmpWorkshareBlockChecker {
43 public:
44 OmpWorkshareBlockChecker(SemanticsContext &context, parser::CharBlock source)
45 : context_{context}, source_{source} {}
46
47 template <typename T> bool Pre(const T &) { return true; }
48 template <typename T> void Post(const T &) {}
49
50 bool Pre(const parser::AssignmentStmt &assignment) {
51 const auto &var{std::get<parser::Variable>(assignment.t)};
52 const auto &expr{std::get<parser::Expr>(assignment.t)};
53 const auto *lhs{GetExpr(context_, var)};
54 const auto *rhs{GetExpr(context_, expr)};
55 if (lhs && rhs) {
56 Tristate isDefined{semantics::IsDefinedAssignment(
57 lhs->GetType(), lhs->Rank(), rhs->GetType(), rhs->Rank())};
58 if (isDefined == Tristate::Yes) {
59 context_.Say(expr.source,
60 "Defined assignment statement is not "
61 "allowed in a WORKSHARE construct"_err_en_US);
62 }
63 }
64 return true;
65 }
66
67 bool Pre(const parser::Expr &expr) {
68 if (const auto *e{GetExpr(context_, expr)}) {
69 for (const Symbol &symbol : evaluate::CollectSymbols(*e)) {
70 const Symbol &root{GetAssociationRoot(symbol)};
71 if (IsFunction(root) && !IsElementalProcedure(root)) {
72 context_.Say(expr.source,
73 "User defined non-ELEMENTAL function "
74 "'%s' is not allowed in a WORKSHARE construct"_err_en_US,
75 root.name());
76 }
77 }
78 }
79 return false;
80 }
81
82 private:
83 SemanticsContext &context_;
84 parser::CharBlock source_;
85 };
86
87 class AssociatedLoopChecker {
88 public:
89 AssociatedLoopChecker(SemanticsContext &context, std::int64_t level)
90 : context_{context}, level_{level} {}
91
92 template <typename T> bool Pre(const T &) { return true; }
93 template <typename T> void Post(const T &) {}
94
95 bool Pre(const parser::DoConstruct &dc) {
96 level_--;
97 const auto &doStmt{
98 std::get<parser::Statement<parser::NonLabelDoStmt>>(dc.t)};
99 const auto &constructName{
100 std::get<std::optional<parser::Name>>(doStmt.statement.t)};
101 if (constructName) {
102 constructNamesAndLevels_.emplace(
103 constructName.value().ToString(), level_);
104 }
105 if (level_ >= 0) {
106 if (dc.IsDoWhile()) {
107 context_.Say(doStmt.source,
108 "The associated loop of a loop-associated directive cannot be a DO WHILE."_err_en_US);
109 }
110 if (!dc.GetLoopControl()) {
111 context_.Say(doStmt.source,
112 "The associated loop of a loop-associated directive cannot be a DO without control."_err_en_US);
113 }
114 }
115 return true;
116 }
117
118 void Post(const parser::DoConstruct &dc) { level_++; }
119
120 bool Pre(const parser::CycleStmt &cyclestmt) {
121 std::map<std::string, std::int64_t>::iterator it;
122 bool err{false};
123 if (cyclestmt.v) {
124 it = constructNamesAndLevels_.find(cyclestmt.v->source.ToString());
125 err = (it != constructNamesAndLevels_.end() && it->second > 0);
126 } else { // If there is no label then use the level of the last enclosing DO
127 err = level_ > 0;
128 }
129 if (err) {
130 context_.Say(*source_,
131 "CYCLE statement to non-innermost associated loop of an OpenMP DO "
132 "construct"_err_en_US);
133 }
134 return true;
135 }
136
137 bool Pre(const parser::ExitStmt &exitStmt) {
138 std::map<std::string, std::int64_t>::iterator it;
139 bool err{false};
140 if (exitStmt.v) {
141 it = constructNamesAndLevels_.find(exitStmt.v->source.ToString());
142 err = (it != constructNamesAndLevels_.end() && it->second >= 0);
143 } else { // If there is no label then use the level of the last enclosing DO
144 err = level_ >= 0;
145 }
146 if (err) {
147 context_.Say(*source_,
148 "EXIT statement terminates associated loop of an OpenMP DO "
149 "construct"_err_en_US);
150 }
151 return true;
152 }
153
154 bool Pre(const parser::Statement<parser::ActionStmt> &actionstmt) {
155 source_ = &actionstmt.source;
156 return true;
157 }
158
159 private:
160 SemanticsContext &context_;
161 const parser::CharBlock *source_;
162 std::int64_t level_;
163 std::map<std::string, std::int64_t> constructNamesAndLevels_;
164 };
165
166 bool OmpStructureChecker::IsCloselyNestedRegion(const OmpDirectiveSet &set) {
167 // Definition of close nesting:
168 //
169 // `A region nested inside another region with no parallel region nested
170 // between them`
171 //
172 // Examples:
173 // non-parallel construct 1
174 // non-parallel construct 2
175 // parallel construct
176 // construct 3
177 // In the above example, construct 3 is NOT closely nested inside construct 1
178 // or 2
179 //
180 // non-parallel construct 1
181 // non-parallel construct 2
182 // construct 3
183 // In the above example, construct 3 is closely nested inside BOTH construct 1
184 // and 2
185 //
186 // Algorithm:
187 // Starting from the parent context, Check in a bottom-up fashion, each level
188 // of the context stack. If we have a match for one of the (supplied)
189 // violating directives, `close nesting` is satisfied. If no match is there in
190 // the entire stack, `close nesting` is not satisfied. If at any level, a
191 // `parallel` region is found, `close nesting` is not satisfied.
192
193 if (CurrentDirectiveIsNested()) {
194 int index = dirContext_.size() - 2;
195 while (index != -1) {
196 if (set.test(dirContext_[index].directive)) {
197 return true;
198 } else if (llvm::omp::allParallelSet.test(dirContext_[index].directive)) {
199 return false;
200 }
201 index--;
202 }
203 }
204 return false;
205 }
206
207 void OmpStructureChecker::CheckMultipleOccurrence(
208 semantics::UnorderedSymbolSet &listVars,
209 const std::list<parser::Name> &nameList, const parser::CharBlock &item,
210 const std::string &clauseName) {
211 for (auto const &var : nameList) {
212 if (llvm::is_contained(listVars, *(var.symbol))) {
213 context_.Say(item,
214 "List item '%s' present at multiple %s clauses"_err_en_US,
215 var.ToString(), clauseName);
216 }
217 listVars.insert(*(var.symbol));
218 }
219 }
220
221 void OmpStructureChecker::CheckMultListItems() {
222 semantics::UnorderedSymbolSet listVars;
223
224 // Aligned clause
225 auto alignedClauses{FindClauses(llvm::omp::Clause::OMPC_aligned)};
226 for (auto itr = alignedClauses.first; itr != alignedClauses.second; ++itr) {
227 const auto &alignedClause{
228 std::get<parser::OmpClause::Aligned>(itr->second->u)};
229 const auto &alignedList{std::get<0>(alignedClause.v.t)};
230 std::list<parser::Name> alignedNameList;
231 for (const auto &ompObject : alignedList.v) {
232 if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
233 if (name->symbol) {
234 if (FindCommonBlockContaining(*(name->symbol))) {
235 context_.Say(itr->second->source,
236 "'%s' is a common block name and can not appear in an "
237 "ALIGNED clause"_err_en_US,
238 name->ToString());
239 } else if (!(IsBuiltinCPtr(*(name->symbol)) ||
240 IsAllocatableOrObjectPointer(
241 &name->symbol->GetUltimate()))) {
242 context_.Say(itr->second->source,
243 "'%s' in ALIGNED clause must be of type C_PTR, POINTER or "
244 "ALLOCATABLE"_err_en_US,
245 name->ToString());
246 } else {
247 alignedNameList.push_back(*name);
248 }
249 } else {
250 // The symbol is null, return early
251 return;
252 }
253 }
254 }
255 CheckMultipleOccurrence(
256 listVars, alignedNameList, itr->second->source, "ALIGNED");
257 }
258
259 // Nontemporal clause
260 auto nonTemporalClauses{FindClauses(llvm::omp::Clause::OMPC_nontemporal)};
261 for (auto itr = nonTemporalClauses.first; itr != nonTemporalClauses.second;
262 ++itr) {
263 const auto &nontempClause{
264 std::get<parser::OmpClause::Nontemporal>(itr->second->u)};
265 const auto &nontempNameList{nontempClause.v};
266 CheckMultipleOccurrence(
267 listVars, nontempNameList, itr->second->source, "NONTEMPORAL");
268 }
269 }
270
271 bool OmpStructureChecker::HasInvalidWorksharingNesting(
272 const parser::CharBlock &source, const OmpDirectiveSet &set) {
273 // set contains all the invalid closely nested directives
274 // for the given directive (`source` here)
275 if (IsCloselyNestedRegion(set)) {
276 context_.Say(source,
277 "A worksharing region may not be closely nested inside a "
278 "worksharing, explicit task, taskloop, critical, ordered, atomic, or "
279 "master region"_err_en_US);
280 return true;
281 }
282 return false;
283 }
284
285 void OmpStructureChecker::HasInvalidDistributeNesting(
286 const parser::OpenMPLoopConstruct &x) {
287 bool violation{false};
288 const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
289 const auto &beginDir{std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
290 if (llvm::omp::topDistributeSet.test(beginDir.v)) {
291 // `distribute` region has to be nested
292 if (!CurrentDirectiveIsNested()) {
293 violation = true;
294 } else {
295 // `distribute` region has to be strictly nested inside `teams`
296 if (!OmpDirectiveSet{llvm::omp::OMPD_teams, llvm::omp::OMPD_target_teams}
297 .test(GetContextParent().directive)) {
298 violation = true;
299 }
300 }
301 }
302 if (violation) {
303 context_.Say(beginDir.source,
304 "`DISTRIBUTE` region has to be strictly nested inside `TEAMS` "
305 "region."_err_en_US);
306 }
307 }
308
309 void OmpStructureChecker::HasInvalidTeamsNesting(
310 const llvm::omp::Directive &dir, const parser::CharBlock &source) {
311 if (!llvm::omp::nestedTeamsAllowedSet.test(dir)) {
312 context_.Say(source,
313 "Only `DISTRIBUTE` or `PARALLEL` regions are allowed to be strictly "
314 "nested inside `TEAMS` region."_err_en_US);
315 }
316 }
317
318 void OmpStructureChecker::CheckPredefinedAllocatorRestriction(
319 const parser::CharBlock &source, const parser::Name &name) {
320 if (const auto *symbol{name.symbol}) {
321 const auto *commonBlock{FindCommonBlockContaining(*symbol)};
322 const auto &scope{context_.FindScope(symbol->name())};
323 const Scope &containingScope{GetProgramUnitContaining(scope)};
324 if (!isPredefinedAllocator &&
325 (IsSaved(*symbol) || commonBlock ||
326 containingScope.kind() == Scope::Kind::Module)) {
327 context_.Say(source,
328 "If list items within the %s directive have the "
329 "SAVE attribute, are a common block name, or are "
330 "declared in the scope of a module, then only "
331 "predefined memory allocator parameters can be used "
332 "in the allocator clause"_err_en_US,
333 ContextDirectiveAsFortran());
334 }
335 }
336 }
337
338 void OmpStructureChecker::CheckPredefinedAllocatorRestriction(
339 const parser::CharBlock &source,
340 const parser::OmpObjectList &ompObjectList) {
341 for (const auto &ompObject : ompObjectList.v) {
342 common::visit(
343 common::visitors{
344 [&](const parser::Designator &designator) {
345 if (const auto *dataRef{
346 std::get_if<parser::DataRef>(&designator.u)}) {
347 if (const auto *name{std::get_if<parser::Name>(&dataRef->u)}) {
348 CheckPredefinedAllocatorRestriction(source, *name);
349 }
350 }
351 },
352 [&](const parser::Name &name) {
353 CheckPredefinedAllocatorRestriction(source, name);
354 },
355 },
356 ompObject.u);
357 }
358 }
359
360 template <class D>
361 void OmpStructureChecker::CheckHintClause(
362 D *leftOmpClauseList, D *rightOmpClauseList) {
363 auto checkForValidHintClause = [&](const D *clauseList) {
364 for (const auto &clause : clauseList->v) {
365 const Fortran::parser::OmpClause *ompClause = nullptr;
366 if constexpr (std::is_same_v<D,
367 const Fortran::parser::OmpAtomicClauseList>) {
368 ompClause = std::get_if<Fortran::parser::OmpClause>(&clause.u);
369 if (!ompClause)
370 continue;
371 } else if constexpr (std::is_same_v<D,
372 const Fortran::parser::OmpClauseList>) {
373 ompClause = &clause;
374 }
375 if (const Fortran::parser::OmpClause::Hint *
376 hintClause{
377 std::get_if<Fortran::parser::OmpClause::Hint>(&ompClause->u)}) {
378 std::optional<std::int64_t> hintValue = GetIntValue(hintClause->v);
379 if (hintValue && *hintValue >= 0) {
380 /*`omp_sync_hint_nonspeculative` and `omp_lock_hint_speculative`*/
381 if ((*hintValue & 0xC) == 0xC
382 /*`omp_sync_hint_uncontended` and omp_sync_hint_contended*/
383 || (*hintValue & 0x3) == 0x3)
384 context_.Say(clause.source,
385 "Hint clause value "
386 "is not a valid OpenMP synchronization value"_err_en_US);
387 } else {
388 context_.Say(clause.source,
389 "Hint clause must have non-negative constant "
390 "integer expression"_err_en_US);
391 }
392 }
393 }
394 };
395
396 if (leftOmpClauseList) {
397 checkForValidHintClause(leftOmpClauseList);
398 }
399 if (rightOmpClauseList) {
400 checkForValidHintClause(rightOmpClauseList);
401 }
402 }
403
404 void OmpStructureChecker::Enter(const parser::OpenMPConstruct &x) {
405 // Simd Construct with Ordered Construct Nesting check
406 // We cannot use CurrentDirectiveIsNested() here because
407 // PushContextAndClauseSets() has not been called yet, it is
408 // called individually for each construct. Therefore a
409 // dirContext_ size `1` means the current construct is nested
410 if (dirContext_.size() >= 1) {
411 if (GetDirectiveNest(SIMDNest) > 0) {
412 CheckSIMDNest(x);
413 }
414 if (GetDirectiveNest(TargetNest) > 0) {
415 CheckTargetNest(x);
416 }
417 }
418 }
419
420 void OmpStructureChecker::Enter(const parser::OpenMPLoopConstruct &x) {
421 const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
422 const auto &beginDir{std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
423
424 // check matching, End directive is optional
425 if (const auto &endLoopDir{
426 std::get<std::optional<parser::OmpEndLoopDirective>>(x.t)}) {
427 const auto &endDir{
428 std::get<parser::OmpLoopDirective>(endLoopDir.value().t)};
429
430 CheckMatching<parser::OmpLoopDirective>(beginDir, endDir);
431 }
432
433 PushContextAndClauseSets(beginDir.source, beginDir.v);
434 if (llvm::omp::allSimdSet.test(GetContext().directive)) {
435 EnterDirectiveNest(SIMDNest);
436 }
437
438 // Combined target loop constructs are target device constructs. Keep track of
439 // whether any such construct has been visited to later check that REQUIRES
440 // directives for target-related options don't appear after them.
441 if (llvm::omp::allTargetSet.test(beginDir.v)) {
442 deviceConstructFound_ = true;
443 }
444
445 if (beginDir.v == llvm::omp::Directive::OMPD_do) {
446 // 2.7.1 do-clause -> private-clause |
447 // firstprivate-clause |
448 // lastprivate-clause |
449 // linear-clause |
450 // reduction-clause |
451 // schedule-clause |
452 // collapse-clause |
453 // ordered-clause
454
455 // nesting check
456 HasInvalidWorksharingNesting(
457 beginDir.source, llvm::omp::nestedWorkshareErrSet);
458 }
459 SetLoopInfo(x);
460
461 if (const auto &doConstruct{
462 std::get<std::optional<parser::DoConstruct>>(x.t)}) {
463 const auto &doBlock{std::get<parser::Block>(doConstruct->t)};
464 CheckNoBranching(doBlock, beginDir.v, beginDir.source);
465 }
466 CheckLoopItrVariableIsInt(x);
467 CheckAssociatedLoopConstraints(x);
468 HasInvalidDistributeNesting(x);
469 if (CurrentDirectiveIsNested() &&
470 llvm::omp::topTeamsSet.test(GetContextParent().directive)) {
471 HasInvalidTeamsNesting(beginDir.v, beginDir.source);
472 }
473 if ((beginDir.v == llvm::omp::Directive::OMPD_distribute_parallel_do_simd) ||
474 (beginDir.v == llvm::omp::Directive::OMPD_distribute_simd)) {
475 CheckDistLinear(x);
476 }
477 }
478 const parser::Name OmpStructureChecker::GetLoopIndex(
479 const parser::DoConstruct *x) {
480 using Bounds = parser::LoopControl::Bounds;
481 return std::get<Bounds>(x->GetLoopControl()->u).name.thing;
482 }
483 void OmpStructureChecker::SetLoopInfo(const parser::OpenMPLoopConstruct &x) {
484 if (const auto &loopConstruct{
485 std::get<std::optional<parser::DoConstruct>>(x.t)}) {
486 const parser::DoConstruct *loop{&*loopConstruct};
487 if (loop && loop->IsDoNormal()) {
488 const parser::Name &itrVal{GetLoopIndex(loop)};
489 SetLoopIv(itrVal.symbol);
490 }
491 }
492 }
493
494 void OmpStructureChecker::CheckLoopItrVariableIsInt(
495 const parser::OpenMPLoopConstruct &x) {
496 if (const auto &loopConstruct{
497 std::get<std::optional<parser::DoConstruct>>(x.t)}) {
498
499 for (const parser::DoConstruct *loop{&*loopConstruct}; loop;) {
500 if (loop->IsDoNormal()) {
501 const parser::Name &itrVal{GetLoopIndex(loop)};
502 if (itrVal.symbol) {
503 const auto *type{itrVal.symbol->GetType()};
504 if (!type->IsNumeric(TypeCategory::Integer)) {
505 context_.Say(itrVal.source,
506 "The DO loop iteration"
507 " variable must be of the type integer."_err_en_US,
508 itrVal.ToString());
509 }
510 }
511 }
512 // Get the next DoConstruct if block is not empty.
513 const auto &block{std::get<parser::Block>(loop->t)};
514 const auto it{block.begin()};
515 loop = it != block.end() ? parser::Unwrap<parser::DoConstruct>(*it)
516 : nullptr;
517 }
518 }
519 }
520
521 void OmpStructureChecker::CheckSIMDNest(const parser::OpenMPConstruct &c) {
522 // Check the following:
523 // The only OpenMP constructs that can be encountered during execution of
524 // a simd region are the `atomic` construct, the `loop` construct, the `simd`
525 // construct and the `ordered` construct with the `simd` clause.
526 // TODO: Expand the check to include `LOOP` construct as well when it is
527 // supported.
528
529 // Check if the parent context has the SIMD clause
530 // Please note that we use GetContext() instead of GetContextParent()
531 // because PushContextAndClauseSets() has not been called on the
532 // current context yet.
533 // TODO: Check for declare simd regions.
534 bool eligibleSIMD{false};
535 common::visit(Fortran::common::visitors{
536 // Allow `!$OMP ORDERED SIMD`
537 [&](const parser::OpenMPBlockConstruct &c) {
538 const auto &beginBlockDir{
539 std::get<parser::OmpBeginBlockDirective>(c.t)};
540 const auto &beginDir{
541 std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
542 if (beginDir.v == llvm::omp::Directive::OMPD_ordered) {
543 const auto &clauses{
544 std::get<parser::OmpClauseList>(beginBlockDir.t)};
545 for (const auto &clause : clauses.v) {
546 if (std::get_if<parser::OmpClause::Simd>(&clause.u)) {
547 eligibleSIMD = true;
548 break;
549 }
550 }
551 }
552 },
553 [&](const parser::OpenMPSimpleStandaloneConstruct &c) {
554 const auto &dir{
555 std::get<parser::OmpSimpleStandaloneDirective>(c.t)};
556 if (dir.v == llvm::omp::Directive::OMPD_ordered) {
557 const auto &clauses{
558 std::get<parser::OmpClauseList>(c.t)};
559 for (const auto &clause : clauses.v) {
560 if (std::get_if<parser::OmpClause::Simd>(&clause.u)) {
561 eligibleSIMD = true;
562 break;
563 }
564 }
565 }
566 },
567 // Allowing SIMD construct
568 [&](const parser::OpenMPLoopConstruct &c) {
569 const auto &beginLoopDir{
570 std::get<parser::OmpBeginLoopDirective>(c.t)};
571 const auto &beginDir{
572 std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
573 if ((beginDir.v == llvm::omp::Directive::OMPD_simd) ||
574 (beginDir.v == llvm::omp::Directive::OMPD_do_simd)) {
575 eligibleSIMD = true;
576 }
577 },
578 [&](const parser::OpenMPAtomicConstruct &c) {
579 // Allow `!$OMP ATOMIC`
580 eligibleSIMD = true;
581 },
582 [&](const auto &c) {},
583 },
584 c.u);
585 if (!eligibleSIMD) {
586 context_.Say(parser::FindSourceLocation(c),
587 "The only OpenMP constructs that can be encountered during execution "
588 "of a 'SIMD' region are the `ATOMIC` construct, the `LOOP` construct, "
589 "the `SIMD` construct and the `ORDERED` construct with the `SIMD` "
590 "clause."_err_en_US);
591 }
592 }
593
594 void OmpStructureChecker::CheckTargetNest(const parser::OpenMPConstruct &c) {
595 // 2.12.5 Target Construct Restriction
596 bool eligibleTarget{true};
597 llvm::omp::Directive ineligibleTargetDir;
598 common::visit(
599 common::visitors{
600 [&](const parser::OpenMPBlockConstruct &c) {
601 const auto &beginBlockDir{
602 std::get<parser::OmpBeginBlockDirective>(c.t)};
603 const auto &beginDir{
604 std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
605 if (beginDir.v == llvm::omp::Directive::OMPD_target_data) {
606 eligibleTarget = false;
607 ineligibleTargetDir = beginDir.v;
608 }
609 },
610 [&](const parser::OpenMPStandaloneConstruct &c) {
611 common::visit(
612 common::visitors{
613 [&](const parser::OpenMPSimpleStandaloneConstruct &c) {
614 const auto &dir{
615 std::get<parser::OmpSimpleStandaloneDirective>(c.t)};
616 if (dir.v == llvm::omp::Directive::OMPD_target_update ||
617 dir.v ==
618 llvm::omp::Directive::OMPD_target_enter_data ||
619 dir.v ==
620 llvm::omp::Directive::OMPD_target_exit_data) {
621 eligibleTarget = false;
622 ineligibleTargetDir = dir.v;
623 }
624 },
625 [&](const auto &c) {},
626 },
627 c.u);
628 },
629 [&](const auto &c) {},
630 },
631 c.u);
632 if (!eligibleTarget &&
633 context_.ShouldWarn(common::UsageWarning::Portability)) {
634 context_.Say(parser::FindSourceLocation(c),
635 "If %s directive is nested inside TARGET region, the behaviour "
636 "is unspecified"_port_en_US,
637 parser::ToUpperCaseLetters(
638 getDirectiveName(ineligibleTargetDir).str()));
639 }
640 }
641
642 std::int64_t OmpStructureChecker::GetOrdCollapseLevel(
643 const parser::OpenMPLoopConstruct &x) {
644 const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
645 const auto &clauseList{std::get<parser::OmpClauseList>(beginLoopDir.t)};
646 std::int64_t orderedCollapseLevel{1};
647 std::int64_t orderedLevel{1};
648 std::int64_t collapseLevel{1};
649
650 for (const auto &clause : clauseList.v) {
651 if (const auto *collapseClause{
652 std::get_if<parser::OmpClause::Collapse>(&clause.u)}) {
653 if (const auto v{GetIntValue(collapseClause->v)}) {
654 collapseLevel = *v;
655 }
656 }
657 if (const auto *orderedClause{
658 std::get_if<parser::OmpClause::Ordered>(&clause.u)}) {
659 if (const auto v{GetIntValue(orderedClause->v)}) {
660 orderedLevel = *v;
661 }
662 }
663 }
664 if (orderedLevel >= collapseLevel) {
665 orderedCollapseLevel = orderedLevel;
666 } else {
667 orderedCollapseLevel = collapseLevel;
668 }
669 return orderedCollapseLevel;
670 }
671
672 void OmpStructureChecker::CheckAssociatedLoopConstraints(
673 const parser::OpenMPLoopConstruct &x) {
674 std::int64_t ordCollapseLevel{GetOrdCollapseLevel(x)};
675 AssociatedLoopChecker checker{context_, ordCollapseLevel};
676 parser::Walk(x, checker);
677 }
678
679 void OmpStructureChecker::CheckDistLinear(
680 const parser::OpenMPLoopConstruct &x) {
681
682 const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
683 const auto &clauses{std::get<parser::OmpClauseList>(beginLoopDir.t)};
684
685 semantics::UnorderedSymbolSet indexVars;
686
687 // Collect symbols of all the variables from linear clauses
688 for (const auto &clause : clauses.v) {
689 if (const auto *linearClause{
690 std::get_if<parser::OmpClause::Linear>(&clause.u)}) {
691
692 std::list<parser::Name> values;
693 // Get the variant type
694 if (std::holds_alternative<parser::OmpLinearClause::WithModifier>(
695 linearClause->v.u)) {
696 const auto &withM{
697 std::get<parser::OmpLinearClause::WithModifier>(linearClause->v.u)};
698 values = withM.names;
699 } else {
700 const auto &withOutM{std::get<parser::OmpLinearClause::WithoutModifier>(
701 linearClause->v.u)};
702 values = withOutM.names;
703 }
704 for (auto const &v : values) {
705 indexVars.insert(*(v.symbol));
706 }
707 }
708 }
709
710 if (!indexVars.empty()) {
711 // Get collapse level, if given, to find which loops are "associated."
712 std::int64_t collapseVal{GetOrdCollapseLevel(x)};
713 // Include the top loop if no collapse is specified
714 if (collapseVal == 0) {
715 collapseVal = 1;
716 }
717
718 // Match the loop index variables with the collected symbols from linear
719 // clauses.
720 if (const auto &loopConstruct{
721 std::get<std::optional<parser::DoConstruct>>(x.t)}) {
722 for (const parser::DoConstruct *loop{&*loopConstruct}; loop;) {
723 if (loop->IsDoNormal()) {
724 const parser::Name &itrVal{GetLoopIndex(loop)};
725 if (itrVal.symbol) {
726 // Remove the symbol from the collcted set
727 indexVars.erase(*(itrVal.symbol));
728 }
729 collapseVal--;
730 if (collapseVal == 0) {
731 break;
732 }
733 }
734 // Get the next DoConstruct if block is not empty.
735 const auto &block{std::get<parser::Block>(loop->t)};
736 const auto it{block.begin()};
737 loop = it != block.end() ? parser::Unwrap<parser::DoConstruct>(*it)
738 : nullptr;
739 }
740 }
741
742 // Show error for the remaining variables
743 for (auto var : indexVars) {
744 const Symbol &root{GetAssociationRoot(var)};
745 context_.Say(parser::FindSourceLocation(x),
746 "Variable '%s' not allowed in `LINEAR` clause, only loop iterator "
747 "can be specified in `LINEAR` clause of a construct combined with "
748 "`DISTRIBUTE`"_err_en_US,
749 root.name());
750 }
751 }
752 }
753
754 void OmpStructureChecker::Leave(const parser::OpenMPLoopConstruct &) {
755 if (llvm::omp::allSimdSet.test(GetContext().directive)) {
756 ExitDirectiveNest(SIMDNest);
757 }
758 dirContext_.pop_back();
759 }
760
761 void OmpStructureChecker::Enter(const parser::OmpEndLoopDirective &x) {
762 const auto &dir{std::get<parser::OmpLoopDirective>(x.t)};
763 ResetPartialContext(dir.source);
764 switch (dir.v) {
765 // 2.7.1 end-do -> END DO [nowait-clause]
766 // 2.8.3 end-do-simd -> END DO SIMD [nowait-clause]
767 case llvm::omp::Directive::OMPD_do:
768 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_end_do);
769 break;
770 case llvm::omp::Directive::OMPD_do_simd:
771 PushContextAndClauseSets(
772 dir.source, llvm::omp::Directive::OMPD_end_do_simd);
773 break;
774 default:
775 // no clauses are allowed
776 break;
777 }
778 }
779
780 void OmpStructureChecker::Leave(const parser::OmpEndLoopDirective &x) {
781 if ((GetContext().directive == llvm::omp::Directive::OMPD_end_do) ||
782 (GetContext().directive == llvm::omp::Directive::OMPD_end_do_simd)) {
783 dirContext_.pop_back();
784 }
785 }
786
787 void OmpStructureChecker::Enter(const parser::OpenMPBlockConstruct &x) {
788 const auto &beginBlockDir{std::get<parser::OmpBeginBlockDirective>(x.t)};
789 const auto &endBlockDir{std::get<parser::OmpEndBlockDirective>(x.t)};
790 const auto &beginDir{std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
791 const auto &endDir{std::get<parser::OmpBlockDirective>(endBlockDir.t)};
792 const parser::Block &block{std::get<parser::Block>(x.t)};
793
794 CheckMatching<parser::OmpBlockDirective>(beginDir, endDir);
795
796 PushContextAndClauseSets(beginDir.source, beginDir.v);
797 if (GetContext().directive == llvm::omp::Directive::OMPD_target) {
798 EnterDirectiveNest(TargetNest);
799 }
800
801 if (CurrentDirectiveIsNested()) {
802 if (llvm::omp::topTeamsSet.test(GetContextParent().directive)) {
803 HasInvalidTeamsNesting(beginDir.v, beginDir.source);
804 }
805 if (GetContext().directive == llvm::omp::Directive::OMPD_master) {
806 CheckMasterNesting(x);
807 }
808 // A teams region can only be strictly nested within the implicit parallel
809 // region or a target region.
810 if (GetContext().directive == llvm::omp::Directive::OMPD_teams &&
811 GetContextParent().directive != llvm::omp::Directive::OMPD_target) {
812 context_.Say(parser::FindSourceLocation(x),
813 "%s region can only be strictly nested within the implicit parallel "
814 "region or TARGET region"_err_en_US,
815 ContextDirectiveAsFortran());
816 }
817 // If a teams construct is nested within a target construct, that target
818 // construct must contain no statements, declarations or directives outside
819 // of the teams construct.
820 if (GetContext().directive == llvm::omp::Directive::OMPD_teams &&
821 GetContextParent().directive == llvm::omp::Directive::OMPD_target &&
822 !GetDirectiveNest(TargetBlockOnlyTeams)) {
823 context_.Say(GetContextParent().directiveSource,
824 "TARGET construct with nested TEAMS region contains statements or "
825 "directives outside of the TEAMS construct"_err_en_US);
826 }
827 }
828
829 CheckNoBranching(block, beginDir.v, beginDir.source);
830
831 // Target block constructs are target device constructs. Keep track of
832 // whether any such construct has been visited to later check that REQUIRES
833 // directives for target-related options don't appear after them.
834 if (llvm::omp::allTargetSet.test(beginDir.v)) {
835 deviceConstructFound_ = true;
836 }
837
838 switch (beginDir.v) {
839 case llvm::omp::Directive::OMPD_target:
840 if (CheckTargetBlockOnlyTeams(block)) {
841 EnterDirectiveNest(TargetBlockOnlyTeams);
842 }
843 break;
844 case llvm::omp::OMPD_workshare:
845 case llvm::omp::OMPD_parallel_workshare:
846 CheckWorkshareBlockStmts(block, beginDir.source);
847 HasInvalidWorksharingNesting(
848 beginDir.source, llvm::omp::nestedWorkshareErrSet);
849 break;
850 case llvm::omp::Directive::OMPD_single:
851 // TODO: This check needs to be extended while implementing nesting of
852 // regions checks.
853 HasInvalidWorksharingNesting(
854 beginDir.source, llvm::omp::nestedWorkshareErrSet);
855 break;
856 default:
857 break;
858 }
859 }
860
861 void OmpStructureChecker::CheckMasterNesting(
862 const parser::OpenMPBlockConstruct &x) {
863 // A MASTER region may not be `closely nested` inside a worksharing, loop,
864 // task, taskloop, or atomic region.
865 // TODO: Expand the check to include `LOOP` construct as well when it is
866 // supported.
867 if (IsCloselyNestedRegion(llvm::omp::nestedMasterErrSet)) {
868 context_.Say(parser::FindSourceLocation(x),
869 "`MASTER` region may not be closely nested inside of `WORKSHARING`, "
870 "`LOOP`, `TASK`, `TASKLOOP`,"
871 " or `ATOMIC` region."_err_en_US);
872 }
873 }
874
875 void OmpStructureChecker::Leave(const parser::OpenMPBlockConstruct &) {
876 if (GetDirectiveNest(TargetBlockOnlyTeams)) {
877 ExitDirectiveNest(TargetBlockOnlyTeams);
878 }
879 if (GetContext().directive == llvm::omp::Directive::OMPD_target) {
880 ExitDirectiveNest(TargetNest);
881 }
882 dirContext_.pop_back();
883 }
884
885 void OmpStructureChecker::ChecksOnOrderedAsBlock() {
886 if (FindClause(llvm::omp::Clause::OMPC_depend)) {
887 context_.Say(GetContext().clauseSource,
888 "DEPEND(*) clauses are not allowed when ORDERED construct is a block"
889 " construct with an ORDERED region"_err_en_US);
890 return;
891 }
892
893 bool isNestedInDo{false};
894 bool isNestedInDoSIMD{false};
895 bool isNestedInSIMD{false};
896 bool noOrderedClause{false};
897 bool isOrderedClauseWithPara{false};
898 bool isCloselyNestedRegion{true};
899 if (CurrentDirectiveIsNested()) {
900 for (int i = (int)dirContext_.size() - 2; i >= 0; i--) {
901 if (llvm::omp::nestedOrderedErrSet.test(dirContext_[i].directive)) {
902 context_.Say(GetContext().directiveSource,
903 "`ORDERED` region may not be closely nested inside of `CRITICAL`, "
904 "`ORDERED`, explicit `TASK` or `TASKLOOP` region."_err_en_US);
905 break;
906 } else if (llvm::omp::allDoSet.test(dirContext_[i].directive)) {
907 isNestedInDo = true;
908 isNestedInDoSIMD =
909 llvm::omp::allDoSimdSet.test(dirContext_[i].directive);
910 if (const auto *clause{
911 FindClause(dirContext_[i], llvm::omp::Clause::OMPC_ordered)}) {
912 const auto &orderedClause{
913 std::get<parser::OmpClause::Ordered>(clause->u)};
914 const auto orderedValue{GetIntValue(orderedClause.v)};
915 isOrderedClauseWithPara = orderedValue > 0;
916 } else {
917 noOrderedClause = true;
918 }
919 break;
920 } else if (llvm::omp::allSimdSet.test(dirContext_[i].directive)) {
921 isNestedInSIMD = true;
922 break;
923 } else if (llvm::omp::nestedOrderedParallelErrSet.test(
924 dirContext_[i].directive)) {
925 isCloselyNestedRegion = false;
926 break;
927 }
928 }
929 }
930
931 if (!isCloselyNestedRegion) {
932 context_.Say(GetContext().directiveSource,
933 "An ORDERED directive without the DEPEND clause must be closely nested "
934 "in a SIMD, worksharing-loop, or worksharing-loop SIMD "
935 "region"_err_en_US);
936 } else {
937 if (CurrentDirectiveIsNested() &&
938 FindClause(llvm::omp::Clause::OMPC_simd) &&
939 (!isNestedInDoSIMD && !isNestedInSIMD)) {
940 context_.Say(GetContext().directiveSource,
941 "An ORDERED directive with SIMD clause must be closely nested in a "
942 "SIMD or worksharing-loop SIMD region"_err_en_US);
943 }
944 if (isNestedInDo && (noOrderedClause || isOrderedClauseWithPara)) {
945 context_.Say(GetContext().directiveSource,
946 "An ORDERED directive without the DEPEND clause must be closely "
947 "nested in a worksharing-loop (or worksharing-loop SIMD) region with "
948 "ORDERED clause without the parameter"_err_en_US);
949 }
950 }
951 }
952
953 void OmpStructureChecker::Leave(const parser::OmpBeginBlockDirective &) {
954 switch (GetContext().directive) {
955 case llvm::omp::Directive::OMPD_ordered:
956 // [5.1] 2.19.9 Ordered Construct Restriction
957 ChecksOnOrderedAsBlock();
958 break;
959 default:
960 break;
961 }
962 }
963
964 void OmpStructureChecker::Enter(const parser::OpenMPSectionsConstruct &x) {
965 const auto &beginSectionsDir{
966 std::get<parser::OmpBeginSectionsDirective>(x.t)};
967 const auto &endSectionsDir{std::get<parser::OmpEndSectionsDirective>(x.t)};
968 const auto &beginDir{
969 std::get<parser::OmpSectionsDirective>(beginSectionsDir.t)};
970 const auto &endDir{std::get<parser::OmpSectionsDirective>(endSectionsDir.t)};
971 CheckMatching<parser::OmpSectionsDirective>(beginDir, endDir);
972
973 PushContextAndClauseSets(beginDir.source, beginDir.v);
974 const auto &sectionBlocks{std::get<parser::OmpSectionBlocks>(x.t)};
975 for (const parser::OpenMPConstruct &block : sectionBlocks.v) {
976 CheckNoBranching(std::get<parser::OpenMPSectionConstruct>(block.u).v,
977 beginDir.v, beginDir.source);
978 }
979 HasInvalidWorksharingNesting(
980 beginDir.source, llvm::omp::nestedWorkshareErrSet);
981 }
982
983 void OmpStructureChecker::Leave(const parser::OpenMPSectionsConstruct &) {
984 dirContext_.pop_back();
985 }
986
987 void OmpStructureChecker::Enter(const parser::OmpEndSectionsDirective &x) {
988 const auto &dir{std::get<parser::OmpSectionsDirective>(x.t)};
989 ResetPartialContext(dir.source);
990 switch (dir.v) {
991 // 2.7.2 end-sections -> END SECTIONS [nowait-clause]
992 case llvm::omp::Directive::OMPD_sections:
993 PushContextAndClauseSets(
994 dir.source, llvm::omp::Directive::OMPD_end_sections);
995 break;
996 default:
997 // no clauses are allowed
998 break;
999 }
1000 }
1001
1002 // TODO: Verify the popping of dirContext requirement after nowait
1003 // implementation, as there is an implicit barrier at the end of the worksharing
1004 // constructs unless a nowait clause is specified. Only OMPD_end_sections is
1005 // popped becuase it is pushed while entering the EndSectionsDirective.
1006 void OmpStructureChecker::Leave(const parser::OmpEndSectionsDirective &x) {
1007 if (GetContext().directive == llvm::omp::Directive::OMPD_end_sections) {
1008 dirContext_.pop_back();
1009 }
1010 }
1011
1012 void OmpStructureChecker::CheckThreadprivateOrDeclareTargetVar(
1013 const parser::OmpObjectList &objList) {
1014 for (const auto &ompObject : objList.v) {
1015 common::visit(
1016 common::visitors{
1017 [&](const parser::Designator &) {
1018 if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
1019 // The symbol is null, return early, CheckSymbolNames
1020 // should have already reported the missing symbol as a
1021 // diagnostic error
1022 if (!name->symbol) {
1023 return;
1024 }
1025
1026 if (name->symbol->GetUltimate().IsSubprogram()) {
1027 if (GetContext().directive ==
1028 llvm::omp::Directive::OMPD_threadprivate)
1029 context_.Say(name->source,
1030 "The procedure name cannot be in a %s "
1031 "directive"_err_en_US,
1032 ContextDirectiveAsFortran());
1033 // TODO: Check for procedure name in declare target directive.
1034 } else if (name->symbol->attrs().test(Attr::PARAMETER)) {
1035 if (GetContext().directive ==
1036 llvm::omp::Directive::OMPD_threadprivate)
1037 context_.Say(name->source,
1038 "The entity with PARAMETER attribute cannot be in a %s "
1039 "directive"_err_en_US,
1040 ContextDirectiveAsFortran());
1041 else if (GetContext().directive ==
1042 llvm::omp::Directive::OMPD_declare_target)
1043 if (context_.ShouldWarn(
1044 common::UsageWarning::OpenMPUsage)) {
1045 context_.Say(name->source,
1046 "The entity with PARAMETER attribute is used in a %s directive"_warn_en_US,
1047 ContextDirectiveAsFortran());
1048 }
1049 } else if (FindCommonBlockContaining(*name->symbol)) {
1050 context_.Say(name->source,
1051 "A variable in a %s directive cannot be an element of a "
1052 "common block"_err_en_US,
1053 ContextDirectiveAsFortran());
1054 } else if (FindEquivalenceSet(*name->symbol)) {
1055 context_.Say(name->source,
1056 "A variable in a %s directive cannot appear in an "
1057 "EQUIVALENCE statement"_err_en_US,
1058 ContextDirectiveAsFortran());
1059 } else if (name->symbol->test(Symbol::Flag::OmpThreadprivate) &&
1060 GetContext().directive ==
1061 llvm::omp::Directive::OMPD_declare_target) {
1062 context_.Say(name->source,
1063 "A THREADPRIVATE variable cannot appear in a %s "
1064 "directive"_err_en_US,
1065 ContextDirectiveAsFortran());
1066 } else {
1067 const semantics::Scope &useScope{
1068 context_.FindScope(GetContext().directiveSource)};
1069 const semantics::Scope &curScope =
1070 name->symbol->GetUltimate().owner();
1071 if (!curScope.IsTopLevel()) {
1072 const semantics::Scope &declScope =
1073 GetProgramUnitOrBlockConstructContaining(curScope);
1074 const semantics::Symbol *sym{
1075 declScope.parent().FindSymbol(name->symbol->name())};
1076 if (sym &&
1077 (sym->has<MainProgramDetails>() ||
1078 sym->has<ModuleDetails>())) {
1079 context_.Say(name->source,
1080 "The module name or main program name cannot be in a "
1081 "%s "
1082 "directive"_err_en_US,
1083 ContextDirectiveAsFortran());
1084 } else if (!IsSaved(*name->symbol) &&
1085 declScope.kind() != Scope::Kind::MainProgram &&
1086 declScope.kind() != Scope::Kind::Module) {
1087 context_.Say(name->source,
1088 "A variable that appears in a %s directive must be "
1089 "declared in the scope of a module or have the SAVE "
1090 "attribute, either explicitly or "
1091 "implicitly"_err_en_US,
1092 ContextDirectiveAsFortran());
1093 } else if (useScope != declScope) {
1094 context_.Say(name->source,
1095 "The %s directive and the common block or variable "
1096 "in it must appear in the same declaration section "
1097 "of a scoping unit"_err_en_US,
1098 ContextDirectiveAsFortran());
1099 }
1100 }
1101 }
1102 }
1103 },
1104 [&](const parser::Name &) {}, // common block
1105 },
1106 ompObject.u);
1107 }
1108 }
1109
1110 void OmpStructureChecker::Enter(const parser::OpenMPThreadprivate &c) {
1111 const auto &dir{std::get<parser::Verbatim>(c.t)};
1112 PushContextAndClauseSets(
1113 dir.source, llvm::omp::Directive::OMPD_threadprivate);
1114 }
1115
1116 void OmpStructureChecker::Leave(const parser::OpenMPThreadprivate &c) {
1117 const auto &dir{std::get<parser::Verbatim>(c.t)};
1118 const auto &objectList{std::get<parser::OmpObjectList>(c.t)};
1119 CheckSymbolNames(dir.source, objectList);
1120 CheckIsVarPartOfAnotherVar(dir.source, objectList);
1121 CheckThreadprivateOrDeclareTargetVar(objectList);
1122 dirContext_.pop_back();
1123 }
1124
1125 void OmpStructureChecker::Enter(const parser::OpenMPDeclareSimdConstruct &x) {
1126 const auto &dir{std::get<parser::Verbatim>(x.t)};
1127 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_declare_simd);
1128 }
1129
1130 void OmpStructureChecker::Leave(const parser::OpenMPDeclareSimdConstruct &) {
1131 dirContext_.pop_back();
1132 }
1133
1134 void OmpStructureChecker::Enter(const parser::OpenMPRequiresConstruct &x) {
1135 const auto &dir{std::get<parser::Verbatim>(x.t)};
1136 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_requires);
1137 }
1138
1139 void OmpStructureChecker::Leave(const parser::OpenMPRequiresConstruct &) {
1140 dirContext_.pop_back();
1141 }
1142
1143 void OmpStructureChecker::Enter(const parser::OpenMPDeclarativeAllocate &x) {
1144 isPredefinedAllocator = true;
1145 const auto &dir{std::get<parser::Verbatim>(x.t)};
1146 const auto &objectList{std::get<parser::OmpObjectList>(x.t)};
1147 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_allocate);
1148 CheckIsVarPartOfAnotherVar(dir.source, objectList);
1149 }
1150
1151 void OmpStructureChecker::Leave(const parser::OpenMPDeclarativeAllocate &x) {
1152 const auto &dir{std::get<parser::Verbatim>(x.t)};
1153 const auto &objectList{std::get<parser::OmpObjectList>(x.t)};
1154 CheckPredefinedAllocatorRestriction(dir.source, objectList);
1155 dirContext_.pop_back();
1156 }
1157
1158 void OmpStructureChecker::Enter(const parser::OmpClause::Allocator &x) {
1159 CheckAllowed(llvm::omp::Clause::OMPC_allocator);
1160 // Note: Predefined allocators are stored in ScalarExpr as numbers
1161 // whereas custom allocators are stored as strings, so if the ScalarExpr
1162 // actually has an int value, then it must be a predefined allocator
1163 isPredefinedAllocator = GetIntValue(x.v).has_value();
1164 RequiresPositiveParameter(llvm::omp::Clause::OMPC_allocator, x.v);
1165 }
1166
1167 void OmpStructureChecker::Enter(const parser::OmpClause::Allocate &x) {
1168 CheckAllowed(llvm::omp::Clause::OMPC_allocate);
1169 if (const auto &modifier{
1170 std::get<std::optional<parser::OmpAllocateClause::AllocateModifier>>(
1171 x.v.t)}) {
1172 common::visit(
1173 common::visitors{
1174 [&](const parser::OmpAllocateClause::AllocateModifier::Allocator
1175 &y) {
1176 RequiresPositiveParameter(llvm::omp::Clause::OMPC_allocate, y.v);
1177 isPredefinedAllocator = GetIntValue(y.v).has_value();
1178 },
1179 [&](const parser::OmpAllocateClause::AllocateModifier::
1180 ComplexModifier &y) {
1181 const auto &alloc = std::get<
1182 parser::OmpAllocateClause::AllocateModifier::Allocator>(y.t);
1183 const auto &align =
1184 std::get<parser::OmpAllocateClause::AllocateModifier::Align>(
1185 y.t);
1186 RequiresPositiveParameter(
1187 llvm::omp::Clause::OMPC_allocate, alloc.v);
1188 RequiresPositiveParameter(
1189 llvm::omp::Clause::OMPC_allocate, align.v);
1190 isPredefinedAllocator = GetIntValue(alloc.v).has_value();
1191 },
1192 [&](const parser::OmpAllocateClause::AllocateModifier::Align &y) {
1193 RequiresPositiveParameter(llvm::omp::Clause::OMPC_allocate, y.v);
1194 },
1195 },
1196 modifier->u);
1197 }
1198 }
1199
1200 void OmpStructureChecker::Enter(const parser::OmpDeclareTargetWithClause &x) {
1201 SetClauseSets(llvm::omp::Directive::OMPD_declare_target);
1202 }
1203
1204 void OmpStructureChecker::Leave(const parser::OmpDeclareTargetWithClause &x) {
1205 if (x.v.v.size() > 0) {
1206 const parser::OmpClause *enterClause =
1207 FindClause(llvm::omp::Clause::OMPC_enter);
1208 const parser::OmpClause *toClause = FindClause(llvm::omp::Clause::OMPC_to);
1209 const parser::OmpClause *linkClause =
1210 FindClause(llvm::omp::Clause::OMPC_link);
1211 if (!enterClause && !toClause && !linkClause) {
1212 context_.Say(x.source,
1213 "If the DECLARE TARGET directive has a clause, it must contain at lease one ENTER clause or LINK clause"_err_en_US);
1214 }
1215 if (toClause && context_.ShouldWarn(common::UsageWarning::OpenMPUsage)) {
1216 context_.Say(toClause->source,
1217 "The usage of TO clause on DECLARE TARGET directive has been deprecated. Use ENTER clause instead."_warn_en_US);
1218 }
1219 }
1220 }
1221
1222 void OmpStructureChecker::Enter(const parser::OpenMPDeclareTargetConstruct &x) {
1223 const auto &dir{std::get<parser::Verbatim>(x.t)};
1224 PushContext(dir.source, llvm::omp::Directive::OMPD_declare_target);
1225 }
1226
1227 void OmpStructureChecker::Enter(const parser::OmpDeclareTargetWithList &x) {
1228 SymbolSourceMap symbols;
1229 GetSymbolsInObjectList(x.v, symbols);
1230 for (auto &[symbol, source] : symbols) {
1231 const GenericDetails *genericDetails = symbol->detailsIf<GenericDetails>();
1232 if (genericDetails) {
1233 context_.Say(source,
1234 "The procedure '%s' in DECLARE TARGET construct cannot be a generic name."_err_en_US,
1235 symbol->name());
1236 genericDetails->specific();
1237 }
1238 if (IsProcedurePointer(*symbol)) {
1239 context_.Say(source,
1240 "The procedure '%s' in DECLARE TARGET construct cannot be a procedure pointer."_err_en_US,
1241 symbol->name());
1242 }
1243 const SubprogramDetails *entryDetails =
1244 symbol->detailsIf<SubprogramDetails>();
1245 if (entryDetails && entryDetails->entryScope()) {
1246 context_.Say(source,
1247 "The procedure '%s' in DECLARE TARGET construct cannot be an entry name."_err_en_US,
1248 symbol->name());
1249 }
1250 if (IsStmtFunction(*symbol)) {
1251 context_.Say(source,
1252 "The procedure '%s' in DECLARE TARGET construct cannot be a statement function."_err_en_US,
1253 symbol->name());
1254 }
1255 }
1256 }
1257
1258 void OmpStructureChecker::CheckSymbolNames(
1259 const parser::CharBlock &source, const parser::OmpObjectList &objList) {
1260 for (const auto &ompObject : objList.v) {
1261 common::visit(
1262 common::visitors{
1263 [&](const parser::Designator &designator) {
1264 if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
1265 if (!name->symbol) {
1266 context_.Say(source,
1267 "The given %s directive clause has an invalid argument"_err_en_US,
1268 ContextDirectiveAsFortran());
1269 }
1270 }
1271 },
1272 [&](const parser::Name &name) {
1273 if (!name.symbol) {
1274 context_.Say(source,
1275 "The given %s directive clause has an invalid argument"_err_en_US,
1276 ContextDirectiveAsFortran());
1277 }
1278 },
1279 },
1280 ompObject.u);
1281 }
1282 }
1283
1284 void OmpStructureChecker::Leave(const parser::OpenMPDeclareTargetConstruct &x) {
1285 const auto &dir{std::get<parser::Verbatim>(x.t)};
1286 const auto &spec{std::get<parser::OmpDeclareTargetSpecifier>(x.t)};
1287 // Handle both forms of DECLARE TARGET.
1288 // - Extended list: It behaves as if there was an ENTER/TO clause with the
1289 // list of objects as argument. It accepts no explicit clauses.
1290 // - With clauses.
1291 if (const auto *objectList{parser::Unwrap<parser::OmpObjectList>(spec.u)}) {
1292 deviceConstructFound_ = true;
1293 CheckSymbolNames(dir.source, *objectList);
1294 CheckIsVarPartOfAnotherVar(dir.source, *objectList);
1295 CheckThreadprivateOrDeclareTargetVar(*objectList);
1296 } else if (const auto *clauseList{
1297 parser::Unwrap<parser::OmpClauseList>(spec.u)}) {
1298 bool toClauseFound{false}, deviceTypeClauseFound{false},
1299 enterClauseFound{false};
1300 for (const auto &clause : clauseList->v) {
1301 common::visit(
1302 common::visitors{
1303 [&](const parser::OmpClause::To &toClause) {
1304 toClauseFound = true;
1305 CheckSymbolNames(dir.source, toClause.v);
1306 CheckIsVarPartOfAnotherVar(dir.source, toClause.v);
1307 CheckThreadprivateOrDeclareTargetVar(toClause.v);
1308 },
1309 [&](const parser::OmpClause::Link &linkClause) {
1310 CheckSymbolNames(dir.source, linkClause.v);
1311 CheckIsVarPartOfAnotherVar(dir.source, linkClause.v);
1312 CheckThreadprivateOrDeclareTargetVar(linkClause.v);
1313 },
1314 [&](const parser::OmpClause::Enter &enterClause) {
1315 enterClauseFound = true;
1316 CheckSymbolNames(dir.source, enterClause.v);
1317 CheckIsVarPartOfAnotherVar(dir.source, enterClause.v);
1318 CheckThreadprivateOrDeclareTargetVar(enterClause.v);
1319 },
1320 [&](const parser::OmpClause::DeviceType &deviceTypeClause) {
1321 deviceTypeClauseFound = true;
1322 if (deviceTypeClause.v.v !=
1323 parser::OmpDeviceTypeClause::Type::Host) {
1324 // Function / subroutine explicitly marked as runnable by the
1325 // target device.
1326 deviceConstructFound_ = true;
1327 }
1328 },
1329 [&](const auto &) {},
1330 },
1331 clause.u);
1332
1333 if ((toClauseFound || enterClauseFound) && !deviceTypeClauseFound) {
1334 deviceConstructFound_ = true;
1335 }
1336 }
1337 }
1338 dirContext_.pop_back();
1339 }
1340
1341 void OmpStructureChecker::Enter(const parser::OpenMPExecutableAllocate &x) {
1342 isPredefinedAllocator = true;
1343 const auto &dir{std::get<parser::Verbatim>(x.t)};
1344 const auto &objectList{std::get<std::optional<parser::OmpObjectList>>(x.t)};
1345 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_allocate);
1346 if (objectList) {
1347 CheckIsVarPartOfAnotherVar(dir.source, *objectList);
1348 }
1349 }
1350
1351 void OmpStructureChecker::Leave(const parser::OpenMPExecutableAllocate &x) {
1352 const auto &dir{std::get<parser::Verbatim>(x.t)};
1353 const auto &objectList{std::get<std::optional<parser::OmpObjectList>>(x.t)};
1354 if (objectList)
1355 CheckPredefinedAllocatorRestriction(dir.source, *objectList);
1356 dirContext_.pop_back();
1357 }
1358
1359 void OmpStructureChecker::Enter(const parser::OpenMPAllocatorsConstruct &x) {
1360 isPredefinedAllocator = true;
1361 const auto &dir{std::get<parser::Verbatim>(x.t)};
1362 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_allocators);
1363 const auto &clauseList{std::get<parser::OmpClauseList>(x.t)};
1364 for (const auto &clause : clauseList.v) {
1365 if (const auto *allocClause{
1366 parser::Unwrap<parser::OmpClause::Allocate>(clause)}) {
1367 CheckIsVarPartOfAnotherVar(
1368 dir.source, std::get<parser::OmpObjectList>(allocClause->v.t));
1369 }
1370 }
1371 }
1372
1373 void OmpStructureChecker::Leave(const parser::OpenMPAllocatorsConstruct &x) {
1374 const auto &dir{std::get<parser::Verbatim>(x.t)};
1375 const auto &clauseList{std::get<parser::OmpClauseList>(x.t)};
1376 for (const auto &clause : clauseList.v) {
1377 if (const auto *allocClause{
1378 std::get_if<parser::OmpClause::Allocate>(&clause.u)}) {
1379 CheckPredefinedAllocatorRestriction(
1380 dir.source, std::get<parser::OmpObjectList>(allocClause->v.t));
1381 }
1382 }
1383 dirContext_.pop_back();
1384 }
1385
1386 void OmpStructureChecker::CheckBarrierNesting(
1387 const parser::OpenMPSimpleStandaloneConstruct &x) {
1388 // A barrier region may not be `closely nested` inside a worksharing, loop,
1389 // task, taskloop, critical, ordered, atomic, or master region.
1390 // TODO: Expand the check to include `LOOP` construct as well when it is
1391 // supported.
1392 if (GetContext().directive == llvm::omp::Directive::OMPD_barrier) {
1393 if (IsCloselyNestedRegion(llvm::omp::nestedBarrierErrSet)) {
1394 context_.Say(parser::FindSourceLocation(x),
1395 "`BARRIER` region may not be closely nested inside of `WORKSHARING`, "
1396 "`LOOP`, `TASK`, `TASKLOOP`,"
1397 "`CRITICAL`, `ORDERED`, `ATOMIC` or `MASTER` region."_err_en_US);
1398 }
1399 }
1400 }
1401
1402 void OmpStructureChecker::ChecksOnOrderedAsStandalone() {
1403 if (FindClause(llvm::omp::Clause::OMPC_threads) ||
1404 FindClause(llvm::omp::Clause::OMPC_simd)) {
1405 context_.Say(GetContext().clauseSource,
1406 "THREADS, SIMD clauses are not allowed when ORDERED construct is a "
1407 "standalone construct with no ORDERED region"_err_en_US);
1408 }
1409
1410 bool isSinkPresent{false};
1411 int dependSourceCount{0};
1412 auto clauseAll = FindClauses(llvm::omp::Clause::OMPC_depend);
1413 for (auto itr = clauseAll.first; itr != clauseAll.second; ++itr) {
1414 const auto &dependClause{
1415 std::get<parser::OmpClause::Depend>(itr->second->u)};
1416 if (std::get_if<parser::OmpDependClause::Source>(&dependClause.v.u)) {
1417 dependSourceCount++;
1418 if (isSinkPresent) {
1419 context_.Say(itr->second->source,
1420 "DEPEND(SOURCE) is not allowed when DEPEND(SINK: vec) is present "
1421 "on ORDERED directive"_err_en_US);
1422 }
1423 if (dependSourceCount > 1) {
1424 context_.Say(itr->second->source,
1425 "At most one DEPEND(SOURCE) clause can appear on the ORDERED "
1426 "directive"_err_en_US);
1427 }
1428 } else if (std::get_if<parser::OmpDependClause::Sink>(&dependClause.v.u)) {
1429 isSinkPresent = true;
1430 if (dependSourceCount > 0) {
1431 context_.Say(itr->second->source,
1432 "DEPEND(SINK: vec) is not allowed when DEPEND(SOURCE) is present "
1433 "on ORDERED directive"_err_en_US);
1434 }
1435 } else {
1436 context_.Say(itr->second->source,
1437 "Only DEPEND(SOURCE) or DEPEND(SINK: vec) are allowed when ORDERED "
1438 "construct is a standalone construct with no ORDERED "
1439 "region"_err_en_US);
1440 }
1441 }
1442
1443 bool isNestedInDoOrderedWithPara{false};
1444 if (CurrentDirectiveIsNested() &&
1445 llvm::omp::nestedOrderedDoAllowedSet.test(GetContextParent().directive)) {
1446 if (const auto *clause{
1447 FindClause(GetContextParent(), llvm::omp::Clause::OMPC_ordered)}) {
1448 const auto &orderedClause{
1449 std::get<parser::OmpClause::Ordered>(clause->u)};
1450 const auto orderedValue{GetIntValue(orderedClause.v)};
1451 if (orderedValue > 0) {
1452 isNestedInDoOrderedWithPara = true;
1453 CheckOrderedDependClause(orderedValue);
1454 }
1455 }
1456 }
1457
1458 if (FindClause(llvm::omp::Clause::OMPC_depend) &&
1459 !isNestedInDoOrderedWithPara) {
1460 context_.Say(GetContext().clauseSource,
1461 "An ORDERED construct with the DEPEND clause must be closely nested "
1462 "in a worksharing-loop (or parallel worksharing-loop) construct with "
1463 "ORDERED clause with a parameter"_err_en_US);
1464 }
1465 }
1466
1467 void OmpStructureChecker::CheckOrderedDependClause(
1468 std::optional<std::int64_t> orderedValue) {
1469 auto clauseAll{FindClauses(llvm::omp::Clause::OMPC_depend)};
1470 for (auto itr = clauseAll.first; itr != clauseAll.second; ++itr) {
1471 const auto &dependClause{
1472 std::get<parser::OmpClause::Depend>(itr->second->u)};
1473 if (const auto *sinkVectors{
1474 std::get_if<parser::OmpDependClause::Sink>(&dependClause.v.u)}) {
1475 std::int64_t numVar = sinkVectors->v.size();
1476 if (orderedValue != numVar) {
1477 context_.Say(itr->second->source,
1478 "The number of variables in DEPEND(SINK: vec) clause does not "
1479 "match the parameter specified in ORDERED clause"_err_en_US);
1480 }
1481 }
1482 }
1483 }
1484
1485 void OmpStructureChecker::CheckTargetUpdate() {
1486 const parser::OmpClause *toClause = FindClause(llvm::omp::Clause::OMPC_to);
1487 const parser::OmpClause *fromClause =
1488 FindClause(llvm::omp::Clause::OMPC_from);
1489 if (!toClause && !fromClause) {
1490 context_.Say(GetContext().directiveSource,
1491 "At least one motion-clause (TO/FROM) must be specified on TARGET UPDATE construct."_err_en_US);
1492 }
1493 if (toClause && fromClause) {
1494 SymbolSourceMap toSymbols, fromSymbols;
1495 GetSymbolsInObjectList(
1496 std::get<parser::OmpClause::To>(toClause->u).v, toSymbols);
1497 GetSymbolsInObjectList(
1498 std::get<parser::OmpClause::From>(fromClause->u).v, fromSymbols);
1499 for (auto &[symbol, source] : toSymbols) {
1500 auto fromSymbol = fromSymbols.find(symbol);
1501 if (fromSymbol != fromSymbols.end()) {
1502 context_.Say(source,
1503 "A list item ('%s') can only appear in a TO or FROM clause, but not in both."_err_en_US,
1504 symbol->name());
1505 context_.Say(source, "'%s' appears in the TO clause."_because_en_US,
1506 symbol->name());
1507 context_.Say(fromSymbol->second,
1508 "'%s' appears in the FROM clause."_because_en_US,
1509 fromSymbol->first->name());
1510 }
1511 }
1512 }
1513 }
1514
1515 void OmpStructureChecker::Enter(
1516 const parser::OpenMPSimpleStandaloneConstruct &x) {
1517 const auto &dir{std::get<parser::OmpSimpleStandaloneDirective>(x.t)};
1518 PushContextAndClauseSets(dir.source, dir.v);
1519 CheckBarrierNesting(x);
1520 }
1521
1522 void OmpStructureChecker::Leave(
1523 const parser::OpenMPSimpleStandaloneConstruct &x) {
1524 switch (GetContext().directive) {
1525 case llvm::omp::Directive::OMPD_ordered:
1526 // [5.1] 2.19.9 Ordered Construct Restriction
1527 ChecksOnOrderedAsStandalone();
1528 break;
1529 case llvm::omp::Directive::OMPD_target_update:
1530 CheckTargetUpdate();
1531 break;
1532 default:
1533 break;
1534 }
1535 dirContext_.pop_back();
1536 }
1537
1538 void OmpStructureChecker::Enter(const parser::OpenMPFlushConstruct &x) {
1539 const auto &dir{std::get<parser::Verbatim>(x.t)};
1540 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_flush);
1541 }
1542
1543 void OmpStructureChecker::Leave(const parser::OpenMPFlushConstruct &x) {
1544 if (FindClause(llvm::omp::Clause::OMPC_acquire) ||
1545 FindClause(llvm::omp::Clause::OMPC_release) ||
1546 FindClause(llvm::omp::Clause::OMPC_acq_rel)) {
1547 if (const auto &flushList{
1548 std::get<std::optional<parser::OmpObjectList>>(x.t)}) {
1549 context_.Say(parser::FindSourceLocation(flushList),
1550 "If memory-order-clause is RELEASE, ACQUIRE, or ACQ_REL, list items "
1551 "must not be specified on the FLUSH directive"_err_en_US);
1552 }
1553 }
1554 dirContext_.pop_back();
1555 }
1556
1557 void OmpStructureChecker::Enter(const parser::OpenMPCancelConstruct &x) {
1558 const auto &dir{std::get<parser::Verbatim>(x.t)};
1559 const auto &type{std::get<parser::OmpCancelType>(x.t)};
1560 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_cancel);
1561 CheckCancellationNest(dir.source, type.v);
1562 }
1563
1564 void OmpStructureChecker::Leave(const parser::OpenMPCancelConstruct &) {
1565 dirContext_.pop_back();
1566 }
1567
1568 void OmpStructureChecker::Enter(const parser::OpenMPCriticalConstruct &x) {
1569 const auto &dir{std::get<parser::OmpCriticalDirective>(x.t)};
1570 const auto &endDir{std::get<parser::OmpEndCriticalDirective>(x.t)};
1571 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_critical);
1572 const auto &block{std::get<parser::Block>(x.t)};
1573 CheckNoBranching(block, llvm::omp::Directive::OMPD_critical, dir.source);
1574 const auto &dirName{std::get<std::optional<parser::Name>>(dir.t)};
1575 const auto &endDirName{std::get<std::optional<parser::Name>>(endDir.t)};
1576 const auto &ompClause{std::get<parser::OmpClauseList>(dir.t)};
1577 if (dirName && endDirName &&
1578 dirName->ToString().compare(endDirName->ToString())) {
1579 context_
1580 .Say(endDirName->source,
1581 parser::MessageFormattedText{
1582 "CRITICAL directive names do not match"_err_en_US})
1583 .Attach(dirName->source, "should be "_en_US);
1584 } else if (dirName && !endDirName) {
1585 context_
1586 .Say(dirName->source,
1587 parser::MessageFormattedText{
1588 "CRITICAL directive names do not match"_err_en_US})
1589 .Attach(dirName->source, "should be NULL"_en_US);
1590 } else if (!dirName && endDirName) {
1591 context_
1592 .Say(endDirName->source,
1593 parser::MessageFormattedText{
1594 "CRITICAL directive names do not match"_err_en_US})
1595 .Attach(endDirName->source, "should be NULL"_en_US);
1596 }
1597 if (!dirName && !ompClause.source.empty() &&
1598 ompClause.source.NULTerminatedToString() != "hint(omp_sync_hint_none)") {
1599 context_.Say(dir.source,
1600 parser::MessageFormattedText{
1601 "Hint clause other than omp_sync_hint_none cannot be specified for "
1602 "an unnamed CRITICAL directive"_err_en_US});
1603 }
1604 CheckHintClause<const parser::OmpClauseList>(&ompClause, nullptr);
1605 }
1606
1607 void OmpStructureChecker::Leave(const parser::OpenMPCriticalConstruct &) {
1608 dirContext_.pop_back();
1609 }
1610
1611 void OmpStructureChecker::Enter(
1612 const parser::OpenMPCancellationPointConstruct &x) {
1613 const auto &dir{std::get<parser::Verbatim>(x.t)};
1614 const auto &type{std::get<parser::OmpCancelType>(x.t)};
1615 PushContextAndClauseSets(
1616 dir.source, llvm::omp::Directive::OMPD_cancellation_point);
1617 CheckCancellationNest(dir.source, type.v);
1618 }
1619
1620 void OmpStructureChecker::Leave(
1621 const parser::OpenMPCancellationPointConstruct &) {
1622 dirContext_.pop_back();
1623 }
1624
1625 void OmpStructureChecker::CheckCancellationNest(
1626 const parser::CharBlock &source, const parser::OmpCancelType::Type &type) {
1627 if (CurrentDirectiveIsNested()) {
1628 // If construct-type-clause is taskgroup, the cancellation construct must be
1629 // closely nested inside a task or a taskloop construct and the cancellation
1630 // region must be closely nested inside a taskgroup region. If
1631 // construct-type-clause is sections, the cancellation construct must be
1632 // closely nested inside a sections or section construct. Otherwise, the
1633 // cancellation construct must be closely nested inside an OpenMP construct
1634 // that matches the type specified in construct-type-clause of the
1635 // cancellation construct.
1636 bool eligibleCancellation{false};
1637 switch (type) {
1638 case parser::OmpCancelType::Type::Taskgroup:
1639 if (llvm::omp::nestedCancelTaskgroupAllowedSet.test(
1640 GetContextParent().directive)) {
1641 eligibleCancellation = true;
1642 if (dirContext_.size() >= 3) {
1643 // Check if the cancellation region is closely nested inside a
1644 // taskgroup region when there are more than two levels of directives
1645 // in the directive context stack.
1646 if (GetContextParent().directive == llvm::omp::Directive::OMPD_task ||
1647 FindClauseParent(llvm::omp::Clause::OMPC_nogroup)) {
1648 for (int i = dirContext_.size() - 3; i >= 0; i--) {
1649 if (dirContext_[i].directive ==
1650 llvm::omp::Directive::OMPD_taskgroup) {
1651 break;
1652 }
1653 if (llvm::omp::nestedCancelParallelAllowedSet.test(
1654 dirContext_[i].directive)) {
1655 eligibleCancellation = false;
1656 break;
1657 }
1658 }
1659 }
1660 }
1661 }
1662 if (!eligibleCancellation) {
1663 context_.Say(source,
1664 "With %s clause, %s construct must be closely nested inside TASK "
1665 "or TASKLOOP construct and %s region must be closely nested inside "
1666 "TASKGROUP region"_err_en_US,
1667 parser::ToUpperCaseLetters(
1668 parser::OmpCancelType::EnumToString(type)),
1669 ContextDirectiveAsFortran(), ContextDirectiveAsFortran());
1670 }
1671 return;
1672 case parser::OmpCancelType::Type::Sections:
1673 if (llvm::omp::nestedCancelSectionsAllowedSet.test(
1674 GetContextParent().directive)) {
1675 eligibleCancellation = true;
1676 }
1677 break;
1678 case Fortran::parser::OmpCancelType::Type::Do:
1679 if (llvm::omp::nestedCancelDoAllowedSet.test(
1680 GetContextParent().directive)) {
1681 eligibleCancellation = true;
1682 }
1683 break;
1684 case parser::OmpCancelType::Type::Parallel:
1685 if (llvm::omp::nestedCancelParallelAllowedSet.test(
1686 GetContextParent().directive)) {
1687 eligibleCancellation = true;
1688 }
1689 break;
1690 }
1691 if (!eligibleCancellation) {
1692 context_.Say(source,
1693 "With %s clause, %s construct cannot be closely nested inside %s "
1694 "construct"_err_en_US,
1695 parser::ToUpperCaseLetters(parser::OmpCancelType::EnumToString(type)),
1696 ContextDirectiveAsFortran(),
1697 parser::ToUpperCaseLetters(
1698 getDirectiveName(GetContextParent().directive).str()));
1699 }
1700 } else {
1701 // The cancellation directive cannot be orphaned.
1702 switch (type) {
1703 case parser::OmpCancelType::Type::Taskgroup:
1704 context_.Say(source,
1705 "%s %s directive is not closely nested inside "
1706 "TASK or TASKLOOP"_err_en_US,
1707 ContextDirectiveAsFortran(),
1708 parser::ToUpperCaseLetters(
1709 parser::OmpCancelType::EnumToString(type)));
1710 break;
1711 case parser::OmpCancelType::Type::Sections:
1712 context_.Say(source,
1713 "%s %s directive is not closely nested inside "
1714 "SECTION or SECTIONS"_err_en_US,
1715 ContextDirectiveAsFortran(),
1716 parser::ToUpperCaseLetters(
1717 parser::OmpCancelType::EnumToString(type)));
1718 break;
1719 case Fortran::parser::OmpCancelType::Type::Do:
1720 context_.Say(source,
1721 "%s %s directive is not closely nested inside "
1722 "the construct that matches the DO clause type"_err_en_US,
1723 ContextDirectiveAsFortran(),
1724 parser::ToUpperCaseLetters(
1725 parser::OmpCancelType::EnumToString(type)));
1726 break;
1727 case parser::OmpCancelType::Type::Parallel:
1728 context_.Say(source,
1729 "%s %s directive is not closely nested inside "
1730 "the construct that matches the PARALLEL clause type"_err_en_US,
1731 ContextDirectiveAsFortran(),
1732 parser::ToUpperCaseLetters(
1733 parser::OmpCancelType::EnumToString(type)));
1734 break;
1735 }
1736 }
1737 }
1738
1739 void OmpStructureChecker::Enter(const parser::OmpEndBlockDirective &x) {
1740 const auto &dir{std::get<parser::OmpBlockDirective>(x.t)};
1741 ResetPartialContext(dir.source);
1742 switch (dir.v) {
1743 // 2.7.3 end-single-clause -> copyprivate-clause |
1744 // nowait-clause
1745 case llvm::omp::Directive::OMPD_single:
1746 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_end_single);
1747 break;
1748 // 2.7.4 end-workshare -> END WORKSHARE [nowait-clause]
1749 case llvm::omp::Directive::OMPD_workshare:
1750 PushContextAndClauseSets(
1751 dir.source, llvm::omp::Directive::OMPD_end_workshare);
1752 break;
1753 default:
1754 // no clauses are allowed
1755 break;
1756 }
1757 }
1758
1759 // TODO: Verify the popping of dirContext requirement after nowait
1760 // implementation, as there is an implicit barrier at the end of the worksharing
1761 // constructs unless a nowait clause is specified. Only OMPD_end_single and
1762 // end_workshareare popped as they are pushed while entering the
1763 // EndBlockDirective.
1764 void OmpStructureChecker::Leave(const parser::OmpEndBlockDirective &x) {
1765 if ((GetContext().directive == llvm::omp::Directive::OMPD_end_single) ||
1766 (GetContext().directive == llvm::omp::Directive::OMPD_end_workshare)) {
1767 dirContext_.pop_back();
1768 }
1769 }
1770
1771 inline void OmpStructureChecker::ErrIfAllocatableVariable(
1772 const parser::Variable &var) {
1773 // Err out if the given symbol has
1774 // ALLOCATABLE attribute
1775 if (const auto *e{GetExpr(context_, var)})
1776 for (const Symbol &symbol : evaluate::CollectSymbols(*e))
1777 if (IsAllocatable(symbol)) {
1778 const auto &designator =
1779 std::get<common::Indirection<parser::Designator>>(var.u);
1780 const auto *dataRef =
1781 std::get_if<Fortran::parser::DataRef>(&designator.value().u);
1782 const Fortran::parser::Name *name =
1783 dataRef ? std::get_if<Fortran::parser::Name>(&dataRef->u) : nullptr;
1784 if (name)
1785 context_.Say(name->source,
1786 "%s must not have ALLOCATABLE "
1787 "attribute"_err_en_US,
1788 name->ToString());
1789 }
1790 }
1791
1792 inline void OmpStructureChecker::ErrIfLHSAndRHSSymbolsMatch(
1793 const parser::Variable &var, const parser::Expr &expr) {
1794 // Err out if the symbol on the LHS is also used on the RHS of the assignment
1795 // statement
1796 const auto *e{GetExpr(context_, expr)};
1797 const auto *v{GetExpr(context_, var)};
1798 if (e && v) {
1799 const Symbol &varSymbol = evaluate::GetSymbolVector(*v).front();
1800 for (const Symbol &symbol : evaluate::GetSymbolVector(*e)) {
1801 if (varSymbol == symbol) {
1802 context_.Say(expr.source,
1803 "RHS expression "
1804 "on atomic assignment statement"
1805 " cannot access '%s'"_err_en_US,
1806 var.GetSource().ToString());
1807 }
1808 }
1809 }
1810 }
1811
1812 inline void OmpStructureChecker::ErrIfNonScalarAssignmentStmt(
1813 const parser::Variable &var, const parser::Expr &expr) {
1814 // Err out if either the variable on the LHS or the expression on the RHS of
1815 // the assignment statement are non-scalar (i.e. have rank > 0)
1816 const auto *e{GetExpr(context_, expr)};
1817 const auto *v{GetExpr(context_, var)};
1818 if (e && v) {
1819 if (e->Rank() != 0)
1820 context_.Say(expr.source,
1821 "Expected scalar expression "
1822 "on the RHS of atomic assignment "
1823 "statement"_err_en_US);
1824 if (v->Rank() != 0)
1825 context_.Say(var.GetSource(),
1826 "Expected scalar variable "
1827 "on the LHS of atomic assignment "
1828 "statement"_err_en_US);
1829 }
1830 }
1831
1832 template <typename T, typename D>
1833 bool OmpStructureChecker::IsOperatorValid(const T &node, const D &variable) {
1834 using AllowedBinaryOperators =
1835 std::variant<parser::Expr::Add, parser::Expr::Multiply,
1836 parser::Expr::Subtract, parser::Expr::Divide, parser::Expr::AND,
1837 parser::Expr::OR, parser::Expr::EQV, parser::Expr::NEQV>;
1838 using BinaryOperators = std::variant<parser::Expr::Add,
1839 parser::Expr::Multiply, parser::Expr::Subtract, parser::Expr::Divide,
1840 parser::Expr::AND, parser::Expr::OR, parser::Expr::EQV,
1841 parser::Expr::NEQV, parser::Expr::Power, parser::Expr::Concat,
1842 parser::Expr::LT, parser::Expr::LE, parser::Expr::EQ, parser::Expr::NE,
1843 parser::Expr::GE, parser::Expr::GT>;
1844
1845 if constexpr (common::HasMember<T, BinaryOperators>) {
1846 const auto &variableName{variable.GetSource().ToString()};
1847 const auto &exprLeft{std::get<0>(node.t)};
1848 const auto &exprRight{std::get<1>(node.t)};
1849 if ((exprLeft.value().source.ToString() != variableName) &&
1850 (exprRight.value().source.ToString() != variableName)) {
1851 context_.Say(variable.GetSource(),
1852 "Atomic update statement should be of form "
1853 "`%s = %s operator expr` OR `%s = expr operator %s`"_err_en_US,
1854 variableName, variableName, variableName, variableName);
1855 }
1856 return common::HasMember<T, AllowedBinaryOperators>;
1857 }
1858 return false;
1859 }
1860
1861 void OmpStructureChecker::CheckAtomicCaptureStmt(
1862 const parser::AssignmentStmt &assignmentStmt) {
1863 const auto &var{std::get<parser::Variable>(assignmentStmt.t)};
1864 const auto &expr{std::get<parser::Expr>(assignmentStmt.t)};
1865 common::visit(
1866 common::visitors{
1867 [&](const common::Indirection<parser::Designator> &designator) {
1868 const auto *dataRef =
1869 std::get_if<Fortran::parser::DataRef>(&designator.value().u);
1870 const auto *name = dataRef
1871 ? std::get_if<Fortran::parser::Name>(&dataRef->u)
1872 : nullptr;
1873 if (name && IsAllocatable(*name->symbol))
1874 context_.Say(name->source,
1875 "%s must not have ALLOCATABLE "
1876 "attribute"_err_en_US,
1877 name->ToString());
1878 },
1879 [&](const auto &) {
1880 // Anything other than a `parser::Designator` is not allowed
1881 context_.Say(expr.source,
1882 "Expected scalar variable "
1883 "of intrinsic type on RHS of atomic "
1884 "assignment statement"_err_en_US);
1885 }},
1886 expr.u);
1887 ErrIfLHSAndRHSSymbolsMatch(var, expr);
1888 ErrIfNonScalarAssignmentStmt(var, expr);
1889 }
1890
1891 void OmpStructureChecker::CheckAtomicWriteStmt(
1892 const parser::AssignmentStmt &assignmentStmt) {
1893 const auto &var{std::get<parser::Variable>(assignmentStmt.t)};
1894 const auto &expr{std::get<parser::Expr>(assignmentStmt.t)};
1895 ErrIfAllocatableVariable(var);
1896 ErrIfLHSAndRHSSymbolsMatch(var, expr);
1897 ErrIfNonScalarAssignmentStmt(var, expr);
1898 }
1899
1900 void OmpStructureChecker::CheckAtomicUpdateStmt(
1901 const parser::AssignmentStmt &assignment) {
1902 const auto &expr{std::get<parser::Expr>(assignment.t)};
1903 const auto &var{std::get<parser::Variable>(assignment.t)};
1904 bool isIntrinsicProcedure{false};
1905 bool isValidOperator{false};
1906 common::visit(
1907 common::visitors{
1908 [&](const common::Indirection<parser::FunctionReference> &x) {
1909 isIntrinsicProcedure = true;
1910 const auto &procedureDesignator{
1911 std::get<parser::ProcedureDesignator>(x.value().v.t)};
1912 const parser::Name *name{
1913 std::get_if<parser::Name>(&procedureDesignator.u)};
1914 if (name &&
1915 !(name->source == "max" || name->source == "min" ||
1916 name->source == "iand" || name->source == "ior" ||
1917 name->source == "ieor")) {
1918 context_.Say(expr.source,
1919 "Invalid intrinsic procedure name in "
1920 "OpenMP ATOMIC (UPDATE) statement"_err_en_US);
1921 }
1922 },
1923 [&](const auto &x) {
1924 if (!IsOperatorValid(x, var)) {
1925 context_.Say(expr.source,
1926 "Invalid or missing operator in atomic update "
1927 "statement"_err_en_US);
1928 } else
1929 isValidOperator = true;
1930 },
1931 },
1932 expr.u);
1933 if (const auto *e{GetExpr(context_, expr)}) {
1934 const auto *v{GetExpr(context_, var)};
1935 if (e->Rank() != 0)
1936 context_.Say(expr.source,
1937 "Expected scalar expression "
1938 "on the RHS of atomic update assignment "
1939 "statement"_err_en_US);
1940 if (v->Rank() != 0)
1941 context_.Say(var.GetSource(),
1942 "Expected scalar variable "
1943 "on the LHS of atomic update assignment "
1944 "statement"_err_en_US);
1945 const Symbol &varSymbol = evaluate::GetSymbolVector(*v).front();
1946 int numOfSymbolMatches{0};
1947 SymbolVector exprSymbols = evaluate::GetSymbolVector(*e);
1948 for (const Symbol &symbol : exprSymbols) {
1949 if (varSymbol == symbol)
1950 numOfSymbolMatches++;
1951 }
1952 if (isIntrinsicProcedure) {
1953 std::string varName = var.GetSource().ToString();
1954 if (numOfSymbolMatches != 1)
1955 context_.Say(expr.source,
1956 "Intrinsic procedure"
1957 " arguments in atomic update statement"
1958 " must have exactly one occurence of '%s'"_err_en_US,
1959 varName);
1960 else if (varSymbol != exprSymbols.front() &&
1961 varSymbol != exprSymbols.back())
1962 context_.Say(expr.source,
1963 "Atomic update statement "
1964 "should be of the form `%s = intrinsic_procedure(%s, expr_list)` "
1965 "OR `%s = intrinsic_procedure(expr_list, %s)`"_err_en_US,
1966 varName, varName, varName, varName);
1967 } else if (isValidOperator) {
1968 if (numOfSymbolMatches != 1)
1969 context_.Say(expr.source,
1970 "Exactly one occurence of '%s' "
1971 "expected on the RHS of atomic update assignment statement"_err_en_US,
1972 var.GetSource().ToString());
1973 }
1974 }
1975
1976 ErrIfAllocatableVariable(var);
1977 }
1978
1979 void OmpStructureChecker::CheckAtomicMemoryOrderClause(
1980 const parser::OmpAtomicClauseList *leftHandClauseList,
1981 const parser::OmpAtomicClauseList *rightHandClauseList) {
1982 int numMemoryOrderClause = 0;
1983 auto checkForValidMemoryOrderClause =
1984 [&](const parser::OmpAtomicClauseList *clauseList) {
1985 for (const auto &clause : clauseList->v) {
1986 if (std::get_if<Fortran::parser::OmpMemoryOrderClause>(&clause.u)) {
1987 numMemoryOrderClause++;
1988 if (numMemoryOrderClause > 1) {
1989 context_.Say(clause.source,
1990 "More than one memory order clause not allowed on "
1991 "OpenMP Atomic construct"_err_en_US);
1992 return;
1993 }
1994 }
1995 }
1996 };
1997 if (leftHandClauseList) {
1998 checkForValidMemoryOrderClause(leftHandClauseList);
1999 }
2000 if (rightHandClauseList) {
2001 checkForValidMemoryOrderClause(rightHandClauseList);
2002 }
2003 }
2004
2005 void OmpStructureChecker::Enter(const parser::OpenMPAtomicConstruct &x) {
2006 common::visit(
2007 common::visitors{
2008 [&](const parser::OmpAtomic &atomicConstruct) {
2009 const auto &dir{std::get<parser::Verbatim>(atomicConstruct.t)};
2010 PushContextAndClauseSets(
2011 dir.source, llvm::omp::Directive::OMPD_atomic);
2012 CheckAtomicUpdateStmt(
2013 std::get<parser::Statement<parser::AssignmentStmt>>(
2014 atomicConstruct.t)
2015 .statement);
2016 CheckAtomicMemoryOrderClause(
2017 &std::get<parser::OmpAtomicClauseList>(atomicConstruct.t),
2018 nullptr);
2019 CheckHintClause<const parser::OmpAtomicClauseList>(
2020 &std::get<parser::OmpAtomicClauseList>(atomicConstruct.t),
2021 nullptr);
2022 },
2023 [&](const parser::OmpAtomicUpdate &atomicUpdate) {
2024 const auto &dir{std::get<parser::Verbatim>(atomicUpdate.t)};
2025 PushContextAndClauseSets(
2026 dir.source, llvm::omp::Directive::OMPD_atomic);
2027 CheckAtomicUpdateStmt(
2028 std::get<parser::Statement<parser::AssignmentStmt>>(
2029 atomicUpdate.t)
2030 .statement);
2031 CheckAtomicMemoryOrderClause(
2032 &std::get<0>(atomicUpdate.t), &std::get<2>(atomicUpdate.t));
2033 CheckHintClause<const parser::OmpAtomicClauseList>(
2034 &std::get<0>(atomicUpdate.t), &std::get<2>(atomicUpdate.t));
2035 },
2036 [&](const parser::OmpAtomicRead &atomicRead) {
2037 const auto &dir{std::get<parser::Verbatim>(atomicRead.t)};
2038 PushContextAndClauseSets(
2039 dir.source, llvm::omp::Directive::OMPD_atomic);
2040 CheckAtomicMemoryOrderClause(
2041 &std::get<0>(atomicRead.t), &std::get<2>(atomicRead.t));
2042 CheckHintClause<const parser::OmpAtomicClauseList>(
2043 &std::get<0>(atomicRead.t), &std::get<2>(atomicRead.t));
2044 CheckAtomicCaptureStmt(
2045 std::get<parser::Statement<parser::AssignmentStmt>>(
2046 atomicRead.t)
2047 .statement);
2048 },
2049 [&](const parser::OmpAtomicWrite &atomicWrite) {
2050 const auto &dir{std::get<parser::Verbatim>(atomicWrite.t)};
2051 PushContextAndClauseSets(
2052 dir.source, llvm::omp::Directive::OMPD_atomic);
2053 CheckAtomicMemoryOrderClause(
2054 &std::get<0>(atomicWrite.t), &std::get<2>(atomicWrite.t));
2055 CheckHintClause<const parser::OmpAtomicClauseList>(
2056 &std::get<0>(atomicWrite.t), &std::get<2>(atomicWrite.t));
2057 CheckAtomicWriteStmt(
2058 std::get<parser::Statement<parser::AssignmentStmt>>(
2059 atomicWrite.t)
2060 .statement);
2061 },
2062 [&](const auto &atomicConstruct) {
2063 const auto &dir{std::get<parser::Verbatim>(atomicConstruct.t)};
2064 PushContextAndClauseSets(
2065 dir.source, llvm::omp::Directive::OMPD_atomic);
2066 CheckAtomicMemoryOrderClause(&std::get<0>(atomicConstruct.t),
2067 &std::get<2>(atomicConstruct.t));
2068 CheckHintClause<const parser::OmpAtomicClauseList>(
2069 &std::get<0>(atomicConstruct.t),
2070 &std::get<2>(atomicConstruct.t));
2071 },
2072 },
2073 x.u);
2074 }
2075
2076 void OmpStructureChecker::Leave(const parser::OpenMPAtomicConstruct &) {
2077 dirContext_.pop_back();
2078 }
2079
2080 // Clauses
2081 // Mainly categorized as
2082 // 1. Checks on 'OmpClauseList' from 'parse-tree.h'.
2083 // 2. Checks on clauses which fall under 'struct OmpClause' from parse-tree.h.
2084 // 3. Checks on clauses which are not in 'struct OmpClause' from parse-tree.h.
2085
2086 void OmpStructureChecker::Leave(const parser::OmpClauseList &) {
2087 // 2.7.1 Loop Construct Restriction
2088 if (llvm::omp::allDoSet.test(GetContext().directive)) {
2089 if (auto *clause{FindClause(llvm::omp::Clause::OMPC_schedule)}) {
2090 // only one schedule clause is allowed
2091 const auto &schedClause{std::get<parser::OmpClause::Schedule>(clause->u)};
2092 if (ScheduleModifierHasType(schedClause.v,
2093 parser::OmpScheduleModifierType::ModType::Nonmonotonic)) {
2094 if (FindClause(llvm::omp::Clause::OMPC_ordered)) {
2095 context_.Say(clause->source,
2096 "The NONMONOTONIC modifier cannot be specified "
2097 "if an ORDERED clause is specified"_err_en_US);
2098 }
2099 if (ScheduleModifierHasType(schedClause.v,
2100 parser::OmpScheduleModifierType::ModType::Monotonic)) {
2101 context_.Say(clause->source,
2102 "The MONOTONIC and NONMONOTONIC modifiers "
2103 "cannot be both specified"_err_en_US);
2104 }
2105 }
2106 }
2107
2108 if (auto *clause{FindClause(llvm::omp::Clause::OMPC_ordered)}) {
2109 // only one ordered clause is allowed
2110 const auto &orderedClause{
2111 std::get<parser::OmpClause::Ordered>(clause->u)};
2112
2113 if (orderedClause.v) {
2114 CheckNotAllowedIfClause(
2115 llvm::omp::Clause::OMPC_ordered, {llvm::omp::Clause::OMPC_linear});
2116
2117 if (auto *clause2{FindClause(llvm::omp::Clause::OMPC_collapse)}) {
2118 const auto &collapseClause{
2119 std::get<parser::OmpClause::Collapse>(clause2->u)};
2120 // ordered and collapse both have parameters
2121 if (const auto orderedValue{GetIntValue(orderedClause.v)}) {
2122 if (const auto collapseValue{GetIntValue(collapseClause.v)}) {
2123 if (*orderedValue > 0 && *orderedValue < *collapseValue) {
2124 context_.Say(clause->source,
2125 "The parameter of the ORDERED clause must be "
2126 "greater than or equal to "
2127 "the parameter of the COLLAPSE clause"_err_en_US);
2128 }
2129 }
2130 }
2131 }
2132 }
2133
2134 // TODO: ordered region binding check (requires nesting implementation)
2135 }
2136 } // doSet
2137
2138 // 2.8.1 Simd Construct Restriction
2139 if (llvm::omp::allSimdSet.test(GetContext().directive)) {
2140 if (auto *clause{FindClause(llvm::omp::Clause::OMPC_simdlen)}) {
2141 if (auto *clause2{FindClause(llvm::omp::Clause::OMPC_safelen)}) {
2142 const auto &simdlenClause{
2143 std::get<parser::OmpClause::Simdlen>(clause->u)};
2144 const auto &safelenClause{
2145 std::get<parser::OmpClause::Safelen>(clause2->u)};
2146 // simdlen and safelen both have parameters
2147 if (const auto simdlenValue{GetIntValue(simdlenClause.v)}) {
2148 if (const auto safelenValue{GetIntValue(safelenClause.v)}) {
2149 if (*safelenValue > 0 && *simdlenValue > *safelenValue) {
2150 context_.Say(clause->source,
2151 "The parameter of the SIMDLEN clause must be less than or "
2152 "equal to the parameter of the SAFELEN clause"_err_en_US);
2153 }
2154 }
2155 }
2156 }
2157 }
2158 // Sema checks related to presence of multiple list items within the same
2159 // clause
2160 CheckMultListItems();
2161 } // SIMD
2162
2163 // 2.7.3 Single Construct Restriction
2164 if (GetContext().directive == llvm::omp::Directive::OMPD_end_single) {
2165 CheckNotAllowedIfClause(
2166 llvm::omp::Clause::OMPC_copyprivate, {llvm::omp::Clause::OMPC_nowait});
2167 }
2168
2169 auto testThreadprivateVarErr = [&](Symbol sym, parser::Name name,
2170 llvmOmpClause clauseTy) {
2171 if (sym.test(Symbol::Flag::OmpThreadprivate))
2172 context_.Say(name.source,
2173 "A THREADPRIVATE variable cannot be in %s clause"_err_en_US,
2174 parser::ToUpperCaseLetters(getClauseName(clauseTy).str()));
2175 };
2176
2177 // [5.1] 2.21.2 Threadprivate Directive Restriction
2178 OmpClauseSet threadprivateAllowedSet{llvm::omp::Clause::OMPC_copyin,
2179 llvm::omp::Clause::OMPC_copyprivate, llvm::omp::Clause::OMPC_schedule,
2180 llvm::omp::Clause::OMPC_num_threads, llvm::omp::Clause::OMPC_thread_limit,
2181 llvm::omp::Clause::OMPC_if};
2182 for (auto it : GetContext().clauseInfo) {
2183 llvmOmpClause type = it.first;
2184 const auto *clause = it.second;
2185 if (!threadprivateAllowedSet.test(type)) {
2186 if (const auto *objList{GetOmpObjectList(*clause)}) {
2187 for (const auto &ompObject : objList->v) {
2188 common::visit(
2189 common::visitors{
2190 [&](const parser::Designator &) {
2191 if (const auto *name{
2192 parser::Unwrap<parser::Name>(ompObject)}) {
2193 if (name->symbol) {
2194 testThreadprivateVarErr(
2195 name->symbol->GetUltimate(), *name, type);
2196 }
2197 }
2198 },
2199 [&](const parser::Name &name) {
2200 if (name.symbol) {
2201 for (const auto &mem :
2202 name.symbol->get<CommonBlockDetails>().objects()) {
2203 testThreadprivateVarErr(mem->GetUltimate(), name, type);
2204 break;
2205 }
2206 }
2207 },
2208 },
2209 ompObject.u);
2210 }
2211 }
2212 }
2213 }
2214
2215 CheckRequireAtLeastOneOf();
2216 }
2217
2218 void OmpStructureChecker::Enter(const parser::OmpClause &x) {
2219 SetContextClause(x);
2220 }
2221
2222 // Following clauses do not have a separate node in parse-tree.h.
2223 CHECK_SIMPLE_CLAUSE(AcqRel, OMPC_acq_rel)
2224 CHECK_SIMPLE_CLAUSE(Acquire, OMPC_acquire)
2225 CHECK_SIMPLE_CLAUSE(Affinity, OMPC_affinity)
2226 CHECK_SIMPLE_CLAUSE(Capture, OMPC_capture)
2227 CHECK_SIMPLE_CLAUSE(Default, OMPC_default)
2228 CHECK_SIMPLE_CLAUSE(Depobj, OMPC_depobj)
2229 CHECK_SIMPLE_CLAUSE(Destroy, OMPC_destroy)
2230 CHECK_SIMPLE_CLAUSE(Detach, OMPC_detach)
2231 CHECK_SIMPLE_CLAUSE(DeviceType, OMPC_device_type)
2232 CHECK_SIMPLE_CLAUSE(DistSchedule, OMPC_dist_schedule)
2233 CHECK_SIMPLE_CLAUSE(Exclusive, OMPC_exclusive)
2234 CHECK_SIMPLE_CLAUSE(Final, OMPC_final)
2235 CHECK_SIMPLE_CLAUSE(Flush, OMPC_flush)
2236 CHECK_SIMPLE_CLAUSE(From, OMPC_from)
2237 CHECK_SIMPLE_CLAUSE(Full, OMPC_full)
2238 CHECK_SIMPLE_CLAUSE(Hint, OMPC_hint)
2239 CHECK_SIMPLE_CLAUSE(InReduction, OMPC_in_reduction)
2240 CHECK_SIMPLE_CLAUSE(Inclusive, OMPC_inclusive)
2241 CHECK_SIMPLE_CLAUSE(Match, OMPC_match)
2242 CHECK_SIMPLE_CLAUSE(Nontemporal, OMPC_nontemporal)
2243 CHECK_SIMPLE_CLAUSE(Order, OMPC_order)
2244 CHECK_SIMPLE_CLAUSE(Read, OMPC_read)
2245 CHECK_SIMPLE_CLAUSE(Threadprivate, OMPC_threadprivate)
2246 CHECK_SIMPLE_CLAUSE(Threads, OMPC_threads)
2247 CHECK_SIMPLE_CLAUSE(Inbranch, OMPC_inbranch)
2248 CHECK_SIMPLE_CLAUSE(Link, OMPC_link)
2249 CHECK_SIMPLE_CLAUSE(Indirect, OMPC_indirect)
2250 CHECK_SIMPLE_CLAUSE(Mergeable, OMPC_mergeable)
2251 CHECK_SIMPLE_CLAUSE(Nogroup, OMPC_nogroup)
2252 CHECK_SIMPLE_CLAUSE(Notinbranch, OMPC_notinbranch)
2253 CHECK_SIMPLE_CLAUSE(Partial, OMPC_partial)
2254 CHECK_SIMPLE_CLAUSE(ProcBind, OMPC_proc_bind)
2255 CHECK_SIMPLE_CLAUSE(Release, OMPC_release)
2256 CHECK_SIMPLE_CLAUSE(Relaxed, OMPC_relaxed)
2257 CHECK_SIMPLE_CLAUSE(SeqCst, OMPC_seq_cst)
2258 CHECK_SIMPLE_CLAUSE(Simd, OMPC_simd)
2259 CHECK_SIMPLE_CLAUSE(Sizes, OMPC_sizes)
2260 CHECK_SIMPLE_CLAUSE(TaskReduction, OMPC_task_reduction)
2261 CHECK_SIMPLE_CLAUSE(To, OMPC_to)
2262 CHECK_SIMPLE_CLAUSE(Uniform, OMPC_uniform)
2263 CHECK_SIMPLE_CLAUSE(Unknown, OMPC_unknown)
2264 CHECK_SIMPLE_CLAUSE(Untied, OMPC_untied)
2265 CHECK_SIMPLE_CLAUSE(UsesAllocators, OMPC_uses_allocators)
2266 CHECK_SIMPLE_CLAUSE(Update, OMPC_update)
2267 CHECK_SIMPLE_CLAUSE(Write, OMPC_write)
2268 CHECK_SIMPLE_CLAUSE(Init, OMPC_init)
2269 CHECK_SIMPLE_CLAUSE(Use, OMPC_use)
2270 CHECK_SIMPLE_CLAUSE(Novariants, OMPC_novariants)
2271 CHECK_SIMPLE_CLAUSE(Nocontext, OMPC_nocontext)
2272 CHECK_SIMPLE_CLAUSE(At, OMPC_at)
2273 CHECK_SIMPLE_CLAUSE(Severity, OMPC_severity)
2274 CHECK_SIMPLE_CLAUSE(Message, OMPC_message)
2275 CHECK_SIMPLE_CLAUSE(Filter, OMPC_filter)
2276 CHECK_SIMPLE_CLAUSE(When, OMPC_when)
2277 CHECK_SIMPLE_CLAUSE(AdjustArgs, OMPC_adjust_args)
2278 CHECK_SIMPLE_CLAUSE(AppendArgs, OMPC_append_args)
2279 CHECK_SIMPLE_CLAUSE(MemoryOrder, OMPC_memory_order)
2280 CHECK_SIMPLE_CLAUSE(Bind, OMPC_bind)
2281 CHECK_SIMPLE_CLAUSE(Align, OMPC_align)
2282 CHECK_SIMPLE_CLAUSE(Compare, OMPC_compare)
2283 CHECK_SIMPLE_CLAUSE(CancellationConstructType, OMPC_cancellation_construct_type)
2284 CHECK_SIMPLE_CLAUSE(Doacross, OMPC_doacross)
2285 CHECK_SIMPLE_CLAUSE(OmpxAttribute, OMPC_ompx_attribute)
2286 CHECK_SIMPLE_CLAUSE(OmpxBare, OMPC_ompx_bare)
2287 CHECK_SIMPLE_CLAUSE(Enter, OMPC_enter)
2288 CHECK_SIMPLE_CLAUSE(Fail, OMPC_fail)
2289 CHECK_SIMPLE_CLAUSE(Weak, OMPC_weak)
2290
2291 CHECK_REQ_SCALAR_INT_CLAUSE(Grainsize, OMPC_grainsize)
2292 CHECK_REQ_SCALAR_INT_CLAUSE(NumTasks, OMPC_num_tasks)
2293 CHECK_REQ_SCALAR_INT_CLAUSE(NumTeams, OMPC_num_teams)
2294 CHECK_REQ_SCALAR_INT_CLAUSE(NumThreads, OMPC_num_threads)
2295 CHECK_REQ_SCALAR_INT_CLAUSE(OmpxDynCgroupMem, OMPC_ompx_dyn_cgroup_mem)
2296 CHECK_REQ_SCALAR_INT_CLAUSE(Priority, OMPC_priority)
2297 CHECK_REQ_SCALAR_INT_CLAUSE(ThreadLimit, OMPC_thread_limit)
2298
2299 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Collapse, OMPC_collapse)
2300 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Safelen, OMPC_safelen)
2301 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Simdlen, OMPC_simdlen)
2302
2303 // Restrictions specific to each clause are implemented apart from the
2304 // generalized restrictions.
2305 void OmpStructureChecker::Enter(const parser::OmpClause::Reduction &x) {
2306 CheckAllowed(llvm::omp::Clause::OMPC_reduction);
2307 if (CheckReductionOperators(x)) {
2308 CheckReductionTypeList(x);
2309 }
2310 CheckReductionModifier(x);
2311 }
2312
2313 bool OmpStructureChecker::CheckReductionOperators(
2314 const parser::OmpClause::Reduction &x) {
2315
2316 const auto &definedOp{std::get<parser::OmpReductionOperator>(x.v.t)};
2317 bool ok = false;
2318 common::visit(
2319 common::visitors{
2320 [&](const parser::DefinedOperator &dOpr) {
2321 if (const auto *intrinsicOp{
2322 std::get_if<parser::DefinedOperator::IntrinsicOperator>(
2323 &dOpr.u)}) {
2324 ok = CheckIntrinsicOperator(*intrinsicOp);
2325 } else {
2326 context_.Say(GetContext().clauseSource,
2327 "Invalid reduction operator in REDUCTION clause."_err_en_US,
2328 ContextDirectiveAsFortran());
2329 }
2330 },
2331 [&](const parser::ProcedureDesignator &procD) {
2332 const parser::Name *name{std::get_if<parser::Name>(&procD.u)};
2333 if (name && name->symbol) {
2334 const SourceName &realName{name->symbol->GetUltimate().name()};
2335 if (realName == "max" || realName == "min" ||
2336 realName == "iand" || realName == "ior" ||
2337 realName == "ieor") {
2338 ok = true;
2339 }
2340 }
2341 if (!ok) {
2342 context_.Say(GetContext().clauseSource,
2343 "Invalid reduction identifier in REDUCTION "
2344 "clause."_err_en_US,
2345 ContextDirectiveAsFortran());
2346 }
2347 },
2348 },
2349 definedOp.u);
2350
2351 return ok;
2352 }
2353 bool OmpStructureChecker::CheckIntrinsicOperator(
2354 const parser::DefinedOperator::IntrinsicOperator &op) {
2355
2356 switch (op) {
2357 case parser::DefinedOperator::IntrinsicOperator::Add:
2358 case parser::DefinedOperator::IntrinsicOperator::Multiply:
2359 case parser::DefinedOperator::IntrinsicOperator::AND:
2360 case parser::DefinedOperator::IntrinsicOperator::OR:
2361 case parser::DefinedOperator::IntrinsicOperator::EQV:
2362 case parser::DefinedOperator::IntrinsicOperator::NEQV:
2363 return true;
2364 case parser::DefinedOperator::IntrinsicOperator::Subtract:
2365 context_.Say(GetContext().clauseSource,
2366 "The minus reduction operator is deprecated since OpenMP 5.2 and is "
2367 "not supported in the REDUCTION clause."_err_en_US,
2368 ContextDirectiveAsFortran());
2369 break;
2370 default:
2371 context_.Say(GetContext().clauseSource,
2372 "Invalid reduction operator in REDUCTION clause."_err_en_US,
2373 ContextDirectiveAsFortran());
2374 }
2375 return false;
2376 }
2377
2378 static bool IsReductionAllowedForType(
2379 const parser::OmpClause::Reduction &x, const DeclTypeSpec &type) {
2380 const auto &definedOp{std::get<parser::OmpReductionOperator>(x.v.t)};
2381 // TODO: user defined reduction operators. Just allow everything for now.
2382 bool ok{true};
2383
2384 auto IsLogical{[](const DeclTypeSpec &type) -> bool {
2385 return type.category() == DeclTypeSpec::Logical;
2386 }};
2387 auto IsCharacter{[](const DeclTypeSpec &type) -> bool {
2388 return type.category() == DeclTypeSpec::Character;
2389 }};
2390
2391 common::visit(
2392 common::visitors{
2393 [&](const parser::DefinedOperator &dOpr) {
2394 if (const auto *intrinsicOp{
2395 std::get_if<parser::DefinedOperator::IntrinsicOperator>(
2396 &dOpr.u)}) {
2397 // OMP5.2: The type [...] of a list item that appears in a
2398 // reduction clause must be valid for the combiner expression
2399 // See F2023: Table 10.2
2400 // .LT., .LE., .GT., .GE. are handled as procedure designators
2401 // below.
2402 switch (*intrinsicOp) {
2403 case parser::DefinedOperator::IntrinsicOperator::Multiply:
2404 [[fallthrough]];
2405 case parser::DefinedOperator::IntrinsicOperator::Add:
2406 [[fallthrough]];
2407 case parser::DefinedOperator::IntrinsicOperator::Subtract:
2408 ok = type.IsNumeric(TypeCategory::Integer) ||
2409 type.IsNumeric(TypeCategory::Real) ||
2410 type.IsNumeric(TypeCategory::Complex);
2411 break;
2412
2413 case parser::DefinedOperator::IntrinsicOperator::AND:
2414 [[fallthrough]];
2415 case parser::DefinedOperator::IntrinsicOperator::OR:
2416 [[fallthrough]];
2417 case parser::DefinedOperator::IntrinsicOperator::EQV:
2418 [[fallthrough]];
2419 case parser::DefinedOperator::IntrinsicOperator::NEQV:
2420 ok = IsLogical(type);
2421 break;
2422
2423 // Reduction identifier is not in OMP5.2 Table 5.2
2424 default:
2425 DIE("This should have been caught in CheckIntrinsicOperator");
2426 ok = false;
2427 break;
2428 }
2429 }
2430 },
2431 [&](const parser::ProcedureDesignator &procD) {
2432 const parser::Name *name{std::get_if<parser::Name>(&procD.u)};
2433 if (name && name->symbol) {
2434 const SourceName &realName{name->symbol->GetUltimate().name()};
2435 // OMP5.2: The type [...] of a list item that appears in a
2436 // reduction clause must be valid for the combiner expression
2437 if (realName == "iand" || realName == "ior" ||
2438 realName == "ieor") {
2439 // IAND: arguments must be integers: F2023 16.9.100
2440 // IEOR: arguments must be integers: F2023 16.9.106
2441 // IOR: arguments must be integers: F2023 16.9.111
2442 ok = type.IsNumeric(TypeCategory::Integer);
2443 } else if (realName == "max" || realName == "min") {
2444 // MAX: arguments must be integer, real, or character:
2445 // F2023 16.9.135
2446 // MIN: arguments must be integer, real, or character:
2447 // F2023 16.9.141
2448 ok = type.IsNumeric(TypeCategory::Integer) ||
2449 type.IsNumeric(TypeCategory::Real) || IsCharacter(type);
2450 }
2451 }
2452 },
2453 },
2454 definedOp.u);
2455
2456 return ok;
2457 }
2458
2459 void OmpStructureChecker::CheckReductionTypeList(
2460 const parser::OmpClause::Reduction &x) {
2461 const auto &ompObjectList{std::get<parser::OmpObjectList>(x.v.t)};
2462 CheckIntentInPointerAndDefinable(
2463 ompObjectList, llvm::omp::Clause::OMPC_reduction);
2464 CheckReductionArraySection(ompObjectList);
2465 // If this is a worksharing construct then ensure the reduction variable
2466 // is not private in the parallel region that it binds to.
2467 if (llvm::omp::nestedReduceWorkshareAllowedSet.test(GetContext().directive)) {
2468 CheckSharedBindingInOuterContext(ompObjectList);
2469 }
2470
2471 SymbolSourceMap symbols;
2472 GetSymbolsInObjectList(ompObjectList, symbols);
2473 for (auto &[symbol, source] : symbols) {
2474 if (IsProcedurePointer(*symbol)) {
2475 context_.Say(source,
2476 "A procedure pointer '%s' must not appear in a REDUCTION clause."_err_en_US,
2477 symbol->name());
2478 } else if (!IsReductionAllowedForType(x, DEREF(symbol->GetType()))) {
2479 context_.Say(source,
2480 "The type of '%s' is incompatible with the reduction operator."_err_en_US,
2481 symbol->name());
2482 }
2483 }
2484 }
2485
2486 void OmpStructureChecker::CheckReductionModifier(
2487 const parser::OmpClause::Reduction &x) {
2488 using ReductionModifier = parser::OmpReductionClause::ReductionModifier;
2489 const auto &maybeModifier{std::get<std::optional<ReductionModifier>>(x.v.t)};
2490 if (!maybeModifier || *maybeModifier == ReductionModifier::Default) {
2491 // No modifier, or the default one is always ok.
2492 return;
2493 }
2494 ReductionModifier modifier{*maybeModifier};
2495 const DirectiveContext &dirCtx{GetContext()};
2496 if (dirCtx.directive == llvm::omp::Directive::OMPD_loop) {
2497 // [5.2:257:33-34]
2498 // If a reduction-modifier is specified in a reduction clause that
2499 // appears on the directive, then the reduction modifier must be
2500 // default.
2501 context_.Say(GetContext().clauseSource,
2502 "REDUCTION modifier on LOOP directive must be DEFAULT"_err_en_US);
2503 }
2504 if (modifier == ReductionModifier::Task) {
2505 // "Task" is only allowed on worksharing or "parallel" directive.
2506 static llvm::omp::Directive worksharing[]{
2507 llvm::omp::Directive::OMPD_do, llvm::omp::Directive::OMPD_scope,
2508 llvm::omp::Directive::OMPD_sections,
2509 // There are more worksharing directives, but they do not apply:
2510 // "for" is C++ only,
2511 // "single" and "workshare" don't allow reduction clause,
2512 // "loop" has different restrictions (checked above).
2513 };
2514 if (dirCtx.directive != llvm::omp::Directive::OMPD_parallel &&
2515 !llvm::is_contained(worksharing, dirCtx.directive)) {
2516 context_.Say(GetContext().clauseSource,
2517 "Modifier 'TASK' on REDUCTION clause is only allowed with "
2518 "PARALLEL or worksharing directive"_err_en_US);
2519 }
2520 } else if (modifier == ReductionModifier::Inscan) {
2521 // "Inscan" is only allowed on worksharing-loop, worksharing-loop simd,
2522 // or "simd" directive.
2523 // The worksharing-loop directives are OMPD_do and OMPD_for. Only the
2524 // former is allowed in Fortran.
2525 switch (dirCtx.directive) {
2526 case llvm::omp::Directive::OMPD_do: // worksharing-loop
2527 case llvm::omp::Directive::OMPD_do_simd: // worksharing-loop simd
2528 case llvm::omp::Directive::OMPD_simd: // "simd"
2529 break;
2530 default:
2531 context_.Say(GetContext().clauseSource,
2532 "Modifier 'INSCAN' on REDUCTION clause is only allowed with "
2533 "worksharing-loop, worksharing-loop simd, "
2534 "or SIMD directive"_err_en_US);
2535 }
2536 } else {
2537 // Catch-all for potential future modifiers to make sure that this
2538 // function is up-to-date.
2539 context_.Say(GetContext().clauseSource,
2540 "Unexpected modifier on REDUCTION clause"_err_en_US);
2541 }
2542 }
2543
2544 void OmpStructureChecker::CheckIntentInPointerAndDefinable(
2545 const parser::OmpObjectList &objectList, const llvm::omp::Clause clause) {
2546 for (const auto &ompObject : objectList.v) {
2547 if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
2548 if (const auto *symbol{name->symbol}) {
2549 if (IsPointer(symbol->GetUltimate()) &&
2550 IsIntentIn(symbol->GetUltimate())) {
2551 context_.Say(GetContext().clauseSource,
2552 "Pointer '%s' with the INTENT(IN) attribute may not appear "
2553 "in a %s clause"_err_en_US,
2554 symbol->name(),
2555 parser::ToUpperCaseLetters(getClauseName(clause).str()));
2556 } else if (auto msg{WhyNotDefinable(name->source,
2557 context_.FindScope(name->source), DefinabilityFlags{},
2558 *symbol)}) {
2559 context_
2560 .Say(GetContext().clauseSource,
2561 "Variable '%s' on the %s clause is not definable"_err_en_US,
2562 symbol->name(),
2563 parser::ToUpperCaseLetters(getClauseName(clause).str()))
2564 .Attach(std::move(msg->set_severity(parser::Severity::Because)));
2565 }
2566 }
2567 }
2568 }
2569 }
2570
2571 void OmpStructureChecker::CheckReductionArraySection(
2572 const parser::OmpObjectList &ompObjectList) {
2573 for (const auto &ompObject : ompObjectList.v) {
2574 if (const auto *dataRef{parser::Unwrap<parser::DataRef>(ompObject)}) {
2575 if (const auto *arrayElement{
2576 parser::Unwrap<parser::ArrayElement>(ompObject)}) {
2577 if (arrayElement) {
2578 CheckArraySection(*arrayElement, GetLastName(*dataRef),
2579 llvm::omp::Clause::OMPC_reduction);
2580 }
2581 }
2582 }
2583 }
2584 }
2585
2586 void OmpStructureChecker::CheckSharedBindingInOuterContext(
2587 const parser::OmpObjectList &redObjectList) {
2588 // TODO: Verify the assumption here that the immediately enclosing region is
2589 // the parallel region to which the worksharing construct having reduction
2590 // binds to.
2591 if (auto *enclosingContext{GetEnclosingDirContext()}) {
2592 for (auto it : enclosingContext->clauseInfo) {
2593 llvmOmpClause type = it.first;
2594 const auto *clause = it.second;
2595 if (llvm::omp::privateReductionSet.test(type)) {
2596 if (const auto *objList{GetOmpObjectList(*clause)}) {
2597 for (const auto &ompObject : objList->v) {
2598 if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
2599 if (const auto *symbol{name->symbol}) {
2600 for (const auto &redOmpObject : redObjectList.v) {
2601 if (const auto *rname{
2602 parser::Unwrap<parser::Name>(redOmpObject)}) {
2603 if (const auto *rsymbol{rname->symbol}) {
2604 if (rsymbol->name() == symbol->name()) {
2605 context_.Say(GetContext().clauseSource,
2606 "%s variable '%s' is %s in outer context must"
2607 " be shared in the parallel regions to which any"
2608 " of the worksharing regions arising from the "
2609 "worksharing construct bind."_err_en_US,
2610 parser::ToUpperCaseLetters(
2611 getClauseName(llvm::omp::Clause::OMPC_reduction)
2612 .str()),
2613 symbol->name(),
2614 parser::ToUpperCaseLetters(
2615 getClauseName(type).str()));
2616 }
2617 }
2618 }
2619 }
2620 }
2621 }
2622 }
2623 }
2624 }
2625 }
2626 }
2627 }
2628
2629 void OmpStructureChecker::Enter(const parser::OmpClause::Ordered &x) {
2630 CheckAllowed(llvm::omp::Clause::OMPC_ordered);
2631 // the parameter of ordered clause is optional
2632 if (const auto &expr{x.v}) {
2633 RequiresConstantPositiveParameter(llvm::omp::Clause::OMPC_ordered, *expr);
2634 // 2.8.3 Loop SIMD Construct Restriction
2635 if (llvm::omp::allDoSimdSet.test(GetContext().directive)) {
2636 context_.Say(GetContext().clauseSource,
2637 "No ORDERED clause with a parameter can be specified "
2638 "on the %s directive"_err_en_US,
2639 ContextDirectiveAsFortran());
2640 }
2641 }
2642 }
2643
2644 void OmpStructureChecker::Enter(const parser::OmpClause::Shared &x) {
2645 CheckAllowed(llvm::omp::Clause::OMPC_shared);
2646 CheckIsVarPartOfAnotherVar(GetContext().clauseSource, x.v, "SHARED");
2647 }
2648 void OmpStructureChecker::Enter(const parser::OmpClause::Private &x) {
2649 CheckAllowed(llvm::omp::Clause::OMPC_private);
2650 CheckIsVarPartOfAnotherVar(GetContext().clauseSource, x.v, "PRIVATE");
2651 CheckIntentInPointer(x.v, llvm::omp::Clause::OMPC_private);
2652 }
2653
2654 void OmpStructureChecker::Enter(const parser::OmpClause::Nowait &x) {
2655 CheckAllowed(llvm::omp::Clause::OMPC_nowait);
2656 if (llvm::omp::noWaitClauseNotAllowedSet.test(GetContext().directive)) {
2657 context_.Say(GetContext().clauseSource,
2658 "%s clause is not allowed on the OMP %s directive,"
2659 " use it on OMP END %s directive "_err_en_US,
2660 parser::ToUpperCaseLetters(
2661 getClauseName(llvm::omp::Clause::OMPC_nowait).str()),
2662 parser::ToUpperCaseLetters(GetContext().directiveSource.ToString()),
2663 parser::ToUpperCaseLetters(GetContext().directiveSource.ToString()));
2664 }
2665 }
2666
2667 bool OmpStructureChecker::IsDataRefTypeParamInquiry(
2668 const parser::DataRef *dataRef) {
2669 bool dataRefIsTypeParamInquiry{false};
2670 if (const auto *structComp{
2671 parser::Unwrap<parser::StructureComponent>(dataRef)}) {
2672 if (const auto *compSymbol{structComp->component.symbol}) {
2673 if (const auto *compSymbolMiscDetails{
2674 std::get_if<MiscDetails>(&compSymbol->details())}) {
2675 const auto detailsKind = compSymbolMiscDetails->kind();
2676 dataRefIsTypeParamInquiry =
2677 (detailsKind == MiscDetails::Kind::KindParamInquiry ||
2678 detailsKind == MiscDetails::Kind::LenParamInquiry);
2679 } else if (compSymbol->has<TypeParamDetails>()) {
2680 dataRefIsTypeParamInquiry = true;
2681 }
2682 }
2683 }
2684 return dataRefIsTypeParamInquiry;
2685 }
2686
2687 void OmpStructureChecker::CheckIsVarPartOfAnotherVar(
2688 const parser::CharBlock &source, const parser::OmpObjectList &objList,
2689 llvm::StringRef clause) {
2690 for (const auto &ompObject : objList.v) {
2691 common::visit(
2692 common::visitors{
2693 [&](const parser::Designator &designator) {
2694 if (const auto *dataRef{
2695 std::get_if<parser::DataRef>(&designator.u)}) {
2696 if (IsDataRefTypeParamInquiry(dataRef)) {
2697 context_.Say(source,
2698 "A type parameter inquiry cannot appear on the %s "
2699 "directive"_err_en_US,
2700 ContextDirectiveAsFortran());
2701 } else if (parser::Unwrap<parser::StructureComponent>(
2702 ompObject) ||
2703 parser::Unwrap<parser::ArrayElement>(ompObject)) {
2704 if (llvm::omp::nonPartialVarSet.test(
2705 GetContext().directive)) {
2706 context_.Say(source,
2707 "A variable that is part of another variable (as an "
2708 "array or structure element) cannot appear on the %s "
2709 "directive"_err_en_US,
2710 ContextDirectiveAsFortran());
2711 } else {
2712 context_.Say(source,
2713 "A variable that is part of another variable (as an "
2714 "array or structure element) cannot appear in a "
2715 "%s clause"_err_en_US,
2716 clause.data());
2717 }
2718 }
2719 }
2720 },
2721 [&](const parser::Name &name) {},
2722 },
2723 ompObject.u);
2724 }
2725 }
2726
2727 void OmpStructureChecker::Enter(const parser::OmpClause::Firstprivate &x) {
2728 CheckAllowed(llvm::omp::Clause::OMPC_firstprivate);
2729
2730 CheckIsVarPartOfAnotherVar(GetContext().clauseSource, x.v, "FIRSTPRIVATE");
2731 CheckIsLoopIvPartOfClause(llvmOmpClause::OMPC_firstprivate, x.v);
2732
2733 SymbolSourceMap currSymbols;
2734 GetSymbolsInObjectList(x.v, currSymbols);
2735 CheckCopyingPolymorphicAllocatable(
2736 currSymbols, llvm::omp::Clause::OMPC_firstprivate);
2737
2738 DirectivesClauseTriple dirClauseTriple;
2739 // Check firstprivate variables in worksharing constructs
2740 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_do,
2741 std::make_pair(
2742 llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
2743 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_sections,
2744 std::make_pair(
2745 llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
2746 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_single,
2747 std::make_pair(
2748 llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
2749 // Check firstprivate variables in distribute construct
2750 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_distribute,
2751 std::make_pair(
2752 llvm::omp::Directive::OMPD_teams, llvm::omp::privateReductionSet));
2753 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_distribute,
2754 std::make_pair(llvm::omp::Directive::OMPD_target_teams,
2755 llvm::omp::privateReductionSet));
2756 // Check firstprivate variables in task and taskloop constructs
2757 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_task,
2758 std::make_pair(llvm::omp::Directive::OMPD_parallel,
2759 OmpClauseSet{llvm::omp::Clause::OMPC_reduction}));
2760 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_taskloop,
2761 std::make_pair(llvm::omp::Directive::OMPD_parallel,
2762 OmpClauseSet{llvm::omp::Clause::OMPC_reduction}));
2763
2764 CheckPrivateSymbolsInOuterCxt(
2765 currSymbols, dirClauseTriple, llvm::omp::Clause::OMPC_firstprivate);
2766 }
2767
2768 void OmpStructureChecker::CheckIsLoopIvPartOfClause(
2769 llvmOmpClause clause, const parser::OmpObjectList &ompObjectList) {
2770 for (const auto &ompObject : ompObjectList.v) {
2771 if (const parser::Name * name{parser::Unwrap<parser::Name>(ompObject)}) {
2772 if (name->symbol == GetContext().loopIV) {
2773 context_.Say(name->source,
2774 "DO iteration variable %s is not allowed in %s clause."_err_en_US,
2775 name->ToString(),
2776 parser::ToUpperCaseLetters(getClauseName(clause).str()));
2777 }
2778 }
2779 }
2780 }
2781 // Following clauses have a separate node in parse-tree.h.
2782 // Atomic-clause
2783 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicRead, OMPC_read)
2784 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicWrite, OMPC_write)
2785 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicUpdate, OMPC_update)
2786 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicCapture, OMPC_capture)
2787
2788 void OmpStructureChecker::Leave(const parser::OmpAtomicRead &) {
2789 CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_read,
2790 {llvm::omp::Clause::OMPC_release, llvm::omp::Clause::OMPC_acq_rel});
2791 }
2792 void OmpStructureChecker::Leave(const parser::OmpAtomicWrite &) {
2793 CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_write,
2794 {llvm::omp::Clause::OMPC_acquire, llvm::omp::Clause::OMPC_acq_rel});
2795 }
2796 void OmpStructureChecker::Leave(const parser::OmpAtomicUpdate &) {
2797 CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_update,
2798 {llvm::omp::Clause::OMPC_acquire, llvm::omp::Clause::OMPC_acq_rel});
2799 }
2800 // OmpAtomic node represents atomic directive without atomic-clause.
2801 // atomic-clause - READ,WRITE,UPDATE,CAPTURE.
2802 void OmpStructureChecker::Leave(const parser::OmpAtomic &) {
2803 if (const auto *clause{FindClause(llvm::omp::Clause::OMPC_acquire)}) {
2804 context_.Say(clause->source,
2805 "Clause ACQUIRE is not allowed on the ATOMIC directive"_err_en_US);
2806 }
2807 if (const auto *clause{FindClause(llvm::omp::Clause::OMPC_acq_rel)}) {
2808 context_.Say(clause->source,
2809 "Clause ACQ_REL is not allowed on the ATOMIC directive"_err_en_US);
2810 }
2811 }
2812 // Restrictions specific to each clause are implemented apart from the
2813 // generalized restrictions.
2814 void OmpStructureChecker::Enter(const parser::OmpClause::Aligned &x) {
2815 CheckAllowed(llvm::omp::Clause::OMPC_aligned);
2816
2817 if (const auto &expr{
2818 std::get<std::optional<parser::ScalarIntConstantExpr>>(x.v.t)}) {
2819 RequiresConstantPositiveParameter(llvm::omp::Clause::OMPC_aligned, *expr);
2820 }
2821 // 2.8.1 TODO: list-item attribute check
2822 }
2823 void OmpStructureChecker::Enter(const parser::OmpClause::Defaultmap &x) {
2824 CheckAllowed(llvm::omp::Clause::OMPC_defaultmap);
2825 using VariableCategory = parser::OmpDefaultmapClause::VariableCategory;
2826 if (!std::get<std::optional<VariableCategory>>(x.v.t)) {
2827 context_.Say(GetContext().clauseSource,
2828 "The argument TOFROM:SCALAR must be specified on the DEFAULTMAP "
2829 "clause"_err_en_US);
2830 }
2831 }
2832 void OmpStructureChecker::Enter(const parser::OmpClause::If &x) {
2833 CheckAllowed(llvm::omp::Clause::OMPC_if);
2834 using dirNameModifier = parser::OmpIfClause::DirectiveNameModifier;
2835 // TODO Check that, when multiple 'if' clauses are applied to a combined
2836 // construct, at most one of them applies to each directive.
2837 static std::unordered_map<dirNameModifier, OmpDirectiveSet>
2838 dirNameModifierMap{{dirNameModifier::Parallel, llvm::omp::allParallelSet},
2839 {dirNameModifier::Simd, llvm::omp::allSimdSet},
2840 {dirNameModifier::Target, llvm::omp::allTargetSet},
2841 {dirNameModifier::TargetData,
2842 {llvm::omp::Directive::OMPD_target_data}},
2843 {dirNameModifier::TargetEnterData,
2844 {llvm::omp::Directive::OMPD_target_enter_data}},
2845 {dirNameModifier::TargetExitData,
2846 {llvm::omp::Directive::OMPD_target_exit_data}},
2847 {dirNameModifier::TargetUpdate,
2848 {llvm::omp::Directive::OMPD_target_update}},
2849 {dirNameModifier::Task, {llvm::omp::Directive::OMPD_task}},
2850 {dirNameModifier::Taskloop, llvm::omp::allTaskloopSet},
2851 {dirNameModifier::Teams, llvm::omp::allTeamsSet}};
2852 if (const auto &directiveName{
2853 std::get<std::optional<dirNameModifier>>(x.v.t)}) {
2854 auto search{dirNameModifierMap.find(*directiveName)};
2855 if (search == dirNameModifierMap.end() ||
2856 !search->second.test(GetContext().directive)) {
2857 context_
2858 .Say(GetContext().clauseSource,
2859 "Unmatched directive name modifier %s on the IF clause"_err_en_US,
2860 parser::ToUpperCaseLetters(
2861 parser::OmpIfClause::EnumToString(*directiveName)))
2862 .Attach(
2863 GetContext().directiveSource, "Cannot apply to directive"_en_US);
2864 }
2865 }
2866 }
2867
2868 void OmpStructureChecker::Enter(const parser::OmpClause::Linear &x) {
2869 CheckAllowed(llvm::omp::Clause::OMPC_linear);
2870
2871 // 2.7 Loop Construct Restriction
2872 if ((llvm::omp::allDoSet | llvm::omp::allSimdSet)
2873 .test(GetContext().directive)) {
2874 if (std::holds_alternative<parser::OmpLinearClause::WithModifier>(x.v.u)) {
2875 context_.Say(GetContext().clauseSource,
2876 "A modifier may not be specified in a LINEAR clause "
2877 "on the %s directive"_err_en_US,
2878 ContextDirectiveAsFortran());
2879 }
2880 }
2881 }
2882
2883 void OmpStructureChecker::CheckAllowedMapTypes(
2884 const parser::OmpMapType::Type &type,
2885 const std::list<parser::OmpMapType::Type> &allowedMapTypeList) {
2886 if (!llvm::is_contained(allowedMapTypeList, type)) {
2887 std::string commaSeparatedMapTypes;
2888 llvm::interleave(
2889 allowedMapTypeList.begin(), allowedMapTypeList.end(),
2890 [&](const parser::OmpMapType::Type &mapType) {
2891 commaSeparatedMapTypes.append(parser::ToUpperCaseLetters(
2892 parser::OmpMapType::EnumToString(mapType)));
2893 },
2894 [&] { commaSeparatedMapTypes.append(", "); });
2895 context_.Say(GetContext().clauseSource,
2896 "Only the %s map types are permitted "
2897 "for MAP clauses on the %s directive"_err_en_US,
2898 commaSeparatedMapTypes, ContextDirectiveAsFortran());
2899 }
2900 }
2901
2902 void OmpStructureChecker::Enter(const parser::OmpClause::Map &x) {
2903 CheckAllowed(llvm::omp::Clause::OMPC_map);
2904
2905 if (const auto &maptype{std::get<std::optional<parser::OmpMapType>>(x.v.t)}) {
2906 using Type = parser::OmpMapType::Type;
2907 const Type &type{std::get<Type>(maptype->t)};
2908 switch (GetContext().directive) {
2909 case llvm::omp::Directive::OMPD_target:
2910 case llvm::omp::Directive::OMPD_target_teams:
2911 case llvm::omp::Directive::OMPD_target_teams_distribute:
2912 case llvm::omp::Directive::OMPD_target_teams_distribute_simd:
2913 case llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do:
2914 case llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do_simd:
2915 case llvm::omp::Directive::OMPD_target_data:
2916 CheckAllowedMapTypes(
2917 type, {Type::To, Type::From, Type::Tofrom, Type::Alloc});
2918 break;
2919 case llvm::omp::Directive::OMPD_target_enter_data:
2920 CheckAllowedMapTypes(type, {Type::To, Type::Alloc});
2921 break;
2922 case llvm::omp::Directive::OMPD_target_exit_data:
2923 CheckAllowedMapTypes(type, {Type::From, Type::Release, Type::Delete});
2924 break;
2925 default:
2926 break;
2927 }
2928 }
2929 }
2930
2931 bool OmpStructureChecker::ScheduleModifierHasType(
2932 const parser::OmpScheduleClause &x,
2933 const parser::OmpScheduleModifierType::ModType &type) {
2934 const auto &modifier{
2935 std::get<std::optional<parser::OmpScheduleModifier>>(x.t)};
2936 if (modifier) {
2937 const auto &modType1{
2938 std::get<parser::OmpScheduleModifier::Modifier1>(modifier->t)};
2939 const auto &modType2{
2940 std::get<std::optional<parser::OmpScheduleModifier::Modifier2>>(
2941 modifier->t)};
2942 if (modType1.v.v == type || (modType2 && modType2->v.v == type)) {
2943 return true;
2944 }
2945 }
2946 return false;
2947 }
2948 void OmpStructureChecker::Enter(const parser::OmpClause::Schedule &x) {
2949 CheckAllowed(llvm::omp::Clause::OMPC_schedule);
2950 const parser::OmpScheduleClause &scheduleClause = x.v;
2951
2952 // 2.7 Loop Construct Restriction
2953 if (llvm::omp::allDoSet.test(GetContext().directive)) {
2954 const auto &kind{std::get<1>(scheduleClause.t)};
2955 const auto &chunk{std::get<2>(scheduleClause.t)};
2956 if (chunk) {
2957 if (kind == parser::OmpScheduleClause::ScheduleType::Runtime ||
2958 kind == parser::OmpScheduleClause::ScheduleType::Auto) {
2959 context_.Say(GetContext().clauseSource,
2960 "When SCHEDULE clause has %s specified, "
2961 "it must not have chunk size specified"_err_en_US,
2962 parser::ToUpperCaseLetters(
2963 parser::OmpScheduleClause::EnumToString(kind)));
2964 }
2965 if (const auto &chunkExpr{std::get<std::optional<parser::ScalarIntExpr>>(
2966 scheduleClause.t)}) {
2967 RequiresPositiveParameter(
2968 llvm::omp::Clause::OMPC_schedule, *chunkExpr, "chunk size");
2969 }
2970 }
2971
2972 if (ScheduleModifierHasType(scheduleClause,
2973 parser::OmpScheduleModifierType::ModType::Nonmonotonic)) {
2974 if (kind != parser::OmpScheduleClause::ScheduleType::Dynamic &&
2975 kind != parser::OmpScheduleClause::ScheduleType::Guided) {
2976 context_.Say(GetContext().clauseSource,
2977 "The NONMONOTONIC modifier can only be specified with "
2978 "SCHEDULE(DYNAMIC) or SCHEDULE(GUIDED)"_err_en_US);
2979 }
2980 }
2981 }
2982 }
2983
2984 void OmpStructureChecker::Enter(const parser::OmpClause::Device &x) {
2985 CheckAllowed(llvm::omp::Clause::OMPC_device);
2986 const parser::OmpDeviceClause &deviceClause = x.v;
2987 const auto &device{std::get<1>(deviceClause.t)};
2988 RequiresPositiveParameter(
2989 llvm::omp::Clause::OMPC_device, device, "device expression");
2990 std::optional<parser::OmpDeviceClause::DeviceModifier> modifier =
2991 std::get<0>(deviceClause.t);
2992 if (modifier &&
2993 *modifier == parser::OmpDeviceClause::DeviceModifier::Ancestor) {
2994 if (GetContext().directive != llvm::omp::OMPD_target) {
2995 context_.Say(GetContext().clauseSource,
2996 "The ANCESTOR device-modifier must not appear on the DEVICE clause on"
2997 " any directive other than the TARGET construct. Found on %s construct."_err_en_US,
2998 parser::ToUpperCaseLetters(getDirectiveName(GetContext().directive)));
2999 }
3000 }
3001 }
3002
3003 void OmpStructureChecker::Enter(const parser::OmpClause::Depend &x) {
3004 CheckAllowed(llvm::omp::Clause::OMPC_depend);
3005 if ((std::holds_alternative<parser::OmpDependClause::Source>(x.v.u) ||
3006 std::holds_alternative<parser::OmpDependClause::Sink>(x.v.u)) &&
3007 GetContext().directive != llvm::omp::OMPD_ordered) {
3008 context_.Say(GetContext().clauseSource,
3009 "DEPEND(SOURCE) or DEPEND(SINK : vec) can be used only with the ordered"
3010 " directive. Used here in the %s construct."_err_en_US,
3011 parser::ToUpperCaseLetters(getDirectiveName(GetContext().directive)));
3012 }
3013 if (const auto *inOut{std::get_if<parser::OmpDependClause::InOut>(&x.v.u)}) {
3014 const auto &designators{std::get<std::list<parser::Designator>>(inOut->t)};
3015 for (const auto &ele : designators) {
3016 if (const auto *dataRef{std::get_if<parser::DataRef>(&ele.u)}) {
3017 CheckDependList(*dataRef);
3018 if (const auto *arr{
3019 std::get_if<common::Indirection<parser::ArrayElement>>(
3020 &dataRef->u)}) {
3021 CheckArraySection(arr->value(), GetLastName(*dataRef),
3022 llvm::omp::Clause::OMPC_depend);
3023 }
3024 }
3025 }
3026 }
3027 }
3028
3029 void OmpStructureChecker::CheckCopyingPolymorphicAllocatable(
3030 SymbolSourceMap &symbols, const llvm::omp::Clause clause) {
3031 if (context_.ShouldWarn(common::UsageWarning::Portability)) {
3032 for (auto it{symbols.begin()}; it != symbols.end(); ++it) {
3033 const auto *symbol{it->first};
3034 const auto source{it->second};
3035 if (IsPolymorphicAllocatable(*symbol)) {
3036 context_.Say(source,
3037 "If a polymorphic variable with allocatable attribute '%s' is in "
3038 "%s clause, the behavior is unspecified"_port_en_US,
3039 symbol->name(),
3040 parser::ToUpperCaseLetters(getClauseName(clause).str()));
3041 }
3042 }
3043 }
3044 }
3045
3046 void OmpStructureChecker::Enter(const parser::OmpClause::Copyprivate &x) {
3047 CheckAllowed(llvm::omp::Clause::OMPC_copyprivate);
3048 CheckIntentInPointer(x.v, llvm::omp::Clause::OMPC_copyprivate);
3049 SymbolSourceMap currSymbols;
3050 GetSymbolsInObjectList(x.v, currSymbols);
3051 CheckCopyingPolymorphicAllocatable(
3052 currSymbols, llvm::omp::Clause::OMPC_copyprivate);
3053 if (GetContext().directive == llvm::omp::Directive::OMPD_single) {
3054 context_.Say(GetContext().clauseSource,
3055 "%s clause is not allowed on the OMP %s directive,"
3056 " use it on OMP END %s directive "_err_en_US,
3057 parser::ToUpperCaseLetters(
3058 getClauseName(llvm::omp::Clause::OMPC_copyprivate).str()),
3059 parser::ToUpperCaseLetters(GetContext().directiveSource.ToString()),
3060 parser::ToUpperCaseLetters(GetContext().directiveSource.ToString()));
3061 }
3062 }
3063
3064 void OmpStructureChecker::Enter(const parser::OmpClause::Lastprivate &x) {
3065 CheckAllowed(llvm::omp::Clause::OMPC_lastprivate);
3066
3067 CheckIsVarPartOfAnotherVar(GetContext().clauseSource, x.v, "LASTPRIVATE");
3068
3069 DirectivesClauseTriple dirClauseTriple;
3070 SymbolSourceMap currSymbols;
3071 GetSymbolsInObjectList(x.v, currSymbols);
3072 CheckDefinableObjects(currSymbols, GetClauseKindForParserClass(x));
3073 CheckCopyingPolymorphicAllocatable(
3074 currSymbols, llvm::omp::Clause::OMPC_lastprivate);
3075
3076 // Check lastprivate variables in worksharing constructs
3077 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_do,
3078 std::make_pair(
3079 llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
3080 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_sections,
3081 std::make_pair(
3082 llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
3083
3084 CheckPrivateSymbolsInOuterCxt(
3085 currSymbols, dirClauseTriple, GetClauseKindForParserClass(x));
3086 }
3087
3088 void OmpStructureChecker::Enter(const parser::OmpClause::Copyin &x) {
3089 CheckAllowed(llvm::omp::Clause::OMPC_copyin);
3090
3091 SymbolSourceMap currSymbols;
3092 GetSymbolsInObjectList(x.v, currSymbols);
3093 CheckCopyingPolymorphicAllocatable(
3094 currSymbols, llvm::omp::Clause::OMPC_copyin);
3095 }
3096
3097 void OmpStructureChecker::CheckStructureElement(
3098 const parser::OmpObjectList &ompObjectList,
3099 const llvm::omp::Clause clause) {
3100 for (const auto &ompObject : ompObjectList.v) {
3101 common::visit(
3102 common::visitors{
3103 [&](const parser::Designator &designator) {
3104 if (std::get_if<parser::DataRef>(&designator.u)) {
3105 if (parser::Unwrap<parser::StructureComponent>(ompObject)) {
3106 context_.Say(GetContext().clauseSource,
3107 "A variable that is part of another variable "
3108 "(structure element) cannot appear on the %s "
3109 "%s clause"_err_en_US,
3110 ContextDirectiveAsFortran(),
3111 parser::ToUpperCaseLetters(getClauseName(clause).str()));
3112 }
3113 }
3114 },
3115 [&](const parser::Name &name) {},
3116 },
3117 ompObject.u);
3118 }
3119 return;
3120 }
3121
3122 void OmpStructureChecker::Enter(const parser::OmpClause::UseDevicePtr &x) {
3123 CheckStructureElement(x.v, llvm::omp::Clause::OMPC_use_device_ptr);
3124 CheckAllowed(llvm::omp::Clause::OMPC_use_device_ptr);
3125 SymbolSourceMap currSymbols;
3126 GetSymbolsInObjectList(x.v, currSymbols);
3127 semantics::UnorderedSymbolSet listVars;
3128 auto useDevicePtrClauses{FindClauses(llvm::omp::Clause::OMPC_use_device_ptr)};
3129 for (auto itr = useDevicePtrClauses.first; itr != useDevicePtrClauses.second;
3130 ++itr) {
3131 const auto &useDevicePtrClause{
3132 std::get<parser::OmpClause::UseDevicePtr>(itr->second->u)};
3133 const auto &useDevicePtrList{useDevicePtrClause.v};
3134 std::list<parser::Name> useDevicePtrNameList;
3135 for (const auto &ompObject : useDevicePtrList.v) {
3136 if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
3137 if (name->symbol) {
3138 if (!(IsBuiltinCPtr(*(name->symbol)))) {
3139 if (context_.ShouldWarn(common::UsageWarning::OpenMPUsage)) {
3140 context_.Say(itr->second->source,
3141 "Use of non-C_PTR type '%s' in USE_DEVICE_PTR is deprecated, use USE_DEVICE_ADDR instead"_warn_en_US,
3142 name->ToString());
3143 }
3144 } else {
3145 useDevicePtrNameList.push_back(*name);
3146 }
3147 }
3148 }
3149 }
3150 CheckMultipleOccurrence(
3151 listVars, useDevicePtrNameList, itr->second->source, "USE_DEVICE_PTR");
3152 }
3153 }
3154
3155 void OmpStructureChecker::Enter(const parser::OmpClause::UseDeviceAddr &x) {
3156 CheckStructureElement(x.v, llvm::omp::Clause::OMPC_use_device_addr);
3157 CheckAllowed(llvm::omp::Clause::OMPC_use_device_addr);
3158 SymbolSourceMap currSymbols;
3159 GetSymbolsInObjectList(x.v, currSymbols);
3160 semantics::UnorderedSymbolSet listVars;
3161 auto useDeviceAddrClauses{
3162 FindClauses(llvm::omp::Clause::OMPC_use_device_addr)};
3163 for (auto itr = useDeviceAddrClauses.first;
3164 itr != useDeviceAddrClauses.second; ++itr) {
3165 const auto &useDeviceAddrClause{
3166 std::get<parser::OmpClause::UseDeviceAddr>(itr->second->u)};
3167 const auto &useDeviceAddrList{useDeviceAddrClause.v};
3168 std::list<parser::Name> useDeviceAddrNameList;
3169 for (const auto &ompObject : useDeviceAddrList.v) {
3170 if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
3171 if (name->symbol) {
3172 useDeviceAddrNameList.push_back(*name);
3173 }
3174 }
3175 }
3176 CheckMultipleOccurrence(listVars, useDeviceAddrNameList,
3177 itr->second->source, "USE_DEVICE_ADDR");
3178 }
3179 }
3180
3181 void OmpStructureChecker::Enter(const parser::OmpClause::IsDevicePtr &x) {
3182 CheckAllowed(llvm::omp::Clause::OMPC_is_device_ptr);
3183 SymbolSourceMap currSymbols;
3184 GetSymbolsInObjectList(x.v, currSymbols);
3185 semantics::UnorderedSymbolSet listVars;
3186 auto isDevicePtrClauses{FindClauses(llvm::omp::Clause::OMPC_is_device_ptr)};
3187 for (auto itr = isDevicePtrClauses.first; itr != isDevicePtrClauses.second;
3188 ++itr) {
3189 const auto &isDevicePtrClause{
3190 std::get<parser::OmpClause::IsDevicePtr>(itr->second->u)};
3191 const auto &isDevicePtrList{isDevicePtrClause.v};
3192 SymbolSourceMap currSymbols;
3193 GetSymbolsInObjectList(isDevicePtrList, currSymbols);
3194 for (auto &[symbol, source] : currSymbols) {
3195 if (!(IsBuiltinCPtr(*symbol))) {
3196 context_.Say(itr->second->source,
3197 "Variable '%s' in IS_DEVICE_PTR clause must be of type C_PTR"_err_en_US,
3198 source.ToString());
3199 } else if (!(IsDummy(*symbol))) {
3200 if (context_.ShouldWarn(common::UsageWarning::OpenMPUsage)) {
3201 context_.Say(itr->second->source,
3202 "Variable '%s' in IS_DEVICE_PTR clause must be a dummy argument. "
3203 "This semantic check is deprecated from OpenMP 5.2 and later."_warn_en_US,
3204 source.ToString());
3205 }
3206 } else if (IsAllocatableOrPointer(*symbol) || IsValue(*symbol)) {
3207 if (context_.ShouldWarn(common::UsageWarning::OpenMPUsage)) {
3208 context_.Say(itr->second->source,
3209 "Variable '%s' in IS_DEVICE_PTR clause must be a dummy argument "
3210 "that does not have the ALLOCATABLE, POINTER or VALUE attribute. "
3211 "This semantic check is deprecated from OpenMP 5.2 and later."_warn_en_US,
3212 source.ToString());
3213 }
3214 }
3215 }
3216 }
3217 }
3218
3219 void OmpStructureChecker::Enter(const parser::OmpClause::HasDeviceAddr &x) {
3220 CheckAllowed(llvm::omp::Clause::OMPC_has_device_addr);
3221 SymbolSourceMap currSymbols;
3222 GetSymbolsInObjectList(x.v, currSymbols);
3223 semantics::UnorderedSymbolSet listVars;
3224 auto hasDeviceAddrClauses{
3225 FindClauses(llvm::omp::Clause::OMPC_has_device_addr)};
3226 for (auto itr = hasDeviceAddrClauses.first;
3227 itr != hasDeviceAddrClauses.second; ++itr) {
3228 const auto &hasDeviceAddrClause{
3229 std::get<parser::OmpClause::HasDeviceAddr>(itr->second->u)};
3230 const auto &hasDeviceAddrList{hasDeviceAddrClause.v};
3231 std::list<parser::Name> hasDeviceAddrNameList;
3232 for (const auto &ompObject : hasDeviceAddrList.v) {
3233 if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
3234 if (name->symbol) {
3235 hasDeviceAddrNameList.push_back(*name);
3236 }
3237 }
3238 }
3239 }
3240 }
3241
3242 llvm::StringRef OmpStructureChecker::getClauseName(llvm::omp::Clause clause) {
3243 return llvm::omp::getOpenMPClauseName(clause);
3244 }
3245
3246 llvm::StringRef OmpStructureChecker::getDirectiveName(
3247 llvm::omp::Directive directive) {
3248 return llvm::omp::getOpenMPDirectiveName(directive);
3249 }
3250
3251 void OmpStructureChecker::CheckDependList(const parser::DataRef &d) {
3252 common::visit(
3253 common::visitors{
3254 [&](const common::Indirection<parser::ArrayElement> &elem) {
3255 // Check if the base element is valid on Depend Clause
3256 CheckDependList(elem.value().base);
3257 },
3258 [&](const common::Indirection<parser::StructureComponent> &) {
3259 context_.Say(GetContext().clauseSource,
3260 "A variable that is part of another variable "
3261 "(such as an element of a structure) but is not an array "
3262 "element or an array section cannot appear in a DEPEND "
3263 "clause"_err_en_US);
3264 },
3265 [&](const common::Indirection<parser::CoindexedNamedObject> &) {
3266 context_.Say(GetContext().clauseSource,
3267 "Coarrays are not supported in DEPEND clause"_err_en_US);
3268 },
3269 [&](const parser::Name &) { return; },
3270 },
3271 d.u);
3272 }
3273
3274 // Called from both Reduction and Depend clause.
3275 void OmpStructureChecker::CheckArraySection(
3276 const parser::ArrayElement &arrayElement, const parser::Name &name,
3277 const llvm::omp::Clause clause) {
3278 if (!arrayElement.subscripts.empty()) {
3279 for (const auto &subscript : arrayElement.subscripts) {
3280 if (const auto *triplet{
3281 std::get_if<parser::SubscriptTriplet>(&subscript.u)}) {
3282 if (std::get<0>(triplet->t) && std::get<1>(triplet->t)) {
3283 const auto &lower{std::get<0>(triplet->t)};
3284 const auto &upper{std::get<1>(triplet->t)};
3285 if (lower && upper) {
3286 const auto lval{GetIntValue(lower)};
3287 const auto uval{GetIntValue(upper)};
3288 if (lval && uval && *uval < *lval) {
3289 context_.Say(GetContext().clauseSource,
3290 "'%s' in %s clause"
3291 " is a zero size array section"_err_en_US,
3292 name.ToString(),
3293 parser::ToUpperCaseLetters(getClauseName(clause).str()));
3294 break;
3295 } else if (std::get<2>(triplet->t)) {
3296 const auto &strideExpr{std::get<2>(triplet->t)};
3297 if (strideExpr) {
3298 if (clause == llvm::omp::Clause::OMPC_depend) {
3299 context_.Say(GetContext().clauseSource,
3300 "Stride should not be specified for array section in "
3301 "DEPEND "
3302 "clause"_err_en_US);
3303 }
3304 const auto stride{GetIntValue(strideExpr)};
3305 if ((stride && stride != 1)) {
3306 context_.Say(GetContext().clauseSource,
3307 "A list item that appears in a REDUCTION clause"
3308 " should have a contiguous storage array "
3309 "section."_err_en_US,
3310 ContextDirectiveAsFortran());
3311 break;
3312 }
3313 }
3314 }
3315 }
3316 }
3317 }
3318 }
3319 }
3320 }
3321
3322 void OmpStructureChecker::CheckIntentInPointer(
3323 const parser::OmpObjectList &objectList, const llvm::omp::Clause clause) {
3324 SymbolSourceMap symbols;
3325 GetSymbolsInObjectList(objectList, symbols);
3326 for (auto it{symbols.begin()}; it != symbols.end(); ++it) {
3327 const auto *symbol{it->first};
3328 const auto source{it->second};
3329 if (IsPointer(*symbol) && IsIntentIn(*symbol)) {
3330 context_.Say(source,
3331 "Pointer '%s' with the INTENT(IN) attribute may not appear "
3332 "in a %s clause"_err_en_US,
3333 symbol->name(),
3334 parser::ToUpperCaseLetters(getClauseName(clause).str()));
3335 }
3336 }
3337 }
3338
3339 void OmpStructureChecker::GetSymbolsInObjectList(
3340 const parser::OmpObjectList &objectList, SymbolSourceMap &symbols) {
3341 for (const auto &ompObject : objectList.v) {
3342 if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
3343 if (const auto *symbol{name->symbol}) {
3344 if (const auto *commonBlockDetails{
3345 symbol->detailsIf<CommonBlockDetails>()}) {
3346 for (const auto &object : commonBlockDetails->objects()) {
3347 symbols.emplace(&object->GetUltimate(), name->source);
3348 }
3349 } else {
3350 symbols.emplace(&symbol->GetUltimate(), name->source);
3351 }
3352 }
3353 }
3354 }
3355 }
3356
3357 void OmpStructureChecker::CheckDefinableObjects(
3358 SymbolSourceMap &symbols, const llvm::omp::Clause clause) {
3359 for (auto it{symbols.begin()}; it != symbols.end(); ++it) {
3360 const auto *symbol{it->first};
3361 const auto source{it->second};
3362 if (auto msg{WhyNotDefinable(source, context_.FindScope(source),
3363 DefinabilityFlags{}, *symbol)}) {
3364 context_
3365 .Say(source,
3366 "Variable '%s' on the %s clause is not definable"_err_en_US,
3367 symbol->name(),
3368 parser::ToUpperCaseLetters(getClauseName(clause).str()))
3369 .Attach(std::move(msg->set_severity(parser::Severity::Because)));
3370 }
3371 }
3372 }
3373
3374 void OmpStructureChecker::CheckPrivateSymbolsInOuterCxt(
3375 SymbolSourceMap &currSymbols, DirectivesClauseTriple &dirClauseTriple,
3376 const llvm::omp::Clause currClause) {
3377 SymbolSourceMap enclosingSymbols;
3378 auto range{dirClauseTriple.equal_range(GetContext().directive)};
3379 for (auto dirIter{range.first}; dirIter != range.second; ++dirIter) {
3380 auto enclosingDir{dirIter->second.first};
3381 auto enclosingClauseSet{dirIter->second.second};
3382 if (auto *enclosingContext{GetEnclosingContextWithDir(enclosingDir)}) {
3383 for (auto it{enclosingContext->clauseInfo.begin()};
3384 it != enclosingContext->clauseInfo.end(); ++it) {
3385 if (enclosingClauseSet.test(it->first)) {
3386 if (const auto *ompObjectList{GetOmpObjectList(*it->second)}) {
3387 GetSymbolsInObjectList(*ompObjectList, enclosingSymbols);
3388 }
3389 }
3390 }
3391
3392 // Check if the symbols in current context are private in outer context
3393 for (auto iter{currSymbols.begin()}; iter != currSymbols.end(); ++iter) {
3394 const auto *symbol{iter->first};
3395 const auto source{iter->second};
3396 if (enclosingSymbols.find(symbol) != enclosingSymbols.end()) {
3397 context_.Say(source,
3398 "%s variable '%s' is PRIVATE in outer context"_err_en_US,
3399 parser::ToUpperCaseLetters(getClauseName(currClause).str()),
3400 symbol->name());
3401 }
3402 }
3403 }
3404 }
3405 }
3406
3407 bool OmpStructureChecker::CheckTargetBlockOnlyTeams(
3408 const parser::Block &block) {
3409 bool nestedTeams{false};
3410
3411 if (!block.empty()) {
3412 auto it{block.begin()};
3413 if (const auto *ompConstruct{
3414 parser::Unwrap<parser::OpenMPConstruct>(*it)}) {
3415 if (const auto *ompBlockConstruct{
3416 std::get_if<parser::OpenMPBlockConstruct>(&ompConstruct->u)}) {
3417 const auto &beginBlockDir{
3418 std::get<parser::OmpBeginBlockDirective>(ompBlockConstruct->t)};
3419 const auto &beginDir{
3420 std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
3421 if (beginDir.v == llvm::omp::Directive::OMPD_teams) {
3422 nestedTeams = true;
3423 }
3424 }
3425 }
3426
3427 if (nestedTeams && ++it == block.end()) {
3428 return true;
3429 }
3430 }
3431
3432 return false;
3433 }
3434
3435 void OmpStructureChecker::CheckWorkshareBlockStmts(
3436 const parser::Block &block, parser::CharBlock source) {
3437 OmpWorkshareBlockChecker ompWorkshareBlockChecker{context_, source};
3438
3439 for (auto it{block.begin()}; it != block.end(); ++it) {
3440 if (parser::Unwrap<parser::AssignmentStmt>(*it) ||
3441 parser::Unwrap<parser::ForallStmt>(*it) ||
3442 parser::Unwrap<parser::ForallConstruct>(*it) ||
3443 parser::Unwrap<parser::WhereStmt>(*it) ||
3444 parser::Unwrap<parser::WhereConstruct>(*it)) {
3445 parser::Walk(*it, ompWorkshareBlockChecker);
3446 } else if (const auto *ompConstruct{
3447 parser::Unwrap<parser::OpenMPConstruct>(*it)}) {
3448 if (const auto *ompAtomicConstruct{
3449 std::get_if<parser::OpenMPAtomicConstruct>(&ompConstruct->u)}) {
3450 // Check if assignment statements in the enclosing OpenMP Atomic
3451 // construct are allowed in the Workshare construct
3452 parser::Walk(*ompAtomicConstruct, ompWorkshareBlockChecker);
3453 } else if (const auto *ompCriticalConstruct{
3454 std::get_if<parser::OpenMPCriticalConstruct>(
3455 &ompConstruct->u)}) {
3456 // All the restrictions on the Workshare construct apply to the
3457 // statements in the enclosing critical constructs
3458 const auto &criticalBlock{
3459 std::get<parser::Block>(ompCriticalConstruct->t)};
3460 CheckWorkshareBlockStmts(criticalBlock, source);
3461 } else {
3462 // Check if OpenMP constructs enclosed in the Workshare construct are
3463 // 'Parallel' constructs
3464 auto currentDir{llvm::omp::Directive::OMPD_unknown};
3465 if (const auto *ompBlockConstruct{
3466 std::get_if<parser::OpenMPBlockConstruct>(&ompConstruct->u)}) {
3467 const auto &beginBlockDir{
3468 std::get<parser::OmpBeginBlockDirective>(ompBlockConstruct->t)};
3469 const auto &beginDir{
3470 std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
3471 currentDir = beginDir.v;
3472 } else if (const auto *ompLoopConstruct{
3473 std::get_if<parser::OpenMPLoopConstruct>(
3474 &ompConstruct->u)}) {
3475 const auto &beginLoopDir{
3476 std::get<parser::OmpBeginLoopDirective>(ompLoopConstruct->t)};
3477 const auto &beginDir{
3478 std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
3479 currentDir = beginDir.v;
3480 } else if (const auto *ompSectionsConstruct{
3481 std::get_if<parser::OpenMPSectionsConstruct>(
3482 &ompConstruct->u)}) {
3483 const auto &beginSectionsDir{
3484 std::get<parser::OmpBeginSectionsDirective>(
3485 ompSectionsConstruct->t)};
3486 const auto &beginDir{
3487 std::get<parser::OmpSectionsDirective>(beginSectionsDir.t)};
3488 currentDir = beginDir.v;
3489 }
3490
3491 if (!llvm::omp::topParallelSet.test(currentDir)) {
3492 context_.Say(source,
3493 "OpenMP constructs enclosed in WORKSHARE construct may consist "
3494 "of ATOMIC, CRITICAL or PARALLEL constructs only"_err_en_US);
3495 }
3496 }
3497 } else {
3498 context_.Say(source,
3499 "The structured block in a WORKSHARE construct may consist of only "
3500 "SCALAR or ARRAY assignments, FORALL or WHERE statements, "
3501 "FORALL, WHERE, ATOMIC, CRITICAL or PARALLEL constructs"_err_en_US);
3502 }
3503 }
3504 }
3505
3506 const parser::OmpObjectList *OmpStructureChecker::GetOmpObjectList(
3507 const parser::OmpClause &clause) {
3508
3509 // Clauses with OmpObjectList as its data member
3510 using MemberObjectListClauses =
3511 std::tuple<parser::OmpClause::Copyprivate, parser::OmpClause::Copyin,
3512 parser::OmpClause::Firstprivate, parser::OmpClause::From,
3513 parser::OmpClause::Lastprivate, parser::OmpClause::Link,
3514 parser::OmpClause::Private, parser::OmpClause::Shared,
3515 parser::OmpClause::To, parser::OmpClause::Enter,
3516 parser::OmpClause::UseDevicePtr, parser::OmpClause::UseDeviceAddr>;
3517
3518 // Clauses with OmpObjectList in the tuple
3519 using TupleObjectListClauses =
3520 std::tuple<parser::OmpClause::Allocate, parser::OmpClause::Map,
3521 parser::OmpClause::Reduction, parser::OmpClause::Aligned>;
3522
3523 // TODO:: Generate the tuples using TableGen.
3524 // Handle other constructs with OmpObjectList such as OpenMPThreadprivate.
3525 return common::visit(
3526 common::visitors{
3527 [&](const auto &x) -> const parser::OmpObjectList * {
3528 using Ty = std::decay_t<decltype(x)>;
3529 if constexpr (common::HasMember<Ty, MemberObjectListClauses>) {
3530 return &x.v;
3531 } else if constexpr (common::HasMember<Ty,
3532 TupleObjectListClauses>) {
3533 return &(std::get<parser::OmpObjectList>(x.v.t));
3534 } else {
3535 return nullptr;
3536 }
3537 },
3538 },
3539 clause.u);
3540 }
3541
3542 void OmpStructureChecker::Enter(
3543 const parser::OmpClause::AtomicDefaultMemOrder &x) {
3544 CheckAllowedRequiresClause(llvm::omp::Clause::OMPC_atomic_default_mem_order);
3545 }
3546
3547 void OmpStructureChecker::Enter(const parser::OmpClause::DynamicAllocators &x) {
3548 CheckAllowedRequiresClause(llvm::omp::Clause::OMPC_dynamic_allocators);
3549 }
3550
3551 void OmpStructureChecker::Enter(const parser::OmpClause::ReverseOffload &x) {
3552 CheckAllowedRequiresClause(llvm::omp::Clause::OMPC_reverse_offload);
3553 }
3554
3555 void OmpStructureChecker::Enter(const parser::OmpClause::UnifiedAddress &x) {
3556 CheckAllowedRequiresClause(llvm::omp::Clause::OMPC_unified_address);
3557 }
3558
3559 void OmpStructureChecker::Enter(
3560 const parser::OmpClause::UnifiedSharedMemory &x) {
3561 CheckAllowedRequiresClause(llvm::omp::Clause::OMPC_unified_shared_memory);
3562 }
3563
3564 void OmpStructureChecker::CheckAllowedRequiresClause(llvmOmpClause clause) {
3565 CheckAllowed(clause);
3566
3567 if (clause != llvm::omp::Clause::OMPC_atomic_default_mem_order) {
3568 // Check that it does not appear after a device construct
3569 if (deviceConstructFound_) {
3570 context_.Say(GetContext().clauseSource,
3571 "REQUIRES directive with '%s' clause found lexically after device "
3572 "construct"_err_en_US,
3573 parser::ToUpperCaseLetters(getClauseName(clause).str()));
3574 }
3575 }
3576 }
3577
3578 } // namespace Fortran::semantics