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 "flang/Parser/parse-tree.h"
11 #include "flang/Semantics/tools.h"
12 #include <algorithm>
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) &&
72             !(root.attrs().test(Attr::ELEMENTAL) ||
73                 root.attrs().test(Attr::INTRINSIC))) {
74           context_.Say(expr.source,
75               "User defined non-ELEMENTAL function "
76               "'%s' is not allowed in a WORKSHARE construct"_err_en_US,
77               root.name());
78         }
79       }
80     }
81     return false;
82   }
83 
84 private:
85   SemanticsContext &context_;
86   parser::CharBlock source_;
87 };
88 
89 class OmpCycleChecker {
90 public:
91   OmpCycleChecker(SemanticsContext &context, std::int64_t cycleLevel)
92       : context_{context}, cycleLevel_{cycleLevel} {}
93 
94   template <typename T> bool Pre(const T &) { return true; }
95   template <typename T> void Post(const T &) {}
96 
97   bool Pre(const parser::DoConstruct &dc) {
98     cycleLevel_--;
99     const auto &labelName{std::get<0>(std::get<0>(dc.t).statement.t)};
100     if (labelName) {
101       labelNamesandLevels_.emplace(labelName.value().ToString(), cycleLevel_);
102     }
103     return true;
104   }
105 
106   bool Pre(const parser::CycleStmt &cyclestmt) {
107     std::map<std::string, std::int64_t>::iterator it;
108     bool err{false};
109     if (cyclestmt.v) {
110       it = labelNamesandLevels_.find(cyclestmt.v->source.ToString());
111       err = (it != labelNamesandLevels_.end() && it->second > 0);
112     }
113     if (cycleLevel_ > 0 || err) {
114       context_.Say(*cycleSource_,
115           "CYCLE statement to non-innermost associated loop of an OpenMP DO construct"_err_en_US);
116     }
117     return true;
118   }
119 
120   bool Pre(const parser::Statement<parser::ActionStmt> &actionstmt) {
121     cycleSource_ = &actionstmt.source;
122     return true;
123   }
124 
125 private:
126   SemanticsContext &context_;
127   const parser::CharBlock *cycleSource_;
128   std::int64_t cycleLevel_;
129   std::map<std::string, std::int64_t> labelNamesandLevels_;
130 };
131 
132 bool OmpStructureChecker::IsCloselyNestedRegion(const OmpDirectiveSet &set) {
133   // Definition of close nesting:
134   //
135   // `A region nested inside another region with no parallel region nested
136   // between them`
137   //
138   // Examples:
139   //   non-parallel construct 1
140   //    non-parallel construct 2
141   //      parallel construct
142   //        construct 3
143   // In the above example, construct 3 is NOT closely nested inside construct 1
144   // or 2
145   //
146   //   non-parallel construct 1
147   //    non-parallel construct 2
148   //        construct 3
149   // In the above example, construct 3 is closely nested inside BOTH construct 1
150   // and 2
151   //
152   // Algorithm:
153   // Starting from the parent context, Check in a bottom-up fashion, each level
154   // of the context stack. If we have a match for one of the (supplied)
155   // violating directives, `close nesting` is satisfied. If no match is there in
156   // the entire stack, `close nesting` is not satisfied. If at any level, a
157   // `parallel` region is found, `close nesting` is not satisfied.
158 
159   if (CurrentDirectiveIsNested()) {
160     int index = dirContext_.size() - 2;
161     while (index != -1) {
162       if (set.test(dirContext_[index].directive)) {
163         return true;
164       } else if (llvm::omp::parallelSet.test(dirContext_[index].directive)) {
165         return false;
166       }
167       index--;
168     }
169   }
170   return false;
171 }
172 
173 void OmpStructureChecker::CheckMultListItems() {
174   semantics::UnorderedSymbolSet listVars;
175   auto checkMultipleOcurrence = [&](const std::list<parser::Name> &nameList,
176                                     const parser::CharBlock &item,
177                                     const std::string &clauseName) {
178     for (auto const &var : nameList) {
179       if (llvm::is_contained(listVars, *(var.symbol))) {
180         context_.Say(item,
181             "List item '%s' present at multiple %s clauses"_err_en_US,
182             var.ToString(), clauseName);
183       }
184       listVars.insert(*(var.symbol));
185     }
186   };
187 
188   // Aligned clause
189   auto alignedClauses{FindClauses(llvm::omp::Clause::OMPC_aligned)};
190   for (auto itr = alignedClauses.first; itr != alignedClauses.second; ++itr) {
191     const auto &alignedClause{
192         std::get<parser::OmpClause::Aligned>(itr->second->u)};
193     const auto &alignedNameList{
194         std::get<std::list<parser::Name>>(alignedClause.v.t)};
195     checkMultipleOcurrence(alignedNameList, itr->second->source, "ALIGNED");
196   }
197 
198   // Nontemporal clause
199   auto nonTemporalClauses{FindClauses(llvm::omp::Clause::OMPC_nontemporal)};
200   for (auto itr = nonTemporalClauses.first; itr != nonTemporalClauses.second;
201        ++itr) {
202     const auto &nontempClause{
203         std::get<parser::OmpClause::Nontemporal>(itr->second->u)};
204     const auto &nontempNameList{nontempClause.v};
205     checkMultipleOcurrence(nontempNameList, itr->second->source, "NONTEMPORAL");
206   }
207 }
208 
209 bool OmpStructureChecker::HasInvalidWorksharingNesting(
210     const parser::CharBlock &source, const OmpDirectiveSet &set) {
211   // set contains all the invalid closely nested directives
212   // for the given directive (`source` here)
213   if (IsCloselyNestedRegion(set)) {
214     context_.Say(source,
215         "A worksharing region may not be closely nested inside a "
216         "worksharing, explicit task, taskloop, critical, ordered, atomic, or "
217         "master region"_err_en_US);
218     return true;
219   }
220   return false;
221 }
222 
223 void OmpStructureChecker::HasInvalidDistributeNesting(
224     const parser::OpenMPLoopConstruct &x) {
225   bool violation{false};
226 
227   OmpDirectiveSet distributeSet{llvm::omp::Directive::OMPD_distribute,
228       llvm::omp::Directive::OMPD_distribute_parallel_do,
229       llvm::omp::Directive::OMPD_distribute_parallel_do_simd,
230       llvm::omp::Directive::OMPD_distribute_parallel_for,
231       llvm::omp::Directive::OMPD_distribute_parallel_for_simd,
232       llvm::omp::Directive::OMPD_distribute_simd};
233 
234   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
235   const auto &beginDir{std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
236   if (distributeSet.test(beginDir.v)) {
237     // `distribute` region has to be nested
238     if (!CurrentDirectiveIsNested()) {
239       violation = true;
240     } else {
241       // `distribute` region has to be strictly nested inside `teams`
242       if (!llvm::omp::teamSet.test(GetContextParent().directive)) {
243         violation = true;
244       }
245     }
246   }
247   if (violation) {
248     context_.Say(beginDir.source,
249         "`DISTRIBUTE` region has to be strictly nested inside `TEAMS` region."_err_en_US);
250   }
251 }
252 
253 void OmpStructureChecker::HasInvalidTeamsNesting(
254     const llvm::omp::Directive &dir, const parser::CharBlock &source) {
255   OmpDirectiveSet allowedSet{llvm::omp::Directive::OMPD_parallel,
256       llvm::omp::Directive::OMPD_parallel_do,
257       llvm::omp::Directive::OMPD_parallel_do_simd,
258       llvm::omp::Directive::OMPD_parallel_for,
259       llvm::omp::Directive::OMPD_parallel_for_simd,
260       llvm::omp::Directive::OMPD_parallel_master,
261       llvm::omp::Directive::OMPD_parallel_master_taskloop,
262       llvm::omp::Directive::OMPD_parallel_master_taskloop_simd,
263       llvm::omp::Directive::OMPD_parallel_sections,
264       llvm::omp::Directive::OMPD_parallel_workshare,
265       llvm::omp::Directive::OMPD_distribute,
266       llvm::omp::Directive::OMPD_distribute_parallel_do,
267       llvm::omp::Directive::OMPD_distribute_parallel_do_simd,
268       llvm::omp::Directive::OMPD_distribute_parallel_for,
269       llvm::omp::Directive::OMPD_distribute_parallel_for_simd,
270       llvm::omp::Directive::OMPD_distribute_simd};
271 
272   if (!allowedSet.test(dir)) {
273     context_.Say(source,
274         "Only `DISTRIBUTE` or `PARALLEL` regions are allowed to be strictly nested inside `TEAMS` region."_err_en_US);
275   }
276 }
277 
278 void OmpStructureChecker::CheckPredefinedAllocatorRestriction(
279     const parser::CharBlock &source, const parser::Name &name) {
280   if (const auto *symbol{name.symbol}) {
281     const auto *commonBlock{FindCommonBlockContaining(*symbol)};
282     const auto &scope{context_.FindScope(symbol->name())};
283     const Scope &containingScope{GetProgramUnitContaining(scope)};
284     if (!isPredefinedAllocator &&
285         (IsSave(*symbol) || commonBlock ||
286             containingScope.kind() == Scope::Kind::Module)) {
287       context_.Say(source,
288           "If list items within the ALLOCATE directive have the "
289           "SAVE attribute, are a common block name, or are "
290           "declared in the scope of a module, then only "
291           "predefined memory allocator parameters can be used "
292           "in the allocator clause"_err_en_US);
293     }
294   }
295 }
296 
297 void OmpStructureChecker::CheckPredefinedAllocatorRestriction(
298     const parser::CharBlock &source,
299     const parser::OmpObjectList &ompObjectList) {
300   for (const auto &ompObject : ompObjectList.v) {
301     common::visit(
302         common::visitors{
303             [&](const parser::Designator &designator) {
304               if (const auto *dataRef{
305                       std::get_if<parser::DataRef>(&designator.u)}) {
306                 if (const auto *name{std::get_if<parser::Name>(&dataRef->u)}) {
307                   CheckPredefinedAllocatorRestriction(source, *name);
308                 }
309               }
310             },
311             [&](const parser::Name &name) {
312               CheckPredefinedAllocatorRestriction(source, name);
313             },
314         },
315         ompObject.u);
316   }
317 }
318 
319 void OmpStructureChecker::Enter(const parser::OpenMPConstruct &x) {
320   // Simd Construct with Ordered Construct Nesting check
321   // We cannot use CurrentDirectiveIsNested() here because
322   // PushContextAndClauseSets() has not been called yet, it is
323   // called individually for each construct.  Therefore a
324   // dirContext_ size `1` means the current construct is nested
325   if (dirContext_.size() >= 1) {
326     if (GetDirectiveNest(SIMDNest) > 0) {
327       CheckSIMDNest(x);
328     }
329     if (GetDirectiveNest(TargetNest) > 0) {
330       CheckTargetNest(x);
331     }
332   }
333 }
334 
335 void OmpStructureChecker::Enter(const parser::OpenMPLoopConstruct &x) {
336   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
337   const auto &beginDir{std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
338 
339   // check matching, End directive is optional
340   if (const auto &endLoopDir{
341           std::get<std::optional<parser::OmpEndLoopDirective>>(x.t)}) {
342     const auto &endDir{
343         std::get<parser::OmpLoopDirective>(endLoopDir.value().t)};
344 
345     CheckMatching<parser::OmpLoopDirective>(beginDir, endDir);
346   }
347 
348   PushContextAndClauseSets(beginDir.source, beginDir.v);
349   if (llvm::omp::simdSet.test(GetContext().directive)) {
350     EnterDirectiveNest(SIMDNest);
351   }
352 
353   if (beginDir.v == llvm::omp::Directive::OMPD_do) {
354     // 2.7.1 do-clause -> private-clause |
355     //                    firstprivate-clause |
356     //                    lastprivate-clause |
357     //                    linear-clause |
358     //                    reduction-clause |
359     //                    schedule-clause |
360     //                    collapse-clause |
361     //                    ordered-clause
362 
363     // nesting check
364     HasInvalidWorksharingNesting(
365         beginDir.source, llvm::omp::nestedWorkshareErrSet);
366   }
367   SetLoopInfo(x);
368 
369   if (const auto &doConstruct{
370           std::get<std::optional<parser::DoConstruct>>(x.t)}) {
371     const auto &doBlock{std::get<parser::Block>(doConstruct->t)};
372     CheckNoBranching(doBlock, beginDir.v, beginDir.source);
373   }
374   CheckDoWhile(x);
375   CheckLoopItrVariableIsInt(x);
376   CheckCycleConstraints(x);
377   HasInvalidDistributeNesting(x);
378   if (CurrentDirectiveIsNested() &&
379       llvm::omp::teamSet.test(GetContextParent().directive)) {
380     HasInvalidTeamsNesting(beginDir.v, beginDir.source);
381   }
382   if ((beginDir.v == llvm::omp::Directive::OMPD_distribute_parallel_do_simd) ||
383       (beginDir.v == llvm::omp::Directive::OMPD_distribute_simd)) {
384     CheckDistLinear(x);
385   }
386 }
387 const parser::Name OmpStructureChecker::GetLoopIndex(
388     const parser::DoConstruct *x) {
389   using Bounds = parser::LoopControl::Bounds;
390   return std::get<Bounds>(x->GetLoopControl()->u).name.thing;
391 }
392 void OmpStructureChecker::SetLoopInfo(const parser::OpenMPLoopConstruct &x) {
393   if (const auto &loopConstruct{
394           std::get<std::optional<parser::DoConstruct>>(x.t)}) {
395     const parser::DoConstruct *loop{&*loopConstruct};
396     if (loop && loop->IsDoNormal()) {
397       const parser::Name &itrVal{GetLoopIndex(loop)};
398       SetLoopIv(itrVal.symbol);
399     }
400   }
401 }
402 void OmpStructureChecker::CheckDoWhile(const parser::OpenMPLoopConstruct &x) {
403   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
404   const auto &beginDir{std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
405   if (beginDir.v == llvm::omp::Directive::OMPD_do) {
406     if (const auto &doConstruct{
407             std::get<std::optional<parser::DoConstruct>>(x.t)}) {
408       if (doConstruct.value().IsDoWhile()) {
409         const auto &doStmt{std::get<parser::Statement<parser::NonLabelDoStmt>>(
410             doConstruct.value().t)};
411         context_.Say(doStmt.source,
412             "The DO loop cannot be a DO WHILE with DO directive."_err_en_US);
413       }
414     }
415   }
416 }
417 
418 void OmpStructureChecker::CheckLoopItrVariableIsInt(
419     const parser::OpenMPLoopConstruct &x) {
420   if (const auto &loopConstruct{
421           std::get<std::optional<parser::DoConstruct>>(x.t)}) {
422 
423     for (const parser::DoConstruct *loop{&*loopConstruct}; loop;) {
424       if (loop->IsDoNormal()) {
425         const parser::Name &itrVal{GetLoopIndex(loop)};
426         if (itrVal.symbol) {
427           const auto *type{itrVal.symbol->GetType()};
428           if (!type->IsNumeric(TypeCategory::Integer)) {
429             context_.Say(itrVal.source,
430                 "The DO loop iteration"
431                 " variable must be of the type integer."_err_en_US,
432                 itrVal.ToString());
433           }
434         }
435       }
436       // Get the next DoConstruct if block is not empty.
437       const auto &block{std::get<parser::Block>(loop->t)};
438       const auto it{block.begin()};
439       loop = it != block.end() ? parser::Unwrap<parser::DoConstruct>(*it)
440                                : nullptr;
441     }
442   }
443 }
444 
445 void OmpStructureChecker::CheckSIMDNest(const parser::OpenMPConstruct &c) {
446   // Check the following:
447   //  The only OpenMP constructs that can be encountered during execution of
448   // a simd region are the `atomic` construct, the `loop` construct, the `simd`
449   // construct and the `ordered` construct with the `simd` clause.
450   // TODO:  Expand the check to include `LOOP` construct as well when it is
451   // supported.
452 
453   // Check if the parent context has the SIMD clause
454   // Please note that we use GetContext() instead of GetContextParent()
455   // because PushContextAndClauseSets() has not been called on the
456   // current context yet.
457   // TODO: Check for declare simd regions.
458   bool eligibleSIMD{false};
459   common::visit(Fortran::common::visitors{
460                     // Allow `!$OMP ORDERED SIMD`
461                     [&](const parser::OpenMPBlockConstruct &c) {
462                       const auto &beginBlockDir{
463                           std::get<parser::OmpBeginBlockDirective>(c.t)};
464                       const auto &beginDir{
465                           std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
466                       if (beginDir.v == llvm::omp::Directive::OMPD_ordered) {
467                         const auto &clauses{
468                             std::get<parser::OmpClauseList>(beginBlockDir.t)};
469                         for (const auto &clause : clauses.v) {
470                           if (std::get_if<parser::OmpClause::Simd>(&clause.u)) {
471                             eligibleSIMD = true;
472                             break;
473                           }
474                         }
475                       }
476                     },
477                     [&](const parser::OpenMPSimpleStandaloneConstruct &c) {
478                       const auto &dir{
479                           std::get<parser::OmpSimpleStandaloneDirective>(c.t)};
480                       if (dir.v == llvm::omp::Directive::OMPD_ordered) {
481                         const auto &clauses{
482                             std::get<parser::OmpClauseList>(c.t)};
483                         for (const auto &clause : clauses.v) {
484                           if (std::get_if<parser::OmpClause::Simd>(&clause.u)) {
485                             eligibleSIMD = true;
486                             break;
487                           }
488                         }
489                       }
490                     },
491                     // Allowing SIMD construct
492                     [&](const parser::OpenMPLoopConstruct &c) {
493                       const auto &beginLoopDir{
494                           std::get<parser::OmpBeginLoopDirective>(c.t)};
495                       const auto &beginDir{
496                           std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
497                       if ((beginDir.v == llvm::omp::Directive::OMPD_simd) ||
498                           (beginDir.v == llvm::omp::Directive::OMPD_do_simd)) {
499                         eligibleSIMD = true;
500                       }
501                     },
502                     [&](const parser::OpenMPAtomicConstruct &c) {
503                       // Allow `!$OMP ATOMIC`
504                       eligibleSIMD = true;
505                     },
506                     [&](const auto &c) {},
507                 },
508       c.u);
509   if (!eligibleSIMD) {
510     context_.Say(parser::FindSourceLocation(c),
511         "The only OpenMP constructs that can be encountered during execution "
512         "of a 'SIMD'"
513         " region are the `ATOMIC` construct, the `LOOP` construct, the `SIMD`"
514         " construct and the `ORDERED` construct with the `SIMD` clause."_err_en_US);
515   }
516 }
517 
518 void OmpStructureChecker::CheckTargetNest(const parser::OpenMPConstruct &c) {
519   // 2.12.5 Target Construct Restriction
520   bool eligibleTarget{true};
521   llvm::omp::Directive ineligibleTargetDir;
522   common::visit(
523       common::visitors{
524           [&](const parser::OpenMPBlockConstruct &c) {
525             const auto &beginBlockDir{
526                 std::get<parser::OmpBeginBlockDirective>(c.t)};
527             const auto &beginDir{
528                 std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
529             if (beginDir.v == llvm::omp::Directive::OMPD_target_data) {
530               eligibleTarget = false;
531               ineligibleTargetDir = beginDir.v;
532             }
533           },
534           [&](const parser::OpenMPStandaloneConstruct &c) {
535             common::visit(
536                 common::visitors{
537                     [&](const parser::OpenMPSimpleStandaloneConstruct &c) {
538                       const auto &dir{
539                           std::get<parser::OmpSimpleStandaloneDirective>(c.t)};
540                       if (dir.v == llvm::omp::Directive::OMPD_target_update ||
541                           dir.v ==
542                               llvm::omp::Directive::OMPD_target_enter_data ||
543                           dir.v ==
544                               llvm::omp::Directive::OMPD_target_exit_data) {
545                         eligibleTarget = false;
546                         ineligibleTargetDir = dir.v;
547                       }
548                     },
549                     [&](const auto &c) {},
550                 },
551                 c.u);
552           },
553           [&](const auto &c) {},
554       },
555       c.u);
556   if (!eligibleTarget) {
557     context_.Say(parser::FindSourceLocation(c),
558         "If %s directive is nested inside TARGET region, the behaviour "
559         "is unspecified"_port_en_US,
560         parser::ToUpperCaseLetters(
561             getDirectiveName(ineligibleTargetDir).str()));
562   }
563 }
564 
565 std::int64_t OmpStructureChecker::GetOrdCollapseLevel(
566     const parser::OpenMPLoopConstruct &x) {
567   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
568   const auto &clauseList{std::get<parser::OmpClauseList>(beginLoopDir.t)};
569   std::int64_t orderedCollapseLevel{1};
570   std::int64_t orderedLevel{0};
571   std::int64_t collapseLevel{0};
572 
573   for (const auto &clause : clauseList.v) {
574     if (const auto *collapseClause{
575             std::get_if<parser::OmpClause::Collapse>(&clause.u)}) {
576       if (const auto v{GetIntValue(collapseClause->v)}) {
577         collapseLevel = *v;
578       }
579     }
580     if (const auto *orderedClause{
581             std::get_if<parser::OmpClause::Ordered>(&clause.u)}) {
582       if (const auto v{GetIntValue(orderedClause->v)}) {
583         orderedLevel = *v;
584       }
585     }
586   }
587   if (orderedLevel >= collapseLevel) {
588     orderedCollapseLevel = orderedLevel;
589   } else {
590     orderedCollapseLevel = collapseLevel;
591   }
592   return orderedCollapseLevel;
593 }
594 
595 void OmpStructureChecker::CheckCycleConstraints(
596     const parser::OpenMPLoopConstruct &x) {
597   std::int64_t ordCollapseLevel{GetOrdCollapseLevel(x)};
598   OmpCycleChecker ompCycleChecker{context_, ordCollapseLevel};
599   parser::Walk(x, ompCycleChecker);
600 }
601 
602 void OmpStructureChecker::CheckDistLinear(
603     const parser::OpenMPLoopConstruct &x) {
604 
605   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
606   const auto &clauses{std::get<parser::OmpClauseList>(beginLoopDir.t)};
607 
608   semantics::UnorderedSymbolSet indexVars;
609 
610   // Collect symbols of all the variables from linear clauses
611   for (const auto &clause : clauses.v) {
612     if (const auto *linearClause{
613             std::get_if<parser::OmpClause::Linear>(&clause.u)}) {
614 
615       std::list<parser::Name> values;
616       // Get the variant type
617       if (std::holds_alternative<parser::OmpLinearClause::WithModifier>(
618               linearClause->v.u)) {
619         const auto &withM{
620             std::get<parser::OmpLinearClause::WithModifier>(linearClause->v.u)};
621         values = withM.names;
622       } else {
623         const auto &withOutM{std::get<parser::OmpLinearClause::WithoutModifier>(
624             linearClause->v.u)};
625         values = withOutM.names;
626       }
627       for (auto const &v : values) {
628         indexVars.insert(*(v.symbol));
629       }
630     }
631   }
632 
633   if (!indexVars.empty()) {
634     // Get collapse level, if given, to find which loops are "associated."
635     std::int64_t collapseVal{GetOrdCollapseLevel(x)};
636     // Include the top loop if no collapse is specified
637     if (collapseVal == 0) {
638       collapseVal = 1;
639     }
640 
641     // Match the loop index variables with the collected symbols from linear
642     // clauses.
643     if (const auto &loopConstruct{
644             std::get<std::optional<parser::DoConstruct>>(x.t)}) {
645       for (const parser::DoConstruct *loop{&*loopConstruct}; loop;) {
646         if (loop->IsDoNormal()) {
647           const parser::Name &itrVal{GetLoopIndex(loop)};
648           if (itrVal.symbol) {
649             // Remove the symbol from the collcted set
650             indexVars.erase(*(itrVal.symbol));
651           }
652           collapseVal--;
653           if (collapseVal == 0) {
654             break;
655           }
656         }
657         // Get the next DoConstruct if block is not empty.
658         const auto &block{std::get<parser::Block>(loop->t)};
659         const auto it{block.begin()};
660         loop = it != block.end() ? parser::Unwrap<parser::DoConstruct>(*it)
661                                  : nullptr;
662       }
663     }
664 
665     // Show error for the remaining variables
666     for (auto var : indexVars) {
667       const Symbol &root{GetAssociationRoot(var)};
668       context_.Say(parser::FindSourceLocation(x),
669           "Variable '%s' not allowed in `LINEAR` clause, only loop iterator can be specified in `LINEAR` clause of a construct combined with `DISTRIBUTE`"_err_en_US,
670           root.name());
671     }
672   }
673 }
674 
675 void OmpStructureChecker::Leave(const parser::OpenMPLoopConstruct &) {
676   if (llvm::omp::simdSet.test(GetContext().directive)) {
677     ExitDirectiveNest(SIMDNest);
678   }
679   dirContext_.pop_back();
680 }
681 
682 void OmpStructureChecker::Enter(const parser::OmpEndLoopDirective &x) {
683   const auto &dir{std::get<parser::OmpLoopDirective>(x.t)};
684   ResetPartialContext(dir.source);
685   switch (dir.v) {
686   // 2.7.1 end-do -> END DO [nowait-clause]
687   // 2.8.3 end-do-simd -> END DO SIMD [nowait-clause]
688   case llvm::omp::Directive::OMPD_do:
689   case llvm::omp::Directive::OMPD_do_simd:
690     SetClauseSets(dir.v);
691     break;
692   default:
693     // no clauses are allowed
694     break;
695   }
696 }
697 
698 void OmpStructureChecker::Enter(const parser::OpenMPBlockConstruct &x) {
699   const auto &beginBlockDir{std::get<parser::OmpBeginBlockDirective>(x.t)};
700   const auto &endBlockDir{std::get<parser::OmpEndBlockDirective>(x.t)};
701   const auto &beginDir{std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
702   const auto &endDir{std::get<parser::OmpBlockDirective>(endBlockDir.t)};
703   const parser::Block &block{std::get<parser::Block>(x.t)};
704 
705   CheckMatching<parser::OmpBlockDirective>(beginDir, endDir);
706 
707   PushContextAndClauseSets(beginDir.source, beginDir.v);
708   if (GetContext().directive == llvm::omp::Directive::OMPD_target) {
709     EnterDirectiveNest(TargetNest);
710   }
711 
712   if (CurrentDirectiveIsNested()) {
713     if (llvm::omp::teamSet.test(GetContextParent().directive)) {
714       HasInvalidTeamsNesting(beginDir.v, beginDir.source);
715     }
716     if (GetContext().directive == llvm::omp::Directive::OMPD_master) {
717       CheckMasterNesting(x);
718     }
719     // A teams region can only be strictly nested within the implicit parallel
720     // region or a target region.
721     if (GetContext().directive == llvm::omp::Directive::OMPD_teams &&
722         GetContextParent().directive != llvm::omp::Directive::OMPD_target) {
723       context_.Say(parser::FindSourceLocation(x),
724           "%s region can only be strictly nested within the implicit parallel "
725           "region or TARGET region"_err_en_US,
726           ContextDirectiveAsFortran());
727     }
728     // If a teams construct is nested within a target construct, that target
729     // construct must contain no statements, declarations or directives outside
730     // of the teams construct.
731     if (GetContext().directive == llvm::omp::Directive::OMPD_teams &&
732         GetContextParent().directive == llvm::omp::Directive::OMPD_target &&
733         !GetDirectiveNest(TargetBlockOnlyTeams)) {
734       context_.Say(GetContextParent().directiveSource,
735           "TARGET construct with nested TEAMS region contains statements or "
736           "directives outside of the TEAMS construct"_err_en_US);
737     }
738   }
739 
740   CheckNoBranching(block, beginDir.v, beginDir.source);
741 
742   switch (beginDir.v) {
743   case llvm::omp::Directive::OMPD_target:
744     if (CheckTargetBlockOnlyTeams(block)) {
745       EnterDirectiveNest(TargetBlockOnlyTeams);
746     }
747     break;
748   case llvm::omp::OMPD_workshare:
749   case llvm::omp::OMPD_parallel_workshare:
750     CheckWorkshareBlockStmts(block, beginDir.source);
751     HasInvalidWorksharingNesting(
752         beginDir.source, llvm::omp::nestedWorkshareErrSet);
753     break;
754   case llvm::omp::Directive::OMPD_single:
755     // TODO: This check needs to be extended while implementing nesting of
756     // regions checks.
757     HasInvalidWorksharingNesting(
758         beginDir.source, llvm::omp::nestedWorkshareErrSet);
759     break;
760   default:
761     break;
762   }
763 }
764 
765 void OmpStructureChecker::CheckMasterNesting(
766     const parser::OpenMPBlockConstruct &x) {
767   // A MASTER region may not be `closely nested` inside a worksharing, loop,
768   // task, taskloop, or atomic region.
769   // TODO:  Expand the check to include `LOOP` construct as well when it is
770   // supported.
771   if (IsCloselyNestedRegion(llvm::omp::nestedMasterErrSet)) {
772     context_.Say(parser::FindSourceLocation(x),
773         "`MASTER` region may not be closely nested inside of `WORKSHARING`, "
774         "`LOOP`, `TASK`, `TASKLOOP`,"
775         " or `ATOMIC` region."_err_en_US);
776   }
777 }
778 
779 void OmpStructureChecker::Leave(const parser::OpenMPBlockConstruct &) {
780   if (GetDirectiveNest(TargetBlockOnlyTeams)) {
781     ExitDirectiveNest(TargetBlockOnlyTeams);
782   }
783   if (GetContext().directive == llvm::omp::Directive::OMPD_target) {
784     ExitDirectiveNest(TargetNest);
785   }
786   dirContext_.pop_back();
787 }
788 
789 void OmpStructureChecker::ChecksOnOrderedAsBlock() {
790   if (FindClause(llvm::omp::Clause::OMPC_depend)) {
791     context_.Say(GetContext().clauseSource,
792         "DEPEND(*) clauses are not allowed when ORDERED construct is a block"
793         " construct with an ORDERED region"_err_en_US);
794     return;
795   }
796 
797   OmpDirectiveSet notAllowedParallelSet{llvm::omp::Directive::OMPD_parallel,
798       llvm::omp::Directive::OMPD_target_parallel,
799       llvm::omp::Directive::OMPD_parallel_sections,
800       llvm::omp::Directive::OMPD_parallel_workshare};
801   bool isNestedInDo{false};
802   bool isNestedInDoSIMD{false};
803   bool isNestedInSIMD{false};
804   bool noOrderedClause{false};
805   bool isOrderedClauseWithPara{false};
806   bool isCloselyNestedRegion{true};
807   if (CurrentDirectiveIsNested()) {
808     for (int i = (int)dirContext_.size() - 2; i >= 0; i--) {
809       if (llvm::omp::nestedOrderedErrSet.test(dirContext_[i].directive)) {
810         context_.Say(GetContext().directiveSource,
811             "`ORDERED` region may not be closely nested inside of `CRITICAL`, "
812             "`ORDERED`, explicit `TASK` or `TASKLOOP` region."_err_en_US);
813         break;
814       } else if (llvm::omp::doSet.test(dirContext_[i].directive)) {
815         isNestedInDo = true;
816         isNestedInDoSIMD = llvm::omp::doSimdSet.test(dirContext_[i].directive);
817         if (const auto *clause{
818                 FindClause(dirContext_[i], llvm::omp::Clause::OMPC_ordered)}) {
819           const auto &orderedClause{
820               std::get<parser::OmpClause::Ordered>(clause->u)};
821           const auto orderedValue{GetIntValue(orderedClause.v)};
822           isOrderedClauseWithPara = orderedValue > 0;
823         } else {
824           noOrderedClause = true;
825         }
826         break;
827       } else if (llvm::omp::simdSet.test(dirContext_[i].directive)) {
828         isNestedInSIMD = true;
829         break;
830       } else if (notAllowedParallelSet.test(dirContext_[i].directive)) {
831         isCloselyNestedRegion = false;
832         break;
833       }
834     }
835   }
836 
837   if (!isCloselyNestedRegion) {
838     context_.Say(GetContext().directiveSource,
839         "An ORDERED directive without the DEPEND clause must be closely nested "
840         "in a SIMD, worksharing-loop, or worksharing-loop SIMD "
841         "region"_err_en_US);
842   } else {
843     if (CurrentDirectiveIsNested() &&
844         FindClause(llvm::omp::Clause::OMPC_simd) &&
845         (!isNestedInDoSIMD && !isNestedInSIMD)) {
846       context_.Say(GetContext().directiveSource,
847           "An ORDERED directive with SIMD clause must be closely nested in a "
848           "SIMD or worksharing-loop SIMD region"_err_en_US);
849     }
850     if (isNestedInDo && (noOrderedClause || isOrderedClauseWithPara)) {
851       context_.Say(GetContext().directiveSource,
852           "An ORDERED directive without the DEPEND clause must be closely "
853           "nested in a worksharing-loop (or worksharing-loop SIMD) region with "
854           "ORDERED clause without the parameter"_err_en_US);
855     }
856   }
857 }
858 
859 void OmpStructureChecker::Leave(const parser::OmpBeginBlockDirective &) {
860   switch (GetContext().directive) {
861   case llvm::omp::Directive::OMPD_ordered:
862     // [5.1] 2.19.9 Ordered Construct Restriction
863     ChecksOnOrderedAsBlock();
864     break;
865   default:
866     break;
867   }
868 }
869 
870 void OmpStructureChecker::Enter(const parser::OpenMPSectionsConstruct &x) {
871   const auto &beginSectionsDir{
872       std::get<parser::OmpBeginSectionsDirective>(x.t)};
873   const auto &endSectionsDir{std::get<parser::OmpEndSectionsDirective>(x.t)};
874   const auto &beginDir{
875       std::get<parser::OmpSectionsDirective>(beginSectionsDir.t)};
876   const auto &endDir{std::get<parser::OmpSectionsDirective>(endSectionsDir.t)};
877   CheckMatching<parser::OmpSectionsDirective>(beginDir, endDir);
878 
879   PushContextAndClauseSets(beginDir.source, beginDir.v);
880   const auto &sectionBlocks{std::get<parser::OmpSectionBlocks>(x.t)};
881   for (const parser::OpenMPConstruct &block : sectionBlocks.v) {
882     CheckNoBranching(std::get<parser::OpenMPSectionConstruct>(block.u).v,
883         beginDir.v, beginDir.source);
884   }
885   HasInvalidWorksharingNesting(
886       beginDir.source, llvm::omp::nestedWorkshareErrSet);
887 }
888 
889 void OmpStructureChecker::Leave(const parser::OpenMPSectionsConstruct &) {
890   dirContext_.pop_back();
891 }
892 
893 void OmpStructureChecker::Enter(const parser::OmpEndSectionsDirective &x) {
894   const auto &dir{std::get<parser::OmpSectionsDirective>(x.t)};
895   ResetPartialContext(dir.source);
896   switch (dir.v) {
897     // 2.7.2 end-sections -> END SECTIONS [nowait-clause]
898   case llvm::omp::Directive::OMPD_sections:
899     PushContextAndClauseSets(
900         dir.source, llvm::omp::Directive::OMPD_end_sections);
901     break;
902   default:
903     // no clauses are allowed
904     break;
905   }
906 }
907 
908 // TODO: Verify the popping of dirContext requirement after nowait
909 // implementation, as there is an implicit barrier at the end of the worksharing
910 // constructs unless a nowait clause is specified. Only OMPD_end_sections is
911 // popped becuase it is pushed while entering the EndSectionsDirective.
912 void OmpStructureChecker::Leave(const parser::OmpEndSectionsDirective &x) {
913   if (GetContext().directive == llvm::omp::Directive::OMPD_end_sections) {
914     dirContext_.pop_back();
915   }
916 }
917 
918 void OmpStructureChecker::CheckThreadprivateOrDeclareTargetVar(
919     const parser::OmpObjectList &objList) {
920   for (const auto &ompObject : objList.v) {
921     common::visit(
922         common::visitors{
923             [&](const parser::Designator &) {
924               if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
925                 const auto &useScope{
926                     context_.FindScope(GetContext().directiveSource)};
927                 const auto &declScope{
928                     GetProgramUnitContaining(name->symbol->GetUltimate())};
929                 const auto *sym =
930                     declScope.parent().FindSymbol(name->symbol->name());
931                 if (sym &&
932                     (sym->has<MainProgramDetails>() ||
933                         sym->has<ModuleDetails>())) {
934                   context_.Say(name->source,
935                       "The module name or main program name cannot be in a %s "
936                       "directive"_err_en_US,
937                       ContextDirectiveAsFortran());
938                 } else if (name->symbol->GetUltimate().IsSubprogram()) {
939                   if (GetContext().directive ==
940                       llvm::omp::Directive::OMPD_threadprivate)
941                     context_.Say(name->source,
942                         "The procedure name cannot be in a %s "
943                         "directive"_err_en_US,
944                         ContextDirectiveAsFortran());
945                   // TODO: Check for procedure name in declare target directive.
946                 } else if (name->symbol->attrs().test(Attr::PARAMETER)) {
947                   if (GetContext().directive ==
948                       llvm::omp::Directive::OMPD_threadprivate)
949                     context_.Say(name->source,
950                         "The entity with PARAMETER attribute cannot be in a %s "
951                         "directive"_err_en_US,
952                         ContextDirectiveAsFortran());
953                   else if (GetContext().directive ==
954                       llvm::omp::Directive::OMPD_declare_target)
955                     context_.Say(name->source,
956                         "The entity with PARAMETER attribute is used in a %s "
957                         "directive"_warn_en_US,
958                         ContextDirectiveAsFortran());
959                 } else if (FindCommonBlockContaining(*name->symbol)) {
960                   context_.Say(name->source,
961                       "A variable in a %s directive cannot be an element of a "
962                       "common block"_err_en_US,
963                       ContextDirectiveAsFortran());
964                 } else if (!IsSave(*name->symbol) &&
965                     declScope.kind() != Scope::Kind::MainProgram &&
966                     declScope.kind() != Scope::Kind::Module) {
967                   context_.Say(name->source,
968                       "A variable that appears in a %s directive must be "
969                       "declared in the scope of a module or have the SAVE "
970                       "attribute, either explicitly or implicitly"_err_en_US,
971                       ContextDirectiveAsFortran());
972                 } else if (useScope != declScope) {
973                   context_.Say(name->source,
974                       "The %s directive and the common block or variable in it "
975                       "must appear in the same declaration section of a "
976                       "scoping unit"_err_en_US,
977                       ContextDirectiveAsFortran());
978                 } else if (FindEquivalenceSet(*name->symbol)) {
979                   context_.Say(name->source,
980                       "A variable in a %s directive cannot appear in an "
981                       "EQUIVALENCE statement"_err_en_US,
982                       ContextDirectiveAsFortran());
983                 } else if (name->symbol->test(Symbol::Flag::OmpThreadprivate) &&
984                     GetContext().directive ==
985                         llvm::omp::Directive::OMPD_declare_target) {
986                   context_.Say(name->source,
987                       "A THREADPRIVATE variable cannot appear in a %s "
988                       "directive"_err_en_US,
989                       ContextDirectiveAsFortran());
990                 }
991               }
992             },
993             [&](const parser::Name &) {}, // common block
994         },
995         ompObject.u);
996   }
997 }
998 
999 void OmpStructureChecker::Enter(const parser::OpenMPThreadprivate &c) {
1000   const auto &dir{std::get<parser::Verbatim>(c.t)};
1001   PushContextAndClauseSets(
1002       dir.source, llvm::omp::Directive::OMPD_threadprivate);
1003 }
1004 
1005 void OmpStructureChecker::Leave(const parser::OpenMPThreadprivate &c) {
1006   const auto &dir{std::get<parser::Verbatim>(c.t)};
1007   const auto &objectList{std::get<parser::OmpObjectList>(c.t)};
1008   CheckIsVarPartOfAnotherVar(dir.source, objectList);
1009   CheckThreadprivateOrDeclareTargetVar(objectList);
1010   dirContext_.pop_back();
1011 }
1012 
1013 void OmpStructureChecker::Enter(const parser::OpenMPDeclareSimdConstruct &x) {
1014   const auto &dir{std::get<parser::Verbatim>(x.t)};
1015   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_declare_simd);
1016 }
1017 
1018 void OmpStructureChecker::Leave(const parser::OpenMPDeclareSimdConstruct &) {
1019   dirContext_.pop_back();
1020 }
1021 
1022 void OmpStructureChecker::Enter(const parser::OpenMPDeclarativeAllocate &x) {
1023   isPredefinedAllocator = true;
1024   const auto &dir{std::get<parser::Verbatim>(x.t)};
1025   const auto &objectList{std::get<parser::OmpObjectList>(x.t)};
1026   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_allocate);
1027   CheckIsVarPartOfAnotherVar(dir.source, objectList);
1028 }
1029 
1030 void OmpStructureChecker::Leave(const parser::OpenMPDeclarativeAllocate &x) {
1031   const auto &dir{std::get<parser::Verbatim>(x.t)};
1032   const auto &objectList{std::get<parser::OmpObjectList>(x.t)};
1033   CheckPredefinedAllocatorRestriction(dir.source, objectList);
1034   dirContext_.pop_back();
1035 }
1036 
1037 void OmpStructureChecker::Enter(const parser::OmpClause::Allocator &x) {
1038   CheckAllowed(llvm::omp::Clause::OMPC_allocator);
1039   // Note: Predefined allocators are stored in ScalarExpr as numbers
1040   //   whereas custom allocators are stored as strings, so if the ScalarExpr
1041   //   actually has an int value, then it must be a predefined allocator
1042   isPredefinedAllocator = GetIntValue(x.v).has_value();
1043   RequiresPositiveParameter(llvm::omp::Clause::OMPC_allocator, x.v);
1044 }
1045 
1046 void OmpStructureChecker::Enter(const parser::OpenMPDeclareTargetConstruct &x) {
1047   const auto &dir{std::get<parser::Verbatim>(x.t)};
1048   PushContext(dir.source, llvm::omp::Directive::OMPD_declare_target);
1049   const auto &spec{std::get<parser::OmpDeclareTargetSpecifier>(x.t)};
1050   if (std::holds_alternative<parser::OmpDeclareTargetWithClause>(spec.u)) {
1051     SetClauseSets(llvm::omp::Directive::OMPD_declare_target);
1052   }
1053 }
1054 
1055 void OmpStructureChecker::Leave(const parser::OpenMPDeclareTargetConstruct &x) {
1056   const auto &dir{std::get<parser::Verbatim>(x.t)};
1057   const auto &spec{std::get<parser::OmpDeclareTargetSpecifier>(x.t)};
1058   if (const auto *objectList{parser::Unwrap<parser::OmpObjectList>(spec.u)}) {
1059     CheckIsVarPartOfAnotherVar(dir.source, *objectList);
1060     CheckThreadprivateOrDeclareTargetVar(*objectList);
1061   } else if (const auto *clauseList{
1062                  parser::Unwrap<parser::OmpClauseList>(spec.u)}) {
1063     for (const auto &clause : clauseList->v) {
1064       if (const auto *toClause{std::get_if<parser::OmpClause::To>(&clause.u)}) {
1065         CheckIsVarPartOfAnotherVar(dir.source, toClause->v);
1066         CheckThreadprivateOrDeclareTargetVar(toClause->v);
1067       } else if (const auto *linkClause{
1068                      std::get_if<parser::OmpClause::Link>(&clause.u)}) {
1069         CheckIsVarPartOfAnotherVar(dir.source, linkClause->v);
1070         CheckThreadprivateOrDeclareTargetVar(linkClause->v);
1071       }
1072     }
1073   }
1074   dirContext_.pop_back();
1075 }
1076 
1077 void OmpStructureChecker::Enter(const parser::OpenMPExecutableAllocate &x) {
1078   isPredefinedAllocator = true;
1079   const auto &dir{std::get<parser::Verbatim>(x.t)};
1080   const auto &objectList{std::get<std::optional<parser::OmpObjectList>>(x.t)};
1081   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_allocate);
1082   if (objectList) {
1083     CheckIsVarPartOfAnotherVar(dir.source, *objectList);
1084   }
1085 }
1086 
1087 void OmpStructureChecker::Leave(const parser::OpenMPExecutableAllocate &x) {
1088   const auto &dir{std::get<parser::Verbatim>(x.t)};
1089   const auto &objectList{std::get<std::optional<parser::OmpObjectList>>(x.t)};
1090   if (objectList)
1091     CheckPredefinedAllocatorRestriction(dir.source, *objectList);
1092   dirContext_.pop_back();
1093 }
1094 
1095 void OmpStructureChecker::CheckBarrierNesting(
1096     const parser::OpenMPSimpleStandaloneConstruct &x) {
1097   // A barrier region may not be `closely nested` inside a worksharing, loop,
1098   // task, taskloop, critical, ordered, atomic, or master region.
1099   // TODO:  Expand the check to include `LOOP` construct as well when it is
1100   // supported.
1101   if (GetContext().directive == llvm::omp::Directive::OMPD_barrier) {
1102     if (IsCloselyNestedRegion(llvm::omp::nestedBarrierErrSet)) {
1103       context_.Say(parser::FindSourceLocation(x),
1104           "`BARRIER` region may not be closely nested inside of `WORKSHARING`, "
1105           "`LOOP`, `TASK`, `TASKLOOP`,"
1106           "`CRITICAL`, `ORDERED`, `ATOMIC` or `MASTER` region."_err_en_US);
1107     }
1108   }
1109 }
1110 
1111 void OmpStructureChecker::ChecksOnOrderedAsStandalone() {
1112   if (FindClause(llvm::omp::Clause::OMPC_threads) ||
1113       FindClause(llvm::omp::Clause::OMPC_simd)) {
1114     context_.Say(GetContext().clauseSource,
1115         "THREADS, SIMD clauses are not allowed when ORDERED construct is a "
1116         "standalone construct with no ORDERED region"_err_en_US);
1117   }
1118 
1119   bool isSinkPresent{false};
1120   int dependSourceCount{0};
1121   auto clauseAll = FindClauses(llvm::omp::Clause::OMPC_depend);
1122   for (auto itr = clauseAll.first; itr != clauseAll.second; ++itr) {
1123     const auto &dependClause{
1124         std::get<parser::OmpClause::Depend>(itr->second->u)};
1125     if (std::get_if<parser::OmpDependClause::Source>(&dependClause.v.u)) {
1126       dependSourceCount++;
1127       if (isSinkPresent) {
1128         context_.Say(itr->second->source,
1129             "DEPEND(SOURCE) is not allowed when DEPEND(SINK: vec) is present "
1130             "on ORDERED directive"_err_en_US);
1131       }
1132       if (dependSourceCount > 1) {
1133         context_.Say(itr->second->source,
1134             "At most one DEPEND(SOURCE) clause can appear on the ORDERED "
1135             "directive"_err_en_US);
1136       }
1137     } else if (std::get_if<parser::OmpDependClause::Sink>(&dependClause.v.u)) {
1138       isSinkPresent = true;
1139       if (dependSourceCount > 0) {
1140         context_.Say(itr->second->source,
1141             "DEPEND(SINK: vec) is not allowed when DEPEND(SOURCE) is present "
1142             "on ORDERED directive"_err_en_US);
1143       }
1144     } else {
1145       context_.Say(itr->second->source,
1146           "Only DEPEND(SOURCE) or DEPEND(SINK: vec) are allowed when ORDERED "
1147           "construct is a standalone construct with no ORDERED "
1148           "region"_err_en_US);
1149     }
1150   }
1151 
1152   OmpDirectiveSet allowedDoSet{llvm::omp::Directive::OMPD_do,
1153       llvm::omp::Directive::OMPD_parallel_do,
1154       llvm::omp::Directive::OMPD_target_parallel_do};
1155   bool isNestedInDoOrderedWithPara{false};
1156   if (CurrentDirectiveIsNested() &&
1157       allowedDoSet.test(GetContextParent().directive)) {
1158     if (const auto *clause{
1159             FindClause(GetContextParent(), llvm::omp::Clause::OMPC_ordered)}) {
1160       const auto &orderedClause{
1161           std::get<parser::OmpClause::Ordered>(clause->u)};
1162       const auto orderedValue{GetIntValue(orderedClause.v)};
1163       if (orderedValue > 0) {
1164         isNestedInDoOrderedWithPara = true;
1165         CheckOrderedDependClause(orderedValue);
1166       }
1167     }
1168   }
1169 
1170   if (FindClause(llvm::omp::Clause::OMPC_depend) &&
1171       !isNestedInDoOrderedWithPara) {
1172     context_.Say(GetContext().clauseSource,
1173         "An ORDERED construct with the DEPEND clause must be closely nested "
1174         "in a worksharing-loop (or parallel worksharing-loop) construct with "
1175         "ORDERED clause with a parameter"_err_en_US);
1176   }
1177 }
1178 
1179 void OmpStructureChecker::CheckOrderedDependClause(
1180     std::optional<std::int64_t> orderedValue) {
1181   auto clauseAll{FindClauses(llvm::omp::Clause::OMPC_depend)};
1182   for (auto itr = clauseAll.first; itr != clauseAll.second; ++itr) {
1183     const auto &dependClause{
1184         std::get<parser::OmpClause::Depend>(itr->second->u)};
1185     if (const auto *sinkVectors{
1186             std::get_if<parser::OmpDependClause::Sink>(&dependClause.v.u)}) {
1187       std::int64_t numVar = sinkVectors->v.size();
1188       if (orderedValue != numVar) {
1189         context_.Say(itr->second->source,
1190             "The number of variables in DEPEND(SINK: vec) clause does not "
1191             "match the parameter specified in ORDERED clause"_err_en_US);
1192       }
1193     }
1194   }
1195 }
1196 
1197 void OmpStructureChecker::Enter(
1198     const parser::OpenMPSimpleStandaloneConstruct &x) {
1199   const auto &dir{std::get<parser::OmpSimpleStandaloneDirective>(x.t)};
1200   PushContextAndClauseSets(dir.source, dir.v);
1201   CheckBarrierNesting(x);
1202 }
1203 
1204 void OmpStructureChecker::Leave(
1205     const parser::OpenMPSimpleStandaloneConstruct &) {
1206   switch (GetContext().directive) {
1207   case llvm::omp::Directive::OMPD_ordered:
1208     // [5.1] 2.19.9 Ordered Construct Restriction
1209     ChecksOnOrderedAsStandalone();
1210     break;
1211   default:
1212     break;
1213   }
1214   dirContext_.pop_back();
1215 }
1216 
1217 void OmpStructureChecker::Enter(const parser::OpenMPFlushConstruct &x) {
1218   const auto &dir{std::get<parser::Verbatim>(x.t)};
1219   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_flush);
1220 }
1221 
1222 void OmpStructureChecker::Leave(const parser::OpenMPFlushConstruct &x) {
1223   if (FindClause(llvm::omp::Clause::OMPC_acquire) ||
1224       FindClause(llvm::omp::Clause::OMPC_release) ||
1225       FindClause(llvm::omp::Clause::OMPC_acq_rel)) {
1226     if (const auto &flushList{
1227             std::get<std::optional<parser::OmpObjectList>>(x.t)}) {
1228       context_.Say(parser::FindSourceLocation(flushList),
1229           "If memory-order-clause is RELEASE, ACQUIRE, or ACQ_REL, list items "
1230           "must not be specified on the FLUSH directive"_err_en_US);
1231     }
1232   }
1233   dirContext_.pop_back();
1234 }
1235 
1236 void OmpStructureChecker::Enter(const parser::OpenMPCancelConstruct &x) {
1237   const auto &dir{std::get<parser::Verbatim>(x.t)};
1238   const auto &type{std::get<parser::OmpCancelType>(x.t)};
1239   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_cancel);
1240   CheckCancellationNest(dir.source, type.v);
1241 }
1242 
1243 void OmpStructureChecker::Leave(const parser::OpenMPCancelConstruct &) {
1244   dirContext_.pop_back();
1245 }
1246 
1247 void OmpStructureChecker::Enter(const parser::OpenMPCriticalConstruct &x) {
1248   const auto &dir{std::get<parser::OmpCriticalDirective>(x.t)};
1249   const auto &endDir{std::get<parser::OmpEndCriticalDirective>(x.t)};
1250   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_critical);
1251   const auto &block{std::get<parser::Block>(x.t)};
1252   CheckNoBranching(block, llvm::omp::Directive::OMPD_critical, dir.source);
1253   const auto &dirName{std::get<std::optional<parser::Name>>(dir.t)};
1254   const auto &endDirName{std::get<std::optional<parser::Name>>(endDir.t)};
1255   const auto &ompClause{std::get<parser::OmpClauseList>(dir.t)};
1256   if (dirName && endDirName &&
1257       dirName->ToString().compare(endDirName->ToString())) {
1258     context_
1259         .Say(endDirName->source,
1260             parser::MessageFormattedText{
1261                 "CRITICAL directive names do not match"_err_en_US})
1262         .Attach(dirName->source, "should be "_en_US);
1263   } else if (dirName && !endDirName) {
1264     context_
1265         .Say(dirName->source,
1266             parser::MessageFormattedText{
1267                 "CRITICAL directive names do not match"_err_en_US})
1268         .Attach(dirName->source, "should be NULL"_en_US);
1269   } else if (!dirName && endDirName) {
1270     context_
1271         .Say(endDirName->source,
1272             parser::MessageFormattedText{
1273                 "CRITICAL directive names do not match"_err_en_US})
1274         .Attach(endDirName->source, "should be NULL"_en_US);
1275   }
1276   if (!dirName && !ompClause.source.empty() &&
1277       ompClause.source.NULTerminatedToString() != "hint(omp_sync_hint_none)") {
1278     context_.Say(dir.source,
1279         parser::MessageFormattedText{
1280             "Hint clause other than omp_sync_hint_none cannot be specified for an unnamed CRITICAL directive"_err_en_US});
1281   }
1282 }
1283 
1284 void OmpStructureChecker::Leave(const parser::OpenMPCriticalConstruct &) {
1285   dirContext_.pop_back();
1286 }
1287 
1288 void OmpStructureChecker::Enter(
1289     const parser::OpenMPCancellationPointConstruct &x) {
1290   const auto &dir{std::get<parser::Verbatim>(x.t)};
1291   const auto &type{std::get<parser::OmpCancelType>(x.t)};
1292   PushContextAndClauseSets(
1293       dir.source, llvm::omp::Directive::OMPD_cancellation_point);
1294   CheckCancellationNest(dir.source, type.v);
1295 }
1296 
1297 void OmpStructureChecker::Leave(
1298     const parser::OpenMPCancellationPointConstruct &) {
1299   dirContext_.pop_back();
1300 }
1301 
1302 void OmpStructureChecker::CheckCancellationNest(
1303     const parser::CharBlock &source, const parser::OmpCancelType::Type &type) {
1304   if (CurrentDirectiveIsNested()) {
1305     // If construct-type-clause is taskgroup, the cancellation construct must be
1306     // closely nested inside a task or a taskloop construct and the cancellation
1307     // region must be closely nested inside a taskgroup region. If
1308     // construct-type-clause is sections, the cancellation construct must be
1309     // closely nested inside a sections or section construct. Otherwise, the
1310     // cancellation construct must be closely nested inside an OpenMP construct
1311     // that matches the type specified in construct-type-clause of the
1312     // cancellation construct.
1313 
1314     OmpDirectiveSet allowedTaskgroupSet{
1315         llvm::omp::Directive::OMPD_task, llvm::omp::Directive::OMPD_taskloop};
1316     OmpDirectiveSet allowedSectionsSet{llvm::omp::Directive::OMPD_sections,
1317         llvm::omp::Directive::OMPD_parallel_sections};
1318     OmpDirectiveSet allowedDoSet{llvm::omp::Directive::OMPD_do,
1319         llvm::omp::Directive::OMPD_distribute_parallel_do,
1320         llvm::omp::Directive::OMPD_parallel_do,
1321         llvm::omp::Directive::OMPD_target_parallel_do,
1322         llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do,
1323         llvm::omp::Directive::OMPD_teams_distribute_parallel_do};
1324     OmpDirectiveSet allowedParallelSet{llvm::omp::Directive::OMPD_parallel,
1325         llvm::omp::Directive::OMPD_target_parallel};
1326 
1327     bool eligibleCancellation{false};
1328     switch (type) {
1329     case parser::OmpCancelType::Type::Taskgroup:
1330       if (allowedTaskgroupSet.test(GetContextParent().directive)) {
1331         eligibleCancellation = true;
1332         if (dirContext_.size() >= 3) {
1333           // Check if the cancellation region is closely nested inside a
1334           // taskgroup region when there are more than two levels of directives
1335           // in the directive context stack.
1336           if (GetContextParent().directive == llvm::omp::Directive::OMPD_task ||
1337               FindClauseParent(llvm::omp::Clause::OMPC_nogroup)) {
1338             for (int i = dirContext_.size() - 3; i >= 0; i--) {
1339               if (dirContext_[i].directive ==
1340                   llvm::omp::Directive::OMPD_taskgroup) {
1341                 break;
1342               }
1343               if (allowedParallelSet.test(dirContext_[i].directive)) {
1344                 eligibleCancellation = false;
1345                 break;
1346               }
1347             }
1348           }
1349         }
1350       }
1351       if (!eligibleCancellation) {
1352         context_.Say(source,
1353             "With %s clause, %s construct must be closely nested inside TASK "
1354             "or TASKLOOP construct and %s region must be closely nested inside "
1355             "TASKGROUP region"_err_en_US,
1356             parser::ToUpperCaseLetters(
1357                 parser::OmpCancelType::EnumToString(type)),
1358             ContextDirectiveAsFortran(), ContextDirectiveAsFortran());
1359       }
1360       return;
1361     case parser::OmpCancelType::Type::Sections:
1362       if (allowedSectionsSet.test(GetContextParent().directive)) {
1363         eligibleCancellation = true;
1364       }
1365       break;
1366     case Fortran::parser::OmpCancelType::Type::Do:
1367       if (allowedDoSet.test(GetContextParent().directive)) {
1368         eligibleCancellation = true;
1369       }
1370       break;
1371     case parser::OmpCancelType::Type::Parallel:
1372       if (allowedParallelSet.test(GetContextParent().directive)) {
1373         eligibleCancellation = true;
1374       }
1375       break;
1376     }
1377     if (!eligibleCancellation) {
1378       context_.Say(source,
1379           "With %s clause, %s construct cannot be closely nested inside %s "
1380           "construct"_err_en_US,
1381           parser::ToUpperCaseLetters(parser::OmpCancelType::EnumToString(type)),
1382           ContextDirectiveAsFortran(),
1383           parser::ToUpperCaseLetters(
1384               getDirectiveName(GetContextParent().directive).str()));
1385     }
1386   } else {
1387     // The cancellation directive cannot be orphaned.
1388     switch (type) {
1389     case parser::OmpCancelType::Type::Taskgroup:
1390       context_.Say(source,
1391           "%s %s directive is not closely nested inside "
1392           "TASK or TASKLOOP"_err_en_US,
1393           ContextDirectiveAsFortran(),
1394           parser::ToUpperCaseLetters(
1395               parser::OmpCancelType::EnumToString(type)));
1396       break;
1397     case parser::OmpCancelType::Type::Sections:
1398       context_.Say(source,
1399           "%s %s directive is not closely nested inside "
1400           "SECTION or SECTIONS"_err_en_US,
1401           ContextDirectiveAsFortran(),
1402           parser::ToUpperCaseLetters(
1403               parser::OmpCancelType::EnumToString(type)));
1404       break;
1405     case Fortran::parser::OmpCancelType::Type::Do:
1406       context_.Say(source,
1407           "%s %s directive is not closely nested inside "
1408           "the construct that matches the DO clause type"_err_en_US,
1409           ContextDirectiveAsFortran(),
1410           parser::ToUpperCaseLetters(
1411               parser::OmpCancelType::EnumToString(type)));
1412       break;
1413     case parser::OmpCancelType::Type::Parallel:
1414       context_.Say(source,
1415           "%s %s directive is not closely nested inside "
1416           "the construct that matches the PARALLEL clause type"_err_en_US,
1417           ContextDirectiveAsFortran(),
1418           parser::ToUpperCaseLetters(
1419               parser::OmpCancelType::EnumToString(type)));
1420       break;
1421     }
1422   }
1423 }
1424 
1425 void OmpStructureChecker::Enter(const parser::OmpEndBlockDirective &x) {
1426   const auto &dir{std::get<parser::OmpBlockDirective>(x.t)};
1427   ResetPartialContext(dir.source);
1428   switch (dir.v) {
1429   // 2.7.3 end-single-clause -> copyprivate-clause |
1430   //                            nowait-clause
1431   case llvm::omp::Directive::OMPD_single:
1432     PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_end_single);
1433     break;
1434   // 2.7.4 end-workshare -> END WORKSHARE [nowait-clause]
1435   case llvm::omp::Directive::OMPD_workshare:
1436     PushContextAndClauseSets(
1437         dir.source, llvm::omp::Directive::OMPD_end_workshare);
1438     break;
1439   default:
1440     // no clauses are allowed
1441     break;
1442   }
1443 }
1444 
1445 // TODO: Verify the popping of dirContext requirement after nowait
1446 // implementation, as there is an implicit barrier at the end of the worksharing
1447 // constructs unless a nowait clause is specified. Only OMPD_end_single and
1448 // end_workshareare popped as they are pushed while entering the
1449 // EndBlockDirective.
1450 void OmpStructureChecker::Leave(const parser::OmpEndBlockDirective &x) {
1451   if ((GetContext().directive == llvm::omp::Directive::OMPD_end_single) ||
1452       (GetContext().directive == llvm::omp::Directive::OMPD_end_workshare)) {
1453     dirContext_.pop_back();
1454   }
1455 }
1456 
1457 template <typename T, typename D>
1458 bool OmpStructureChecker::IsOperatorValid(const T &node, const D &variable) {
1459   using AllowedBinaryOperators =
1460       std::variant<parser::Expr::Add, parser::Expr::Multiply,
1461           parser::Expr::Subtract, parser::Expr::Divide, parser::Expr::AND,
1462           parser::Expr::OR, parser::Expr::EQV, parser::Expr::NEQV>;
1463   using BinaryOperators = std::variant<parser::Expr::Add,
1464       parser::Expr::Multiply, parser::Expr::Subtract, parser::Expr::Divide,
1465       parser::Expr::AND, parser::Expr::OR, parser::Expr::EQV,
1466       parser::Expr::NEQV, parser::Expr::Power, parser::Expr::Concat,
1467       parser::Expr::LT, parser::Expr::LE, parser::Expr::EQ, parser::Expr::NE,
1468       parser::Expr::GE, parser::Expr::GT>;
1469 
1470   if constexpr (common::HasMember<T, BinaryOperators>) {
1471     const auto &variableName{variable.GetSource().ToString()};
1472     const auto &exprLeft{std::get<0>(node.t)};
1473     const auto &exprRight{std::get<1>(node.t)};
1474     if ((exprLeft.value().source.ToString() != variableName) &&
1475         (exprRight.value().source.ToString() != variableName)) {
1476       context_.Say(variable.GetSource(),
1477           "Atomic update variable '%s' not found in the RHS of the "
1478           "assignment statement in an ATOMIC (UPDATE) construct"_err_en_US,
1479           variableName);
1480     }
1481     return common::HasMember<T, AllowedBinaryOperators>;
1482   }
1483   return true;
1484 }
1485 
1486 void OmpStructureChecker::CheckAtomicUpdateAssignmentStmt(
1487     const parser::AssignmentStmt &assignment) {
1488   const auto &expr{std::get<parser::Expr>(assignment.t)};
1489   const auto &var{std::get<parser::Variable>(assignment.t)};
1490   common::visit(
1491       common::visitors{
1492           [&](const common::Indirection<parser::FunctionReference> &x) {
1493             const auto &procedureDesignator{
1494                 std::get<parser::ProcedureDesignator>(x.value().v.t)};
1495             const parser::Name *name{
1496                 std::get_if<parser::Name>(&procedureDesignator.u)};
1497             if (name &&
1498                 !(name->source == "max" || name->source == "min" ||
1499                     name->source == "iand" || name->source == "ior" ||
1500                     name->source == "ieor")) {
1501               context_.Say(expr.source,
1502                   "Invalid intrinsic procedure name in "
1503                   "OpenMP ATOMIC (UPDATE) statement"_err_en_US);
1504             } else if (name) {
1505               bool foundMatch{false};
1506               if (auto varDesignatorIndirection =
1507                       std::get_if<Fortran::common::Indirection<
1508                           Fortran::parser::Designator>>(&var.u)) {
1509                 const auto &varDesignator = varDesignatorIndirection->value();
1510                 if (const auto *dataRef = std::get_if<Fortran::parser::DataRef>(
1511                         &varDesignator.u)) {
1512                   if (const auto *name =
1513                           std::get_if<Fortran::parser::Name>(&dataRef->u)) {
1514                     const auto &varSymbol = *name->symbol;
1515                     if (const auto *e{GetExpr(context_, expr)}) {
1516                       for (const Symbol &symbol :
1517                           evaluate::CollectSymbols(*e)) {
1518                         if (symbol == varSymbol) {
1519                           foundMatch = true;
1520                           break;
1521                         }
1522                       }
1523                     }
1524                   }
1525                 }
1526               }
1527               if (!foundMatch) {
1528                 context_.Say(expr.source,
1529                     "Atomic update variable '%s' not found in the "
1530                     "argument list of intrinsic procedure"_err_en_US,
1531                     var.GetSource().ToString());
1532               }
1533             }
1534           },
1535           [&](const auto &x) {
1536             if (!IsOperatorValid(x, var)) {
1537               context_.Say(expr.source,
1538                   "Invalid operator in OpenMP ATOMIC (UPDATE) statement"_err_en_US);
1539             }
1540           },
1541       },
1542       expr.u);
1543 }
1544 
1545 void OmpStructureChecker::CheckAtomicMemoryOrderClause(
1546     const parser::OmpAtomicClauseList *leftHandClauseList,
1547     const parser::OmpAtomicClauseList *rightHandClauseList) {
1548   int numMemoryOrderClause = 0;
1549   auto checkForValidMemoryOrderClause =
1550       [&](const parser::OmpAtomicClauseList *clauseList) {
1551         for (const auto &clause : clauseList->v) {
1552           if (std::get_if<Fortran::parser::OmpMemoryOrderClause>(&clause.u)) {
1553             numMemoryOrderClause++;
1554             if (numMemoryOrderClause > 1) {
1555               context_.Say(clause.source,
1556                   "More than one memory order clause not allowed on "
1557                   "OpenMP Atomic construct"_err_en_US);
1558               return;
1559             }
1560           }
1561         }
1562       };
1563   if (leftHandClauseList) {
1564     checkForValidMemoryOrderClause(leftHandClauseList);
1565   }
1566   if (rightHandClauseList) {
1567     checkForValidMemoryOrderClause(rightHandClauseList);
1568   }
1569 }
1570 
1571 void OmpStructureChecker::Enter(const parser::OpenMPAtomicConstruct &x) {
1572   common::visit(
1573       common::visitors{
1574           [&](const parser::OmpAtomic &atomicConstruct) {
1575             const auto &dir{std::get<parser::Verbatim>(atomicConstruct.t)};
1576             PushContextAndClauseSets(
1577                 dir.source, llvm::omp::Directive::OMPD_atomic);
1578             CheckAtomicUpdateAssignmentStmt(
1579                 std::get<parser::Statement<parser::AssignmentStmt>>(
1580                     atomicConstruct.t)
1581                     .statement);
1582             CheckAtomicMemoryOrderClause(
1583                 &std::get<parser::OmpAtomicClauseList>(atomicConstruct.t),
1584                 nullptr);
1585           },
1586           [&](const parser::OmpAtomicUpdate &atomicUpdate) {
1587             const auto &dir{std::get<parser::Verbatim>(atomicUpdate.t)};
1588             PushContextAndClauseSets(
1589                 dir.source, llvm::omp::Directive::OMPD_atomic);
1590             CheckAtomicUpdateAssignmentStmt(
1591                 std::get<parser::Statement<parser::AssignmentStmt>>(
1592                     atomicUpdate.t)
1593                     .statement);
1594             CheckAtomicMemoryOrderClause(
1595                 &std::get<0>(atomicUpdate.t), &std::get<2>(atomicUpdate.t));
1596           },
1597           [&](const auto &atomicConstruct) {
1598             const auto &dir{std::get<parser::Verbatim>(atomicConstruct.t)};
1599             PushContextAndClauseSets(
1600                 dir.source, llvm::omp::Directive::OMPD_atomic);
1601             CheckAtomicMemoryOrderClause(&std::get<0>(atomicConstruct.t),
1602                 &std::get<2>(atomicConstruct.t));
1603           },
1604       },
1605       x.u);
1606 }
1607 
1608 void OmpStructureChecker::Leave(const parser::OpenMPAtomicConstruct &) {
1609   dirContext_.pop_back();
1610 }
1611 
1612 // Clauses
1613 // Mainly categorized as
1614 // 1. Checks on 'OmpClauseList' from 'parse-tree.h'.
1615 // 2. Checks on clauses which fall under 'struct OmpClause' from parse-tree.h.
1616 // 3. Checks on clauses which are not in 'struct OmpClause' from parse-tree.h.
1617 
1618 void OmpStructureChecker::Leave(const parser::OmpClauseList &) {
1619   // 2.7.1 Loop Construct Restriction
1620   if (llvm::omp::doSet.test(GetContext().directive)) {
1621     if (auto *clause{FindClause(llvm::omp::Clause::OMPC_schedule)}) {
1622       // only one schedule clause is allowed
1623       const auto &schedClause{std::get<parser::OmpClause::Schedule>(clause->u)};
1624       if (ScheduleModifierHasType(schedClause.v,
1625               parser::OmpScheduleModifierType::ModType::Nonmonotonic)) {
1626         if (FindClause(llvm::omp::Clause::OMPC_ordered)) {
1627           context_.Say(clause->source,
1628               "The NONMONOTONIC modifier cannot be specified "
1629               "if an ORDERED clause is specified"_err_en_US);
1630         }
1631         if (ScheduleModifierHasType(schedClause.v,
1632                 parser::OmpScheduleModifierType::ModType::Monotonic)) {
1633           context_.Say(clause->source,
1634               "The MONOTONIC and NONMONOTONIC modifiers "
1635               "cannot be both specified"_err_en_US);
1636         }
1637       }
1638     }
1639 
1640     if (auto *clause{FindClause(llvm::omp::Clause::OMPC_ordered)}) {
1641       // only one ordered clause is allowed
1642       const auto &orderedClause{
1643           std::get<parser::OmpClause::Ordered>(clause->u)};
1644 
1645       if (orderedClause.v) {
1646         CheckNotAllowedIfClause(
1647             llvm::omp::Clause::OMPC_ordered, {llvm::omp::Clause::OMPC_linear});
1648 
1649         if (auto *clause2{FindClause(llvm::omp::Clause::OMPC_collapse)}) {
1650           const auto &collapseClause{
1651               std::get<parser::OmpClause::Collapse>(clause2->u)};
1652           // ordered and collapse both have parameters
1653           if (const auto orderedValue{GetIntValue(orderedClause.v)}) {
1654             if (const auto collapseValue{GetIntValue(collapseClause.v)}) {
1655               if (*orderedValue > 0 && *orderedValue < *collapseValue) {
1656                 context_.Say(clause->source,
1657                     "The parameter of the ORDERED clause must be "
1658                     "greater than or equal to "
1659                     "the parameter of the COLLAPSE clause"_err_en_US);
1660               }
1661             }
1662           }
1663         }
1664       }
1665 
1666       // TODO: ordered region binding check (requires nesting implementation)
1667     }
1668   } // doSet
1669 
1670   // 2.8.1 Simd Construct Restriction
1671   if (llvm::omp::simdSet.test(GetContext().directive)) {
1672     if (auto *clause{FindClause(llvm::omp::Clause::OMPC_simdlen)}) {
1673       if (auto *clause2{FindClause(llvm::omp::Clause::OMPC_safelen)}) {
1674         const auto &simdlenClause{
1675             std::get<parser::OmpClause::Simdlen>(clause->u)};
1676         const auto &safelenClause{
1677             std::get<parser::OmpClause::Safelen>(clause2->u)};
1678         // simdlen and safelen both have parameters
1679         if (const auto simdlenValue{GetIntValue(simdlenClause.v)}) {
1680           if (const auto safelenValue{GetIntValue(safelenClause.v)}) {
1681             if (*safelenValue > 0 && *simdlenValue > *safelenValue) {
1682               context_.Say(clause->source,
1683                   "The parameter of the SIMDLEN clause must be less than or "
1684                   "equal to the parameter of the SAFELEN clause"_err_en_US);
1685             }
1686           }
1687         }
1688       }
1689     }
1690     // Sema checks related to presence of multiple list items within the same
1691     // clause
1692     CheckMultListItems();
1693   } // SIMD
1694 
1695   // 2.7.3 Single Construct Restriction
1696   if (GetContext().directive == llvm::omp::Directive::OMPD_end_single) {
1697     CheckNotAllowedIfClause(
1698         llvm::omp::Clause::OMPC_copyprivate, {llvm::omp::Clause::OMPC_nowait});
1699   }
1700 
1701   auto testThreadprivateVarErr = [&](Symbol sym, parser::Name name,
1702                                      llvmOmpClause clauseTy) {
1703     if (sym.test(Symbol::Flag::OmpThreadprivate))
1704       context_.Say(name.source,
1705           "A THREADPRIVATE variable cannot be in %s clause"_err_en_US,
1706           parser::ToUpperCaseLetters(getClauseName(clauseTy).str()));
1707   };
1708 
1709   // [5.1] 2.21.2 Threadprivate Directive Restriction
1710   OmpClauseSet threadprivateAllowedSet{llvm::omp::Clause::OMPC_copyin,
1711       llvm::omp::Clause::OMPC_copyprivate, llvm::omp::Clause::OMPC_schedule,
1712       llvm::omp::Clause::OMPC_num_threads, llvm::omp::Clause::OMPC_thread_limit,
1713       llvm::omp::Clause::OMPC_if};
1714   for (auto it : GetContext().clauseInfo) {
1715     llvmOmpClause type = it.first;
1716     const auto *clause = it.second;
1717     if (!threadprivateAllowedSet.test(type)) {
1718       if (const auto *objList{GetOmpObjectList(*clause)}) {
1719         for (const auto &ompObject : objList->v) {
1720           common::visit(
1721               common::visitors{
1722                   [&](const parser::Designator &) {
1723                     if (const auto *name{
1724                             parser::Unwrap<parser::Name>(ompObject)})
1725                       testThreadprivateVarErr(
1726                           name->symbol->GetUltimate(), *name, type);
1727                   },
1728                   [&](const parser::Name &name) {
1729                     if (name.symbol) {
1730                       for (const auto &mem :
1731                           name.symbol->get<CommonBlockDetails>().objects()) {
1732                         testThreadprivateVarErr(mem->GetUltimate(), name, type);
1733                         break;
1734                       }
1735                     }
1736                   },
1737               },
1738               ompObject.u);
1739         }
1740       }
1741     }
1742   }
1743 
1744   CheckRequireAtLeastOneOf();
1745 }
1746 
1747 void OmpStructureChecker::Enter(const parser::OmpClause &x) {
1748   SetContextClause(x);
1749 }
1750 
1751 // Following clauses do not have a separate node in parse-tree.h.
1752 CHECK_SIMPLE_CLAUSE(AcqRel, OMPC_acq_rel)
1753 CHECK_SIMPLE_CLAUSE(Acquire, OMPC_acquire)
1754 CHECK_SIMPLE_CLAUSE(AtomicDefaultMemOrder, OMPC_atomic_default_mem_order)
1755 CHECK_SIMPLE_CLAUSE(Affinity, OMPC_affinity)
1756 CHECK_SIMPLE_CLAUSE(Allocate, OMPC_allocate)
1757 CHECK_SIMPLE_CLAUSE(Capture, OMPC_capture)
1758 CHECK_SIMPLE_CLAUSE(Default, OMPC_default)
1759 CHECK_SIMPLE_CLAUSE(Depobj, OMPC_depobj)
1760 CHECK_SIMPLE_CLAUSE(Destroy, OMPC_destroy)
1761 CHECK_SIMPLE_CLAUSE(Detach, OMPC_detach)
1762 CHECK_SIMPLE_CLAUSE(DeviceType, OMPC_device_type)
1763 CHECK_SIMPLE_CLAUSE(DistSchedule, OMPC_dist_schedule)
1764 CHECK_SIMPLE_CLAUSE(DynamicAllocators, OMPC_dynamic_allocators)
1765 CHECK_SIMPLE_CLAUSE(Exclusive, OMPC_exclusive)
1766 CHECK_SIMPLE_CLAUSE(Final, OMPC_final)
1767 CHECK_SIMPLE_CLAUSE(Flush, OMPC_flush)
1768 CHECK_SIMPLE_CLAUSE(From, OMPC_from)
1769 CHECK_SIMPLE_CLAUSE(Full, OMPC_full)
1770 CHECK_SIMPLE_CLAUSE(Hint, OMPC_hint)
1771 CHECK_SIMPLE_CLAUSE(InReduction, OMPC_in_reduction)
1772 CHECK_SIMPLE_CLAUSE(Inclusive, OMPC_inclusive)
1773 CHECK_SIMPLE_CLAUSE(Match, OMPC_match)
1774 CHECK_SIMPLE_CLAUSE(Nontemporal, OMPC_nontemporal)
1775 CHECK_SIMPLE_CLAUSE(Order, OMPC_order)
1776 CHECK_SIMPLE_CLAUSE(Read, OMPC_read)
1777 CHECK_SIMPLE_CLAUSE(ReverseOffload, OMPC_reverse_offload)
1778 CHECK_SIMPLE_CLAUSE(Threadprivate, OMPC_threadprivate)
1779 CHECK_SIMPLE_CLAUSE(Threads, OMPC_threads)
1780 CHECK_SIMPLE_CLAUSE(Inbranch, OMPC_inbranch)
1781 CHECK_SIMPLE_CLAUSE(IsDevicePtr, OMPC_is_device_ptr)
1782 CHECK_SIMPLE_CLAUSE(HasDeviceAddr, OMPC_has_device_addr)
1783 CHECK_SIMPLE_CLAUSE(Link, OMPC_link)
1784 CHECK_SIMPLE_CLAUSE(Indirect, OMPC_indirect)
1785 CHECK_SIMPLE_CLAUSE(Mergeable, OMPC_mergeable)
1786 CHECK_SIMPLE_CLAUSE(Nogroup, OMPC_nogroup)
1787 CHECK_SIMPLE_CLAUSE(Notinbranch, OMPC_notinbranch)
1788 CHECK_SIMPLE_CLAUSE(Nowait, OMPC_nowait)
1789 CHECK_SIMPLE_CLAUSE(Partial, OMPC_partial)
1790 CHECK_SIMPLE_CLAUSE(ProcBind, OMPC_proc_bind)
1791 CHECK_SIMPLE_CLAUSE(Release, OMPC_release)
1792 CHECK_SIMPLE_CLAUSE(Relaxed, OMPC_relaxed)
1793 CHECK_SIMPLE_CLAUSE(SeqCst, OMPC_seq_cst)
1794 CHECK_SIMPLE_CLAUSE(Simd, OMPC_simd)
1795 CHECK_SIMPLE_CLAUSE(Sizes, OMPC_sizes)
1796 CHECK_SIMPLE_CLAUSE(TaskReduction, OMPC_task_reduction)
1797 CHECK_SIMPLE_CLAUSE(To, OMPC_to)
1798 CHECK_SIMPLE_CLAUSE(UnifiedAddress, OMPC_unified_address)
1799 CHECK_SIMPLE_CLAUSE(UnifiedSharedMemory, OMPC_unified_shared_memory)
1800 CHECK_SIMPLE_CLAUSE(Uniform, OMPC_uniform)
1801 CHECK_SIMPLE_CLAUSE(Unknown, OMPC_unknown)
1802 CHECK_SIMPLE_CLAUSE(Untied, OMPC_untied)
1803 CHECK_SIMPLE_CLAUSE(UseDevicePtr, OMPC_use_device_ptr)
1804 CHECK_SIMPLE_CLAUSE(UsesAllocators, OMPC_uses_allocators)
1805 CHECK_SIMPLE_CLAUSE(Update, OMPC_update)
1806 CHECK_SIMPLE_CLAUSE(UseDeviceAddr, OMPC_use_device_addr)
1807 CHECK_SIMPLE_CLAUSE(Write, OMPC_write)
1808 CHECK_SIMPLE_CLAUSE(Init, OMPC_init)
1809 CHECK_SIMPLE_CLAUSE(Use, OMPC_use)
1810 CHECK_SIMPLE_CLAUSE(Novariants, OMPC_novariants)
1811 CHECK_SIMPLE_CLAUSE(Nocontext, OMPC_nocontext)
1812 CHECK_SIMPLE_CLAUSE(Filter, OMPC_filter)
1813 CHECK_SIMPLE_CLAUSE(When, OMPC_when)
1814 CHECK_SIMPLE_CLAUSE(AdjustArgs, OMPC_adjust_args)
1815 CHECK_SIMPLE_CLAUSE(AppendArgs, OMPC_append_args)
1816 CHECK_SIMPLE_CLAUSE(MemoryOrder, OMPC_memory_order)
1817 CHECK_SIMPLE_CLAUSE(Bind, OMPC_bind)
1818 CHECK_SIMPLE_CLAUSE(Align, OMPC_align)
1819 CHECK_SIMPLE_CLAUSE(Compare, OMPC_compare)
1820 CHECK_SIMPLE_CLAUSE(CancellationConstructType, OMPC_cancellation_construct_type)
1821 
1822 CHECK_REQ_SCALAR_INT_CLAUSE(Grainsize, OMPC_grainsize)
1823 CHECK_REQ_SCALAR_INT_CLAUSE(NumTasks, OMPC_num_tasks)
1824 CHECK_REQ_SCALAR_INT_CLAUSE(NumTeams, OMPC_num_teams)
1825 CHECK_REQ_SCALAR_INT_CLAUSE(NumThreads, OMPC_num_threads)
1826 CHECK_REQ_SCALAR_INT_CLAUSE(Priority, OMPC_priority)
1827 CHECK_REQ_SCALAR_INT_CLAUSE(ThreadLimit, OMPC_thread_limit)
1828 CHECK_REQ_SCALAR_INT_CLAUSE(Device, OMPC_device)
1829 
1830 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Collapse, OMPC_collapse)
1831 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Safelen, OMPC_safelen)
1832 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Simdlen, OMPC_simdlen)
1833 
1834 // Restrictions specific to each clause are implemented apart from the
1835 // generalized restrictions.
1836 void OmpStructureChecker::Enter(const parser::OmpClause::Reduction &x) {
1837   CheckAllowed(llvm::omp::Clause::OMPC_reduction);
1838   if (CheckReductionOperators(x)) {
1839     CheckReductionTypeList(x);
1840   }
1841 }
1842 bool OmpStructureChecker::CheckReductionOperators(
1843     const parser::OmpClause::Reduction &x) {
1844 
1845   const auto &definedOp{std::get<0>(x.v.t)};
1846   bool ok = false;
1847   common::visit(
1848       common::visitors{
1849           [&](const parser::DefinedOperator &dOpr) {
1850             const auto &intrinsicOp{
1851                 std::get<parser::DefinedOperator::IntrinsicOperator>(dOpr.u)};
1852             ok = CheckIntrinsicOperator(intrinsicOp);
1853           },
1854           [&](const parser::ProcedureDesignator &procD) {
1855             const parser::Name *name{std::get_if<parser::Name>(&procD.u)};
1856             if (name) {
1857               if (name->source == "max" || name->source == "min" ||
1858                   name->source == "iand" || name->source == "ior" ||
1859                   name->source == "ieor") {
1860                 ok = true;
1861               } else {
1862                 context_.Say(GetContext().clauseSource,
1863                     "Invalid reduction identifier in REDUCTION clause."_err_en_US,
1864                     ContextDirectiveAsFortran());
1865               }
1866             }
1867           },
1868       },
1869       definedOp.u);
1870 
1871   return ok;
1872 }
1873 bool OmpStructureChecker::CheckIntrinsicOperator(
1874     const parser::DefinedOperator::IntrinsicOperator &op) {
1875 
1876   switch (op) {
1877   case parser::DefinedOperator::IntrinsicOperator::Add:
1878   case parser::DefinedOperator::IntrinsicOperator::Subtract:
1879   case parser::DefinedOperator::IntrinsicOperator::Multiply:
1880   case parser::DefinedOperator::IntrinsicOperator::AND:
1881   case parser::DefinedOperator::IntrinsicOperator::OR:
1882   case parser::DefinedOperator::IntrinsicOperator::EQV:
1883   case parser::DefinedOperator::IntrinsicOperator::NEQV:
1884     return true;
1885   default:
1886     context_.Say(GetContext().clauseSource,
1887         "Invalid reduction operator in REDUCTION clause."_err_en_US,
1888         ContextDirectiveAsFortran());
1889   }
1890   return false;
1891 }
1892 
1893 void OmpStructureChecker::CheckReductionTypeList(
1894     const parser::OmpClause::Reduction &x) {
1895   const auto &ompObjectList{std::get<parser::OmpObjectList>(x.v.t)};
1896   CheckIntentInPointerAndDefinable(
1897       ompObjectList, llvm::omp::Clause::OMPC_reduction);
1898   CheckReductionArraySection(ompObjectList);
1899   CheckMultipleAppearanceAcrossContext(ompObjectList);
1900 }
1901 
1902 void OmpStructureChecker::CheckIntentInPointerAndDefinable(
1903     const parser::OmpObjectList &objectList, const llvm::omp::Clause clause) {
1904   for (const auto &ompObject : objectList.v) {
1905     if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
1906       if (const auto *symbol{name->symbol}) {
1907         if (IsPointer(symbol->GetUltimate()) &&
1908             IsIntentIn(symbol->GetUltimate())) {
1909           context_.Say(GetContext().clauseSource,
1910               "Pointer '%s' with the INTENT(IN) attribute may not appear "
1911               "in a %s clause"_err_en_US,
1912               symbol->name(),
1913               parser::ToUpperCaseLetters(getClauseName(clause).str()));
1914         }
1915         if (auto msg{
1916                 WhyNotModifiable(*symbol, context_.FindScope(name->source))}) {
1917           context_
1918               .Say(GetContext().clauseSource,
1919                   "Variable '%s' on the %s clause is not definable"_err_en_US,
1920                   symbol->name(),
1921                   parser::ToUpperCaseLetters(getClauseName(clause).str()))
1922               .Attach(std::move(*msg));
1923         }
1924       }
1925     }
1926   }
1927 }
1928 
1929 void OmpStructureChecker::CheckReductionArraySection(
1930     const parser::OmpObjectList &ompObjectList) {
1931   for (const auto &ompObject : ompObjectList.v) {
1932     if (const auto *dataRef{parser::Unwrap<parser::DataRef>(ompObject)}) {
1933       if (const auto *arrayElement{
1934               parser::Unwrap<parser::ArrayElement>(ompObject)}) {
1935         if (arrayElement) {
1936           CheckArraySection(*arrayElement, GetLastName(*dataRef),
1937               llvm::omp::Clause::OMPC_reduction);
1938         }
1939       }
1940     }
1941   }
1942 }
1943 
1944 void OmpStructureChecker::CheckMultipleAppearanceAcrossContext(
1945     const parser::OmpObjectList &redObjectList) {
1946   //  TODO: Verify the assumption here that the immediately enclosing region is
1947   //  the parallel region to which the worksharing construct having reduction
1948   //  binds to.
1949   if (auto *enclosingContext{GetEnclosingDirContext()}) {
1950     for (auto it : enclosingContext->clauseInfo) {
1951       llvmOmpClause type = it.first;
1952       const auto *clause = it.second;
1953       if (llvm::omp::privateReductionSet.test(type)) {
1954         if (const auto *objList{GetOmpObjectList(*clause)}) {
1955           for (const auto &ompObject : objList->v) {
1956             if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
1957               if (const auto *symbol{name->symbol}) {
1958                 for (const auto &redOmpObject : redObjectList.v) {
1959                   if (const auto *rname{
1960                           parser::Unwrap<parser::Name>(redOmpObject)}) {
1961                     if (const auto *rsymbol{rname->symbol}) {
1962                       if (rsymbol->name() == symbol->name()) {
1963                         context_.Say(GetContext().clauseSource,
1964                             "%s variable '%s' is %s in outer context must"
1965                             " be shared in the parallel regions to which any"
1966                             " of the worksharing regions arising from the "
1967                             "worksharing"
1968                             " construct bind."_err_en_US,
1969                             parser::ToUpperCaseLetters(
1970                                 getClauseName(llvm::omp::Clause::OMPC_reduction)
1971                                     .str()),
1972                             symbol->name(),
1973                             parser::ToUpperCaseLetters(
1974                                 getClauseName(type).str()));
1975                       }
1976                     }
1977                   }
1978                 }
1979               }
1980             }
1981           }
1982         }
1983       }
1984     }
1985   }
1986 }
1987 
1988 void OmpStructureChecker::Enter(const parser::OmpClause::Ordered &x) {
1989   CheckAllowed(llvm::omp::Clause::OMPC_ordered);
1990   // the parameter of ordered clause is optional
1991   if (const auto &expr{x.v}) {
1992     RequiresConstantPositiveParameter(llvm::omp::Clause::OMPC_ordered, *expr);
1993     // 2.8.3 Loop SIMD Construct Restriction
1994     if (llvm::omp::doSimdSet.test(GetContext().directive)) {
1995       context_.Say(GetContext().clauseSource,
1996           "No ORDERED clause with a parameter can be specified "
1997           "on the %s directive"_err_en_US,
1998           ContextDirectiveAsFortran());
1999     }
2000   }
2001 }
2002 
2003 void OmpStructureChecker::Enter(const parser::OmpClause::Shared &x) {
2004   CheckAllowed(llvm::omp::Clause::OMPC_shared);
2005   CheckIsVarPartOfAnotherVar(GetContext().clauseSource, x.v);
2006 }
2007 void OmpStructureChecker::Enter(const parser::OmpClause::Private &x) {
2008   CheckAllowed(llvm::omp::Clause::OMPC_private);
2009   CheckIsVarPartOfAnotherVar(GetContext().clauseSource, x.v);
2010   CheckIntentInPointer(x.v, llvm::omp::Clause::OMPC_private);
2011 }
2012 
2013 bool OmpStructureChecker::IsDataRefTypeParamInquiry(
2014     const parser::DataRef *dataRef) {
2015   bool dataRefIsTypeParamInquiry{false};
2016   if (const auto *structComp{
2017           parser::Unwrap<parser::StructureComponent>(dataRef)}) {
2018     if (const auto *compSymbol{structComp->component.symbol}) {
2019       if (const auto *compSymbolMiscDetails{
2020               std::get_if<MiscDetails>(&compSymbol->details())}) {
2021         const auto detailsKind = compSymbolMiscDetails->kind();
2022         dataRefIsTypeParamInquiry =
2023             (detailsKind == MiscDetails::Kind::KindParamInquiry ||
2024                 detailsKind == MiscDetails::Kind::LenParamInquiry);
2025       } else if (compSymbol->has<TypeParamDetails>()) {
2026         dataRefIsTypeParamInquiry = true;
2027       }
2028     }
2029   }
2030   return dataRefIsTypeParamInquiry;
2031 }
2032 
2033 void OmpStructureChecker::CheckIsVarPartOfAnotherVar(
2034     const parser::CharBlock &source, const parser::OmpObjectList &objList) {
2035   OmpDirectiveSet nonPartialVarSet{llvm::omp::Directive::OMPD_allocate,
2036       llvm::omp::Directive::OMPD_threadprivate,
2037       llvm::omp::Directive::OMPD_declare_target};
2038   for (const auto &ompObject : objList.v) {
2039     common::visit(
2040         common::visitors{
2041             [&](const parser::Designator &designator) {
2042               if (const auto *dataRef{
2043                       std::get_if<parser::DataRef>(&designator.u)}) {
2044                 if (IsDataRefTypeParamInquiry(dataRef)) {
2045                   context_.Say(source,
2046                       "A type parameter inquiry cannot appear on the %s "
2047                       "directive"_err_en_US,
2048                       ContextDirectiveAsFortran());
2049                 } else if (parser::Unwrap<parser::StructureComponent>(
2050                                ompObject) ||
2051                     parser::Unwrap<parser::ArrayElement>(ompObject)) {
2052                   if (nonPartialVarSet.test(GetContext().directive)) {
2053                     context_.Say(source,
2054                         "A variable that is part of another variable (as an "
2055                         "array or structure element) cannot appear on the %s "
2056                         "directive"_err_en_US,
2057                         ContextDirectiveAsFortran());
2058                   } else {
2059                     context_.Say(source,
2060                         "A variable that is part of another variable (as an "
2061                         "array or structure element) cannot appear in a "
2062                         "PRIVATE or SHARED clause"_err_en_US);
2063                   }
2064                 }
2065               }
2066             },
2067             [&](const parser::Name &name) {},
2068         },
2069         ompObject.u);
2070   }
2071 }
2072 
2073 void OmpStructureChecker::Enter(const parser::OmpClause::Firstprivate &x) {
2074   CheckAllowed(llvm::omp::Clause::OMPC_firstprivate);
2075   CheckIsLoopIvPartOfClause(llvmOmpClause::OMPC_firstprivate, x.v);
2076 
2077   SymbolSourceMap currSymbols;
2078   GetSymbolsInObjectList(x.v, currSymbols);
2079   CheckCopyingPolymorphicAllocatable(
2080       currSymbols, llvm::omp::Clause::OMPC_firstprivate);
2081 
2082   DirectivesClauseTriple dirClauseTriple;
2083   // Check firstprivate variables in worksharing constructs
2084   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_do,
2085       std::make_pair(
2086           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
2087   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_sections,
2088       std::make_pair(
2089           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
2090   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_single,
2091       std::make_pair(
2092           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
2093   // Check firstprivate variables in distribute construct
2094   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_distribute,
2095       std::make_pair(
2096           llvm::omp::Directive::OMPD_teams, llvm::omp::privateReductionSet));
2097   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_distribute,
2098       std::make_pair(llvm::omp::Directive::OMPD_target_teams,
2099           llvm::omp::privateReductionSet));
2100   // Check firstprivate variables in task and taskloop constructs
2101   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_task,
2102       std::make_pair(llvm::omp::Directive::OMPD_parallel,
2103           OmpClauseSet{llvm::omp::Clause::OMPC_reduction}));
2104   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_taskloop,
2105       std::make_pair(llvm::omp::Directive::OMPD_parallel,
2106           OmpClauseSet{llvm::omp::Clause::OMPC_reduction}));
2107 
2108   CheckPrivateSymbolsInOuterCxt(
2109       currSymbols, dirClauseTriple, llvm::omp::Clause::OMPC_firstprivate);
2110 }
2111 
2112 void OmpStructureChecker::CheckIsLoopIvPartOfClause(
2113     llvmOmpClause clause, const parser::OmpObjectList &ompObjectList) {
2114   for (const auto &ompObject : ompObjectList.v) {
2115     if (const parser::Name * name{parser::Unwrap<parser::Name>(ompObject)}) {
2116       if (name->symbol == GetContext().loopIV) {
2117         context_.Say(name->source,
2118             "DO iteration variable %s is not allowed in %s clause."_err_en_US,
2119             name->ToString(),
2120             parser::ToUpperCaseLetters(getClauseName(clause).str()));
2121       }
2122     }
2123   }
2124 }
2125 // Following clauses have a seperate node in parse-tree.h.
2126 // Atomic-clause
2127 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicRead, OMPC_read)
2128 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicWrite, OMPC_write)
2129 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicUpdate, OMPC_update)
2130 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicCapture, OMPC_capture)
2131 
2132 void OmpStructureChecker::Leave(const parser::OmpAtomicRead &) {
2133   CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_read,
2134       {llvm::omp::Clause::OMPC_release, llvm::omp::Clause::OMPC_acq_rel});
2135 }
2136 void OmpStructureChecker::Leave(const parser::OmpAtomicWrite &) {
2137   CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_write,
2138       {llvm::omp::Clause::OMPC_acquire, llvm::omp::Clause::OMPC_acq_rel});
2139 }
2140 void OmpStructureChecker::Leave(const parser::OmpAtomicUpdate &) {
2141   CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_update,
2142       {llvm::omp::Clause::OMPC_acquire, llvm::omp::Clause::OMPC_acq_rel});
2143 }
2144 // OmpAtomic node represents atomic directive without atomic-clause.
2145 // atomic-clause - READ,WRITE,UPDATE,CAPTURE.
2146 void OmpStructureChecker::Leave(const parser::OmpAtomic &) {
2147   if (const auto *clause{FindClause(llvm::omp::Clause::OMPC_acquire)}) {
2148     context_.Say(clause->source,
2149         "Clause ACQUIRE is not allowed on the ATOMIC directive"_err_en_US);
2150   }
2151   if (const auto *clause{FindClause(llvm::omp::Clause::OMPC_acq_rel)}) {
2152     context_.Say(clause->source,
2153         "Clause ACQ_REL is not allowed on the ATOMIC directive"_err_en_US);
2154   }
2155 }
2156 // Restrictions specific to each clause are implemented apart from the
2157 // generalized restrictions.
2158 void OmpStructureChecker::Enter(const parser::OmpClause::Aligned &x) {
2159   CheckAllowed(llvm::omp::Clause::OMPC_aligned);
2160 
2161   if (const auto &expr{
2162           std::get<std::optional<parser::ScalarIntConstantExpr>>(x.v.t)}) {
2163     RequiresConstantPositiveParameter(llvm::omp::Clause::OMPC_aligned, *expr);
2164   }
2165   // 2.8.1 TODO: list-item attribute check
2166 }
2167 void OmpStructureChecker::Enter(const parser::OmpClause::Defaultmap &x) {
2168   CheckAllowed(llvm::omp::Clause::OMPC_defaultmap);
2169   using VariableCategory = parser::OmpDefaultmapClause::VariableCategory;
2170   if (!std::get<std::optional<VariableCategory>>(x.v.t)) {
2171     context_.Say(GetContext().clauseSource,
2172         "The argument TOFROM:SCALAR must be specified on the DEFAULTMAP "
2173         "clause"_err_en_US);
2174   }
2175 }
2176 void OmpStructureChecker::Enter(const parser::OmpClause::If &x) {
2177   CheckAllowed(llvm::omp::Clause::OMPC_if);
2178   using dirNameModifier = parser::OmpIfClause::DirectiveNameModifier;
2179   static std::unordered_map<dirNameModifier, OmpDirectiveSet>
2180       dirNameModifierMap{{dirNameModifier::Parallel, llvm::omp::parallelSet},
2181           {dirNameModifier::Target, llvm::omp::targetSet},
2182           {dirNameModifier::TargetEnterData,
2183               {llvm::omp::Directive::OMPD_target_enter_data}},
2184           {dirNameModifier::TargetExitData,
2185               {llvm::omp::Directive::OMPD_target_exit_data}},
2186           {dirNameModifier::TargetData,
2187               {llvm::omp::Directive::OMPD_target_data}},
2188           {dirNameModifier::TargetUpdate,
2189               {llvm::omp::Directive::OMPD_target_update}},
2190           {dirNameModifier::Task, {llvm::omp::Directive::OMPD_task}},
2191           {dirNameModifier::Taskloop, llvm::omp::taskloopSet}};
2192   if (const auto &directiveName{
2193           std::get<std::optional<dirNameModifier>>(x.v.t)}) {
2194     auto search{dirNameModifierMap.find(*directiveName)};
2195     if (search == dirNameModifierMap.end() ||
2196         !search->second.test(GetContext().directive)) {
2197       context_
2198           .Say(GetContext().clauseSource,
2199               "Unmatched directive name modifier %s on the IF clause"_err_en_US,
2200               parser::ToUpperCaseLetters(
2201                   parser::OmpIfClause::EnumToString(*directiveName)))
2202           .Attach(
2203               GetContext().directiveSource, "Cannot apply to directive"_en_US);
2204     }
2205   }
2206 }
2207 
2208 void OmpStructureChecker::Enter(const parser::OmpClause::Linear &x) {
2209   CheckAllowed(llvm::omp::Clause::OMPC_linear);
2210 
2211   // 2.7 Loop Construct Restriction
2212   if ((llvm::omp::doSet | llvm::omp::simdSet).test(GetContext().directive)) {
2213     if (std::holds_alternative<parser::OmpLinearClause::WithModifier>(x.v.u)) {
2214       context_.Say(GetContext().clauseSource,
2215           "A modifier may not be specified in a LINEAR clause "
2216           "on the %s directive"_err_en_US,
2217           ContextDirectiveAsFortran());
2218     }
2219   }
2220 }
2221 
2222 void OmpStructureChecker::CheckAllowedMapTypes(
2223     const parser::OmpMapType::Type &type,
2224     const std::list<parser::OmpMapType::Type> &allowedMapTypeList) {
2225   const auto found{std::find(
2226       std::begin(allowedMapTypeList), std::end(allowedMapTypeList), type)};
2227   if (found == std::end(allowedMapTypeList)) {
2228     std::string commaSeperatedMapTypes;
2229     llvm::interleave(
2230         allowedMapTypeList.begin(), allowedMapTypeList.end(),
2231         [&](const parser::OmpMapType::Type &mapType) {
2232           commaSeperatedMapTypes.append(parser::ToUpperCaseLetters(
2233               parser::OmpMapType::EnumToString(mapType)));
2234         },
2235         [&] { commaSeperatedMapTypes.append(", "); });
2236     context_.Say(GetContext().clauseSource,
2237         "Only the %s map types are permitted "
2238         "for MAP clauses on the %s directive"_err_en_US,
2239         commaSeperatedMapTypes, ContextDirectiveAsFortran());
2240   }
2241 }
2242 
2243 void OmpStructureChecker::Enter(const parser::OmpClause::Map &x) {
2244   CheckAllowed(llvm::omp::Clause::OMPC_map);
2245 
2246   if (const auto &maptype{std::get<std::optional<parser::OmpMapType>>(x.v.t)}) {
2247     using Type = parser::OmpMapType::Type;
2248     const Type &type{std::get<Type>(maptype->t)};
2249     switch (GetContext().directive) {
2250     case llvm::omp::Directive::OMPD_target:
2251     case llvm::omp::Directive::OMPD_target_teams:
2252     case llvm::omp::Directive::OMPD_target_teams_distribute:
2253     case llvm::omp::Directive::OMPD_target_teams_distribute_simd:
2254     case llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do:
2255     case llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do_simd:
2256     case llvm::omp::Directive::OMPD_target_data:
2257       CheckAllowedMapTypes(
2258           type, {Type::To, Type::From, Type::Tofrom, Type::Alloc});
2259       break;
2260     case llvm::omp::Directive::OMPD_target_enter_data:
2261       CheckAllowedMapTypes(type, {Type::To, Type::Alloc});
2262       break;
2263     case llvm::omp::Directive::OMPD_target_exit_data:
2264       CheckAllowedMapTypes(type, {Type::From, Type::Release, Type::Delete});
2265       break;
2266     default:
2267       break;
2268     }
2269   }
2270 }
2271 
2272 bool OmpStructureChecker::ScheduleModifierHasType(
2273     const parser::OmpScheduleClause &x,
2274     const parser::OmpScheduleModifierType::ModType &type) {
2275   const auto &modifier{
2276       std::get<std::optional<parser::OmpScheduleModifier>>(x.t)};
2277   if (modifier) {
2278     const auto &modType1{
2279         std::get<parser::OmpScheduleModifier::Modifier1>(modifier->t)};
2280     const auto &modType2{
2281         std::get<std::optional<parser::OmpScheduleModifier::Modifier2>>(
2282             modifier->t)};
2283     if (modType1.v.v == type || (modType2 && modType2->v.v == type)) {
2284       return true;
2285     }
2286   }
2287   return false;
2288 }
2289 void OmpStructureChecker::Enter(const parser::OmpClause::Schedule &x) {
2290   CheckAllowed(llvm::omp::Clause::OMPC_schedule);
2291   const parser::OmpScheduleClause &scheduleClause = x.v;
2292 
2293   // 2.7 Loop Construct Restriction
2294   if (llvm::omp::doSet.test(GetContext().directive)) {
2295     const auto &kind{std::get<1>(scheduleClause.t)};
2296     const auto &chunk{std::get<2>(scheduleClause.t)};
2297     if (chunk) {
2298       if (kind == parser::OmpScheduleClause::ScheduleType::Runtime ||
2299           kind == parser::OmpScheduleClause::ScheduleType::Auto) {
2300         context_.Say(GetContext().clauseSource,
2301             "When SCHEDULE clause has %s specified, "
2302             "it must not have chunk size specified"_err_en_US,
2303             parser::ToUpperCaseLetters(
2304                 parser::OmpScheduleClause::EnumToString(kind)));
2305       }
2306       if (const auto &chunkExpr{std::get<std::optional<parser::ScalarIntExpr>>(
2307               scheduleClause.t)}) {
2308         RequiresPositiveParameter(
2309             llvm::omp::Clause::OMPC_schedule, *chunkExpr, "chunk size");
2310       }
2311     }
2312 
2313     if (ScheduleModifierHasType(scheduleClause,
2314             parser::OmpScheduleModifierType::ModType::Nonmonotonic)) {
2315       if (kind != parser::OmpScheduleClause::ScheduleType::Dynamic &&
2316           kind != parser::OmpScheduleClause::ScheduleType::Guided) {
2317         context_.Say(GetContext().clauseSource,
2318             "The NONMONOTONIC modifier can only be specified with "
2319             "SCHEDULE(DYNAMIC) or SCHEDULE(GUIDED)"_err_en_US);
2320       }
2321     }
2322   }
2323 }
2324 
2325 void OmpStructureChecker::Enter(const parser::OmpClause::Depend &x) {
2326   CheckAllowed(llvm::omp::Clause::OMPC_depend);
2327   if (const auto *inOut{std::get_if<parser::OmpDependClause::InOut>(&x.v.u)}) {
2328     const auto &designators{std::get<std::list<parser::Designator>>(inOut->t)};
2329     for (const auto &ele : designators) {
2330       if (const auto *dataRef{std::get_if<parser::DataRef>(&ele.u)}) {
2331         CheckDependList(*dataRef);
2332         if (const auto *arr{
2333                 std::get_if<common::Indirection<parser::ArrayElement>>(
2334                     &dataRef->u)}) {
2335           CheckArraySection(arr->value(), GetLastName(*dataRef),
2336               llvm::omp::Clause::OMPC_depend);
2337         }
2338       }
2339     }
2340   }
2341 }
2342 
2343 void OmpStructureChecker::CheckCopyingPolymorphicAllocatable(
2344     SymbolSourceMap &symbols, const llvm::omp::Clause clause) {
2345   for (auto it{symbols.begin()}; it != symbols.end(); ++it) {
2346     const auto *symbol{it->first};
2347     const auto source{it->second};
2348     if (IsPolymorphicAllocatable(*symbol)) {
2349       context_.Say(source,
2350           "If a polymorphic variable with allocatable attribute '%s' is in "
2351           "%s clause, the behavior is unspecified"_port_en_US,
2352           symbol->name(),
2353           parser::ToUpperCaseLetters(getClauseName(clause).str()));
2354     }
2355   }
2356 }
2357 
2358 void OmpStructureChecker::Enter(const parser::OmpClause::Copyprivate &x) {
2359   CheckAllowed(llvm::omp::Clause::OMPC_copyprivate);
2360   CheckIntentInPointer(x.v, llvm::omp::Clause::OMPC_copyprivate);
2361   SymbolSourceMap currSymbols;
2362   GetSymbolsInObjectList(x.v, currSymbols);
2363   CheckCopyingPolymorphicAllocatable(
2364       currSymbols, llvm::omp::Clause::OMPC_copyprivate);
2365 }
2366 
2367 void OmpStructureChecker::Enter(const parser::OmpClause::Lastprivate &x) {
2368   CheckAllowed(llvm::omp::Clause::OMPC_lastprivate);
2369 
2370   DirectivesClauseTriple dirClauseTriple;
2371   SymbolSourceMap currSymbols;
2372   GetSymbolsInObjectList(x.v, currSymbols);
2373   CheckDefinableObjects(currSymbols, GetClauseKindForParserClass(x));
2374   CheckCopyingPolymorphicAllocatable(
2375       currSymbols, llvm::omp::Clause::OMPC_lastprivate);
2376 
2377   // Check lastprivate variables in worksharing constructs
2378   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_do,
2379       std::make_pair(
2380           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
2381   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_sections,
2382       std::make_pair(
2383           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
2384 
2385   CheckPrivateSymbolsInOuterCxt(
2386       currSymbols, dirClauseTriple, GetClauseKindForParserClass(x));
2387 }
2388 
2389 void OmpStructureChecker::Enter(const parser::OmpClause::Copyin &x) {
2390   CheckAllowed(llvm::omp::Clause::OMPC_copyin);
2391 
2392   SymbolSourceMap currSymbols;
2393   GetSymbolsInObjectList(x.v, currSymbols);
2394   CheckCopyingPolymorphicAllocatable(
2395       currSymbols, llvm::omp::Clause::OMPC_copyin);
2396 }
2397 
2398 llvm::StringRef OmpStructureChecker::getClauseName(llvm::omp::Clause clause) {
2399   return llvm::omp::getOpenMPClauseName(clause);
2400 }
2401 
2402 llvm::StringRef OmpStructureChecker::getDirectiveName(
2403     llvm::omp::Directive directive) {
2404   return llvm::omp::getOpenMPDirectiveName(directive);
2405 }
2406 
2407 void OmpStructureChecker::CheckDependList(const parser::DataRef &d) {
2408   common::visit(
2409       common::visitors{
2410           [&](const common::Indirection<parser::ArrayElement> &elem) {
2411             // Check if the base element is valid on Depend Clause
2412             CheckDependList(elem.value().base);
2413           },
2414           [&](const common::Indirection<parser::StructureComponent> &) {
2415             context_.Say(GetContext().clauseSource,
2416                 "A variable that is part of another variable "
2417                 "(such as an element of a structure) but is not an array "
2418                 "element or an array section cannot appear in a DEPEND "
2419                 "clause"_err_en_US);
2420           },
2421           [&](const common::Indirection<parser::CoindexedNamedObject> &) {
2422             context_.Say(GetContext().clauseSource,
2423                 "Coarrays are not supported in DEPEND clause"_err_en_US);
2424           },
2425           [&](const parser::Name &) { return; },
2426       },
2427       d.u);
2428 }
2429 
2430 // Called from both Reduction and Depend clause.
2431 void OmpStructureChecker::CheckArraySection(
2432     const parser::ArrayElement &arrayElement, const parser::Name &name,
2433     const llvm::omp::Clause clause) {
2434   if (!arrayElement.subscripts.empty()) {
2435     for (const auto &subscript : arrayElement.subscripts) {
2436       if (const auto *triplet{
2437               std::get_if<parser::SubscriptTriplet>(&subscript.u)}) {
2438         if (std::get<0>(triplet->t) && std::get<1>(triplet->t)) {
2439           const auto &lower{std::get<0>(triplet->t)};
2440           const auto &upper{std::get<1>(triplet->t)};
2441           if (lower && upper) {
2442             const auto lval{GetIntValue(lower)};
2443             const auto uval{GetIntValue(upper)};
2444             if (lval && uval && *uval < *lval) {
2445               context_.Say(GetContext().clauseSource,
2446                   "'%s' in %s clause"
2447                   " is a zero size array section"_err_en_US,
2448                   name.ToString(),
2449                   parser::ToUpperCaseLetters(getClauseName(clause).str()));
2450               break;
2451             } else if (std::get<2>(triplet->t)) {
2452               const auto &strideExpr{std::get<2>(triplet->t)};
2453               if (strideExpr) {
2454                 if (clause == llvm::omp::Clause::OMPC_depend) {
2455                   context_.Say(GetContext().clauseSource,
2456                       "Stride should not be specified for array section in "
2457                       "DEPEND "
2458                       "clause"_err_en_US);
2459                 }
2460                 const auto stride{GetIntValue(strideExpr)};
2461                 if ((stride && stride != 1)) {
2462                   context_.Say(GetContext().clauseSource,
2463                       "A list item that appears in a REDUCTION clause"
2464                       " should have a contiguous storage array section."_err_en_US,
2465                       ContextDirectiveAsFortran());
2466                   break;
2467                 }
2468               }
2469             }
2470           }
2471         }
2472       }
2473     }
2474   }
2475 }
2476 
2477 void OmpStructureChecker::CheckIntentInPointer(
2478     const parser::OmpObjectList &objectList, const llvm::omp::Clause clause) {
2479   SymbolSourceMap symbols;
2480   GetSymbolsInObjectList(objectList, symbols);
2481   for (auto it{symbols.begin()}; it != symbols.end(); ++it) {
2482     const auto *symbol{it->first};
2483     const auto source{it->second};
2484     if (IsPointer(*symbol) && IsIntentIn(*symbol)) {
2485       context_.Say(source,
2486           "Pointer '%s' with the INTENT(IN) attribute may not appear "
2487           "in a %s clause"_err_en_US,
2488           symbol->name(),
2489           parser::ToUpperCaseLetters(getClauseName(clause).str()));
2490     }
2491   }
2492 }
2493 
2494 void OmpStructureChecker::GetSymbolsInObjectList(
2495     const parser::OmpObjectList &objectList, SymbolSourceMap &symbols) {
2496   for (const auto &ompObject : objectList.v) {
2497     if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
2498       if (const auto *symbol{name->symbol}) {
2499         if (const auto *commonBlockDetails{
2500                 symbol->detailsIf<CommonBlockDetails>()}) {
2501           for (const auto &object : commonBlockDetails->objects()) {
2502             symbols.emplace(&object->GetUltimate(), name->source);
2503           }
2504         } else {
2505           symbols.emplace(&symbol->GetUltimate(), name->source);
2506         }
2507       }
2508     }
2509   }
2510 }
2511 
2512 void OmpStructureChecker::CheckDefinableObjects(
2513     SymbolSourceMap &symbols, const llvm::omp::Clause clause) {
2514   for (auto it{symbols.begin()}; it != symbols.end(); ++it) {
2515     const auto *symbol{it->first};
2516     const auto source{it->second};
2517     if (auto msg{WhyNotModifiable(*symbol, context_.FindScope(source))}) {
2518       context_
2519           .Say(source,
2520               "Variable '%s' on the %s clause is not definable"_err_en_US,
2521               symbol->name(),
2522               parser::ToUpperCaseLetters(getClauseName(clause).str()))
2523           .Attach(std::move(*msg));
2524     }
2525   }
2526 }
2527 
2528 void OmpStructureChecker::CheckPrivateSymbolsInOuterCxt(
2529     SymbolSourceMap &currSymbols, DirectivesClauseTriple &dirClauseTriple,
2530     const llvm::omp::Clause currClause) {
2531   SymbolSourceMap enclosingSymbols;
2532   auto range{dirClauseTriple.equal_range(GetContext().directive)};
2533   for (auto dirIter{range.first}; dirIter != range.second; ++dirIter) {
2534     auto enclosingDir{dirIter->second.first};
2535     auto enclosingClauseSet{dirIter->second.second};
2536     if (auto *enclosingContext{GetEnclosingContextWithDir(enclosingDir)}) {
2537       for (auto it{enclosingContext->clauseInfo.begin()};
2538            it != enclosingContext->clauseInfo.end(); ++it) {
2539         if (enclosingClauseSet.test(it->first)) {
2540           if (const auto *ompObjectList{GetOmpObjectList(*it->second)}) {
2541             GetSymbolsInObjectList(*ompObjectList, enclosingSymbols);
2542           }
2543         }
2544       }
2545 
2546       // Check if the symbols in current context are private in outer context
2547       for (auto iter{currSymbols.begin()}; iter != currSymbols.end(); ++iter) {
2548         const auto *symbol{iter->first};
2549         const auto source{iter->second};
2550         if (enclosingSymbols.find(symbol) != enclosingSymbols.end()) {
2551           context_.Say(source,
2552               "%s variable '%s' is PRIVATE in outer context"_err_en_US,
2553               parser::ToUpperCaseLetters(getClauseName(currClause).str()),
2554               symbol->name());
2555         }
2556       }
2557     }
2558   }
2559 }
2560 
2561 bool OmpStructureChecker::CheckTargetBlockOnlyTeams(
2562     const parser::Block &block) {
2563   bool nestedTeams{false};
2564   auto it{block.begin()};
2565 
2566   if (const auto *ompConstruct{parser::Unwrap<parser::OpenMPConstruct>(*it)}) {
2567     if (const auto *ompBlockConstruct{
2568             std::get_if<parser::OpenMPBlockConstruct>(&ompConstruct->u)}) {
2569       const auto &beginBlockDir{
2570           std::get<parser::OmpBeginBlockDirective>(ompBlockConstruct->t)};
2571       const auto &beginDir{
2572           std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
2573       if (beginDir.v == llvm::omp::Directive::OMPD_teams) {
2574         nestedTeams = true;
2575       }
2576     }
2577   }
2578 
2579   if (nestedTeams && ++it == block.end()) {
2580     return true;
2581   }
2582   return false;
2583 }
2584 
2585 void OmpStructureChecker::CheckWorkshareBlockStmts(
2586     const parser::Block &block, parser::CharBlock source) {
2587   OmpWorkshareBlockChecker ompWorkshareBlockChecker{context_, source};
2588 
2589   for (auto it{block.begin()}; it != block.end(); ++it) {
2590     if (parser::Unwrap<parser::AssignmentStmt>(*it) ||
2591         parser::Unwrap<parser::ForallStmt>(*it) ||
2592         parser::Unwrap<parser::ForallConstruct>(*it) ||
2593         parser::Unwrap<parser::WhereStmt>(*it) ||
2594         parser::Unwrap<parser::WhereConstruct>(*it)) {
2595       parser::Walk(*it, ompWorkshareBlockChecker);
2596     } else if (const auto *ompConstruct{
2597                    parser::Unwrap<parser::OpenMPConstruct>(*it)}) {
2598       if (const auto *ompAtomicConstruct{
2599               std::get_if<parser::OpenMPAtomicConstruct>(&ompConstruct->u)}) {
2600         // Check if assignment statements in the enclosing OpenMP Atomic
2601         // construct are allowed in the Workshare construct
2602         parser::Walk(*ompAtomicConstruct, ompWorkshareBlockChecker);
2603       } else if (const auto *ompCriticalConstruct{
2604                      std::get_if<parser::OpenMPCriticalConstruct>(
2605                          &ompConstruct->u)}) {
2606         // All the restrictions on the Workshare construct apply to the
2607         // statements in the enclosing critical constructs
2608         const auto &criticalBlock{
2609             std::get<parser::Block>(ompCriticalConstruct->t)};
2610         CheckWorkshareBlockStmts(criticalBlock, source);
2611       } else {
2612         // Check if OpenMP constructs enclosed in the Workshare construct are
2613         // 'Parallel' constructs
2614         auto currentDir{llvm::omp::Directive::OMPD_unknown};
2615         const OmpDirectiveSet parallelDirSet{
2616             llvm::omp::Directive::OMPD_parallel,
2617             llvm::omp::Directive::OMPD_parallel_do,
2618             llvm::omp::Directive::OMPD_parallel_sections,
2619             llvm::omp::Directive::OMPD_parallel_workshare,
2620             llvm::omp::Directive::OMPD_parallel_do_simd};
2621 
2622         if (const auto *ompBlockConstruct{
2623                 std::get_if<parser::OpenMPBlockConstruct>(&ompConstruct->u)}) {
2624           const auto &beginBlockDir{
2625               std::get<parser::OmpBeginBlockDirective>(ompBlockConstruct->t)};
2626           const auto &beginDir{
2627               std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
2628           currentDir = beginDir.v;
2629         } else if (const auto *ompLoopConstruct{
2630                        std::get_if<parser::OpenMPLoopConstruct>(
2631                            &ompConstruct->u)}) {
2632           const auto &beginLoopDir{
2633               std::get<parser::OmpBeginLoopDirective>(ompLoopConstruct->t)};
2634           const auto &beginDir{
2635               std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
2636           currentDir = beginDir.v;
2637         } else if (const auto *ompSectionsConstruct{
2638                        std::get_if<parser::OpenMPSectionsConstruct>(
2639                            &ompConstruct->u)}) {
2640           const auto &beginSectionsDir{
2641               std::get<parser::OmpBeginSectionsDirective>(
2642                   ompSectionsConstruct->t)};
2643           const auto &beginDir{
2644               std::get<parser::OmpSectionsDirective>(beginSectionsDir.t)};
2645           currentDir = beginDir.v;
2646         }
2647 
2648         if (!parallelDirSet.test(currentDir)) {
2649           context_.Say(source,
2650               "OpenMP constructs enclosed in WORKSHARE construct may consist "
2651               "of ATOMIC, CRITICAL or PARALLEL constructs only"_err_en_US);
2652         }
2653       }
2654     } else {
2655       context_.Say(source,
2656           "The structured block in a WORKSHARE construct may consist of only "
2657           "SCALAR or ARRAY assignments, FORALL or WHERE statements, "
2658           "FORALL, WHERE, ATOMIC, CRITICAL or PARALLEL constructs"_err_en_US);
2659     }
2660   }
2661 }
2662 
2663 const parser::OmpObjectList *OmpStructureChecker::GetOmpObjectList(
2664     const parser::OmpClause &clause) {
2665 
2666   // Clauses with OmpObjectList as its data member
2667   using MemberObjectListClauses = std::tuple<parser::OmpClause::Copyprivate,
2668       parser::OmpClause::Copyin, parser::OmpClause::Firstprivate,
2669       parser::OmpClause::From, parser::OmpClause::Lastprivate,
2670       parser::OmpClause::Link, parser::OmpClause::Private,
2671       parser::OmpClause::Shared, parser::OmpClause::To>;
2672 
2673   // Clauses with OmpObjectList in the tuple
2674   using TupleObjectListClauses = std::tuple<parser::OmpClause::Allocate,
2675       parser::OmpClause::Map, parser::OmpClause::Reduction>;
2676 
2677   // TODO:: Generate the tuples using TableGen.
2678   // Handle other constructs with OmpObjectList such as OpenMPThreadprivate.
2679   return common::visit(
2680       common::visitors{
2681           [&](const auto &x) -> const parser::OmpObjectList * {
2682             using Ty = std::decay_t<decltype(x)>;
2683             if constexpr (common::HasMember<Ty, MemberObjectListClauses>) {
2684               return &x.v;
2685             } else if constexpr (common::HasMember<Ty,
2686                                      TupleObjectListClauses>) {
2687               return &(std::get<parser::OmpObjectList>(x.v.t));
2688             } else {
2689               return nullptr;
2690             }
2691           },
2692       },
2693       clause.u);
2694 }
2695 
2696 } // namespace Fortran::semantics
2697