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 §ionBlocks{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 &declScope{ 926 GetProgramUnitContaining(name->symbol->GetUltimate())}; 927 const auto *sym = 928 declScope.parent().FindSymbol(name->symbol->name()); 929 if (sym && 930 (sym->has<MainProgramDetails>() || 931 sym->has<ModuleDetails>())) { 932 context_.Say(name->source, 933 "The module name or main program name cannot be in a %s " 934 "directive"_err_en_US, 935 ContextDirectiveAsFortran()); 936 } else if (name->symbol->GetUltimate().IsSubprogram()) { 937 if (GetContext().directive == 938 llvm::omp::Directive::OMPD_threadprivate) 939 context_.Say(name->source, 940 "The procedure name cannot be in a %s " 941 "directive"_err_en_US, 942 ContextDirectiveAsFortran()); 943 // TODO: Check for procedure name in declare target directive. 944 } else if (name->symbol->attrs().test(Attr::PARAMETER)) { 945 if (GetContext().directive == 946 llvm::omp::Directive::OMPD_threadprivate) 947 context_.Say(name->source, 948 "The entity with PARAMETER attribute cannot be in a %s " 949 "directive"_err_en_US, 950 ContextDirectiveAsFortran()); 951 else if (GetContext().directive == 952 llvm::omp::Directive::OMPD_declare_target) 953 context_.Say(name->source, 954 "The entity with PARAMETER attribute is used in a %s " 955 "directive"_warn_en_US, 956 ContextDirectiveAsFortran()); 957 } else if (FindCommonBlockContaining(*name->symbol)) { 958 context_.Say(name->source, 959 "A variable in a %s directive cannot be an element of a " 960 "common block"_err_en_US, 961 ContextDirectiveAsFortran()); 962 } else if (!IsSave(*name->symbol) && 963 declScope.kind() != Scope::Kind::MainProgram && 964 declScope.kind() != Scope::Kind::Module) { 965 context_.Say(name->source, 966 "A variable that appears in a %s directive must be " 967 "declared in the scope of a module or have the SAVE " 968 "attribute, either explicitly or implicitly"_err_en_US, 969 ContextDirectiveAsFortran()); 970 } else if (FindEquivalenceSet(*name->symbol)) { 971 context_.Say(name->source, 972 "A variable in a %s directive cannot appear in an " 973 "EQUIVALENCE statement"_err_en_US, 974 ContextDirectiveAsFortran()); 975 } else if (name->symbol->test(Symbol::Flag::OmpThreadprivate) && 976 GetContext().directive == 977 llvm::omp::Directive::OMPD_declare_target) { 978 context_.Say(name->source, 979 "A THREADPRIVATE variable cannot appear in a %s " 980 "directive"_err_en_US, 981 ContextDirectiveAsFortran()); 982 } 983 } 984 }, 985 [&](const parser::Name &) {}, // common block 986 }, 987 ompObject.u); 988 } 989 } 990 991 void OmpStructureChecker::Enter(const parser::OpenMPThreadprivate &c) { 992 const auto &dir{std::get<parser::Verbatim>(c.t)}; 993 PushContextAndClauseSets( 994 dir.source, llvm::omp::Directive::OMPD_threadprivate); 995 } 996 997 void OmpStructureChecker::Leave(const parser::OpenMPThreadprivate &c) { 998 const auto &dir{std::get<parser::Verbatim>(c.t)}; 999 const auto &objectList{std::get<parser::OmpObjectList>(c.t)}; 1000 CheckIsVarPartOfAnotherVar(dir.source, objectList); 1001 CheckThreadprivateOrDeclareTargetVar(objectList); 1002 dirContext_.pop_back(); 1003 } 1004 1005 void OmpStructureChecker::Enter(const parser::OpenMPDeclareSimdConstruct &x) { 1006 const auto &dir{std::get<parser::Verbatim>(x.t)}; 1007 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_declare_simd); 1008 } 1009 1010 void OmpStructureChecker::Leave(const parser::OpenMPDeclareSimdConstruct &) { 1011 dirContext_.pop_back(); 1012 } 1013 1014 void OmpStructureChecker::Enter(const parser::OpenMPDeclarativeAllocate &x) { 1015 isPredefinedAllocator = true; 1016 const auto &dir{std::get<parser::Verbatim>(x.t)}; 1017 const auto &objectList{std::get<parser::OmpObjectList>(x.t)}; 1018 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_allocate); 1019 CheckIsVarPartOfAnotherVar(dir.source, objectList); 1020 } 1021 1022 void OmpStructureChecker::Leave(const parser::OpenMPDeclarativeAllocate &x) { 1023 const auto &dir{std::get<parser::Verbatim>(x.t)}; 1024 const auto &objectList{std::get<parser::OmpObjectList>(x.t)}; 1025 CheckPredefinedAllocatorRestriction(dir.source, objectList); 1026 dirContext_.pop_back(); 1027 } 1028 1029 void OmpStructureChecker::Enter(const parser::OmpClause::Allocator &x) { 1030 CheckAllowed(llvm::omp::Clause::OMPC_allocator); 1031 // Note: Predefined allocators are stored in ScalarExpr as numbers 1032 // whereas custom allocators are stored as strings, so if the ScalarExpr 1033 // actually has an int value, then it must be a predefined allocator 1034 isPredefinedAllocator = GetIntValue(x.v).has_value(); 1035 RequiresPositiveParameter(llvm::omp::Clause::OMPC_allocator, x.v); 1036 } 1037 1038 void OmpStructureChecker::Enter(const parser::OpenMPDeclareTargetConstruct &x) { 1039 const auto &dir{std::get<parser::Verbatim>(x.t)}; 1040 PushContext(dir.source, llvm::omp::Directive::OMPD_declare_target); 1041 const auto &spec{std::get<parser::OmpDeclareTargetSpecifier>(x.t)}; 1042 if (std::holds_alternative<parser::OmpDeclareTargetWithClause>(spec.u)) { 1043 SetClauseSets(llvm::omp::Directive::OMPD_declare_target); 1044 } 1045 } 1046 1047 void OmpStructureChecker::Leave(const parser::OpenMPDeclareTargetConstruct &x) { 1048 const auto &dir{std::get<parser::Verbatim>(x.t)}; 1049 const auto &spec{std::get<parser::OmpDeclareTargetSpecifier>(x.t)}; 1050 if (const auto *objectList{parser::Unwrap<parser::OmpObjectList>(spec.u)}) { 1051 CheckIsVarPartOfAnotherVar(dir.source, *objectList); 1052 CheckThreadprivateOrDeclareTargetVar(*objectList); 1053 } else if (const auto *clauseList{ 1054 parser::Unwrap<parser::OmpClauseList>(spec.u)}) { 1055 for (const auto &clause : clauseList->v) { 1056 if (const auto *toClause{std::get_if<parser::OmpClause::To>(&clause.u)}) { 1057 CheckIsVarPartOfAnotherVar(dir.source, toClause->v); 1058 CheckThreadprivateOrDeclareTargetVar(toClause->v); 1059 } else if (const auto *linkClause{ 1060 std::get_if<parser::OmpClause::Link>(&clause.u)}) { 1061 CheckIsVarPartOfAnotherVar(dir.source, linkClause->v); 1062 CheckThreadprivateOrDeclareTargetVar(linkClause->v); 1063 } 1064 } 1065 } 1066 dirContext_.pop_back(); 1067 } 1068 1069 void OmpStructureChecker::Enter(const parser::OpenMPExecutableAllocate &x) { 1070 isPredefinedAllocator = true; 1071 const auto &dir{std::get<parser::Verbatim>(x.t)}; 1072 const auto &objectList{std::get<std::optional<parser::OmpObjectList>>(x.t)}; 1073 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_allocate); 1074 if (objectList) { 1075 CheckIsVarPartOfAnotherVar(dir.source, *objectList); 1076 } 1077 } 1078 1079 void OmpStructureChecker::Leave(const parser::OpenMPExecutableAllocate &x) { 1080 const auto &dir{std::get<parser::Verbatim>(x.t)}; 1081 const auto &objectList{std::get<std::optional<parser::OmpObjectList>>(x.t)}; 1082 if (objectList) 1083 CheckPredefinedAllocatorRestriction(dir.source, *objectList); 1084 dirContext_.pop_back(); 1085 } 1086 1087 void OmpStructureChecker::CheckBarrierNesting( 1088 const parser::OpenMPSimpleStandaloneConstruct &x) { 1089 // A barrier region may not be `closely nested` inside a worksharing, loop, 1090 // task, taskloop, critical, ordered, atomic, or master region. 1091 // TODO: Expand the check to include `LOOP` construct as well when it is 1092 // supported. 1093 if (GetContext().directive == llvm::omp::Directive::OMPD_barrier) { 1094 if (IsCloselyNestedRegion(llvm::omp::nestedBarrierErrSet)) { 1095 context_.Say(parser::FindSourceLocation(x), 1096 "`BARRIER` region may not be closely nested inside of `WORKSHARING`, " 1097 "`LOOP`, `TASK`, `TASKLOOP`," 1098 "`CRITICAL`, `ORDERED`, `ATOMIC` or `MASTER` region."_err_en_US); 1099 } 1100 } 1101 } 1102 1103 void OmpStructureChecker::ChecksOnOrderedAsStandalone() { 1104 if (FindClause(llvm::omp::Clause::OMPC_threads) || 1105 FindClause(llvm::omp::Clause::OMPC_simd)) { 1106 context_.Say(GetContext().clauseSource, 1107 "THREADS, SIMD clauses are not allowed when ORDERED construct is a " 1108 "standalone construct with no ORDERED region"_err_en_US); 1109 } 1110 1111 bool isSinkPresent{false}; 1112 int dependSourceCount{0}; 1113 auto clauseAll = FindClauses(llvm::omp::Clause::OMPC_depend); 1114 for (auto itr = clauseAll.first; itr != clauseAll.second; ++itr) { 1115 const auto &dependClause{ 1116 std::get<parser::OmpClause::Depend>(itr->second->u)}; 1117 if (std::get_if<parser::OmpDependClause::Source>(&dependClause.v.u)) { 1118 dependSourceCount++; 1119 if (isSinkPresent) { 1120 context_.Say(itr->second->source, 1121 "DEPEND(SOURCE) is not allowed when DEPEND(SINK: vec) is present " 1122 "on ORDERED directive"_err_en_US); 1123 } 1124 if (dependSourceCount > 1) { 1125 context_.Say(itr->second->source, 1126 "At most one DEPEND(SOURCE) clause can appear on the ORDERED " 1127 "directive"_err_en_US); 1128 } 1129 } else if (std::get_if<parser::OmpDependClause::Sink>(&dependClause.v.u)) { 1130 isSinkPresent = true; 1131 if (dependSourceCount > 0) { 1132 context_.Say(itr->second->source, 1133 "DEPEND(SINK: vec) is not allowed when DEPEND(SOURCE) is present " 1134 "on ORDERED directive"_err_en_US); 1135 } 1136 } else { 1137 context_.Say(itr->second->source, 1138 "Only DEPEND(SOURCE) or DEPEND(SINK: vec) are allowed when ORDERED " 1139 "construct is a standalone construct with no ORDERED " 1140 "region"_err_en_US); 1141 } 1142 } 1143 1144 OmpDirectiveSet allowedDoSet{llvm::omp::Directive::OMPD_do, 1145 llvm::omp::Directive::OMPD_parallel_do, 1146 llvm::omp::Directive::OMPD_target_parallel_do}; 1147 bool isNestedInDoOrderedWithPara{false}; 1148 if (CurrentDirectiveIsNested() && 1149 allowedDoSet.test(GetContextParent().directive)) { 1150 if (const auto *clause{ 1151 FindClause(GetContextParent(), llvm::omp::Clause::OMPC_ordered)}) { 1152 const auto &orderedClause{ 1153 std::get<parser::OmpClause::Ordered>(clause->u)}; 1154 const auto orderedValue{GetIntValue(orderedClause.v)}; 1155 if (orderedValue > 0) { 1156 isNestedInDoOrderedWithPara = true; 1157 CheckOrderedDependClause(orderedValue); 1158 } 1159 } 1160 } 1161 1162 if (FindClause(llvm::omp::Clause::OMPC_depend) && 1163 !isNestedInDoOrderedWithPara) { 1164 context_.Say(GetContext().clauseSource, 1165 "An ORDERED construct with the DEPEND clause must be closely nested " 1166 "in a worksharing-loop (or parallel worksharing-loop) construct with " 1167 "ORDERED clause with a parameter"_err_en_US); 1168 } 1169 } 1170 1171 void OmpStructureChecker::CheckOrderedDependClause( 1172 std::optional<std::int64_t> orderedValue) { 1173 auto clauseAll{FindClauses(llvm::omp::Clause::OMPC_depend)}; 1174 for (auto itr = clauseAll.first; itr != clauseAll.second; ++itr) { 1175 const auto &dependClause{ 1176 std::get<parser::OmpClause::Depend>(itr->second->u)}; 1177 if (const auto *sinkVectors{ 1178 std::get_if<parser::OmpDependClause::Sink>(&dependClause.v.u)}) { 1179 std::int64_t numVar = sinkVectors->v.size(); 1180 if (orderedValue != numVar) { 1181 context_.Say(itr->second->source, 1182 "The number of variables in DEPEND(SINK: vec) clause does not " 1183 "match the parameter specified in ORDERED clause"_err_en_US); 1184 } 1185 } 1186 } 1187 } 1188 1189 void OmpStructureChecker::Enter( 1190 const parser::OpenMPSimpleStandaloneConstruct &x) { 1191 const auto &dir{std::get<parser::OmpSimpleStandaloneDirective>(x.t)}; 1192 PushContextAndClauseSets(dir.source, dir.v); 1193 CheckBarrierNesting(x); 1194 } 1195 1196 void OmpStructureChecker::Leave( 1197 const parser::OpenMPSimpleStandaloneConstruct &) { 1198 switch (GetContext().directive) { 1199 case llvm::omp::Directive::OMPD_ordered: 1200 // [5.1] 2.19.9 Ordered Construct Restriction 1201 ChecksOnOrderedAsStandalone(); 1202 break; 1203 default: 1204 break; 1205 } 1206 dirContext_.pop_back(); 1207 } 1208 1209 void OmpStructureChecker::Enter(const parser::OpenMPFlushConstruct &x) { 1210 const auto &dir{std::get<parser::Verbatim>(x.t)}; 1211 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_flush); 1212 } 1213 1214 void OmpStructureChecker::Leave(const parser::OpenMPFlushConstruct &x) { 1215 if (FindClause(llvm::omp::Clause::OMPC_acquire) || 1216 FindClause(llvm::omp::Clause::OMPC_release) || 1217 FindClause(llvm::omp::Clause::OMPC_acq_rel)) { 1218 if (const auto &flushList{ 1219 std::get<std::optional<parser::OmpObjectList>>(x.t)}) { 1220 context_.Say(parser::FindSourceLocation(flushList), 1221 "If memory-order-clause is RELEASE, ACQUIRE, or ACQ_REL, list items " 1222 "must not be specified on the FLUSH directive"_err_en_US); 1223 } 1224 } 1225 dirContext_.pop_back(); 1226 } 1227 1228 void OmpStructureChecker::Enter(const parser::OpenMPCancelConstruct &x) { 1229 const auto &dir{std::get<parser::Verbatim>(x.t)}; 1230 const auto &type{std::get<parser::OmpCancelType>(x.t)}; 1231 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_cancel); 1232 CheckCancellationNest(dir.source, type.v); 1233 } 1234 1235 void OmpStructureChecker::Leave(const parser::OpenMPCancelConstruct &) { 1236 dirContext_.pop_back(); 1237 } 1238 1239 void OmpStructureChecker::Enter(const parser::OpenMPCriticalConstruct &x) { 1240 const auto &dir{std::get<parser::OmpCriticalDirective>(x.t)}; 1241 const auto &endDir{std::get<parser::OmpEndCriticalDirective>(x.t)}; 1242 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_critical); 1243 const auto &block{std::get<parser::Block>(x.t)}; 1244 CheckNoBranching(block, llvm::omp::Directive::OMPD_critical, dir.source); 1245 const auto &dirName{std::get<std::optional<parser::Name>>(dir.t)}; 1246 const auto &endDirName{std::get<std::optional<parser::Name>>(endDir.t)}; 1247 const auto &ompClause{std::get<parser::OmpClauseList>(dir.t)}; 1248 if (dirName && endDirName && 1249 dirName->ToString().compare(endDirName->ToString())) { 1250 context_ 1251 .Say(endDirName->source, 1252 parser::MessageFormattedText{ 1253 "CRITICAL directive names do not match"_err_en_US}) 1254 .Attach(dirName->source, "should be "_en_US); 1255 } else if (dirName && !endDirName) { 1256 context_ 1257 .Say(dirName->source, 1258 parser::MessageFormattedText{ 1259 "CRITICAL directive names do not match"_err_en_US}) 1260 .Attach(dirName->source, "should be NULL"_en_US); 1261 } else if (!dirName && endDirName) { 1262 context_ 1263 .Say(endDirName->source, 1264 parser::MessageFormattedText{ 1265 "CRITICAL directive names do not match"_err_en_US}) 1266 .Attach(endDirName->source, "should be NULL"_en_US); 1267 } 1268 if (!dirName && !ompClause.source.empty() && 1269 ompClause.source.NULTerminatedToString() != "hint(omp_sync_hint_none)") { 1270 context_.Say(dir.source, 1271 parser::MessageFormattedText{ 1272 "Hint clause other than omp_sync_hint_none cannot be specified for an unnamed CRITICAL directive"_err_en_US}); 1273 } 1274 } 1275 1276 void OmpStructureChecker::Leave(const parser::OpenMPCriticalConstruct &) { 1277 dirContext_.pop_back(); 1278 } 1279 1280 void OmpStructureChecker::Enter( 1281 const parser::OpenMPCancellationPointConstruct &x) { 1282 const auto &dir{std::get<parser::Verbatim>(x.t)}; 1283 const auto &type{std::get<parser::OmpCancelType>(x.t)}; 1284 PushContextAndClauseSets( 1285 dir.source, llvm::omp::Directive::OMPD_cancellation_point); 1286 CheckCancellationNest(dir.source, type.v); 1287 } 1288 1289 void OmpStructureChecker::Leave( 1290 const parser::OpenMPCancellationPointConstruct &) { 1291 dirContext_.pop_back(); 1292 } 1293 1294 void OmpStructureChecker::CheckCancellationNest( 1295 const parser::CharBlock &source, const parser::OmpCancelType::Type &type) { 1296 if (CurrentDirectiveIsNested()) { 1297 // If construct-type-clause is taskgroup, the cancellation construct must be 1298 // closely nested inside a task or a taskloop construct and the cancellation 1299 // region must be closely nested inside a taskgroup region. If 1300 // construct-type-clause is sections, the cancellation construct must be 1301 // closely nested inside a sections or section construct. Otherwise, the 1302 // cancellation construct must be closely nested inside an OpenMP construct 1303 // that matches the type specified in construct-type-clause of the 1304 // cancellation construct. 1305 1306 OmpDirectiveSet allowedTaskgroupSet{ 1307 llvm::omp::Directive::OMPD_task, llvm::omp::Directive::OMPD_taskloop}; 1308 OmpDirectiveSet allowedSectionsSet{llvm::omp::Directive::OMPD_sections, 1309 llvm::omp::Directive::OMPD_parallel_sections}; 1310 OmpDirectiveSet allowedDoSet{llvm::omp::Directive::OMPD_do, 1311 llvm::omp::Directive::OMPD_distribute_parallel_do, 1312 llvm::omp::Directive::OMPD_parallel_do, 1313 llvm::omp::Directive::OMPD_target_parallel_do, 1314 llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do, 1315 llvm::omp::Directive::OMPD_teams_distribute_parallel_do}; 1316 OmpDirectiveSet allowedParallelSet{llvm::omp::Directive::OMPD_parallel, 1317 llvm::omp::Directive::OMPD_target_parallel}; 1318 1319 bool eligibleCancellation{false}; 1320 switch (type) { 1321 case parser::OmpCancelType::Type::Taskgroup: 1322 if (allowedTaskgroupSet.test(GetContextParent().directive)) { 1323 eligibleCancellation = true; 1324 if (dirContext_.size() >= 3) { 1325 // Check if the cancellation region is closely nested inside a 1326 // taskgroup region when there are more than two levels of directives 1327 // in the directive context stack. 1328 if (GetContextParent().directive == llvm::omp::Directive::OMPD_task || 1329 FindClauseParent(llvm::omp::Clause::OMPC_nogroup)) { 1330 for (int i = dirContext_.size() - 3; i >= 0; i--) { 1331 if (dirContext_[i].directive == 1332 llvm::omp::Directive::OMPD_taskgroup) { 1333 break; 1334 } 1335 if (allowedParallelSet.test(dirContext_[i].directive)) { 1336 eligibleCancellation = false; 1337 break; 1338 } 1339 } 1340 } 1341 } 1342 } 1343 if (!eligibleCancellation) { 1344 context_.Say(source, 1345 "With %s clause, %s construct must be closely nested inside TASK " 1346 "or TASKLOOP construct and %s region must be closely nested inside " 1347 "TASKGROUP region"_err_en_US, 1348 parser::ToUpperCaseLetters( 1349 parser::OmpCancelType::EnumToString(type)), 1350 ContextDirectiveAsFortran(), ContextDirectiveAsFortran()); 1351 } 1352 return; 1353 case parser::OmpCancelType::Type::Sections: 1354 if (allowedSectionsSet.test(GetContextParent().directive)) { 1355 eligibleCancellation = true; 1356 } 1357 break; 1358 case Fortran::parser::OmpCancelType::Type::Do: 1359 if (allowedDoSet.test(GetContextParent().directive)) { 1360 eligibleCancellation = true; 1361 } 1362 break; 1363 case parser::OmpCancelType::Type::Parallel: 1364 if (allowedParallelSet.test(GetContextParent().directive)) { 1365 eligibleCancellation = true; 1366 } 1367 break; 1368 } 1369 if (!eligibleCancellation) { 1370 context_.Say(source, 1371 "With %s clause, %s construct cannot be closely nested inside %s " 1372 "construct"_err_en_US, 1373 parser::ToUpperCaseLetters(parser::OmpCancelType::EnumToString(type)), 1374 ContextDirectiveAsFortran(), 1375 parser::ToUpperCaseLetters( 1376 getDirectiveName(GetContextParent().directive).str())); 1377 } 1378 } else { 1379 // The cancellation directive cannot be orphaned. 1380 switch (type) { 1381 case parser::OmpCancelType::Type::Taskgroup: 1382 context_.Say(source, 1383 "%s %s directive is not closely nested inside " 1384 "TASK or TASKLOOP"_err_en_US, 1385 ContextDirectiveAsFortran(), 1386 parser::ToUpperCaseLetters( 1387 parser::OmpCancelType::EnumToString(type))); 1388 break; 1389 case parser::OmpCancelType::Type::Sections: 1390 context_.Say(source, 1391 "%s %s directive is not closely nested inside " 1392 "SECTION or SECTIONS"_err_en_US, 1393 ContextDirectiveAsFortran(), 1394 parser::ToUpperCaseLetters( 1395 parser::OmpCancelType::EnumToString(type))); 1396 break; 1397 case Fortran::parser::OmpCancelType::Type::Do: 1398 context_.Say(source, 1399 "%s %s directive is not closely nested inside " 1400 "the construct that matches the DO clause type"_err_en_US, 1401 ContextDirectiveAsFortran(), 1402 parser::ToUpperCaseLetters( 1403 parser::OmpCancelType::EnumToString(type))); 1404 break; 1405 case parser::OmpCancelType::Type::Parallel: 1406 context_.Say(source, 1407 "%s %s directive is not closely nested inside " 1408 "the construct that matches the PARALLEL clause type"_err_en_US, 1409 ContextDirectiveAsFortran(), 1410 parser::ToUpperCaseLetters( 1411 parser::OmpCancelType::EnumToString(type))); 1412 break; 1413 } 1414 } 1415 } 1416 1417 void OmpStructureChecker::Enter(const parser::OmpEndBlockDirective &x) { 1418 const auto &dir{std::get<parser::OmpBlockDirective>(x.t)}; 1419 ResetPartialContext(dir.source); 1420 switch (dir.v) { 1421 // 2.7.3 end-single-clause -> copyprivate-clause | 1422 // nowait-clause 1423 case llvm::omp::Directive::OMPD_single: 1424 PushContextAndClauseSets(dir.source, llvm::omp::Directive::OMPD_end_single); 1425 break; 1426 // 2.7.4 end-workshare -> END WORKSHARE [nowait-clause] 1427 case llvm::omp::Directive::OMPD_workshare: 1428 PushContextAndClauseSets( 1429 dir.source, llvm::omp::Directive::OMPD_end_workshare); 1430 break; 1431 default: 1432 // no clauses are allowed 1433 break; 1434 } 1435 } 1436 1437 // TODO: Verify the popping of dirContext requirement after nowait 1438 // implementation, as there is an implicit barrier at the end of the worksharing 1439 // constructs unless a nowait clause is specified. Only OMPD_end_single and 1440 // end_workshareare popped as they are pushed while entering the 1441 // EndBlockDirective. 1442 void OmpStructureChecker::Leave(const parser::OmpEndBlockDirective &x) { 1443 if ((GetContext().directive == llvm::omp::Directive::OMPD_end_single) || 1444 (GetContext().directive == llvm::omp::Directive::OMPD_end_workshare)) { 1445 dirContext_.pop_back(); 1446 } 1447 } 1448 1449 template <typename T, typename D> 1450 bool OmpStructureChecker::IsOperatorValid(const T &node, const D &variable) { 1451 using AllowedBinaryOperators = 1452 std::variant<parser::Expr::Add, parser::Expr::Multiply, 1453 parser::Expr::Subtract, parser::Expr::Divide, parser::Expr::AND, 1454 parser::Expr::OR, parser::Expr::EQV, parser::Expr::NEQV>; 1455 using BinaryOperators = std::variant<parser::Expr::Add, 1456 parser::Expr::Multiply, parser::Expr::Subtract, parser::Expr::Divide, 1457 parser::Expr::AND, parser::Expr::OR, parser::Expr::EQV, 1458 parser::Expr::NEQV, parser::Expr::Power, parser::Expr::Concat, 1459 parser::Expr::LT, parser::Expr::LE, parser::Expr::EQ, parser::Expr::NE, 1460 parser::Expr::GE, parser::Expr::GT>; 1461 1462 if constexpr (common::HasMember<T, BinaryOperators>) { 1463 const auto &variableName{variable.GetSource().ToString()}; 1464 const auto &exprLeft{std::get<0>(node.t)}; 1465 const auto &exprRight{std::get<1>(node.t)}; 1466 if ((exprLeft.value().source.ToString() != variableName) && 1467 (exprRight.value().source.ToString() != variableName)) { 1468 context_.Say(variable.GetSource(), 1469 "Atomic update variable '%s' not found in the RHS of the " 1470 "assignment statement in an ATOMIC (UPDATE) construct"_err_en_US, 1471 variableName); 1472 } 1473 return common::HasMember<T, AllowedBinaryOperators>; 1474 } 1475 return true; 1476 } 1477 1478 void OmpStructureChecker::CheckAtomicUpdateAssignmentStmt( 1479 const parser::AssignmentStmt &assignment) { 1480 const auto &expr{std::get<parser::Expr>(assignment.t)}; 1481 const auto &var{std::get<parser::Variable>(assignment.t)}; 1482 common::visit( 1483 common::visitors{ 1484 [&](const common::Indirection<parser::FunctionReference> &x) { 1485 const auto &procedureDesignator{ 1486 std::get<parser::ProcedureDesignator>(x.value().v.t)}; 1487 const parser::Name *name{ 1488 std::get_if<parser::Name>(&procedureDesignator.u)}; 1489 if (name && 1490 !(name->source == "max" || name->source == "min" || 1491 name->source == "iand" || name->source == "ior" || 1492 name->source == "ieor")) { 1493 context_.Say(expr.source, 1494 "Invalid intrinsic procedure name in " 1495 "OpenMP ATOMIC (UPDATE) statement"_err_en_US); 1496 } else if (name) { 1497 bool foundMatch{false}; 1498 if (auto varDesignatorIndirection = 1499 std::get_if<Fortran::common::Indirection< 1500 Fortran::parser::Designator>>(&var.u)) { 1501 const auto &varDesignator = varDesignatorIndirection->value(); 1502 if (const auto *dataRef = std::get_if<Fortran::parser::DataRef>( 1503 &varDesignator.u)) { 1504 if (const auto *name = 1505 std::get_if<Fortran::parser::Name>(&dataRef->u)) { 1506 const auto &varSymbol = *name->symbol; 1507 if (const auto *e{GetExpr(context_, expr)}) { 1508 for (const Symbol &symbol : 1509 evaluate::CollectSymbols(*e)) { 1510 if (symbol == varSymbol) { 1511 foundMatch = true; 1512 break; 1513 } 1514 } 1515 } 1516 } 1517 } 1518 } 1519 if (!foundMatch) { 1520 context_.Say(expr.source, 1521 "Atomic update variable '%s' not found in the " 1522 "argument list of intrinsic procedure"_err_en_US, 1523 var.GetSource().ToString()); 1524 } 1525 } 1526 }, 1527 [&](const auto &x) { 1528 if (!IsOperatorValid(x, var)) { 1529 context_.Say(expr.source, 1530 "Invalid operator in OpenMP ATOMIC (UPDATE) statement"_err_en_US); 1531 } 1532 }, 1533 }, 1534 expr.u); 1535 } 1536 1537 void OmpStructureChecker::CheckAtomicMemoryOrderClause( 1538 const parser::OmpAtomicClauseList &clauseList) { 1539 int numMemoryOrderClause = 0; 1540 for (const auto &clause : clauseList.v) { 1541 if (std::get_if<Fortran::parser::OmpMemoryOrderClause>(&clause.u)) { 1542 numMemoryOrderClause++; 1543 if (numMemoryOrderClause > 1) { 1544 context_.Say(clause.source, 1545 "More than one memory order clause not allowed on OpenMP " 1546 "Atomic construct"_err_en_US); 1547 return; 1548 } 1549 } 1550 } 1551 } 1552 1553 void OmpStructureChecker::CheckAtomicMemoryOrderClause( 1554 const parser::OmpAtomicClauseList &leftHandClauseList, 1555 const parser::OmpAtomicClauseList &rightHandClauseList) { 1556 int numMemoryOrderClause = 0; 1557 for (const auto &clause : leftHandClauseList.v) { 1558 if (std::get_if<Fortran::parser::OmpMemoryOrderClause>(&clause.u)) { 1559 numMemoryOrderClause++; 1560 if (numMemoryOrderClause > 1) { 1561 context_.Say(clause.source, 1562 "More than one memory order clause not allowed on " 1563 "OpenMP Atomic construct"_err_en_US); 1564 return; 1565 } 1566 } 1567 } 1568 for (const auto &clause : rightHandClauseList.v) { 1569 if (std::get_if<Fortran::parser::OmpMemoryOrderClause>(&clause.u)) { 1570 numMemoryOrderClause++; 1571 if (numMemoryOrderClause > 1) { 1572 context_.Say(clause.source, 1573 "More than one memory order clause not " 1574 "allowed on OpenMP Atomic construct"_err_en_US); 1575 return; 1576 } 1577 } 1578 } 1579 } 1580 1581 void OmpStructureChecker::Enter(const parser::OpenMPAtomicConstruct &x) { 1582 common::visit( 1583 common::visitors{ 1584 [&](const parser::OmpAtomic &atomicConstruct) { 1585 const auto &dir{std::get<parser::Verbatim>(atomicConstruct.t)}; 1586 PushContextAndClauseSets( 1587 dir.source, llvm::omp::Directive::OMPD_atomic); 1588 CheckAtomicUpdateAssignmentStmt( 1589 std::get<parser::Statement<parser::AssignmentStmt>>( 1590 atomicConstruct.t) 1591 .statement); 1592 CheckAtomicMemoryOrderClause( 1593 std::get<parser::OmpAtomicClauseList>(atomicConstruct.t)); 1594 }, 1595 [&](const parser::OmpAtomicUpdate &atomicConstruct) { 1596 const auto &dir{std::get<parser::Verbatim>(atomicConstruct.t)}; 1597 PushContextAndClauseSets( 1598 dir.source, llvm::omp::Directive::OMPD_atomic); 1599 CheckAtomicUpdateAssignmentStmt( 1600 std::get<parser::Statement<parser::AssignmentStmt>>( 1601 atomicConstruct.t) 1602 .statement); 1603 CheckAtomicMemoryOrderClause( 1604 std::get<0>(atomicConstruct.t), std::get<2>(atomicConstruct.t)); 1605 }, 1606 [&](const auto &atomicConstruct) { 1607 const auto &dir{std::get<parser::Verbatim>(atomicConstruct.t)}; 1608 PushContextAndClauseSets( 1609 dir.source, llvm::omp::Directive::OMPD_atomic); 1610 CheckAtomicMemoryOrderClause( 1611 std::get<0>(atomicConstruct.t), std::get<2>(atomicConstruct.t)); 1612 }, 1613 }, 1614 x.u); 1615 } 1616 1617 void OmpStructureChecker::Leave(const parser::OpenMPAtomicConstruct &) { 1618 dirContext_.pop_back(); 1619 } 1620 1621 // Clauses 1622 // Mainly categorized as 1623 // 1. Checks on 'OmpClauseList' from 'parse-tree.h'. 1624 // 2. Checks on clauses which fall under 'struct OmpClause' from parse-tree.h. 1625 // 3. Checks on clauses which are not in 'struct OmpClause' from parse-tree.h. 1626 1627 void OmpStructureChecker::Leave(const parser::OmpClauseList &) { 1628 // 2.7.1 Loop Construct Restriction 1629 if (llvm::omp::doSet.test(GetContext().directive)) { 1630 if (auto *clause{FindClause(llvm::omp::Clause::OMPC_schedule)}) { 1631 // only one schedule clause is allowed 1632 const auto &schedClause{std::get<parser::OmpClause::Schedule>(clause->u)}; 1633 if (ScheduleModifierHasType(schedClause.v, 1634 parser::OmpScheduleModifierType::ModType::Nonmonotonic)) { 1635 if (FindClause(llvm::omp::Clause::OMPC_ordered)) { 1636 context_.Say(clause->source, 1637 "The NONMONOTONIC modifier cannot be specified " 1638 "if an ORDERED clause is specified"_err_en_US); 1639 } 1640 if (ScheduleModifierHasType(schedClause.v, 1641 parser::OmpScheduleModifierType::ModType::Monotonic)) { 1642 context_.Say(clause->source, 1643 "The MONOTONIC and NONMONOTONIC modifiers " 1644 "cannot be both specified"_err_en_US); 1645 } 1646 } 1647 } 1648 1649 if (auto *clause{FindClause(llvm::omp::Clause::OMPC_ordered)}) { 1650 // only one ordered clause is allowed 1651 const auto &orderedClause{ 1652 std::get<parser::OmpClause::Ordered>(clause->u)}; 1653 1654 if (orderedClause.v) { 1655 CheckNotAllowedIfClause( 1656 llvm::omp::Clause::OMPC_ordered, {llvm::omp::Clause::OMPC_linear}); 1657 1658 if (auto *clause2{FindClause(llvm::omp::Clause::OMPC_collapse)}) { 1659 const auto &collapseClause{ 1660 std::get<parser::OmpClause::Collapse>(clause2->u)}; 1661 // ordered and collapse both have parameters 1662 if (const auto orderedValue{GetIntValue(orderedClause.v)}) { 1663 if (const auto collapseValue{GetIntValue(collapseClause.v)}) { 1664 if (*orderedValue > 0 && *orderedValue < *collapseValue) { 1665 context_.Say(clause->source, 1666 "The parameter of the ORDERED clause must be " 1667 "greater than or equal to " 1668 "the parameter of the COLLAPSE clause"_err_en_US); 1669 } 1670 } 1671 } 1672 } 1673 } 1674 1675 // TODO: ordered region binding check (requires nesting implementation) 1676 } 1677 } // doSet 1678 1679 // 2.8.1 Simd Construct Restriction 1680 if (llvm::omp::simdSet.test(GetContext().directive)) { 1681 if (auto *clause{FindClause(llvm::omp::Clause::OMPC_simdlen)}) { 1682 if (auto *clause2{FindClause(llvm::omp::Clause::OMPC_safelen)}) { 1683 const auto &simdlenClause{ 1684 std::get<parser::OmpClause::Simdlen>(clause->u)}; 1685 const auto &safelenClause{ 1686 std::get<parser::OmpClause::Safelen>(clause2->u)}; 1687 // simdlen and safelen both have parameters 1688 if (const auto simdlenValue{GetIntValue(simdlenClause.v)}) { 1689 if (const auto safelenValue{GetIntValue(safelenClause.v)}) { 1690 if (*safelenValue > 0 && *simdlenValue > *safelenValue) { 1691 context_.Say(clause->source, 1692 "The parameter of the SIMDLEN clause must be less than or " 1693 "equal to the parameter of the SAFELEN clause"_err_en_US); 1694 } 1695 } 1696 } 1697 } 1698 } 1699 // Sema checks related to presence of multiple list items within the same 1700 // clause 1701 CheckMultListItems(); 1702 } // SIMD 1703 1704 // 2.7.3 Single Construct Restriction 1705 if (GetContext().directive == llvm::omp::Directive::OMPD_end_single) { 1706 CheckNotAllowedIfClause( 1707 llvm::omp::Clause::OMPC_copyprivate, {llvm::omp::Clause::OMPC_nowait}); 1708 } 1709 1710 auto testThreadprivateVarErr = [&](Symbol sym, parser::Name name, 1711 llvmOmpClause clauseTy) { 1712 if (sym.test(Symbol::Flag::OmpThreadprivate)) 1713 context_.Say(name.source, 1714 "A THREADPRIVATE variable cannot be in %s clause"_err_en_US, 1715 parser::ToUpperCaseLetters(getClauseName(clauseTy).str())); 1716 }; 1717 1718 // [5.1] 2.21.2 Threadprivate Directive Restriction 1719 OmpClauseSet threadprivateAllowedSet{llvm::omp::Clause::OMPC_copyin, 1720 llvm::omp::Clause::OMPC_copyprivate, llvm::omp::Clause::OMPC_schedule, 1721 llvm::omp::Clause::OMPC_num_threads, llvm::omp::Clause::OMPC_thread_limit, 1722 llvm::omp::Clause::OMPC_if}; 1723 for (auto it : GetContext().clauseInfo) { 1724 llvmOmpClause type = it.first; 1725 const auto *clause = it.second; 1726 if (!threadprivateAllowedSet.test(type)) { 1727 if (const auto *objList{GetOmpObjectList(*clause)}) { 1728 for (const auto &ompObject : objList->v) { 1729 common::visit( 1730 common::visitors{ 1731 [&](const parser::Designator &) { 1732 if (const auto *name{ 1733 parser::Unwrap<parser::Name>(ompObject)}) 1734 testThreadprivateVarErr( 1735 name->symbol->GetUltimate(), *name, type); 1736 }, 1737 [&](const parser::Name &name) { 1738 if (name.symbol) { 1739 for (const auto &mem : 1740 name.symbol->get<CommonBlockDetails>().objects()) { 1741 testThreadprivateVarErr(mem->GetUltimate(), name, type); 1742 break; 1743 } 1744 } 1745 }, 1746 }, 1747 ompObject.u); 1748 } 1749 } 1750 } 1751 } 1752 1753 CheckRequireAtLeastOneOf(); 1754 } 1755 1756 void OmpStructureChecker::Enter(const parser::OmpClause &x) { 1757 SetContextClause(x); 1758 } 1759 1760 // Following clauses do not have a separate node in parse-tree.h. 1761 CHECK_SIMPLE_CLAUSE(AcqRel, OMPC_acq_rel) 1762 CHECK_SIMPLE_CLAUSE(Acquire, OMPC_acquire) 1763 CHECK_SIMPLE_CLAUSE(AtomicDefaultMemOrder, OMPC_atomic_default_mem_order) 1764 CHECK_SIMPLE_CLAUSE(Affinity, OMPC_affinity) 1765 CHECK_SIMPLE_CLAUSE(Allocate, OMPC_allocate) 1766 CHECK_SIMPLE_CLAUSE(Capture, OMPC_capture) 1767 CHECK_SIMPLE_CLAUSE(Copyin, OMPC_copyin) 1768 CHECK_SIMPLE_CLAUSE(Default, OMPC_default) 1769 CHECK_SIMPLE_CLAUSE(Depobj, OMPC_depobj) 1770 CHECK_SIMPLE_CLAUSE(Destroy, OMPC_destroy) 1771 CHECK_SIMPLE_CLAUSE(Detach, OMPC_detach) 1772 CHECK_SIMPLE_CLAUSE(DeviceType, OMPC_device_type) 1773 CHECK_SIMPLE_CLAUSE(DistSchedule, OMPC_dist_schedule) 1774 CHECK_SIMPLE_CLAUSE(DynamicAllocators, OMPC_dynamic_allocators) 1775 CHECK_SIMPLE_CLAUSE(Exclusive, OMPC_exclusive) 1776 CHECK_SIMPLE_CLAUSE(Final, OMPC_final) 1777 CHECK_SIMPLE_CLAUSE(Flush, OMPC_flush) 1778 CHECK_SIMPLE_CLAUSE(From, OMPC_from) 1779 CHECK_SIMPLE_CLAUSE(Full, OMPC_full) 1780 CHECK_SIMPLE_CLAUSE(Hint, OMPC_hint) 1781 CHECK_SIMPLE_CLAUSE(InReduction, OMPC_in_reduction) 1782 CHECK_SIMPLE_CLAUSE(Inclusive, OMPC_inclusive) 1783 CHECK_SIMPLE_CLAUSE(Match, OMPC_match) 1784 CHECK_SIMPLE_CLAUSE(Nontemporal, OMPC_nontemporal) 1785 CHECK_SIMPLE_CLAUSE(Order, OMPC_order) 1786 CHECK_SIMPLE_CLAUSE(Read, OMPC_read) 1787 CHECK_SIMPLE_CLAUSE(ReverseOffload, OMPC_reverse_offload) 1788 CHECK_SIMPLE_CLAUSE(Threadprivate, OMPC_threadprivate) 1789 CHECK_SIMPLE_CLAUSE(Threads, OMPC_threads) 1790 CHECK_SIMPLE_CLAUSE(Inbranch, OMPC_inbranch) 1791 CHECK_SIMPLE_CLAUSE(IsDevicePtr, OMPC_is_device_ptr) 1792 CHECK_SIMPLE_CLAUSE(HasDeviceAddr, OMPC_has_device_addr) 1793 CHECK_SIMPLE_CLAUSE(Link, OMPC_link) 1794 CHECK_SIMPLE_CLAUSE(Indirect, OMPC_indirect) 1795 CHECK_SIMPLE_CLAUSE(Mergeable, OMPC_mergeable) 1796 CHECK_SIMPLE_CLAUSE(Nogroup, OMPC_nogroup) 1797 CHECK_SIMPLE_CLAUSE(Notinbranch, OMPC_notinbranch) 1798 CHECK_SIMPLE_CLAUSE(Nowait, OMPC_nowait) 1799 CHECK_SIMPLE_CLAUSE(Partial, OMPC_partial) 1800 CHECK_SIMPLE_CLAUSE(ProcBind, OMPC_proc_bind) 1801 CHECK_SIMPLE_CLAUSE(Release, OMPC_release) 1802 CHECK_SIMPLE_CLAUSE(Relaxed, OMPC_relaxed) 1803 CHECK_SIMPLE_CLAUSE(SeqCst, OMPC_seq_cst) 1804 CHECK_SIMPLE_CLAUSE(Simd, OMPC_simd) 1805 CHECK_SIMPLE_CLAUSE(Sizes, OMPC_sizes) 1806 CHECK_SIMPLE_CLAUSE(TaskReduction, OMPC_task_reduction) 1807 CHECK_SIMPLE_CLAUSE(To, OMPC_to) 1808 CHECK_SIMPLE_CLAUSE(UnifiedAddress, OMPC_unified_address) 1809 CHECK_SIMPLE_CLAUSE(UnifiedSharedMemory, OMPC_unified_shared_memory) 1810 CHECK_SIMPLE_CLAUSE(Uniform, OMPC_uniform) 1811 CHECK_SIMPLE_CLAUSE(Unknown, OMPC_unknown) 1812 CHECK_SIMPLE_CLAUSE(Untied, OMPC_untied) 1813 CHECK_SIMPLE_CLAUSE(UseDevicePtr, OMPC_use_device_ptr) 1814 CHECK_SIMPLE_CLAUSE(UsesAllocators, OMPC_uses_allocators) 1815 CHECK_SIMPLE_CLAUSE(Update, OMPC_update) 1816 CHECK_SIMPLE_CLAUSE(UseDeviceAddr, OMPC_use_device_addr) 1817 CHECK_SIMPLE_CLAUSE(Write, OMPC_write) 1818 CHECK_SIMPLE_CLAUSE(Init, OMPC_init) 1819 CHECK_SIMPLE_CLAUSE(Use, OMPC_use) 1820 CHECK_SIMPLE_CLAUSE(Novariants, OMPC_novariants) 1821 CHECK_SIMPLE_CLAUSE(Nocontext, OMPC_nocontext) 1822 CHECK_SIMPLE_CLAUSE(Filter, OMPC_filter) 1823 CHECK_SIMPLE_CLAUSE(When, OMPC_when) 1824 CHECK_SIMPLE_CLAUSE(AdjustArgs, OMPC_adjust_args) 1825 CHECK_SIMPLE_CLAUSE(AppendArgs, OMPC_append_args) 1826 CHECK_SIMPLE_CLAUSE(MemoryOrder, OMPC_memory_order) 1827 CHECK_SIMPLE_CLAUSE(Bind, OMPC_bind) 1828 CHECK_SIMPLE_CLAUSE(Align, OMPC_align) 1829 CHECK_SIMPLE_CLAUSE(Compare, OMPC_compare) 1830 CHECK_SIMPLE_CLAUSE(CancellationConstructType, OMPC_cancellation_construct_type) 1831 1832 CHECK_REQ_SCALAR_INT_CLAUSE(Grainsize, OMPC_grainsize) 1833 CHECK_REQ_SCALAR_INT_CLAUSE(NumTasks, OMPC_num_tasks) 1834 CHECK_REQ_SCALAR_INT_CLAUSE(NumTeams, OMPC_num_teams) 1835 CHECK_REQ_SCALAR_INT_CLAUSE(NumThreads, OMPC_num_threads) 1836 CHECK_REQ_SCALAR_INT_CLAUSE(Priority, OMPC_priority) 1837 CHECK_REQ_SCALAR_INT_CLAUSE(ThreadLimit, OMPC_thread_limit) 1838 CHECK_REQ_SCALAR_INT_CLAUSE(Device, OMPC_device) 1839 1840 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Collapse, OMPC_collapse) 1841 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Safelen, OMPC_safelen) 1842 CHECK_REQ_CONSTANT_SCALAR_INT_CLAUSE(Simdlen, OMPC_simdlen) 1843 1844 // Restrictions specific to each clause are implemented apart from the 1845 // generalized restrictions. 1846 void OmpStructureChecker::Enter(const parser::OmpClause::Reduction &x) { 1847 CheckAllowed(llvm::omp::Clause::OMPC_reduction); 1848 if (CheckReductionOperators(x)) { 1849 CheckReductionTypeList(x); 1850 } 1851 } 1852 bool OmpStructureChecker::CheckReductionOperators( 1853 const parser::OmpClause::Reduction &x) { 1854 1855 const auto &definedOp{std::get<0>(x.v.t)}; 1856 bool ok = false; 1857 common::visit( 1858 common::visitors{ 1859 [&](const parser::DefinedOperator &dOpr) { 1860 const auto &intrinsicOp{ 1861 std::get<parser::DefinedOperator::IntrinsicOperator>(dOpr.u)}; 1862 ok = CheckIntrinsicOperator(intrinsicOp); 1863 }, 1864 [&](const parser::ProcedureDesignator &procD) { 1865 const parser::Name *name{std::get_if<parser::Name>(&procD.u)}; 1866 if (name) { 1867 if (name->source == "max" || name->source == "min" || 1868 name->source == "iand" || name->source == "ior" || 1869 name->source == "ieor") { 1870 ok = true; 1871 } else { 1872 context_.Say(GetContext().clauseSource, 1873 "Invalid reduction identifier in REDUCTION clause."_err_en_US, 1874 ContextDirectiveAsFortran()); 1875 } 1876 } 1877 }, 1878 }, 1879 definedOp.u); 1880 1881 return ok; 1882 } 1883 bool OmpStructureChecker::CheckIntrinsicOperator( 1884 const parser::DefinedOperator::IntrinsicOperator &op) { 1885 1886 switch (op) { 1887 case parser::DefinedOperator::IntrinsicOperator::Add: 1888 case parser::DefinedOperator::IntrinsicOperator::Subtract: 1889 case parser::DefinedOperator::IntrinsicOperator::Multiply: 1890 case parser::DefinedOperator::IntrinsicOperator::AND: 1891 case parser::DefinedOperator::IntrinsicOperator::OR: 1892 case parser::DefinedOperator::IntrinsicOperator::EQV: 1893 case parser::DefinedOperator::IntrinsicOperator::NEQV: 1894 return true; 1895 default: 1896 context_.Say(GetContext().clauseSource, 1897 "Invalid reduction operator in REDUCTION clause."_err_en_US, 1898 ContextDirectiveAsFortran()); 1899 } 1900 return false; 1901 } 1902 1903 void OmpStructureChecker::CheckReductionTypeList( 1904 const parser::OmpClause::Reduction &x) { 1905 const auto &ompObjectList{std::get<parser::OmpObjectList>(x.v.t)}; 1906 CheckIntentInPointerAndDefinable( 1907 ompObjectList, llvm::omp::Clause::OMPC_reduction); 1908 CheckReductionArraySection(ompObjectList); 1909 CheckMultipleAppearanceAcrossContext(ompObjectList); 1910 } 1911 1912 void OmpStructureChecker::CheckIntentInPointerAndDefinable( 1913 const parser::OmpObjectList &objectList, const llvm::omp::Clause clause) { 1914 for (const auto &ompObject : objectList.v) { 1915 if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) { 1916 if (const auto *symbol{name->symbol}) { 1917 if (IsPointer(symbol->GetUltimate()) && 1918 IsIntentIn(symbol->GetUltimate())) { 1919 context_.Say(GetContext().clauseSource, 1920 "Pointer '%s' with the INTENT(IN) attribute may not appear " 1921 "in a %s clause"_err_en_US, 1922 symbol->name(), 1923 parser::ToUpperCaseLetters(getClauseName(clause).str())); 1924 } 1925 if (auto msg{ 1926 WhyNotModifiable(*symbol, context_.FindScope(name->source))}) { 1927 context_ 1928 .Say(GetContext().clauseSource, 1929 "Variable '%s' on the %s clause is not definable"_err_en_US, 1930 symbol->name(), 1931 parser::ToUpperCaseLetters(getClauseName(clause).str())) 1932 .Attach(std::move(*msg)); 1933 } 1934 } 1935 } 1936 } 1937 } 1938 1939 void OmpStructureChecker::CheckReductionArraySection( 1940 const parser::OmpObjectList &ompObjectList) { 1941 for (const auto &ompObject : ompObjectList.v) { 1942 if (const auto *dataRef{parser::Unwrap<parser::DataRef>(ompObject)}) { 1943 if (const auto *arrayElement{ 1944 parser::Unwrap<parser::ArrayElement>(ompObject)}) { 1945 if (arrayElement) { 1946 CheckArraySection(*arrayElement, GetLastName(*dataRef), 1947 llvm::omp::Clause::OMPC_reduction); 1948 } 1949 } 1950 } 1951 } 1952 } 1953 1954 void OmpStructureChecker::CheckMultipleAppearanceAcrossContext( 1955 const parser::OmpObjectList &redObjectList) { 1956 // TODO: Verify the assumption here that the immediately enclosing region is 1957 // the parallel region to which the worksharing construct having reduction 1958 // binds to. 1959 if (auto *enclosingContext{GetEnclosingDirContext()}) { 1960 for (auto it : enclosingContext->clauseInfo) { 1961 llvmOmpClause type = it.first; 1962 const auto *clause = it.second; 1963 if (llvm::omp::privateReductionSet.test(type)) { 1964 if (const auto *objList{GetOmpObjectList(*clause)}) { 1965 for (const auto &ompObject : objList->v) { 1966 if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) { 1967 if (const auto *symbol{name->symbol}) { 1968 for (const auto &redOmpObject : redObjectList.v) { 1969 if (const auto *rname{ 1970 parser::Unwrap<parser::Name>(redOmpObject)}) { 1971 if (const auto *rsymbol{rname->symbol}) { 1972 if (rsymbol->name() == symbol->name()) { 1973 context_.Say(GetContext().clauseSource, 1974 "%s variable '%s' is %s in outer context must" 1975 " be shared in the parallel regions to which any" 1976 " of the worksharing regions arising from the " 1977 "worksharing" 1978 " construct bind."_err_en_US, 1979 parser::ToUpperCaseLetters( 1980 getClauseName(llvm::omp::Clause::OMPC_reduction) 1981 .str()), 1982 symbol->name(), 1983 parser::ToUpperCaseLetters( 1984 getClauseName(type).str())); 1985 } 1986 } 1987 } 1988 } 1989 } 1990 } 1991 } 1992 } 1993 } 1994 } 1995 } 1996 } 1997 1998 void OmpStructureChecker::Enter(const parser::OmpClause::Ordered &x) { 1999 CheckAllowed(llvm::omp::Clause::OMPC_ordered); 2000 // the parameter of ordered clause is optional 2001 if (const auto &expr{x.v}) { 2002 RequiresConstantPositiveParameter(llvm::omp::Clause::OMPC_ordered, *expr); 2003 // 2.8.3 Loop SIMD Construct Restriction 2004 if (llvm::omp::doSimdSet.test(GetContext().directive)) { 2005 context_.Say(GetContext().clauseSource, 2006 "No ORDERED clause with a parameter can be specified " 2007 "on the %s directive"_err_en_US, 2008 ContextDirectiveAsFortran()); 2009 } 2010 } 2011 } 2012 2013 void OmpStructureChecker::Enter(const parser::OmpClause::Shared &x) { 2014 CheckAllowed(llvm::omp::Clause::OMPC_shared); 2015 CheckIsVarPartOfAnotherVar(GetContext().clauseSource, x.v); 2016 } 2017 void OmpStructureChecker::Enter(const parser::OmpClause::Private &x) { 2018 CheckAllowed(llvm::omp::Clause::OMPC_private); 2019 CheckIsVarPartOfAnotherVar(GetContext().clauseSource, x.v); 2020 CheckIntentInPointer(x.v, llvm::omp::Clause::OMPC_private); 2021 } 2022 2023 bool OmpStructureChecker::IsDataRefTypeParamInquiry( 2024 const parser::DataRef *dataRef) { 2025 bool dataRefIsTypeParamInquiry{false}; 2026 if (const auto *structComp{ 2027 parser::Unwrap<parser::StructureComponent>(dataRef)}) { 2028 if (const auto *compSymbol{structComp->component.symbol}) { 2029 if (const auto *compSymbolMiscDetails{ 2030 std::get_if<MiscDetails>(&compSymbol->details())}) { 2031 const auto detailsKind = compSymbolMiscDetails->kind(); 2032 dataRefIsTypeParamInquiry = 2033 (detailsKind == MiscDetails::Kind::KindParamInquiry || 2034 detailsKind == MiscDetails::Kind::LenParamInquiry); 2035 } else if (compSymbol->has<TypeParamDetails>()) { 2036 dataRefIsTypeParamInquiry = true; 2037 } 2038 } 2039 } 2040 return dataRefIsTypeParamInquiry; 2041 } 2042 2043 void OmpStructureChecker::CheckIsVarPartOfAnotherVar( 2044 const parser::CharBlock &source, const parser::OmpObjectList &objList) { 2045 OmpDirectiveSet nonPartialVarSet{llvm::omp::Directive::OMPD_allocate, 2046 llvm::omp::Directive::OMPD_threadprivate, 2047 llvm::omp::Directive::OMPD_declare_target}; 2048 for (const auto &ompObject : objList.v) { 2049 common::visit( 2050 common::visitors{ 2051 [&](const parser::Designator &designator) { 2052 if (const auto *dataRef{ 2053 std::get_if<parser::DataRef>(&designator.u)}) { 2054 if (IsDataRefTypeParamInquiry(dataRef)) { 2055 context_.Say(source, 2056 "A type parameter inquiry cannot appear on the %s " 2057 "directive"_err_en_US, 2058 ContextDirectiveAsFortran()); 2059 } else if (parser::Unwrap<parser::StructureComponent>( 2060 ompObject) || 2061 parser::Unwrap<parser::ArrayElement>(ompObject)) { 2062 if (nonPartialVarSet.test(GetContext().directive)) { 2063 context_.Say(source, 2064 "A variable that is part of another variable (as an " 2065 "array or structure element) cannot appear on the %s " 2066 "directive"_err_en_US, 2067 ContextDirectiveAsFortran()); 2068 } else { 2069 context_.Say(source, 2070 "A variable that is part of another variable (as an " 2071 "array or structure element) cannot appear in a " 2072 "PRIVATE or SHARED clause"_err_en_US); 2073 } 2074 } 2075 } 2076 }, 2077 [&](const parser::Name &name) {}, 2078 }, 2079 ompObject.u); 2080 } 2081 } 2082 2083 void OmpStructureChecker::Enter(const parser::OmpClause::Firstprivate &x) { 2084 CheckAllowed(llvm::omp::Clause::OMPC_firstprivate); 2085 CheckIsLoopIvPartOfClause(llvmOmpClause::OMPC_firstprivate, x.v); 2086 2087 SymbolSourceMap currSymbols; 2088 GetSymbolsInObjectList(x.v, currSymbols); 2089 2090 DirectivesClauseTriple dirClauseTriple; 2091 // Check firstprivate variables in worksharing constructs 2092 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_do, 2093 std::make_pair( 2094 llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet)); 2095 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_sections, 2096 std::make_pair( 2097 llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet)); 2098 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_single, 2099 std::make_pair( 2100 llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet)); 2101 // Check firstprivate variables in distribute construct 2102 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_distribute, 2103 std::make_pair( 2104 llvm::omp::Directive::OMPD_teams, llvm::omp::privateReductionSet)); 2105 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_distribute, 2106 std::make_pair(llvm::omp::Directive::OMPD_target_teams, 2107 llvm::omp::privateReductionSet)); 2108 // Check firstprivate variables in task and taskloop constructs 2109 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_task, 2110 std::make_pair(llvm::omp::Directive::OMPD_parallel, 2111 OmpClauseSet{llvm::omp::Clause::OMPC_reduction})); 2112 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_taskloop, 2113 std::make_pair(llvm::omp::Directive::OMPD_parallel, 2114 OmpClauseSet{llvm::omp::Clause::OMPC_reduction})); 2115 2116 CheckPrivateSymbolsInOuterCxt( 2117 currSymbols, dirClauseTriple, llvm::omp::Clause::OMPC_firstprivate); 2118 } 2119 2120 void OmpStructureChecker::CheckIsLoopIvPartOfClause( 2121 llvmOmpClause clause, const parser::OmpObjectList &ompObjectList) { 2122 for (const auto &ompObject : ompObjectList.v) { 2123 if (const parser::Name * name{parser::Unwrap<parser::Name>(ompObject)}) { 2124 if (name->symbol == GetContext().loopIV) { 2125 context_.Say(name->source, 2126 "DO iteration variable %s is not allowed in %s clause."_err_en_US, 2127 name->ToString(), 2128 parser::ToUpperCaseLetters(getClauseName(clause).str())); 2129 } 2130 } 2131 } 2132 } 2133 // Following clauses have a seperate node in parse-tree.h. 2134 // Atomic-clause 2135 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicRead, OMPC_read) 2136 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicWrite, OMPC_write) 2137 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicUpdate, OMPC_update) 2138 CHECK_SIMPLE_PARSER_CLAUSE(OmpAtomicCapture, OMPC_capture) 2139 2140 void OmpStructureChecker::Leave(const parser::OmpAtomicRead &) { 2141 CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_read, 2142 {llvm::omp::Clause::OMPC_release, llvm::omp::Clause::OMPC_acq_rel}); 2143 } 2144 void OmpStructureChecker::Leave(const parser::OmpAtomicWrite &) { 2145 CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_write, 2146 {llvm::omp::Clause::OMPC_acquire, llvm::omp::Clause::OMPC_acq_rel}); 2147 } 2148 void OmpStructureChecker::Leave(const parser::OmpAtomicUpdate &) { 2149 CheckNotAllowedIfClause(llvm::omp::Clause::OMPC_update, 2150 {llvm::omp::Clause::OMPC_acquire, llvm::omp::Clause::OMPC_acq_rel}); 2151 } 2152 // OmpAtomic node represents atomic directive without atomic-clause. 2153 // atomic-clause - READ,WRITE,UPDATE,CAPTURE. 2154 void OmpStructureChecker::Leave(const parser::OmpAtomic &) { 2155 if (const auto *clause{FindClause(llvm::omp::Clause::OMPC_acquire)}) { 2156 context_.Say(clause->source, 2157 "Clause ACQUIRE is not allowed on the ATOMIC directive"_err_en_US); 2158 } 2159 if (const auto *clause{FindClause(llvm::omp::Clause::OMPC_acq_rel)}) { 2160 context_.Say(clause->source, 2161 "Clause ACQ_REL is not allowed on the ATOMIC directive"_err_en_US); 2162 } 2163 } 2164 // Restrictions specific to each clause are implemented apart from the 2165 // generalized restrictions. 2166 void OmpStructureChecker::Enter(const parser::OmpClause::Aligned &x) { 2167 CheckAllowed(llvm::omp::Clause::OMPC_aligned); 2168 2169 if (const auto &expr{ 2170 std::get<std::optional<parser::ScalarIntConstantExpr>>(x.v.t)}) { 2171 RequiresConstantPositiveParameter(llvm::omp::Clause::OMPC_aligned, *expr); 2172 } 2173 // 2.8.1 TODO: list-item attribute check 2174 } 2175 void OmpStructureChecker::Enter(const parser::OmpClause::Defaultmap &x) { 2176 CheckAllowed(llvm::omp::Clause::OMPC_defaultmap); 2177 using VariableCategory = parser::OmpDefaultmapClause::VariableCategory; 2178 if (!std::get<std::optional<VariableCategory>>(x.v.t)) { 2179 context_.Say(GetContext().clauseSource, 2180 "The argument TOFROM:SCALAR must be specified on the DEFAULTMAP " 2181 "clause"_err_en_US); 2182 } 2183 } 2184 void OmpStructureChecker::Enter(const parser::OmpClause::If &x) { 2185 CheckAllowed(llvm::omp::Clause::OMPC_if); 2186 using dirNameModifier = parser::OmpIfClause::DirectiveNameModifier; 2187 static std::unordered_map<dirNameModifier, OmpDirectiveSet> 2188 dirNameModifierMap{{dirNameModifier::Parallel, llvm::omp::parallelSet}, 2189 {dirNameModifier::Target, llvm::omp::targetSet}, 2190 {dirNameModifier::TargetEnterData, 2191 {llvm::omp::Directive::OMPD_target_enter_data}}, 2192 {dirNameModifier::TargetExitData, 2193 {llvm::omp::Directive::OMPD_target_exit_data}}, 2194 {dirNameModifier::TargetData, 2195 {llvm::omp::Directive::OMPD_target_data}}, 2196 {dirNameModifier::TargetUpdate, 2197 {llvm::omp::Directive::OMPD_target_update}}, 2198 {dirNameModifier::Task, {llvm::omp::Directive::OMPD_task}}, 2199 {dirNameModifier::Taskloop, llvm::omp::taskloopSet}}; 2200 if (const auto &directiveName{ 2201 std::get<std::optional<dirNameModifier>>(x.v.t)}) { 2202 auto search{dirNameModifierMap.find(*directiveName)}; 2203 if (search == dirNameModifierMap.end() || 2204 !search->second.test(GetContext().directive)) { 2205 context_ 2206 .Say(GetContext().clauseSource, 2207 "Unmatched directive name modifier %s on the IF clause"_err_en_US, 2208 parser::ToUpperCaseLetters( 2209 parser::OmpIfClause::EnumToString(*directiveName))) 2210 .Attach( 2211 GetContext().directiveSource, "Cannot apply to directive"_en_US); 2212 } 2213 } 2214 } 2215 2216 void OmpStructureChecker::Enter(const parser::OmpClause::Linear &x) { 2217 CheckAllowed(llvm::omp::Clause::OMPC_linear); 2218 2219 // 2.7 Loop Construct Restriction 2220 if ((llvm::omp::doSet | llvm::omp::simdSet).test(GetContext().directive)) { 2221 if (std::holds_alternative<parser::OmpLinearClause::WithModifier>(x.v.u)) { 2222 context_.Say(GetContext().clauseSource, 2223 "A modifier may not be specified in a LINEAR clause " 2224 "on the %s directive"_err_en_US, 2225 ContextDirectiveAsFortran()); 2226 } 2227 } 2228 } 2229 2230 void OmpStructureChecker::CheckAllowedMapTypes( 2231 const parser::OmpMapType::Type &type, 2232 const std::list<parser::OmpMapType::Type> &allowedMapTypeList) { 2233 const auto found{std::find( 2234 std::begin(allowedMapTypeList), std::end(allowedMapTypeList), type)}; 2235 if (found == std::end(allowedMapTypeList)) { 2236 std::string commaSeperatedMapTypes; 2237 llvm::interleave( 2238 allowedMapTypeList.begin(), allowedMapTypeList.end(), 2239 [&](const parser::OmpMapType::Type &mapType) { 2240 commaSeperatedMapTypes.append(parser::ToUpperCaseLetters( 2241 parser::OmpMapType::EnumToString(mapType))); 2242 }, 2243 [&] { commaSeperatedMapTypes.append(", "); }); 2244 context_.Say(GetContext().clauseSource, 2245 "Only the %s map types are permitted " 2246 "for MAP clauses on the %s directive"_err_en_US, 2247 commaSeperatedMapTypes, ContextDirectiveAsFortran()); 2248 } 2249 } 2250 2251 void OmpStructureChecker::Enter(const parser::OmpClause::Map &x) { 2252 CheckAllowed(llvm::omp::Clause::OMPC_map); 2253 2254 if (const auto &maptype{std::get<std::optional<parser::OmpMapType>>(x.v.t)}) { 2255 using Type = parser::OmpMapType::Type; 2256 const Type &type{std::get<Type>(maptype->t)}; 2257 switch (GetContext().directive) { 2258 case llvm::omp::Directive::OMPD_target: 2259 case llvm::omp::Directive::OMPD_target_teams: 2260 case llvm::omp::Directive::OMPD_target_teams_distribute: 2261 case llvm::omp::Directive::OMPD_target_teams_distribute_simd: 2262 case llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do: 2263 case llvm::omp::Directive::OMPD_target_teams_distribute_parallel_do_simd: 2264 case llvm::omp::Directive::OMPD_target_data: 2265 CheckAllowedMapTypes( 2266 type, {Type::To, Type::From, Type::Tofrom, Type::Alloc}); 2267 break; 2268 case llvm::omp::Directive::OMPD_target_enter_data: 2269 CheckAllowedMapTypes(type, {Type::To, Type::Alloc}); 2270 break; 2271 case llvm::omp::Directive::OMPD_target_exit_data: 2272 CheckAllowedMapTypes(type, {Type::From, Type::Release, Type::Delete}); 2273 break; 2274 default: 2275 break; 2276 } 2277 } 2278 } 2279 2280 bool OmpStructureChecker::ScheduleModifierHasType( 2281 const parser::OmpScheduleClause &x, 2282 const parser::OmpScheduleModifierType::ModType &type) { 2283 const auto &modifier{ 2284 std::get<std::optional<parser::OmpScheduleModifier>>(x.t)}; 2285 if (modifier) { 2286 const auto &modType1{ 2287 std::get<parser::OmpScheduleModifier::Modifier1>(modifier->t)}; 2288 const auto &modType2{ 2289 std::get<std::optional<parser::OmpScheduleModifier::Modifier2>>( 2290 modifier->t)}; 2291 if (modType1.v.v == type || (modType2 && modType2->v.v == type)) { 2292 return true; 2293 } 2294 } 2295 return false; 2296 } 2297 void OmpStructureChecker::Enter(const parser::OmpClause::Schedule &x) { 2298 CheckAllowed(llvm::omp::Clause::OMPC_schedule); 2299 const parser::OmpScheduleClause &scheduleClause = x.v; 2300 2301 // 2.7 Loop Construct Restriction 2302 if (llvm::omp::doSet.test(GetContext().directive)) { 2303 const auto &kind{std::get<1>(scheduleClause.t)}; 2304 const auto &chunk{std::get<2>(scheduleClause.t)}; 2305 if (chunk) { 2306 if (kind == parser::OmpScheduleClause::ScheduleType::Runtime || 2307 kind == parser::OmpScheduleClause::ScheduleType::Auto) { 2308 context_.Say(GetContext().clauseSource, 2309 "When SCHEDULE clause has %s specified, " 2310 "it must not have chunk size specified"_err_en_US, 2311 parser::ToUpperCaseLetters( 2312 parser::OmpScheduleClause::EnumToString(kind))); 2313 } 2314 if (const auto &chunkExpr{std::get<std::optional<parser::ScalarIntExpr>>( 2315 scheduleClause.t)}) { 2316 RequiresPositiveParameter( 2317 llvm::omp::Clause::OMPC_schedule, *chunkExpr, "chunk size"); 2318 } 2319 } 2320 2321 if (ScheduleModifierHasType(scheduleClause, 2322 parser::OmpScheduleModifierType::ModType::Nonmonotonic)) { 2323 if (kind != parser::OmpScheduleClause::ScheduleType::Dynamic && 2324 kind != parser::OmpScheduleClause::ScheduleType::Guided) { 2325 context_.Say(GetContext().clauseSource, 2326 "The NONMONOTONIC modifier can only be specified with " 2327 "SCHEDULE(DYNAMIC) or SCHEDULE(GUIDED)"_err_en_US); 2328 } 2329 } 2330 } 2331 } 2332 2333 void OmpStructureChecker::Enter(const parser::OmpClause::Depend &x) { 2334 CheckAllowed(llvm::omp::Clause::OMPC_depend); 2335 if (const auto *inOut{std::get_if<parser::OmpDependClause::InOut>(&x.v.u)}) { 2336 const auto &designators{std::get<std::list<parser::Designator>>(inOut->t)}; 2337 for (const auto &ele : designators) { 2338 if (const auto *dataRef{std::get_if<parser::DataRef>(&ele.u)}) { 2339 CheckDependList(*dataRef); 2340 if (const auto *arr{ 2341 std::get_if<common::Indirection<parser::ArrayElement>>( 2342 &dataRef->u)}) { 2343 CheckArraySection(arr->value(), GetLastName(*dataRef), 2344 llvm::omp::Clause::OMPC_depend); 2345 } 2346 } 2347 } 2348 } 2349 } 2350 2351 void OmpStructureChecker::Enter(const parser::OmpClause::Copyprivate &x) { 2352 CheckAllowed(llvm::omp::Clause::OMPC_copyprivate); 2353 CheckIntentInPointer(x.v, llvm::omp::Clause::OMPC_copyprivate); 2354 } 2355 2356 void OmpStructureChecker::Enter(const parser::OmpClause::Lastprivate &x) { 2357 CheckAllowed(llvm::omp::Clause::OMPC_lastprivate); 2358 2359 DirectivesClauseTriple dirClauseTriple; 2360 SymbolSourceMap currSymbols; 2361 GetSymbolsInObjectList(x.v, currSymbols); 2362 CheckDefinableObjects(currSymbols, GetClauseKindForParserClass(x)); 2363 2364 // Check lastprivate variables in worksharing constructs 2365 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_do, 2366 std::make_pair( 2367 llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet)); 2368 dirClauseTriple.emplace(llvm::omp::Directive::OMPD_sections, 2369 std::make_pair( 2370 llvm::omp::Directive::OMPD_parallel, llvm::omp::privateReductionSet)); 2371 2372 CheckPrivateSymbolsInOuterCxt( 2373 currSymbols, dirClauseTriple, GetClauseKindForParserClass(x)); 2374 } 2375 2376 llvm::StringRef OmpStructureChecker::getClauseName(llvm::omp::Clause clause) { 2377 return llvm::omp::getOpenMPClauseName(clause); 2378 } 2379 2380 llvm::StringRef OmpStructureChecker::getDirectiveName( 2381 llvm::omp::Directive directive) { 2382 return llvm::omp::getOpenMPDirectiveName(directive); 2383 } 2384 2385 void OmpStructureChecker::CheckDependList(const parser::DataRef &d) { 2386 common::visit( 2387 common::visitors{ 2388 [&](const common::Indirection<parser::ArrayElement> &elem) { 2389 // Check if the base element is valid on Depend Clause 2390 CheckDependList(elem.value().base); 2391 }, 2392 [&](const common::Indirection<parser::StructureComponent> &) { 2393 context_.Say(GetContext().clauseSource, 2394 "A variable that is part of another variable " 2395 "(such as an element of a structure) but is not an array " 2396 "element or an array section cannot appear in a DEPEND " 2397 "clause"_err_en_US); 2398 }, 2399 [&](const common::Indirection<parser::CoindexedNamedObject> &) { 2400 context_.Say(GetContext().clauseSource, 2401 "Coarrays are not supported in DEPEND clause"_err_en_US); 2402 }, 2403 [&](const parser::Name &) { return; }, 2404 }, 2405 d.u); 2406 } 2407 2408 // Called from both Reduction and Depend clause. 2409 void OmpStructureChecker::CheckArraySection( 2410 const parser::ArrayElement &arrayElement, const parser::Name &name, 2411 const llvm::omp::Clause clause) { 2412 if (!arrayElement.subscripts.empty()) { 2413 for (const auto &subscript : arrayElement.subscripts) { 2414 if (const auto *triplet{ 2415 std::get_if<parser::SubscriptTriplet>(&subscript.u)}) { 2416 if (std::get<0>(triplet->t) && std::get<1>(triplet->t)) { 2417 const auto &lower{std::get<0>(triplet->t)}; 2418 const auto &upper{std::get<1>(triplet->t)}; 2419 if (lower && upper) { 2420 const auto lval{GetIntValue(lower)}; 2421 const auto uval{GetIntValue(upper)}; 2422 if (lval && uval && *uval < *lval) { 2423 context_.Say(GetContext().clauseSource, 2424 "'%s' in %s clause" 2425 " is a zero size array section"_err_en_US, 2426 name.ToString(), 2427 parser::ToUpperCaseLetters(getClauseName(clause).str())); 2428 break; 2429 } else if (std::get<2>(triplet->t)) { 2430 const auto &strideExpr{std::get<2>(triplet->t)}; 2431 if (strideExpr) { 2432 if (clause == llvm::omp::Clause::OMPC_depend) { 2433 context_.Say(GetContext().clauseSource, 2434 "Stride should not be specified for array section in " 2435 "DEPEND " 2436 "clause"_err_en_US); 2437 } 2438 const auto stride{GetIntValue(strideExpr)}; 2439 if ((stride && stride != 1)) { 2440 context_.Say(GetContext().clauseSource, 2441 "A list item that appears in a REDUCTION clause" 2442 " should have a contiguous storage array section."_err_en_US, 2443 ContextDirectiveAsFortran()); 2444 break; 2445 } 2446 } 2447 } 2448 } 2449 } 2450 } 2451 } 2452 } 2453 } 2454 2455 void OmpStructureChecker::CheckIntentInPointer( 2456 const parser::OmpObjectList &objectList, const llvm::omp::Clause clause) { 2457 SymbolSourceMap symbols; 2458 GetSymbolsInObjectList(objectList, symbols); 2459 for (auto it{symbols.begin()}; it != symbols.end(); ++it) { 2460 const auto *symbol{it->first}; 2461 const auto source{it->second}; 2462 if (IsPointer(*symbol) && IsIntentIn(*symbol)) { 2463 context_.Say(source, 2464 "Pointer '%s' with the INTENT(IN) attribute may not appear " 2465 "in a %s clause"_err_en_US, 2466 symbol->name(), 2467 parser::ToUpperCaseLetters(getClauseName(clause).str())); 2468 } 2469 } 2470 } 2471 2472 void OmpStructureChecker::GetSymbolsInObjectList( 2473 const parser::OmpObjectList &objectList, SymbolSourceMap &symbols) { 2474 for (const auto &ompObject : objectList.v) { 2475 if (const auto *name{parser::Unwrap<parser::Name>(ompObject)}) { 2476 if (const auto *symbol{name->symbol}) { 2477 if (const auto *commonBlockDetails{ 2478 symbol->detailsIf<CommonBlockDetails>()}) { 2479 for (const auto &object : commonBlockDetails->objects()) { 2480 symbols.emplace(&object->GetUltimate(), name->source); 2481 } 2482 } else { 2483 symbols.emplace(&symbol->GetUltimate(), name->source); 2484 } 2485 } 2486 } 2487 } 2488 } 2489 2490 void OmpStructureChecker::CheckDefinableObjects( 2491 SymbolSourceMap &symbols, const llvm::omp::Clause clause) { 2492 for (auto it{symbols.begin()}; it != symbols.end(); ++it) { 2493 const auto *symbol{it->first}; 2494 const auto source{it->second}; 2495 if (auto msg{WhyNotModifiable(*symbol, context_.FindScope(source))}) { 2496 context_ 2497 .Say(source, 2498 "Variable '%s' on the %s clause is not definable"_err_en_US, 2499 symbol->name(), 2500 parser::ToUpperCaseLetters(getClauseName(clause).str())) 2501 .Attach(std::move(*msg)); 2502 } 2503 } 2504 } 2505 2506 void OmpStructureChecker::CheckPrivateSymbolsInOuterCxt( 2507 SymbolSourceMap &currSymbols, DirectivesClauseTriple &dirClauseTriple, 2508 const llvm::omp::Clause currClause) { 2509 SymbolSourceMap enclosingSymbols; 2510 auto range{dirClauseTriple.equal_range(GetContext().directive)}; 2511 for (auto dirIter{range.first}; dirIter != range.second; ++dirIter) { 2512 auto enclosingDir{dirIter->second.first}; 2513 auto enclosingClauseSet{dirIter->second.second}; 2514 if (auto *enclosingContext{GetEnclosingContextWithDir(enclosingDir)}) { 2515 for (auto it{enclosingContext->clauseInfo.begin()}; 2516 it != enclosingContext->clauseInfo.end(); ++it) { 2517 if (enclosingClauseSet.test(it->first)) { 2518 if (const auto *ompObjectList{GetOmpObjectList(*it->second)}) { 2519 GetSymbolsInObjectList(*ompObjectList, enclosingSymbols); 2520 } 2521 } 2522 } 2523 2524 // Check if the symbols in current context are private in outer context 2525 for (auto iter{currSymbols.begin()}; iter != currSymbols.end(); ++iter) { 2526 const auto *symbol{iter->first}; 2527 const auto source{iter->second}; 2528 if (enclosingSymbols.find(symbol) != enclosingSymbols.end()) { 2529 context_.Say(source, 2530 "%s variable '%s' is PRIVATE in outer context"_err_en_US, 2531 parser::ToUpperCaseLetters(getClauseName(currClause).str()), 2532 symbol->name()); 2533 } 2534 } 2535 } 2536 } 2537 } 2538 2539 bool OmpStructureChecker::CheckTargetBlockOnlyTeams( 2540 const parser::Block &block) { 2541 bool nestedTeams{false}; 2542 auto it{block.begin()}; 2543 2544 if (const auto *ompConstruct{parser::Unwrap<parser::OpenMPConstruct>(*it)}) { 2545 if (const auto *ompBlockConstruct{ 2546 std::get_if<parser::OpenMPBlockConstruct>(&ompConstruct->u)}) { 2547 const auto &beginBlockDir{ 2548 std::get<parser::OmpBeginBlockDirective>(ompBlockConstruct->t)}; 2549 const auto &beginDir{ 2550 std::get<parser::OmpBlockDirective>(beginBlockDir.t)}; 2551 if (beginDir.v == llvm::omp::Directive::OMPD_teams) { 2552 nestedTeams = true; 2553 } 2554 } 2555 } 2556 2557 if (nestedTeams && ++it == block.end()) { 2558 return true; 2559 } 2560 return false; 2561 } 2562 2563 void OmpStructureChecker::CheckWorkshareBlockStmts( 2564 const parser::Block &block, parser::CharBlock source) { 2565 OmpWorkshareBlockChecker ompWorkshareBlockChecker{context_, source}; 2566 2567 for (auto it{block.begin()}; it != block.end(); ++it) { 2568 if (parser::Unwrap<parser::AssignmentStmt>(*it) || 2569 parser::Unwrap<parser::ForallStmt>(*it) || 2570 parser::Unwrap<parser::ForallConstruct>(*it) || 2571 parser::Unwrap<parser::WhereStmt>(*it) || 2572 parser::Unwrap<parser::WhereConstruct>(*it)) { 2573 parser::Walk(*it, ompWorkshareBlockChecker); 2574 } else if (const auto *ompConstruct{ 2575 parser::Unwrap<parser::OpenMPConstruct>(*it)}) { 2576 if (const auto *ompAtomicConstruct{ 2577 std::get_if<parser::OpenMPAtomicConstruct>(&ompConstruct->u)}) { 2578 // Check if assignment statements in the enclosing OpenMP Atomic 2579 // construct are allowed in the Workshare construct 2580 parser::Walk(*ompAtomicConstruct, ompWorkshareBlockChecker); 2581 } else if (const auto *ompCriticalConstruct{ 2582 std::get_if<parser::OpenMPCriticalConstruct>( 2583 &ompConstruct->u)}) { 2584 // All the restrictions on the Workshare construct apply to the 2585 // statements in the enclosing critical constructs 2586 const auto &criticalBlock{ 2587 std::get<parser::Block>(ompCriticalConstruct->t)}; 2588 CheckWorkshareBlockStmts(criticalBlock, source); 2589 } else { 2590 // Check if OpenMP constructs enclosed in the Workshare construct are 2591 // 'Parallel' constructs 2592 auto currentDir{llvm::omp::Directive::OMPD_unknown}; 2593 const OmpDirectiveSet parallelDirSet{ 2594 llvm::omp::Directive::OMPD_parallel, 2595 llvm::omp::Directive::OMPD_parallel_do, 2596 llvm::omp::Directive::OMPD_parallel_sections, 2597 llvm::omp::Directive::OMPD_parallel_workshare, 2598 llvm::omp::Directive::OMPD_parallel_do_simd}; 2599 2600 if (const auto *ompBlockConstruct{ 2601 std::get_if<parser::OpenMPBlockConstruct>(&ompConstruct->u)}) { 2602 const auto &beginBlockDir{ 2603 std::get<parser::OmpBeginBlockDirective>(ompBlockConstruct->t)}; 2604 const auto &beginDir{ 2605 std::get<parser::OmpBlockDirective>(beginBlockDir.t)}; 2606 currentDir = beginDir.v; 2607 } else if (const auto *ompLoopConstruct{ 2608 std::get_if<parser::OpenMPLoopConstruct>( 2609 &ompConstruct->u)}) { 2610 const auto &beginLoopDir{ 2611 std::get<parser::OmpBeginLoopDirective>(ompLoopConstruct->t)}; 2612 const auto &beginDir{ 2613 std::get<parser::OmpLoopDirective>(beginLoopDir.t)}; 2614 currentDir = beginDir.v; 2615 } else if (const auto *ompSectionsConstruct{ 2616 std::get_if<parser::OpenMPSectionsConstruct>( 2617 &ompConstruct->u)}) { 2618 const auto &beginSectionsDir{ 2619 std::get<parser::OmpBeginSectionsDirective>( 2620 ompSectionsConstruct->t)}; 2621 const auto &beginDir{ 2622 std::get<parser::OmpSectionsDirective>(beginSectionsDir.t)}; 2623 currentDir = beginDir.v; 2624 } 2625 2626 if (!parallelDirSet.test(currentDir)) { 2627 context_.Say(source, 2628 "OpenMP constructs enclosed in WORKSHARE construct may consist " 2629 "of ATOMIC, CRITICAL or PARALLEL constructs only"_err_en_US); 2630 } 2631 } 2632 } else { 2633 context_.Say(source, 2634 "The structured block in a WORKSHARE construct may consist of only " 2635 "SCALAR or ARRAY assignments, FORALL or WHERE statements, " 2636 "FORALL, WHERE, ATOMIC, CRITICAL or PARALLEL constructs"_err_en_US); 2637 } 2638 } 2639 } 2640 2641 const parser::OmpObjectList *OmpStructureChecker::GetOmpObjectList( 2642 const parser::OmpClause &clause) { 2643 2644 // Clauses with OmpObjectList as its data member 2645 using MemberObjectListClauses = std::tuple<parser::OmpClause::Copyprivate, 2646 parser::OmpClause::Copyin, parser::OmpClause::Firstprivate, 2647 parser::OmpClause::From, parser::OmpClause::Lastprivate, 2648 parser::OmpClause::Link, parser::OmpClause::Private, 2649 parser::OmpClause::Shared, parser::OmpClause::To>; 2650 2651 // Clauses with OmpObjectList in the tuple 2652 using TupleObjectListClauses = std::tuple<parser::OmpClause::Allocate, 2653 parser::OmpClause::Map, parser::OmpClause::Reduction>; 2654 2655 // TODO:: Generate the tuples using TableGen. 2656 // Handle other constructs with OmpObjectList such as OpenMPThreadprivate. 2657 return common::visit( 2658 common::visitors{ 2659 [&](const auto &x) -> const parser::OmpObjectList * { 2660 using Ty = std::decay_t<decltype(x)>; 2661 if constexpr (common::HasMember<Ty, MemberObjectListClauses>) { 2662 return &x.v; 2663 } else if constexpr (common::HasMember<Ty, 2664 TupleObjectListClauses>) { 2665 return &(std::get<parser::OmpObjectList>(x.v.t)); 2666 } else { 2667 return nullptr; 2668 } 2669 }, 2670 }, 2671 clause.u); 2672 } 2673 2674 } // namespace Fortran::semantics 2675