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(var)};
54     const auto *rhs{GetExpr(expr)};
55     Tristate isDefined{semantics::IsDefinedAssignment(
56         lhs->GetType(), lhs->Rank(), rhs->GetType(), rhs->Rank())};
57     if (isDefined == Tristate::Yes) {
58       context_.Say(expr.source,
59           "Defined assignment statement is not "
60           "allowed in a WORKSHARE construct"_err_en_US);
61     }
62     return true;
63   }
64 
65   bool Pre(const parser::Expr &expr) {
66     if (const auto *e{GetExpr(expr)}) {
67       for (const Symbol &symbol : evaluate::CollectSymbols(*e)) {
68         const Symbol &root{GetAssociationRoot(symbol)};
69         if (IsFunction(root) &&
70             !(root.attrs().test(Attr::ELEMENTAL) ||
71                 root.attrs().test(Attr::INTRINSIC))) {
72           context_.Say(expr.source,
73               "User defined non-ELEMENTAL function "
74               "'%s' is not allowed in a WORKSHARE construct"_err_en_US,
75               root.name());
76         }
77       }
78     }
79     return false;
80   }
81 
82 private:
83   SemanticsContext &context_;
84   parser::CharBlock source_;
85 };
86 
87 class OmpCycleChecker {
88 public:
89   OmpCycleChecker(SemanticsContext &context, std::int64_t cycleLevel)
90       : context_{context}, cycleLevel_{cycleLevel} {}
91 
92   template <typename T> bool Pre(const T &) { return true; }
93   template <typename T> void Post(const T &) {}
94 
95   bool Pre(const parser::DoConstruct &dc) {
96     cycleLevel_--;
97     const auto &labelName{std::get<0>(std::get<0>(dc.t).statement.t)};
98     if (labelName) {
99       labelNamesandLevels_.emplace(labelName.value().ToString(), cycleLevel_);
100     }
101     return true;
102   }
103 
104   bool Pre(const parser::CycleStmt &cyclestmt) {
105     std::map<std::string, std::int64_t>::iterator it;
106     bool err{false};
107     if (cyclestmt.v) {
108       it = labelNamesandLevels_.find(cyclestmt.v->source.ToString());
109       err = (it != labelNamesandLevels_.end() && it->second > 0);
110     }
111     if (cycleLevel_ > 0 || err) {
112       context_.Say(*cycleSource_,
113           "CYCLE statement to non-innermost associated loop of an OpenMP DO construct"_err_en_US);
114     }
115     return true;
116   }
117 
118   bool Pre(const parser::Statement<parser::ActionStmt> &actionstmt) {
119     cycleSource_ = &actionstmt.source;
120     return true;
121   }
122 
123 private:
124   SemanticsContext &context_;
125   const parser::CharBlock *cycleSource_;
126   std::int64_t cycleLevel_;
127   std::map<std::string, std::int64_t> labelNamesandLevels_;
128 };
129 
130 bool OmpStructureChecker::IsCloselyNestedRegion(const OmpDirectiveSet &set) {
131   // Definition of close nesting:
132   //
133   // `A region nested inside another region with no parallel region nested
134   // between them`
135   //
136   // Examples:
137   //   non-parallel construct 1
138   //    non-parallel construct 2
139   //      parallel construct
140   //        construct 3
141   // In the above example, construct 3 is NOT closely nested inside construct 1
142   // or 2
143   //
144   //   non-parallel construct 1
145   //    non-parallel construct 2
146   //        construct 3
147   // In the above example, construct 3 is closely nested inside BOTH construct 1
148   // and 2
149   //
150   // Algorithm:
151   // Starting from the parent context, Check in a bottom-up fashion, each level
152   // of the context stack. If we have a match for one of the (supplied)
153   // violating directives, `close nesting` is satisfied. If no match is there in
154   // the entire stack, `close nesting` is not satisfied. If at any level, a
155   // `parallel` region is found, `close nesting` is not satisfied.
156 
157   if (CurrentDirectiveIsNested()) {
158     int index = dirContext_.size() - 2;
159     while (index != -1) {
160       if (set.test(dirContext_[index].directive)) {
161         return true;
162       } else if (llvm::omp::parallelSet.test(dirContext_[index].directive)) {
163         return false;
164       }
165       index--;
166     }
167   }
168   return false;
169 }
170 
171 bool OmpStructureChecker::HasInvalidWorksharingNesting(
172     const parser::CharBlock &source, const OmpDirectiveSet &set) {
173   // set contains all the invalid closely nested directives
174   // for the given directive (`source` here)
175   if (IsCloselyNestedRegion(set)) {
176     context_.Say(source,
177         "A worksharing region may not be closely nested inside a "
178         "worksharing, explicit task, taskloop, critical, ordered, atomic, or "
179         "master region"_err_en_US);
180     return true;
181   }
182   return false;
183 }
184 
185 void OmpStructureChecker::HasInvalidDistributeNesting(
186     const parser::OpenMPLoopConstruct &x) {
187   bool violation{false};
188 
189   OmpDirectiveSet distributeSet{llvm::omp::Directive::OMPD_distribute,
190       llvm::omp::Directive::OMPD_distribute_parallel_do,
191       llvm::omp::Directive::OMPD_distribute_parallel_do_simd,
192       llvm::omp::Directive::OMPD_distribute_parallel_for,
193       llvm::omp::Directive::OMPD_distribute_parallel_for_simd,
194       llvm::omp::Directive::OMPD_distribute_simd};
195 
196   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
197   const auto &beginDir{std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
198   if (distributeSet.test(beginDir.v)) {
199     // `distribute` region has to be nested
200     if (!CurrentDirectiveIsNested()) {
201       violation = true;
202     } else {
203       // `distribute` region has to be strictly nested inside `teams`
204       if (!llvm::omp::teamSet.test(GetContextParent().directive)) {
205         violation = true;
206       }
207     }
208   }
209   if (violation) {
210     context_.Say(beginDir.source,
211         "`DISTRIBUTE` region has to be strictly nested inside `TEAMS` region."_err_en_US);
212   }
213 }
214 
215 void OmpStructureChecker::HasInvalidTeamsNesting(
216     const llvm::omp::Directive &dir, const parser::CharBlock &source) {
217   OmpDirectiveSet allowedSet{llvm::omp::Directive::OMPD_parallel,
218       llvm::omp::Directive::OMPD_parallel_do,
219       llvm::omp::Directive::OMPD_parallel_do_simd,
220       llvm::omp::Directive::OMPD_parallel_for,
221       llvm::omp::Directive::OMPD_parallel_for_simd,
222       llvm::omp::Directive::OMPD_parallel_master,
223       llvm::omp::Directive::OMPD_parallel_master_taskloop,
224       llvm::omp::Directive::OMPD_parallel_master_taskloop_simd,
225       llvm::omp::Directive::OMPD_parallel_sections,
226       llvm::omp::Directive::OMPD_parallel_workshare,
227       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   if (!allowedSet.test(dir)) {
235     context_.Say(source,
236         "Only `DISTRIBUTE` or `PARALLEL` regions are allowed to be strictly nested inside `TEAMS` region."_err_en_US);
237   }
238 }
239 
240 void OmpStructureChecker::CheckPredefinedAllocatorRestriction(
241     const parser::CharBlock &source, const parser::Name &name) {
242   if (const auto *symbol{name.symbol}) {
243     const auto *commonBlock{FindCommonBlockContaining(*symbol)};
244     const auto &scope{context_.FindScope(symbol->name())};
245     const Scope &containingScope{GetProgramUnitContaining(scope)};
246     if (!isPredefinedAllocator &&
247         (IsSave(*symbol) || commonBlock ||
248             containingScope.kind() == Scope::Kind::Module)) {
249       context_.Say(source,
250           "If list items within the ALLOCATE directive have the "
251           "SAVE attribute, are a common block name, or are "
252           "declared in the scope of a module, then only "
253           "predefined memory allocator parameters can be used "
254           "in the allocator clause"_err_en_US);
255     }
256   }
257 }
258 
259 void OmpStructureChecker::CheckPredefinedAllocatorRestriction(
260     const parser::CharBlock &source,
261     const parser::OmpObjectList &ompObjectList) {
262   for (const auto &ompObject : ompObjectList.v) {
263     std::visit(
264         common::visitors{
265             [&](const parser::Designator &designator) {
266               if (const auto *dataRef{
267                       std::get_if<parser::DataRef>(&designator.u)}) {
268                 if (const auto *name{std::get_if<parser::Name>(&dataRef->u)}) {
269                   CheckPredefinedAllocatorRestriction(source, *name);
270                 }
271               }
272             },
273             [&](const parser::Name &name) {
274               CheckPredefinedAllocatorRestriction(source, name);
275             },
276         },
277         ompObject.u);
278   }
279 }
280 
281 void OmpStructureChecker::Enter(const parser::OpenMPConstruct &x) {
282   // Simd Construct with Ordered Construct Nesting check
283   // We cannot use CurrentDirectiveIsNested() here because
284   // PushContextAndClauseSets() has not been called yet, it is
285   // called individually for each construct.  Therefore a
286   // dirContext_ size `1` means the current construct is nested
287   if (dirContext_.size() >= 1) {
288     if (GetSIMDNest() > 0) {
289       CheckSIMDNest(x);
290     }
291   }
292 }
293 
294 void OmpStructureChecker::Enter(const parser::OpenMPLoopConstruct &x) {
295   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
296   const auto &beginDir{std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
297 
298   // check matching, End directive is optional
299   if (const auto &endLoopDir{
300           std::get<std::optional<parser::OmpEndLoopDirective>>(x.t)}) {
301     const auto &endDir{
302         std::get<parser::OmpLoopDirective>(endLoopDir.value().t)};
303 
304     CheckMatching<parser::OmpLoopDirective>(beginDir, endDir);
305   }
306 
307   PushContextAndClauseSets(beginDir.source, beginDir.v);
308   if (llvm::omp::simdSet.test(GetContext().directive)) {
309     EnterSIMDNest();
310   }
311 
312   if (beginDir.v == llvm::omp::Directive::OMPD_do) {
313     // 2.7.1 do-clause -> private-clause |
314     //                    firstprivate-clause |
315     //                    lastprivate-clause |
316     //                    linear-clause |
317     //                    reduction-clause |
318     //                    schedule-clause |
319     //                    collapse-clause |
320     //                    ordered-clause
321 
322     // nesting check
323     HasInvalidWorksharingNesting(
324         beginDir.source, llvm::omp::nestedWorkshareErrSet);
325   }
326   SetLoopInfo(x);
327 
328   if (const auto &doConstruct{
329           std::get<std::optional<parser::DoConstruct>>(x.t)}) {
330     const auto &doBlock{std::get<parser::Block>(doConstruct->t)};
331     CheckNoBranching(doBlock, beginDir.v, beginDir.source);
332   }
333   CheckDoWhile(x);
334   CheckLoopItrVariableIsInt(x);
335   CheckCycleConstraints(x);
336   HasInvalidDistributeNesting(x);
337   if (CurrentDirectiveIsNested() &&
338       llvm::omp::teamSet.test(GetContextParent().directive)) {
339     HasInvalidTeamsNesting(beginDir.v, beginDir.source);
340   }
341   if ((beginDir.v == llvm::omp::Directive::OMPD_distribute_parallel_do_simd) ||
342       (beginDir.v == llvm::omp::Directive::OMPD_distribute_simd)) {
343     CheckDistLinear(x);
344   }
345 }
346 const parser::Name OmpStructureChecker::GetLoopIndex(
347     const parser::DoConstruct *x) {
348   using Bounds = parser::LoopControl::Bounds;
349   return std::get<Bounds>(x->GetLoopControl()->u).name.thing;
350 }
351 void OmpStructureChecker::SetLoopInfo(const parser::OpenMPLoopConstruct &x) {
352   if (const auto &loopConstruct{
353           std::get<std::optional<parser::DoConstruct>>(x.t)}) {
354     const parser::DoConstruct *loop{&*loopConstruct};
355     if (loop && loop->IsDoNormal()) {
356       const parser::Name &itrVal{GetLoopIndex(loop)};
357       SetLoopIv(itrVal.symbol);
358     }
359   }
360 }
361 void OmpStructureChecker::CheckDoWhile(const parser::OpenMPLoopConstruct &x) {
362   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
363   const auto &beginDir{std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
364   if (beginDir.v == llvm::omp::Directive::OMPD_do) {
365     if (const auto &doConstruct{
366             std::get<std::optional<parser::DoConstruct>>(x.t)}) {
367       if (doConstruct.value().IsDoWhile()) {
368         const auto &doStmt{std::get<parser::Statement<parser::NonLabelDoStmt>>(
369             doConstruct.value().t)};
370         context_.Say(doStmt.source,
371             "The DO loop cannot be a DO WHILE with DO directive."_err_en_US);
372       }
373     }
374   }
375 }
376 
377 void OmpStructureChecker::CheckLoopItrVariableIsInt(
378     const parser::OpenMPLoopConstruct &x) {
379   if (const auto &loopConstruct{
380           std::get<std::optional<parser::DoConstruct>>(x.t)}) {
381 
382     for (const parser::DoConstruct *loop{&*loopConstruct}; loop;) {
383       if (loop->IsDoNormal()) {
384         const parser::Name &itrVal{GetLoopIndex(loop)};
385         if (itrVal.symbol) {
386           const auto *type{itrVal.symbol->GetType()};
387           if (!type->IsNumeric(TypeCategory::Integer)) {
388             context_.Say(itrVal.source,
389                 "The DO loop iteration"
390                 " variable must be of the type integer."_err_en_US,
391                 itrVal.ToString());
392           }
393         }
394       }
395       // Get the next DoConstruct if block is not empty.
396       const auto &block{std::get<parser::Block>(loop->t)};
397       const auto it{block.begin()};
398       loop = it != block.end() ? parser::Unwrap<parser::DoConstruct>(*it)
399                                : nullptr;
400     }
401   }
402 }
403 
404 void OmpStructureChecker::CheckSIMDNest(const parser::OpenMPConstruct &c) {
405   // Check the following:
406   //  The only OpenMP constructs that can be encountered during execution of
407   // a simd region are the `atomic` construct, the `loop` construct, the `simd`
408   // construct and the `ordered` construct with the `simd` clause.
409   // TODO:  Expand the check to include `LOOP` construct as well when it is
410   // supported.
411 
412   // Check if the parent context has the SIMD clause
413   // Please note that we use GetContext() instead of GetContextParent()
414   // because PushContextAndClauseSets() has not been called on the
415   // current context yet.
416   // TODO: Check for declare simd regions.
417   bool eligibleSIMD{false};
418   std::visit(Fortran::common::visitors{
419                  // Allow `!$OMP ORDERED SIMD`
420                  [&](const parser::OpenMPBlockConstruct &c) {
421                    const auto &beginBlockDir{
422                        std::get<parser::OmpBeginBlockDirective>(c.t)};
423                    const auto &beginDir{
424                        std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
425                    if (beginDir.v == llvm::omp::Directive::OMPD_ordered) {
426                      const auto &clauses{
427                          std::get<parser::OmpClauseList>(beginBlockDir.t)};
428                      for (const auto &clause : clauses.v) {
429                        if (std::get_if<parser::OmpClause::Simd>(&clause.u)) {
430                          eligibleSIMD = true;
431                          break;
432                        }
433                      }
434                    }
435                  },
436                  [&](const parser::OpenMPSimpleStandaloneConstruct &c) {
437                    const auto &dir{
438                        std::get<parser::OmpSimpleStandaloneDirective>(c.t)};
439                    if (dir.v == llvm::omp::Directive::OMPD_ordered) {
440                      const auto &clauses{std::get<parser::OmpClauseList>(c.t)};
441                      for (const auto &clause : clauses.v) {
442                        if (std::get_if<parser::OmpClause::Simd>(&clause.u)) {
443                          eligibleSIMD = true;
444                          break;
445                        }
446                      }
447                    }
448                  },
449                  // Allowing SIMD construct
450                  [&](const parser::OpenMPLoopConstruct &c) {
451                    const auto &beginLoopDir{
452                        std::get<parser::OmpBeginLoopDirective>(c.t)};
453                    const auto &beginDir{
454                        std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
455                    if ((beginDir.v == llvm::omp::Directive::OMPD_simd) ||
456                        (beginDir.v == llvm::omp::Directive::OMPD_do_simd)) {
457                      eligibleSIMD = true;
458                    }
459                  },
460                  [&](const parser::OpenMPAtomicConstruct &c) {
461                    // Allow `!$OMP ATOMIC`
462                    eligibleSIMD = true;
463                  },
464                  [&](const auto &c) {},
465              },
466       c.u);
467   if (!eligibleSIMD) {
468     context_.Say(parser::FindSourceLocation(c),
469         "The only OpenMP constructs that can be encountered during execution "
470         "of a 'SIMD'"
471         " region are the `ATOMIC` construct, the `LOOP` construct, the `SIMD`"
472         " construct and the `ORDERED` construct with the `SIMD` clause."_err_en_US);
473   }
474 }
475 
476 std::int64_t OmpStructureChecker::GetOrdCollapseLevel(
477     const parser::OpenMPLoopConstruct &x) {
478   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
479   const auto &clauseList{std::get<parser::OmpClauseList>(beginLoopDir.t)};
480   std::int64_t orderedCollapseLevel{1};
481   std::int64_t orderedLevel{0};
482   std::int64_t collapseLevel{0};
483 
484   for (const auto &clause : clauseList.v) {
485     if (const auto *collapseClause{
486             std::get_if<parser::OmpClause::Collapse>(&clause.u)}) {
487       if (const auto v{GetIntValue(collapseClause->v)}) {
488         collapseLevel = *v;
489       }
490     }
491     if (const auto *orderedClause{
492             std::get_if<parser::OmpClause::Ordered>(&clause.u)}) {
493       if (const auto v{GetIntValue(orderedClause->v)}) {
494         orderedLevel = *v;
495       }
496     }
497   }
498   if (orderedLevel >= collapseLevel) {
499     orderedCollapseLevel = orderedLevel;
500   } else {
501     orderedCollapseLevel = collapseLevel;
502   }
503   return orderedCollapseLevel;
504 }
505 
506 void OmpStructureChecker::CheckCycleConstraints(
507     const parser::OpenMPLoopConstruct &x) {
508   std::int64_t ordCollapseLevel{GetOrdCollapseLevel(x)};
509   OmpCycleChecker ompCycleChecker{context_, ordCollapseLevel};
510   parser::Walk(x, ompCycleChecker);
511 }
512 
513 void OmpStructureChecker::CheckDistLinear(
514     const parser::OpenMPLoopConstruct &x) {
515 
516   const auto &beginLoopDir{std::get<parser::OmpBeginLoopDirective>(x.t)};
517   const auto &clauses{std::get<parser::OmpClauseList>(beginLoopDir.t)};
518 
519   semantics::UnorderedSymbolSet indexVars;
520 
521   // Collect symbols of all the variables from linear clauses
522   for (const auto &clause : clauses.v) {
523     if (const auto *linearClause{
524             std::get_if<parser::OmpClause::Linear>(&clause.u)}) {
525 
526       std::list<parser::Name> values;
527       // Get the variant type
528       if (std::holds_alternative<parser::OmpLinearClause::WithModifier>(
529               linearClause->v.u)) {
530         const auto &withM{
531             std::get<parser::OmpLinearClause::WithModifier>(linearClause->v.u)};
532         values = withM.names;
533       } else {
534         const auto &withOutM{std::get<parser::OmpLinearClause::WithoutModifier>(
535             linearClause->v.u)};
536         values = withOutM.names;
537       }
538       for (auto const &v : values) {
539         indexVars.insert(*(v.symbol));
540       }
541     }
542   }
543 
544   if (!indexVars.empty()) {
545     // Get collapse level, if given, to find which loops are "associated."
546     std::int64_t collapseVal{GetOrdCollapseLevel(x)};
547     // Include the top loop if no collapse is specified
548     if (collapseVal == 0) {
549       collapseVal = 1;
550     }
551 
552     // Match the loop index variables with the collected symbols from linear
553     // clauses.
554     if (const auto &loopConstruct{
555             std::get<std::optional<parser::DoConstruct>>(x.t)}) {
556       for (const parser::DoConstruct *loop{&*loopConstruct}; loop;) {
557         if (loop->IsDoNormal()) {
558           const parser::Name &itrVal{GetLoopIndex(loop)};
559           if (itrVal.symbol) {
560             // Remove the symbol from the collcted set
561             indexVars.erase(*(itrVal.symbol));
562           }
563           collapseVal--;
564           if (collapseVal == 0) {
565             break;
566           }
567         }
568         // Get the next DoConstruct if block is not empty.
569         const auto &block{std::get<parser::Block>(loop->t)};
570         const auto it{block.begin()};
571         loop = it != block.end() ? parser::Unwrap<parser::DoConstruct>(*it)
572                                  : nullptr;
573       }
574     }
575 
576     // Show error for the remaining variables
577     for (auto var : indexVars) {
578       const Symbol &root{GetAssociationRoot(var)};
579       context_.Say(parser::FindSourceLocation(x),
580           "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,
581           root.name());
582     }
583   }
584 }
585 
586 void OmpStructureChecker::Leave(const parser::OpenMPLoopConstruct &) {
587   if (llvm::omp::simdSet.test(GetContext().directive)) {
588     ExitSIMDNest();
589   }
590   dirContext_.pop_back();
591 }
592 
593 void OmpStructureChecker::Enter(const parser::OmpEndLoopDirective &x) {
594   const auto &dir{std::get<parser::OmpLoopDirective>(x.t)};
595   ResetPartialContext(dir.source);
596   switch (dir.v) {
597   // 2.7.1 end-do -> END DO [nowait-clause]
598   // 2.8.3 end-do-simd -> END DO SIMD [nowait-clause]
599   case llvm::omp::Directive::OMPD_do:
600   case llvm::omp::Directive::OMPD_do_simd:
601     SetClauseSets(dir.v);
602     break;
603   default:
604     // no clauses are allowed
605     break;
606   }
607 }
608 
609 void OmpStructureChecker::Enter(const parser::OpenMPBlockConstruct &x) {
610   const auto &beginBlockDir{std::get<parser::OmpBeginBlockDirective>(x.t)};
611   const auto &endBlockDir{std::get<parser::OmpEndBlockDirective>(x.t)};
612   const auto &beginDir{std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
613   const auto &endDir{std::get<parser::OmpBlockDirective>(endBlockDir.t)};
614   const parser::Block &block{std::get<parser::Block>(x.t)};
615 
616   CheckMatching<parser::OmpBlockDirective>(beginDir, endDir);
617 
618   PushContextAndClauseSets(beginDir.source, beginDir.v);
619 
620   if (CurrentDirectiveIsNested()) {
621     CheckIfDoOrderedClause(beginDir);
622     if (llvm::omp::teamSet.test(GetContextParent().directive)) {
623       HasInvalidTeamsNesting(beginDir.v, beginDir.source);
624     }
625     if (GetContext().directive == llvm::omp::Directive::OMPD_master) {
626       CheckMasterNesting(x);
627     }
628   }
629 
630   CheckNoBranching(block, beginDir.v, beginDir.source);
631 
632   switch (beginDir.v) {
633   case llvm::omp::OMPD_workshare:
634   case llvm::omp::OMPD_parallel_workshare:
635     CheckWorkshareBlockStmts(block, beginDir.source);
636     HasInvalidWorksharingNesting(
637         beginDir.source, llvm::omp::nestedWorkshareErrSet);
638     break;
639   case llvm::omp::Directive::OMPD_single:
640     // TODO: This check needs to be extended while implementing nesting of
641     // regions checks.
642     HasInvalidWorksharingNesting(
643         beginDir.source, llvm::omp::nestedWorkshareErrSet);
644     break;
645   default:
646     break;
647   }
648 }
649 
650 void OmpStructureChecker::CheckMasterNesting(
651     const parser::OpenMPBlockConstruct &x) {
652   // A MASTER region may not be `closely nested` inside a worksharing, loop,
653   // task, taskloop, or atomic region.
654   // TODO:  Expand the check to include `LOOP` construct as well when it is
655   // supported.
656   if (IsCloselyNestedRegion(llvm::omp::nestedMasterErrSet)) {
657     context_.Say(parser::FindSourceLocation(x),
658         "`MASTER` region may not be closely nested inside of `WORKSHARING`, "
659         "`LOOP`, `TASK`, `TASKLOOP`,"
660         " or `ATOMIC` region."_err_en_US);
661   }
662 }
663 
664 void OmpStructureChecker::CheckIfDoOrderedClause(
665     const parser::OmpBlockDirective &blkDirective) {
666   if (blkDirective.v == llvm::omp::OMPD_ordered) {
667     // Loops
668     if (llvm::omp::doSet.test(GetContextParent().directive) &&
669         !FindClauseParent(llvm::omp::Clause::OMPC_ordered)) {
670       context_.Say(blkDirective.source,
671           "The ORDERED clause must be present on the loop"
672           " construct if any ORDERED region ever binds"
673           " to a loop region arising from the loop construct."_err_en_US);
674     }
675     // Other disallowed nestings, these directives do not support
676     // ordered clause in them, so no need to check
677     else if (IsCloselyNestedRegion(llvm::omp::nestedOrderedErrSet)) {
678       context_.Say(blkDirective.source,
679           "`ORDERED` region may not be closely nested inside of "
680           "`CRITICAL`, `ORDERED`, explicit `TASK` or `TASKLOOP` region."_err_en_US);
681     }
682   }
683 }
684 
685 void OmpStructureChecker::Leave(const parser::OpenMPBlockConstruct &) {
686   dirContext_.pop_back();
687 }
688 
689 void OmpStructureChecker::Enter(const parser::OpenMPSectionsConstruct &x) {
690   const auto &beginSectionsDir{
691       std::get<parser::OmpBeginSectionsDirective>(x.t)};
692   const auto &endSectionsDir{std::get<parser::OmpEndSectionsDirective>(x.t)};
693   const auto &beginDir{
694       std::get<parser::OmpSectionsDirective>(beginSectionsDir.t)};
695   const auto &endDir{std::get<parser::OmpSectionsDirective>(endSectionsDir.t)};
696   CheckMatching<parser::OmpSectionsDirective>(beginDir, endDir);
697 
698   PushContextAndClauseSets(beginDir.source, beginDir.v);
699   const auto &sectionBlocks{std::get<parser::OmpSectionBlocks>(x.t)};
700   for (const auto &block : sectionBlocks.v) {
701     CheckNoBranching(block, beginDir.v, beginDir.source);
702   }
703   HasInvalidWorksharingNesting(
704       beginDir.source, llvm::omp::nestedWorkshareErrSet);
705 }
706 
707 void OmpStructureChecker::Leave(const parser::OpenMPSectionsConstruct &) {
708   dirContext_.pop_back();
709 }
710 
711 void OmpStructureChecker::Enter(const parser::OmpEndSectionsDirective &x) {
712   const auto &dir{std::get<parser::OmpSectionsDirective>(x.t)};
713   ResetPartialContext(dir.source);
714   switch (dir.v) {
715     // 2.7.2 end-sections -> END SECTIONS [nowait-clause]
716   case llvm::omp::Directive::OMPD_sections:
717     PushContextAndClauseSets(
718         dir.source, llvm::omp::Directive::OMPD_end_sections);
719     break;
720   default:
721     // no clauses are allowed
722     break;
723   }
724 }
725 
726 // TODO: Verify the popping of dirContext requirement after nowait
727 // implementation, as there is an implicit barrier at the end of the worksharing
728 // constructs unless a nowait clause is specified. Only OMPD_end_sections is
729 // popped becuase it is pushed while entering the EndSectionsDirective.
730 void OmpStructureChecker::Leave(const parser::OmpEndSectionsDirective &x) {
731   if (GetContext().directive == llvm::omp::Directive::OMPD_end_sections) {
732     dirContext_.pop_back();
733   }
734 }
735 
736 void OmpStructureChecker::Enter(const parser::OpenMPDeclareSimdConstruct &x) {
737   const auto &dir{std::get<parser::Verbatim>(x.t)};
738   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_declare_simd);
739 }
740 
741 void OmpStructureChecker::Leave(const parser::OpenMPDeclareSimdConstruct &) {
742   dirContext_.pop_back();
743 }
744 
745 void OmpStructureChecker::Enter(const parser::OpenMPDeclarativeAllocate &x) {
746   isPredefinedAllocator = true;
747   const auto &dir{std::get<parser::Verbatim>(x.t)};
748   const auto &objectList{std::get<parser::OmpObjectList>(x.t)};
749   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_allocate);
750   CheckIsVarPartOfAnotherVar(dir.source, objectList);
751 }
752 
753 void OmpStructureChecker::Leave(const parser::OpenMPDeclarativeAllocate &x) {
754   const auto &dir{std::get<parser::Verbatim>(x.t)};
755   const auto &objectList{std::get<parser::OmpObjectList>(x.t)};
756   CheckPredefinedAllocatorRestriction(dir.source, objectList);
757   dirContext_.pop_back();
758 }
759 
760 void OmpStructureChecker::Enter(const parser::OmpClause::Allocator &x) {
761   CheckAllowed(llvm::omp::Clause::OMPC_allocator);
762   // Note: Predefined allocators are stored in ScalarExpr as numbers
763   //   whereas custom allocators are stored as strings, so if the ScalarExpr
764   //   actually has an int value, then it must be a predefined allocator
765   isPredefinedAllocator = GetIntValue(x.v).has_value();
766   RequiresPositiveParameter(llvm::omp::Clause::OMPC_allocator, x.v);
767 }
768 
769 void OmpStructureChecker::Enter(const parser::OpenMPDeclareTargetConstruct &x) {
770   const auto &dir{std::get<parser::Verbatim>(x.t)};
771   PushContext(dir.source, llvm::omp::Directive::OMPD_declare_target);
772   const auto &spec{std::get<parser::OmpDeclareTargetSpecifier>(x.t)};
773   if (std::holds_alternative<parser::OmpDeclareTargetWithClause>(spec.u)) {
774     SetClauseSets(llvm::omp::Directive::OMPD_declare_target);
775   }
776 }
777 
778 void OmpStructureChecker::Leave(const parser::OpenMPDeclareTargetConstruct &) {
779   dirContext_.pop_back();
780 }
781 
782 void OmpStructureChecker::Enter(const parser::OpenMPExecutableAllocate &x) {
783   isPredefinedAllocator = true;
784   const auto &dir{std::get<parser::Verbatim>(x.t)};
785   const auto &objectList{std::get<std::optional<parser::OmpObjectList>>(x.t)};
786   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_allocate);
787   if (objectList) {
788     CheckIsVarPartOfAnotherVar(dir.source, *objectList);
789   }
790 }
791 
792 void OmpStructureChecker::Leave(const parser::OpenMPExecutableAllocate &x) {
793   const auto &dir{std::get<parser::Verbatim>(x.t)};
794   const auto &objectList{std::get<std::optional<parser::OmpObjectList>>(x.t)};
795   if (objectList)
796     CheckPredefinedAllocatorRestriction(dir.source, *objectList);
797   dirContext_.pop_back();
798 }
799 
800 void OmpStructureChecker::Enter(
801     const parser::OpenMPSimpleStandaloneConstruct &x) {
802   const auto &dir{std::get<parser::OmpSimpleStandaloneDirective>(x.t)};
803   PushContextAndClauseSets(dir.source, dir.v);
804 }
805 
806 void OmpStructureChecker::Leave(
807     const parser::OpenMPSimpleStandaloneConstruct &) {
808   dirContext_.pop_back();
809 }
810 
811 void OmpStructureChecker::Enter(const parser::OpenMPFlushConstruct &x) {
812   const auto &dir{std::get<parser::Verbatim>(x.t)};
813   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_flush);
814 }
815 
816 void OmpStructureChecker::Leave(const parser::OpenMPFlushConstruct &x) {
817   if (FindClause(llvm::omp::Clause::OMPC_acquire) ||
818       FindClause(llvm::omp::Clause::OMPC_release) ||
819       FindClause(llvm::omp::Clause::OMPC_acq_rel)) {
820     if (const auto &flushList{
821             std::get<std::optional<parser::OmpObjectList>>(x.t)}) {
822       context_.Say(parser::FindSourceLocation(flushList),
823           "If memory-order-clause is RELEASE, ACQUIRE, or ACQ_REL, list items "
824           "must not be specified on the FLUSH directive"_err_en_US);
825     }
826   }
827   dirContext_.pop_back();
828 }
829 
830 void OmpStructureChecker::Enter(const parser::OpenMPCancelConstruct &x) {
831   const auto &dir{std::get<parser::Verbatim>(x.t)};
832   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_cancel);
833 }
834 
835 void OmpStructureChecker::Leave(const parser::OpenMPCancelConstruct &) {
836   dirContext_.pop_back();
837 }
838 
839 void OmpStructureChecker::Enter(const parser::OpenMPCriticalConstruct &x) {
840   const auto &dir{std::get<parser::OmpCriticalDirective>(x.t)};
841   PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_critical);
842   const auto &block{std::get<parser::Block>(x.t)};
843   CheckNoBranching(block, llvm::omp::Directive::OMPD_critical, dir.source);
844 }
845 
846 void OmpStructureChecker::Leave(const parser::OpenMPCriticalConstruct &) {
847   dirContext_.pop_back();
848 }
849 
850 void OmpStructureChecker::Enter(
851     const parser::OpenMPCancellationPointConstruct &x) {
852   const auto &dir{std::get<parser::Verbatim>(x.t)};
853   PushContextAndClauseSets(
854       dir.source, llvm::omp::Directive::OMPD_cancellation_point);
855 }
856 
857 void OmpStructureChecker::Leave(
858     const parser::OpenMPCancellationPointConstruct &) {
859   dirContext_.pop_back();
860 }
861 
862 void OmpStructureChecker::Enter(const parser::OmpEndBlockDirective &x) {
863   const auto &dir{std::get<parser::OmpBlockDirective>(x.t)};
864   ResetPartialContext(dir.source);
865   switch (dir.v) {
866   // 2.7.3 end-single-clause -> copyprivate-clause |
867   //                            nowait-clause
868   case llvm::omp::Directive::OMPD_single:
869     PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_end_single);
870     break;
871   // 2.7.4 end-workshare -> END WORKSHARE [nowait-clause]
872   case llvm::omp::Directive::OMPD_workshare:
873     PushContextAndClauseSets(
874         dir.source, llvm::omp::Directive::OMPD_end_workshare);
875     break;
876   default:
877     // no clauses are allowed
878     break;
879   }
880 }
881 
882 // TODO: Verify the popping of dirContext requirement after nowait
883 // implementation, as there is an implicit barrier at the end of the worksharing
884 // constructs unless a nowait clause is specified. Only OMPD_end_single and
885 // end_workshareare popped as they are pushed while entering the
886 // EndBlockDirective.
887 void OmpStructureChecker::Leave(const parser::OmpEndBlockDirective &x) {
888   if ((GetContext().directive == llvm::omp::Directive::OMPD_end_single) ||
889       (GetContext().directive == llvm::omp::Directive::OMPD_end_workshare)) {
890     dirContext_.pop_back();
891   }
892 }
893 
894 void OmpStructureChecker::Enter(const parser::OpenMPAtomicConstruct &x) {
895   std::visit(
896       common::visitors{
897           [&](const auto &someAtomicConstruct) {
898             const auto &dir{std::get<parser::Verbatim>(someAtomicConstruct.t)};
899             PushContextAndClauseSets(
900                 dir.source, llvm::omp::Directive::OMPD_atomic);
901           },
902       },
903       x.u);
904 }
905 
906 void OmpStructureChecker::Leave(const parser::OpenMPAtomicConstruct &) {
907   dirContext_.pop_back();
908 }
909 
910 // Clauses
911 // Mainly categorized as
912 // 1. Checks on 'OmpClauseList' from 'parse-tree.h'.
913 // 2. Checks on clauses which fall under 'struct OmpClause' from parse-tree.h.
914 // 3. Checks on clauses which are not in 'struct OmpClause' from parse-tree.h.
915 
916 void OmpStructureChecker::Leave(const parser::OmpClauseList &) {
917   // 2.7 Loop Construct Restriction
918   if (llvm::omp::doSet.test(GetContext().directive)) {
919     if (auto *clause{FindClause(llvm::omp::Clause::OMPC_schedule)}) {
920       // only one schedule clause is allowed
921       const auto &schedClause{std::get<parser::OmpClause::Schedule>(clause->u)};
922       if (ScheduleModifierHasType(schedClause.v,
923               parser::OmpScheduleModifierType::ModType::Nonmonotonic)) {
924         if (FindClause(llvm::omp::Clause::OMPC_ordered)) {
925           context_.Say(clause->source,
926               "The NONMONOTONIC modifier cannot be specified "
927               "if an ORDERED clause is specified"_err_en_US);
928         }
929         if (ScheduleModifierHasType(schedClause.v,
930                 parser::OmpScheduleModifierType::ModType::Monotonic)) {
931           context_.Say(clause->source,
932               "The MONOTONIC and NONMONOTONIC modifiers "
933               "cannot be both specified"_err_en_US);
934         }
935       }
936     }
937 
938     if (auto *clause{FindClause(llvm::omp::Clause::OMPC_ordered)}) {
939       // only one ordered clause is allowed
940       const auto &orderedClause{
941           std::get<parser::OmpClause::Ordered>(clause->u)};
942 
943       if (orderedClause.v) {
944         CheckNotAllowedIfClause(
945             llvm::omp::Clause::OMPC_ordered, {llvm::omp::Clause::OMPC_linear});
946 
947         if (auto *clause2{FindClause(llvm::omp::Clause::OMPC_collapse)}) {
948           const auto &collapseClause{
949               std::get<parser::OmpClause::Collapse>(clause2->u)};
950           // ordered and collapse both have parameters
951           if (const auto orderedValue{GetIntValue(orderedClause.v)}) {
952             if (const auto collapseValue{GetIntValue(collapseClause.v)}) {
953               if (*orderedValue > 0 && *orderedValue < *collapseValue) {
954                 context_.Say(clause->source,
955                     "The parameter of the ORDERED clause must be "
956                     "greater than or equal to "
957                     "the parameter of the COLLAPSE clause"_err_en_US);
958               }
959             }
960           }
961         }
962       }
963 
964       // TODO: ordered region binding check (requires nesting implementation)
965     }
966   } // doSet
967 
968   // 2.8.1 Simd Construct Restriction
969   if (llvm::omp::simdSet.test(GetContext().directive)) {
970     if (auto *clause{FindClause(llvm::omp::Clause::OMPC_simdlen)}) {
971       if (auto *clause2{FindClause(llvm::omp::Clause::OMPC_safelen)}) {
972         const auto &simdlenClause{
973             std::get<parser::OmpClause::Simdlen>(clause->u)};
974         const auto &safelenClause{
975             std::get<parser::OmpClause::Safelen>(clause2->u)};
976         // simdlen and safelen both have parameters
977         if (const auto simdlenValue{GetIntValue(simdlenClause.v)}) {
978           if (const auto safelenValue{GetIntValue(safelenClause.v)}) {
979             if (*safelenValue > 0 && *simdlenValue > *safelenValue) {
980               context_.Say(clause->source,
981                   "The parameter of the SIMDLEN clause must be less than or "
982                   "equal to the parameter of the SAFELEN clause"_err_en_US);
983             }
984           }
985         }
986       }
987     }
988     // A list-item cannot appear in more than one aligned clause
989     semantics::UnorderedSymbolSet alignedVars;
990     auto clauseAll = FindClauses(llvm::omp::Clause::OMPC_aligned);
991     for (auto itr = clauseAll.first; itr != clauseAll.second; ++itr) {
992       const auto &alignedClause{
993           std::get<parser::OmpClause::Aligned>(itr->second->u)};
994       const auto &alignedNameList{
995           std::get<std::list<parser::Name>>(alignedClause.v.t)};
996       for (auto const &var : alignedNameList) {
997         if (alignedVars.count(*(var.symbol)) == 1) {
998           context_.Say(itr->second->source,
999               "List item '%s' present at multiple ALIGNED clauses"_err_en_US,
1000               var.ToString());
1001           break;
1002         }
1003         alignedVars.insert(*(var.symbol));
1004       }
1005     }
1006   } // SIMD
1007 
1008   // 2.7.3 Single Construct Restriction
1009   if (GetContext().directive == llvm::omp::Directive::OMPD_end_single) {
1010     CheckNotAllowedIfClause(
1011         llvm::omp::Clause::OMPC_copyprivate, {llvm::omp::Clause::OMPC_nowait});
1012   }
1013 
1014   CheckRequireAtLeastOneOf();
1015 }
1016 
1017 void OmpStructureChecker::Enter(const parser::OmpClause &x) {
1018   SetContextClause(x);
1019 }
1020 
1021 // Following clauses do not have a separate node in parse-tree.h.
1022 CHECK_SIMPLE_CLAUSE(AcqRel, OMPC_acq_rel)
1023 CHECK_SIMPLE_CLAUSE(Acquire, OMPC_acquire)
1024 CHECK_SIMPLE_CLAUSE(AtomicDefaultMemOrder, OMPC_atomic_default_mem_order)
1025 CHECK_SIMPLE_CLAUSE(Affinity, OMPC_affinity)
1026 CHECK_SIMPLE_CLAUSE(Allocate, OMPC_allocate)
1027 CHECK_SIMPLE_CLAUSE(Capture, OMPC_capture)
1028 CHECK_SIMPLE_CLAUSE(Copyin, OMPC_copyin)
1029 CHECK_SIMPLE_CLAUSE(Default, OMPC_default)
1030 CHECK_SIMPLE_CLAUSE(Depobj, OMPC_depobj)
1031 CHECK_SIMPLE_CLAUSE(Destroy, OMPC_destroy)
1032 CHECK_SIMPLE_CLAUSE(Detach, OMPC_detach)
1033 CHECK_SIMPLE_CLAUSE(Device, OMPC_device)
1034 CHECK_SIMPLE_CLAUSE(DeviceType, OMPC_device_type)
1035 CHECK_SIMPLE_CLAUSE(DistSchedule, OMPC_dist_schedule)
1036 CHECK_SIMPLE_CLAUSE(DynamicAllocators, OMPC_dynamic_allocators)
1037 CHECK_SIMPLE_CLAUSE(Exclusive, OMPC_exclusive)
1038 CHECK_SIMPLE_CLAUSE(Final, OMPC_final)
1039 CHECK_SIMPLE_CLAUSE(Flush, OMPC_flush)
1040 CHECK_SIMPLE_CLAUSE(From, OMPC_from)
1041 CHECK_SIMPLE_CLAUSE(Full, OMPC_full)
1042 CHECK_SIMPLE_CLAUSE(Hint, OMPC_hint)
1043 CHECK_SIMPLE_CLAUSE(InReduction, OMPC_in_reduction)
1044 CHECK_SIMPLE_CLAUSE(Inclusive, OMPC_inclusive)
1045 CHECK_SIMPLE_CLAUSE(Match, OMPC_match)
1046 CHECK_SIMPLE_CLAUSE(Nontemporal, OMPC_nontemporal)
1047 CHECK_SIMPLE_CLAUSE(Order, OMPC_order)
1048 CHECK_SIMPLE_CLAUSE(Read, OMPC_read)
1049 CHECK_SIMPLE_CLAUSE(ReverseOffload, OMPC_reverse_offload)
1050 CHECK_SIMPLE_CLAUSE(Threadprivate, OMPC_threadprivate)
1051 CHECK_SIMPLE_CLAUSE(Threads, OMPC_threads)
1052 CHECK_SIMPLE_CLAUSE(Inbranch, OMPC_inbranch)
1053 CHECK_SIMPLE_CLAUSE(IsDevicePtr, OMPC_is_device_ptr)
1054 CHECK_SIMPLE_CLAUSE(Link, OMPC_link)
1055 CHECK_SIMPLE_CLAUSE(Mergeable, OMPC_mergeable)
1056 CHECK_SIMPLE_CLAUSE(Nogroup, OMPC_nogroup)
1057 CHECK_SIMPLE_CLAUSE(Notinbranch, OMPC_notinbranch)
1058 CHECK_SIMPLE_CLAUSE(Nowait, OMPC_nowait)
1059 CHECK_SIMPLE_CLAUSE(Partial, OMPC_partial)
1060 CHECK_SIMPLE_CLAUSE(ProcBind, OMPC_proc_bind)
1061 CHECK_SIMPLE_CLAUSE(Release, OMPC_release)
1062 CHECK_SIMPLE_CLAUSE(Relaxed, OMPC_relaxed)
1063 CHECK_SIMPLE_CLAUSE(SeqCst, OMPC_seq_cst)
1064 CHECK_SIMPLE_CLAUSE(Simd, OMPC_simd)
1065 CHECK_SIMPLE_CLAUSE(Sizes, OMPC_sizes)
1066 CHECK_SIMPLE_CLAUSE(TaskReduction, OMPC_task_reduction)
1067 CHECK_SIMPLE_CLAUSE(To, OMPC_to)
1068 CHECK_SIMPLE_CLAUSE(UnifiedAddress, OMPC_unified_address)
1069 CHECK_SIMPLE_CLAUSE(UnifiedSharedMemory, OMPC_unified_shared_memory)
1070 CHECK_SIMPLE_CLAUSE(Uniform, OMPC_uniform)
1071 CHECK_SIMPLE_CLAUSE(Unknown, OMPC_unknown)
1072 CHECK_SIMPLE_CLAUSE(Untied, OMPC_untied)
1073 CHECK_SIMPLE_CLAUSE(UseDevicePtr, OMPC_use_device_ptr)
1074 CHECK_SIMPLE_CLAUSE(UsesAllocators, OMPC_uses_allocators)
1075 CHECK_SIMPLE_CLAUSE(Update, OMPC_update)
1076 CHECK_SIMPLE_CLAUSE(UseDeviceAddr, OMPC_use_device_addr)
1077 CHECK_SIMPLE_CLAUSE(Write, OMPC_write)
1078 CHECK_SIMPLE_CLAUSE(Init, OMPC_init)
1079 CHECK_SIMPLE_CLAUSE(Use, OMPC_use)
1080 CHECK_SIMPLE_CLAUSE(Novariants, OMPC_novariants)
1081 CHECK_SIMPLE_CLAUSE(Nocontext, OMPC_nocontext)
1082 CHECK_SIMPLE_CLAUSE(Filter, OMPC_filter)
1083 
1084 CHECK_REQ_SCALAR_INT_CLAUSE(Grainsize, OMPC_grainsize)
1085 CHECK_REQ_SCALAR_INT_CLAUSE(NumTasks, OMPC_num_tasks)
1086 CHECK_REQ_SCALAR_INT_CLAUSE(NumTeams, OMPC_num_teams)
1087 CHECK_REQ_SCALAR_INT_CLAUSE(NumThreads, OMPC_num_threads)
1088 CHECK_REQ_SCALAR_INT_CLAUSE(Priority, OMPC_priority)
1089 CHECK_REQ_SCALAR_INT_CLAUSE(ThreadLimit, OMPC_thread_limit)
1090 
1091 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Collapse, OMPC_collapse)
1092 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Safelen, OMPC_safelen)
1093 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Simdlen, OMPC_simdlen)
1094 
1095 // Restrictions specific to each clause are implemented apart from the
1096 // generalized restrictions.
1097 void OmpStructureChecker::Enter(const parser::OmpClause::Reduction &x) {
1098   CheckAllowed(llvm::omp::Clause::OMPC_reduction);
1099   if (CheckReductionOperators(x)) {
1100     CheckReductionTypeList(x);
1101   }
1102 }
1103 bool OmpStructureChecker::CheckReductionOperators(
1104     const parser::OmpClause::Reduction &x) {
1105 
1106   const auto &definedOp{std::get<0>(x.v.t)};
1107   bool ok = false;
1108   std::visit(
1109       common::visitors{
1110           [&](const parser::DefinedOperator &dOpr) {
1111             const auto &intrinsicOp{
1112                 std::get<parser::DefinedOperator::IntrinsicOperator>(dOpr.u)};
1113             ok = CheckIntrinsicOperator(intrinsicOp);
1114           },
1115           [&](const parser::ProcedureDesignator &procD) {
1116             const parser::Name *name{std::get_if<parser::Name>(&procD.u)};
1117             if (name) {
1118               if (name->source == "max" || name->source == "min" ||
1119                   name->source == "iand" || name->source == "ior" ||
1120                   name->source == "ieor") {
1121                 ok = true;
1122               } else {
1123                 context_.Say(GetContext().clauseSource,
1124                     "Invalid reduction identifier in REDUCTION clause."_err_en_US,
1125                     ContextDirectiveAsFortran());
1126               }
1127             }
1128           },
1129       },
1130       definedOp.u);
1131 
1132   return ok;
1133 }
1134 bool OmpStructureChecker::CheckIntrinsicOperator(
1135     const parser::DefinedOperator::IntrinsicOperator &op) {
1136 
1137   switch (op) {
1138   case parser::DefinedOperator::IntrinsicOperator::Add:
1139   case parser::DefinedOperator::IntrinsicOperator::Subtract:
1140   case parser::DefinedOperator::IntrinsicOperator::Multiply:
1141   case parser::DefinedOperator::IntrinsicOperator::AND:
1142   case parser::DefinedOperator::IntrinsicOperator::OR:
1143   case parser::DefinedOperator::IntrinsicOperator::EQV:
1144   case parser::DefinedOperator::IntrinsicOperator::NEQV:
1145     return true;
1146   default:
1147     context_.Say(GetContext().clauseSource,
1148         "Invalid reduction operator in REDUCTION clause."_err_en_US,
1149         ContextDirectiveAsFortran());
1150   }
1151   return false;
1152 }
1153 
1154 void OmpStructureChecker::CheckReductionTypeList(
1155     const parser::OmpClause::Reduction &x) {
1156   const auto &ompObjectList{std::get<parser::OmpObjectList>(x.v.t)};
1157   CheckIntentInPointerAndDefinable(
1158       ompObjectList, llvm::omp::Clause::OMPC_reduction);
1159   CheckReductionArraySection(ompObjectList);
1160   CheckMultipleAppearanceAcrossContext(ompObjectList);
1161 }
1162 
1163 void OmpStructureChecker::CheckIntentInPointerAndDefinable(
1164     const parser::OmpObjectList &objectList, const llvm::omp::Clause clause) {
1165   for (const auto &ompObject : objectList.v) {
1166     if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
1167       if (const auto *symbol{name->symbol}) {
1168         if (IsPointer(symbol->GetUltimate()) &&
1169             IsIntentIn(symbol->GetUltimate())) {
1170           context_.Say(GetContext().clauseSource,
1171               "Pointer '%s' with the INTENT(IN) attribute may not appear "
1172               "in a %s clause"_err_en_US,
1173               symbol->name(),
1174               parser::ToUpperCaseLetters(getClauseName(clause).str()));
1175         }
1176         if (auto msg{
1177                 WhyNotModifiable(*symbol, context_.FindScope(name->source))}) {
1178           context_.Say(GetContext().clauseSource,
1179               "Variable '%s' on the %s clause is not definable"_err_en_US,
1180               symbol->name(),
1181               parser::ToUpperCaseLetters(getClauseName(clause).str()));
1182         }
1183       }
1184     }
1185   }
1186 }
1187 
1188 void OmpStructureChecker::CheckReductionArraySection(
1189     const parser::OmpObjectList &ompObjectList) {
1190   for (const auto &ompObject : ompObjectList.v) {
1191     if (const auto *dataRef{parser::Unwrap<parser::DataRef>(ompObject)}) {
1192       if (const auto *arrayElement{
1193               parser::Unwrap<parser::ArrayElement>(ompObject)}) {
1194         if (arrayElement) {
1195           CheckArraySection(*arrayElement, GetLastName(*dataRef),
1196               llvm::omp::Clause::OMPC_reduction);
1197         }
1198       }
1199     }
1200   }
1201 }
1202 
1203 void OmpStructureChecker::CheckMultipleAppearanceAcrossContext(
1204     const parser::OmpObjectList &redObjectList) {
1205   //  TODO: Verify the assumption here that the immediately enclosing region is
1206   //  the parallel region to which the worksharing construct having reduction
1207   //  binds to.
1208   if (auto *enclosingContext{GetEnclosingDirContext()}) {
1209     for (auto it : enclosingContext->clauseInfo) {
1210       llvmOmpClause type = it.first;
1211       const auto *clause = it.second;
1212       if (llvm::omp::privateReductionSet.test(type)) {
1213         if (const auto *objList{GetOmpObjectList(*clause)}) {
1214           for (const auto &ompObject : objList->v) {
1215             if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
1216               if (const auto *symbol{name->symbol}) {
1217                 for (const auto &redOmpObject : redObjectList.v) {
1218                   if (const auto *rname{
1219                           parser::Unwrap<parser::Name>(redOmpObject)}) {
1220                     if (const auto *rsymbol{rname->symbol}) {
1221                       if (rsymbol->name() == symbol->name()) {
1222                         context_.Say(GetContext().clauseSource,
1223                             "%s variable '%s' is %s in outer context must"
1224                             " be shared in the parallel regions to which any"
1225                             " of the worksharing regions arising from the "
1226                             "worksharing"
1227                             " construct bind."_err_en_US,
1228                             parser::ToUpperCaseLetters(
1229                                 getClauseName(llvm::omp::Clause::OMPC_reduction)
1230                                     .str()),
1231                             symbol->name(),
1232                             parser::ToUpperCaseLetters(
1233                                 getClauseName(type).str()));
1234                       }
1235                     }
1236                   }
1237                 }
1238               }
1239             }
1240           }
1241         }
1242       }
1243     }
1244   }
1245 }
1246 
1247 void OmpStructureChecker::Enter(const parser::OmpClause::Ordered &x) {
1248   CheckAllowed(llvm::omp::Clause::OMPC_ordered);
1249   // the parameter of ordered clause is optional
1250   if (const auto &expr{x.v}) {
1251     RequiresConstantPositiveParameter(llvm::omp::Clause::OMPC_ordered, *expr);
1252     // 2.8.3 Loop SIMD Construct Restriction
1253     if (llvm::omp::doSimdSet.test(GetContext().directive)) {
1254       context_.Say(GetContext().clauseSource,
1255           "No ORDERED clause with a parameter can be specified "
1256           "on the %s directive"_err_en_US,
1257           ContextDirectiveAsFortran());
1258     }
1259   }
1260 }
1261 
1262 void OmpStructureChecker::Enter(const parser::OmpClause::Shared &x) {
1263   CheckAllowed(llvm::omp::Clause::OMPC_shared);
1264   CheckIsVarPartOfAnotherVar(GetContext().clauseSource, x.v);
1265 }
1266 void OmpStructureChecker::Enter(const parser::OmpClause::Private &x) {
1267   CheckAllowed(llvm::omp::Clause::OMPC_private);
1268   CheckIsVarPartOfAnotherVar(GetContext().clauseSource, x.v);
1269   CheckIntentInPointer(x.v, llvm::omp::Clause::OMPC_private);
1270 }
1271 
1272 bool OmpStructureChecker::IsDataRefTypeParamInquiry(
1273     const parser::DataRef *dataRef) {
1274   bool dataRefIsTypeParamInquiry{false};
1275   if (const auto *structComp{
1276           parser::Unwrap<parser::StructureComponent>(dataRef)}) {
1277     if (const auto *compSymbol{structComp->component.symbol}) {
1278       if (const auto *compSymbolMiscDetails{
1279               std::get_if<MiscDetails>(&compSymbol->details())}) {
1280         const auto detailsKind = compSymbolMiscDetails->kind();
1281         dataRefIsTypeParamInquiry =
1282             (detailsKind == MiscDetails::Kind::KindParamInquiry ||
1283                 detailsKind == MiscDetails::Kind::LenParamInquiry);
1284       } else if (compSymbol->has<TypeParamDetails>()) {
1285         dataRefIsTypeParamInquiry = true;
1286       }
1287     }
1288   }
1289   return dataRefIsTypeParamInquiry;
1290 }
1291 
1292 void OmpStructureChecker::CheckIsVarPartOfAnotherVar(
1293     const parser::CharBlock &source, const parser::OmpObjectList &objList) {
1294 
1295   for (const auto &ompObject : objList.v) {
1296     std::visit(
1297         common::visitors{
1298             [&](const parser::Designator &designator) {
1299               if (const auto *dataRef{
1300                       std::get_if<parser::DataRef>(&designator.u)}) {
1301                 if (IsDataRefTypeParamInquiry(dataRef)) {
1302                   context_.Say(source,
1303                       "A type parameter inquiry cannot appear in an ALLOCATE directive"_err_en_US);
1304                 } else if (parser::Unwrap<parser::StructureComponent>(
1305                                ompObject) ||
1306                     parser::Unwrap<parser::ArrayElement>(ompObject)) {
1307                   context_.Say(source,
1308                       "A variable that is part of another variable (as an "
1309                       "array or structure element)"
1310                       " cannot appear in a PRIVATE or SHARED clause or on the ALLOCATE directive."_err_en_US);
1311                 }
1312               }
1313             },
1314             [&](const parser::Name &name) {},
1315         },
1316         ompObject.u);
1317   }
1318 }
1319 
1320 void OmpStructureChecker::Enter(const parser::OmpClause::Firstprivate &x) {
1321   CheckAllowed(llvm::omp::Clause::OMPC_firstprivate);
1322   CheckIsLoopIvPartOfClause(llvmOmpClause::OMPC_firstprivate, x.v);
1323 
1324   SymbolSourceMap currSymbols;
1325   GetSymbolsInObjectList(x.v, currSymbols);
1326 
1327   DirectivesClauseTriple dirClauseTriple;
1328   // Check firstprivate variables in worksharing constructs
1329   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_do,
1330       std::make_pair(
1331           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
1332   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_sections,
1333       std::make_pair(
1334           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
1335   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_single,
1336       std::make_pair(
1337           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
1338   // Check firstprivate variables in distribute construct
1339   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_distribute,
1340       std::make_pair(
1341           llvm::omp::Directive::OMPD_teams, llvm::omp::privateReductionSet));
1342   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_distribute,
1343       std::make_pair(llvm::omp::Directive::OMPD_target_teams,
1344           llvm::omp::privateReductionSet));
1345   // Check firstprivate variables in task and taskloop constructs
1346   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_task,
1347       std::make_pair(llvm::omp::Directive::OMPD_parallel,
1348           OmpClauseSet{llvm::omp::Clause::OMPC_reduction}));
1349   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_taskloop,
1350       std::make_pair(llvm::omp::Directive::OMPD_parallel,
1351           OmpClauseSet{llvm::omp::Clause::OMPC_reduction}));
1352 
1353   CheckPrivateSymbolsInOuterCxt(
1354       currSymbols, dirClauseTriple, llvm::omp::Clause::OMPC_firstprivate);
1355 }
1356 
1357 void OmpStructureChecker::CheckIsLoopIvPartOfClause(
1358     llvmOmpClause clause, const parser::OmpObjectList &ompObjectList) {
1359   for (const auto &ompObject : ompObjectList.v) {
1360     if (const parser::Name * name{parser::Unwrap<parser::Name>(ompObject)}) {
1361       if (name->symbol == GetContext().loopIV) {
1362         context_.Say(name->source,
1363             "DO iteration variable %s is not allowed in %s clause."_err_en_US,
1364             name->ToString(),
1365             parser::ToUpperCaseLetters(getClauseName(clause).str()));
1366       }
1367     }
1368   }
1369 }
1370 // Following clauses have a seperate node in parse-tree.h.
1371 // Atomic-clause
1372 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicRead, OMPC_read)
1373 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicWrite, OMPC_write)
1374 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicUpdate, OMPC_update)
1375 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicCapture, OMPC_capture)
1376 
1377 void OmpStructureChecker::Leave(const parser::OmpAtomicRead &) {
1378   CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_read,
1379       {llvm::omp::Clause::OMPC_release, llvm::omp::Clause::OMPC_acq_rel});
1380 }
1381 void OmpStructureChecker::Leave(const parser::OmpAtomicWrite &) {
1382   CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_write,
1383       {llvm::omp::Clause::OMPC_acquire, llvm::omp::Clause::OMPC_acq_rel});
1384 }
1385 void OmpStructureChecker::Leave(const parser::OmpAtomicUpdate &) {
1386   CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_update,
1387       {llvm::omp::Clause::OMPC_acquire, llvm::omp::Clause::OMPC_acq_rel});
1388 }
1389 // OmpAtomic node represents atomic directive without atomic-clause.
1390 // atomic-clause - READ,WRITE,UPDATE,CAPTURE.
1391 void OmpStructureChecker::Leave(const parser::OmpAtomic &) {
1392   if (const auto *clause{FindClause(llvm::omp::Clause::OMPC_acquire)}) {
1393     context_.Say(clause->source,
1394         "Clause ACQUIRE is not allowed on the ATOMIC directive"_err_en_US);
1395   }
1396   if (const auto *clause{FindClause(llvm::omp::Clause::OMPC_acq_rel)}) {
1397     context_.Say(clause->source,
1398         "Clause ACQ_REL is not allowed on the ATOMIC directive"_err_en_US);
1399   }
1400 }
1401 // Restrictions specific to each clause are implemented apart from the
1402 // generalized restrictions.
1403 void OmpStructureChecker::Enter(const parser::OmpClause::Aligned &x) {
1404   CheckAllowed(llvm::omp::Clause::OMPC_aligned);
1405 
1406   if (const auto &expr{
1407           std::get<std::optional<parser::ScalarIntConstantExpr>>(x.v.t)}) {
1408     RequiresConstantPositiveParameter(llvm::omp::Clause::OMPC_aligned, *expr);
1409   }
1410   // 2.8.1 TODO: list-item attribute check
1411 }
1412 void OmpStructureChecker::Enter(const parser::OmpClause::Defaultmap &x) {
1413   CheckAllowed(llvm::omp::Clause::OMPC_defaultmap);
1414   using VariableCategory = parser::OmpDefaultmapClause::VariableCategory;
1415   if (!std::get<std::optional<VariableCategory>>(x.v.t)) {
1416     context_.Say(GetContext().clauseSource,
1417         "The argument TOFROM:SCALAR must be specified on the DEFAULTMAP "
1418         "clause"_err_en_US);
1419   }
1420 }
1421 void OmpStructureChecker::Enter(const parser::OmpClause::If &x) {
1422   CheckAllowed(llvm::omp::Clause::OMPC_if);
1423   using dirNameModifier = parser::OmpIfClause::DirectiveNameModifier;
1424   static std::unordered_map<dirNameModifier, OmpDirectiveSet>
1425       dirNameModifierMap{{dirNameModifier::Parallel, llvm::omp::parallelSet},
1426           {dirNameModifier::Target, llvm::omp::targetSet},
1427           {dirNameModifier::TargetEnterData,
1428               {llvm::omp::Directive::OMPD_target_enter_data}},
1429           {dirNameModifier::TargetExitData,
1430               {llvm::omp::Directive::OMPD_target_exit_data}},
1431           {dirNameModifier::TargetData,
1432               {llvm::omp::Directive::OMPD_target_data}},
1433           {dirNameModifier::TargetUpdate,
1434               {llvm::omp::Directive::OMPD_target_update}},
1435           {dirNameModifier::Task, {llvm::omp::Directive::OMPD_task}},
1436           {dirNameModifier::Taskloop, llvm::omp::taskloopSet}};
1437   if (const auto &directiveName{
1438           std::get<std::optional<dirNameModifier>>(x.v.t)}) {
1439     auto search{dirNameModifierMap.find(*directiveName)};
1440     if (search == dirNameModifierMap.end() ||
1441         !search->second.test(GetContext().directive)) {
1442       context_
1443           .Say(GetContext().clauseSource,
1444               "Unmatched directive name modifier %s on the IF clause"_err_en_US,
1445               parser::ToUpperCaseLetters(
1446                   parser::OmpIfClause::EnumToString(*directiveName)))
1447           .Attach(
1448               GetContext().directiveSource, "Cannot apply to directive"_en_US);
1449     }
1450   }
1451 }
1452 
1453 void OmpStructureChecker::Enter(const parser::OmpClause::Linear &x) {
1454   CheckAllowed(llvm::omp::Clause::OMPC_linear);
1455 
1456   // 2.7 Loop Construct Restriction
1457   if ((llvm::omp::doSet | llvm::omp::simdSet).test(GetContext().directive)) {
1458     if (std::holds_alternative<parser::OmpLinearClause::WithModifier>(x.v.u)) {
1459       context_.Say(GetContext().clauseSource,
1460           "A modifier may not be specified in a LINEAR clause "
1461           "on the %s directive"_err_en_US,
1462           ContextDirectiveAsFortran());
1463     }
1464   }
1465 }
1466 
1467 void OmpStructureChecker::CheckAllowedMapTypes(
1468     const parser::OmpMapType::Type &type,
1469     const std::list<parser::OmpMapType::Type> &allowedMapTypeList) {
1470   const auto found{std::find(
1471       std::begin(allowedMapTypeList), std::end(allowedMapTypeList), type)};
1472   if (found == std::end(allowedMapTypeList)) {
1473     std::string commaSeperatedMapTypes;
1474     llvm::interleave(
1475         allowedMapTypeList.begin(), allowedMapTypeList.end(),
1476         [&](const parser::OmpMapType::Type &mapType) {
1477           commaSeperatedMapTypes.append(parser::ToUpperCaseLetters(
1478               parser::OmpMapType::EnumToString(mapType)));
1479         },
1480         [&] { commaSeperatedMapTypes.append(", "); });
1481     context_.Say(GetContext().clauseSource,
1482         "Only the %s map types are permitted "
1483         "for MAP clauses on the %s directive"_err_en_US,
1484         commaSeperatedMapTypes, ContextDirectiveAsFortran());
1485   }
1486 }
1487 
1488 void OmpStructureChecker::Enter(const parser::OmpClause::Map &x) {
1489   CheckAllowed(llvm::omp::Clause::OMPC_map);
1490 
1491   if (const auto &maptype{std::get<std::optional<parser::OmpMapType>>(x.v.t)}) {
1492     using Type = parser::OmpMapType::Type;
1493     const Type &type{std::get<Type>(maptype->t)};
1494     switch (GetContext().directive) {
1495     case llvm::omp::Directive::OMPD_target:
1496     case llvm::omp::Directive::OMPD_target_teams:
1497     case llvm::omp::Directive::OMPD_target_teams_distribute:
1498     case llvm::omp::Directive::OMPD_target_teams_distribute_simd:
1499     case llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do:
1500     case llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do_simd:
1501     case llvm::omp::Directive::OMPD_target_data:
1502       CheckAllowedMapTypes(
1503           type, {Type::To, Type::From, Type::Tofrom, Type::Alloc});
1504       break;
1505     case llvm::omp::Directive::OMPD_target_enter_data:
1506       CheckAllowedMapTypes(type, {Type::To, Type::Alloc});
1507       break;
1508     case llvm::omp::Directive::OMPD_target_exit_data:
1509       CheckAllowedMapTypes(type, {Type::From, Type::Release, Type::Delete});
1510       break;
1511     default:
1512       break;
1513     }
1514   }
1515 }
1516 
1517 bool OmpStructureChecker::ScheduleModifierHasType(
1518     const parser::OmpScheduleClause &x,
1519     const parser::OmpScheduleModifierType::ModType &type) {
1520   const auto &modifier{
1521       std::get<std::optional<parser::OmpScheduleModifier>>(x.t)};
1522   if (modifier) {
1523     const auto &modType1{
1524         std::get<parser::OmpScheduleModifier::Modifier1>(modifier->t)};
1525     const auto &modType2{
1526         std::get<std::optional<parser::OmpScheduleModifier::Modifier2>>(
1527             modifier->t)};
1528     if (modType1.v.v == type || (modType2 && modType2->v.v == type)) {
1529       return true;
1530     }
1531   }
1532   return false;
1533 }
1534 void OmpStructureChecker::Enter(const parser::OmpClause::Schedule &x) {
1535   CheckAllowed(llvm::omp::Clause::OMPC_schedule);
1536   const parser::OmpScheduleClause &scheduleClause = x.v;
1537 
1538   // 2.7 Loop Construct Restriction
1539   if (llvm::omp::doSet.test(GetContext().directive)) {
1540     const auto &kind{std::get<1>(scheduleClause.t)};
1541     const auto &chunk{std::get<2>(scheduleClause.t)};
1542     if (chunk) {
1543       if (kind == parser::OmpScheduleClause::ScheduleType::Runtime ||
1544           kind == parser::OmpScheduleClause::ScheduleType::Auto) {
1545         context_.Say(GetContext().clauseSource,
1546             "When SCHEDULE clause has %s specified, "
1547             "it must not have chunk size specified"_err_en_US,
1548             parser::ToUpperCaseLetters(
1549                 parser::OmpScheduleClause::EnumToString(kind)));
1550       }
1551       if (const auto &chunkExpr{std::get<std::optional<parser::ScalarIntExpr>>(
1552               scheduleClause.t)}) {
1553         RequiresPositiveParameter(
1554             llvm::omp::Clause::OMPC_schedule, *chunkExpr, "chunk size");
1555       }
1556     }
1557 
1558     if (ScheduleModifierHasType(scheduleClause,
1559             parser::OmpScheduleModifierType::ModType::Nonmonotonic)) {
1560       if (kind != parser::OmpScheduleClause::ScheduleType::Dynamic &&
1561           kind != parser::OmpScheduleClause::ScheduleType::Guided) {
1562         context_.Say(GetContext().clauseSource,
1563             "The NONMONOTONIC modifier can only be specified with "
1564             "SCHEDULE(DYNAMIC) or SCHEDULE(GUIDED)"_err_en_US);
1565       }
1566     }
1567   }
1568 }
1569 
1570 void OmpStructureChecker::Enter(const parser::OmpClause::Depend &x) {
1571   CheckAllowed(llvm::omp::Clause::OMPC_depend);
1572   if (const auto *inOut{std::get_if<parser::OmpDependClause::InOut>(&x.v.u)}) {
1573     const auto &designators{std::get<std::list<parser::Designator>>(inOut->t)};
1574     for (const auto &ele : designators) {
1575       if (const auto *dataRef{std::get_if<parser::DataRef>(&ele.u)}) {
1576         CheckDependList(*dataRef);
1577         if (const auto *arr{
1578                 std::get_if<common::Indirection<parser::ArrayElement>>(
1579                     &dataRef->u)}) {
1580           CheckArraySection(arr->value(), GetLastName(*dataRef),
1581               llvm::omp::Clause::OMPC_depend);
1582         }
1583       }
1584     }
1585   }
1586 }
1587 
1588 void OmpStructureChecker::Enter(const parser::OmpClause::Copyprivate &x) {
1589   CheckAllowed(llvm::omp::Clause::OMPC_copyprivate);
1590   CheckIntentInPointer(x.v, llvm::omp::Clause::OMPC_copyprivate);
1591 }
1592 
1593 void OmpStructureChecker::Enter(const parser::OmpClause::Lastprivate &x) {
1594   CheckAllowed(llvm::omp::Clause::OMPC_lastprivate);
1595 
1596   DirectivesClauseTriple dirClauseTriple;
1597   SymbolSourceMap currSymbols;
1598   GetSymbolsInObjectList(x.v, currSymbols);
1599   CheckDefinableObjects(currSymbols, GetClauseKindForParserClass(x));
1600 
1601   // Check lastprivate variables in worksharing constructs
1602   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_do,
1603       std::make_pair(
1604           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
1605   dirClauseTriple.emplace(llvm::omp::Directive::OMPD_sections,
1606       std::make_pair(
1607           llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet));
1608 
1609   CheckPrivateSymbolsInOuterCxt(
1610       currSymbols, dirClauseTriple, GetClauseKindForParserClass(x));
1611 }
1612 
1613 llvm::StringRef OmpStructureChecker::getClauseName(llvm::omp::Clause clause) {
1614   return llvm::omp::getOpenMPClauseName(clause);
1615 }
1616 
1617 llvm::StringRef OmpStructureChecker::getDirectiveName(
1618     llvm::omp::Directive directive) {
1619   return llvm::omp::getOpenMPDirectiveName(directive);
1620 }
1621 
1622 void OmpStructureChecker::CheckDependList(const parser::DataRef &d) {
1623   std::visit(
1624       common::visitors{
1625           [&](const common::Indirection<parser::ArrayElement> &elem) {
1626             // Check if the base element is valid on Depend Clause
1627             CheckDependList(elem.value().base);
1628           },
1629           [&](const common::Indirection<parser::StructureComponent> &) {
1630             context_.Say(GetContext().clauseSource,
1631                 "A variable that is part of another variable "
1632                 "(such as an element of a structure) but is not an array "
1633                 "element or an array section cannot appear in a DEPEND "
1634                 "clause"_err_en_US);
1635           },
1636           [&](const common::Indirection<parser::CoindexedNamedObject> &) {
1637             context_.Say(GetContext().clauseSource,
1638                 "Coarrays are not supported in DEPEND clause"_err_en_US);
1639           },
1640           [&](const parser::Name &) { return; },
1641       },
1642       d.u);
1643 }
1644 
1645 // Called from both Reduction and Depend clause.
1646 void OmpStructureChecker::CheckArraySection(
1647     const parser::ArrayElement &arrayElement, const parser::Name &name,
1648     const llvm::omp::Clause clause) {
1649   if (!arrayElement.subscripts.empty()) {
1650     for (const auto &subscript : arrayElement.subscripts) {
1651       if (const auto *triplet{
1652               std::get_if<parser::SubscriptTriplet>(&subscript.u)}) {
1653         if (std::get<0>(triplet->t) && std::get<1>(triplet->t)) {
1654           const auto &lower{std::get<0>(triplet->t)};
1655           const auto &upper{std::get<1>(triplet->t)};
1656           if (lower && upper) {
1657             const auto lval{GetIntValue(lower)};
1658             const auto uval{GetIntValue(upper)};
1659             if (lval && uval && *uval < *lval) {
1660               context_.Say(GetContext().clauseSource,
1661                   "'%s' in %s clause"
1662                   " is a zero size array section"_err_en_US,
1663                   name.ToString(),
1664                   parser::ToUpperCaseLetters(getClauseName(clause).str()));
1665               break;
1666             } else if (std::get<2>(triplet->t)) {
1667               const auto &strideExpr{std::get<2>(triplet->t)};
1668               if (strideExpr) {
1669                 if (clause == llvm::omp::Clause::OMPC_depend) {
1670                   context_.Say(GetContext().clauseSource,
1671                       "Stride should not be specified for array section in "
1672                       "DEPEND "
1673                       "clause"_err_en_US);
1674                 }
1675                 const auto stride{GetIntValue(strideExpr)};
1676                 if ((stride && stride != 1)) {
1677                   context_.Say(GetContext().clauseSource,
1678                       "A list item that appears in a REDUCTION clause"
1679                       " should have a contiguous storage array section."_err_en_US,
1680                       ContextDirectiveAsFortran());
1681                   break;
1682                 }
1683               }
1684             }
1685           }
1686         }
1687       }
1688     }
1689   }
1690 }
1691 
1692 void OmpStructureChecker::CheckIntentInPointer(
1693     const parser::OmpObjectList &objectList, const llvm::omp::Clause clause) {
1694   SymbolSourceMap symbols;
1695   GetSymbolsInObjectList(objectList, symbols);
1696   for (auto it{symbols.begin()}; it != symbols.end(); ++it) {
1697     const auto *symbol{it->first};
1698     const auto source{it->second};
1699     if (IsPointer(*symbol) && IsIntentIn(*symbol)) {
1700       context_.Say(source,
1701           "Pointer '%s' with the INTENT(IN) attribute may not appear "
1702           "in a %s clause"_err_en_US,
1703           symbol->name(),
1704           parser::ToUpperCaseLetters(getClauseName(clause).str()));
1705     }
1706   }
1707 }
1708 
1709 void OmpStructureChecker::GetSymbolsInObjectList(
1710     const parser::OmpObjectList &objectList, SymbolSourceMap &symbols) {
1711   for (const auto &ompObject : objectList.v) {
1712     if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) {
1713       if (const auto *symbol{name->symbol}) {
1714         if (const auto *commonBlockDetails{
1715                 symbol->detailsIf<CommonBlockDetails>()}) {
1716           for (const auto &object : commonBlockDetails->objects()) {
1717             symbols.emplace(&object->GetUltimate(), name->source);
1718           }
1719         } else {
1720           symbols.emplace(&symbol->GetUltimate(), name->source);
1721         }
1722       }
1723     }
1724   }
1725 }
1726 
1727 void OmpStructureChecker::CheckDefinableObjects(
1728     SymbolSourceMap &symbols, const llvm::omp::Clause clause) {
1729   for (auto it{symbols.begin()}; it != symbols.end(); ++it) {
1730     const auto *symbol{it->first};
1731     const auto source{it->second};
1732     if (auto msg{WhyNotModifiable(*symbol, context_.FindScope(source))}) {
1733       context_
1734           .Say(source,
1735               "Variable '%s' on the %s clause is not definable"_err_en_US,
1736               symbol->name(),
1737               parser::ToUpperCaseLetters(getClauseName(clause).str()))
1738           .Attach(source, std::move(*msg), symbol->name());
1739     }
1740   }
1741 }
1742 
1743 void OmpStructureChecker::CheckPrivateSymbolsInOuterCxt(
1744     SymbolSourceMap &currSymbols, DirectivesClauseTriple &dirClauseTriple,
1745     const llvm::omp::Clause currClause) {
1746   SymbolSourceMap enclosingSymbols;
1747   auto range{dirClauseTriple.equal_range(GetContext().directive)};
1748   for (auto dirIter{range.first}; dirIter != range.second; ++dirIter) {
1749     auto enclosingDir{dirIter->second.first};
1750     auto enclosingClauseSet{dirIter->second.second};
1751     if (auto *enclosingContext{GetEnclosingContextWithDir(enclosingDir)}) {
1752       for (auto it{enclosingContext->clauseInfo.begin()};
1753            it != enclosingContext->clauseInfo.end(); ++it) {
1754         if (enclosingClauseSet.test(it->first)) {
1755           if (const auto *ompObjectList{GetOmpObjectList(*it->second)}) {
1756             GetSymbolsInObjectList(*ompObjectList, enclosingSymbols);
1757           }
1758         }
1759       }
1760 
1761       // Check if the symbols in current context are private in outer context
1762       for (auto iter{currSymbols.begin()}; iter != currSymbols.end(); ++iter) {
1763         const auto *symbol{iter->first};
1764         const auto source{iter->second};
1765         if (enclosingSymbols.find(symbol) != enclosingSymbols.end()) {
1766           context_.Say(source,
1767               "%s variable '%s' is PRIVATE in outer context"_err_en_US,
1768               parser::ToUpperCaseLetters(getClauseName(currClause).str()),
1769               symbol->name());
1770         }
1771       }
1772     }
1773   }
1774 }
1775 
1776 void OmpStructureChecker::CheckWorkshareBlockStmts(
1777     const parser::Block &block, parser::CharBlock source) {
1778   OmpWorkshareBlockChecker ompWorkshareBlockChecker{context_, source};
1779 
1780   for (auto it{block.begin()}; it != block.end(); ++it) {
1781     if (parser::Unwrap<parser::AssignmentStmt>(*it) ||
1782         parser::Unwrap<parser::ForallStmt>(*it) ||
1783         parser::Unwrap<parser::ForallConstruct>(*it) ||
1784         parser::Unwrap<parser::WhereStmt>(*it) ||
1785         parser::Unwrap<parser::WhereConstruct>(*it)) {
1786       parser::Walk(*it, ompWorkshareBlockChecker);
1787     } else if (const auto *ompConstruct{
1788                    parser::Unwrap<parser::OpenMPConstruct>(*it)}) {
1789       if (const auto *ompAtomicConstruct{
1790               std::get_if<parser::OpenMPAtomicConstruct>(&ompConstruct->u)}) {
1791         // Check if assignment statements in the enclosing OpenMP Atomic
1792         // construct are allowed in the Workshare construct
1793         parser::Walk(*ompAtomicConstruct, ompWorkshareBlockChecker);
1794       } else if (const auto *ompCriticalConstruct{
1795                      std::get_if<parser::OpenMPCriticalConstruct>(
1796                          &ompConstruct->u)}) {
1797         // All the restrictions on the Workshare construct apply to the
1798         // statements in the enclosing critical constructs
1799         const auto &criticalBlock{
1800             std::get<parser::Block>(ompCriticalConstruct->t)};
1801         CheckWorkshareBlockStmts(criticalBlock, source);
1802       } else {
1803         // Check if OpenMP constructs enclosed in the Workshare construct are
1804         // 'Parallel' constructs
1805         auto currentDir{llvm::omp::Directive::OMPD_unknown};
1806         const OmpDirectiveSet parallelDirSet{
1807             llvm::omp::Directive::OMPD_parallel,
1808             llvm::omp::Directive::OMPD_parallel_do,
1809             llvm::omp::Directive::OMPD_parallel_sections,
1810             llvm::omp::Directive::OMPD_parallel_workshare,
1811             llvm::omp::Directive::OMPD_parallel_do_simd};
1812 
1813         if (const auto *ompBlockConstruct{
1814                 std::get_if<parser::OpenMPBlockConstruct>(&ompConstruct->u)}) {
1815           const auto &beginBlockDir{
1816               std::get<parser::OmpBeginBlockDirective>(ompBlockConstruct->t)};
1817           const auto &beginDir{
1818               std::get<parser::OmpBlockDirective>(beginBlockDir.t)};
1819           currentDir = beginDir.v;
1820         } else if (const auto *ompLoopConstruct{
1821                        std::get_if<parser::OpenMPLoopConstruct>(
1822                            &ompConstruct->u)}) {
1823           const auto &beginLoopDir{
1824               std::get<parser::OmpBeginLoopDirective>(ompLoopConstruct->t)};
1825           const auto &beginDir{
1826               std::get<parser::OmpLoopDirective>(beginLoopDir.t)};
1827           currentDir = beginDir.v;
1828         } else if (const auto *ompSectionsConstruct{
1829                        std::get_if<parser::OpenMPSectionsConstruct>(
1830                            &ompConstruct->u)}) {
1831           const auto &beginSectionsDir{
1832               std::get<parser::OmpBeginSectionsDirective>(
1833                   ompSectionsConstruct->t)};
1834           const auto &beginDir{
1835               std::get<parser::OmpSectionsDirective>(beginSectionsDir.t)};
1836           currentDir = beginDir.v;
1837         }
1838 
1839         if (!parallelDirSet.test(currentDir)) {
1840           context_.Say(source,
1841               "OpenMP constructs enclosed in WORKSHARE construct may consist "
1842               "of ATOMIC, CRITICAL or PARALLEL constructs only"_err_en_US);
1843         }
1844       }
1845     } else {
1846       context_.Say(source,
1847           "The structured block in a WORKSHARE construct may consist of only "
1848           "SCALAR or ARRAY assignments, FORALL or WHERE statements, "
1849           "FORALL, WHERE, ATOMIC, CRITICAL or PARALLEL constructs"_err_en_US);
1850     }
1851   }
1852 }
1853 
1854 const parser::OmpObjectList *OmpStructureChecker::GetOmpObjectList(
1855     const parser::OmpClause &clause) {
1856 
1857   // Clauses with OmpObjectList as its data member
1858   using MemberObjectListClauses = std::tuple<parser::OmpClause::Copyprivate,
1859       parser::OmpClause::Copyin, parser::OmpClause::Firstprivate,
1860       parser::OmpClause::From, parser::OmpClause::Lastprivate,
1861       parser::OmpClause::Link, parser::OmpClause::Private,
1862       parser::OmpClause::Shared, parser::OmpClause::To>;
1863 
1864   // Clauses with OmpObjectList in the tuple
1865   using TupleObjectListClauses = std::tuple<parser::OmpClause::Allocate,
1866       parser::OmpClause::Map, parser::OmpClause::Reduction>;
1867 
1868   // TODO:: Generate the tuples using TableGen.
1869   // Handle other constructs with OmpObjectList such as OpenMPThreadprivate.
1870   return std::visit(
1871       common::visitors{
1872           [&](const auto &x) -> const parser::OmpObjectList * {
1873             using Ty = std::decay_t<decltype(x)>;
1874             if constexpr (common::HasMember<Ty, MemberObjectListClauses>) {
1875               return &x.v;
1876             } else if constexpr (common::HasMember<Ty,
1877                                      TupleObjectListClauses>) {
1878               return &(std::get<parser::OmpObjectList>(x.v.t));
1879             } else {
1880               return nullptr;
1881             }
1882           },
1883       },
1884       clause.u);
1885 }
1886 
1887 } // namespace Fortran::semantics
1888