1 //===--- ParseOpenMP.cpp - OpenMP directives parsing ----------------------===// 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 /// \file 9 /// This file implements parsing of all OpenMP directives and clauses. 10 /// 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/OpenMPClause.h" 15 #include "clang/AST/StmtOpenMP.h" 16 #include "clang/Basic/OpenMPKinds.h" 17 #include "clang/Basic/TargetInfo.h" 18 #include "clang/Basic/TokenKinds.h" 19 #include "clang/Parse/ParseDiagnostic.h" 20 #include "clang/Parse/Parser.h" 21 #include "clang/Parse/RAIIObjectsForParser.h" 22 #include "clang/Sema/Scope.h" 23 #include "llvm/ADT/PointerIntPair.h" 24 #include "llvm/ADT/StringSwitch.h" 25 #include "llvm/ADT/UniqueVector.h" 26 #include "llvm/Frontend/OpenMP/OMPAssume.h" 27 #include "llvm/Frontend/OpenMP/OMPContext.h" 28 29 using namespace clang; 30 using namespace llvm::omp; 31 32 //===----------------------------------------------------------------------===// 33 // OpenMP declarative directives. 34 //===----------------------------------------------------------------------===// 35 36 namespace { 37 enum OpenMPDirectiveKindEx { 38 OMPD_cancellation = llvm::omp::Directive_enumSize + 1, 39 OMPD_data, 40 OMPD_declare, 41 OMPD_end, 42 OMPD_end_declare, 43 OMPD_enter, 44 OMPD_exit, 45 OMPD_point, 46 OMPD_reduction, 47 OMPD_target_enter, 48 OMPD_target_exit, 49 OMPD_update, 50 OMPD_distribute_parallel, 51 OMPD_teams_distribute_parallel, 52 OMPD_target_teams_distribute_parallel, 53 OMPD_mapper, 54 OMPD_variant, 55 OMPD_begin, 56 OMPD_begin_declare, 57 }; 58 59 // Helper to unify the enum class OpenMPDirectiveKind with its extension 60 // the OpenMPDirectiveKindEx enum which allows to use them together as if they 61 // are unsigned values. 62 struct OpenMPDirectiveKindExWrapper { 63 OpenMPDirectiveKindExWrapper(unsigned Value) : Value(Value) {} 64 OpenMPDirectiveKindExWrapper(OpenMPDirectiveKind DK) : Value(unsigned(DK)) {} 65 bool operator==(OpenMPDirectiveKindExWrapper V) const { 66 return Value == V.Value; 67 } 68 bool operator!=(OpenMPDirectiveKindExWrapper V) const { 69 return Value != V.Value; 70 } 71 bool operator==(OpenMPDirectiveKind V) const { return Value == unsigned(V); } 72 bool operator!=(OpenMPDirectiveKind V) const { return Value != unsigned(V); } 73 bool operator<(OpenMPDirectiveKind V) const { return Value < unsigned(V); } 74 operator unsigned() const { return Value; } 75 operator OpenMPDirectiveKind() const { return OpenMPDirectiveKind(Value); } 76 unsigned Value; 77 }; 78 79 class DeclDirectiveListParserHelper final { 80 SmallVector<Expr *, 4> Identifiers; 81 Parser *P; 82 OpenMPDirectiveKind Kind; 83 84 public: 85 DeclDirectiveListParserHelper(Parser *P, OpenMPDirectiveKind Kind) 86 : P(P), Kind(Kind) {} 87 void operator()(CXXScopeSpec &SS, DeclarationNameInfo NameInfo) { 88 ExprResult Res = P->getActions().ActOnOpenMPIdExpression( 89 P->getCurScope(), SS, NameInfo, Kind); 90 if (Res.isUsable()) 91 Identifiers.push_back(Res.get()); 92 } 93 llvm::ArrayRef<Expr *> getIdentifiers() const { return Identifiers; } 94 }; 95 } // namespace 96 97 // Map token string to extended OMP token kind that are 98 // OpenMPDirectiveKind + OpenMPDirectiveKindEx. 99 static unsigned getOpenMPDirectiveKindEx(StringRef S) { 100 OpenMPDirectiveKindExWrapper DKind = getOpenMPDirectiveKind(S); 101 if (DKind != OMPD_unknown) 102 return DKind; 103 104 return llvm::StringSwitch<OpenMPDirectiveKindExWrapper>(S) 105 .Case("cancellation", OMPD_cancellation) 106 .Case("data", OMPD_data) 107 .Case("declare", OMPD_declare) 108 .Case("end", OMPD_end) 109 .Case("enter", OMPD_enter) 110 .Case("exit", OMPD_exit) 111 .Case("point", OMPD_point) 112 .Case("reduction", OMPD_reduction) 113 .Case("update", OMPD_update) 114 .Case("mapper", OMPD_mapper) 115 .Case("variant", OMPD_variant) 116 .Case("begin", OMPD_begin) 117 .Default(OMPD_unknown); 118 } 119 120 static OpenMPDirectiveKindExWrapper parseOpenMPDirectiveKind(Parser &P) { 121 // Array of foldings: F[i][0] F[i][1] ===> F[i][2]. 122 // E.g.: OMPD_for OMPD_simd ===> OMPD_for_simd 123 // TODO: add other combined directives in topological order. 124 static const OpenMPDirectiveKindExWrapper F[][3] = { 125 {OMPD_begin, OMPD_declare, OMPD_begin_declare}, 126 {OMPD_begin, OMPD_assumes, OMPD_begin_assumes}, 127 {OMPD_end, OMPD_declare, OMPD_end_declare}, 128 {OMPD_end, OMPD_assumes, OMPD_end_assumes}, 129 {OMPD_cancellation, OMPD_point, OMPD_cancellation_point}, 130 {OMPD_declare, OMPD_reduction, OMPD_declare_reduction}, 131 {OMPD_declare, OMPD_mapper, OMPD_declare_mapper}, 132 {OMPD_declare, OMPD_simd, OMPD_declare_simd}, 133 {OMPD_declare, OMPD_target, OMPD_declare_target}, 134 {OMPD_declare, OMPD_variant, OMPD_declare_variant}, 135 {OMPD_begin_declare, OMPD_target, OMPD_begin_declare_target}, 136 {OMPD_begin_declare, OMPD_variant, OMPD_begin_declare_variant}, 137 {OMPD_end_declare, OMPD_variant, OMPD_end_declare_variant}, 138 {OMPD_distribute, OMPD_parallel, OMPD_distribute_parallel}, 139 {OMPD_distribute_parallel, OMPD_for, OMPD_distribute_parallel_for}, 140 {OMPD_distribute_parallel_for, OMPD_simd, 141 OMPD_distribute_parallel_for_simd}, 142 {OMPD_distribute, OMPD_simd, OMPD_distribute_simd}, 143 {OMPD_end_declare, OMPD_target, OMPD_end_declare_target}, 144 {OMPD_target, OMPD_data, OMPD_target_data}, 145 {OMPD_target, OMPD_enter, OMPD_target_enter}, 146 {OMPD_target, OMPD_exit, OMPD_target_exit}, 147 {OMPD_target, OMPD_update, OMPD_target_update}, 148 {OMPD_target_enter, OMPD_data, OMPD_target_enter_data}, 149 {OMPD_target_exit, OMPD_data, OMPD_target_exit_data}, 150 {OMPD_for, OMPD_simd, OMPD_for_simd}, 151 {OMPD_parallel, OMPD_for, OMPD_parallel_for}, 152 {OMPD_parallel_for, OMPD_simd, OMPD_parallel_for_simd}, 153 {OMPD_parallel, OMPD_sections, OMPD_parallel_sections}, 154 {OMPD_taskloop, OMPD_simd, OMPD_taskloop_simd}, 155 {OMPD_target, OMPD_parallel, OMPD_target_parallel}, 156 {OMPD_target, OMPD_simd, OMPD_target_simd}, 157 {OMPD_target_parallel, OMPD_for, OMPD_target_parallel_for}, 158 {OMPD_target_parallel_for, OMPD_simd, OMPD_target_parallel_for_simd}, 159 {OMPD_teams, OMPD_distribute, OMPD_teams_distribute}, 160 {OMPD_teams_distribute, OMPD_simd, OMPD_teams_distribute_simd}, 161 {OMPD_teams_distribute, OMPD_parallel, OMPD_teams_distribute_parallel}, 162 {OMPD_teams_distribute_parallel, OMPD_for, 163 OMPD_teams_distribute_parallel_for}, 164 {OMPD_teams_distribute_parallel_for, OMPD_simd, 165 OMPD_teams_distribute_parallel_for_simd}, 166 {OMPD_teams, OMPD_loop, OMPD_teams_loop}, 167 {OMPD_target, OMPD_teams, OMPD_target_teams}, 168 {OMPD_target_teams, OMPD_distribute, OMPD_target_teams_distribute}, 169 {OMPD_target_teams_distribute, OMPD_parallel, 170 OMPD_target_teams_distribute_parallel}, 171 {OMPD_target_teams_distribute, OMPD_simd, 172 OMPD_target_teams_distribute_simd}, 173 {OMPD_target_teams_distribute_parallel, OMPD_for, 174 OMPD_target_teams_distribute_parallel_for}, 175 {OMPD_target_teams_distribute_parallel_for, OMPD_simd, 176 OMPD_target_teams_distribute_parallel_for_simd}, 177 {OMPD_master, OMPD_taskloop, OMPD_master_taskloop}, 178 {OMPD_master_taskloop, OMPD_simd, OMPD_master_taskloop_simd}, 179 {OMPD_parallel, OMPD_master, OMPD_parallel_master}, 180 {OMPD_parallel_master, OMPD_taskloop, OMPD_parallel_master_taskloop}, 181 {OMPD_parallel_master_taskloop, OMPD_simd, 182 OMPD_parallel_master_taskloop_simd}}; 183 enum { CancellationPoint = 0, DeclareReduction = 1, TargetData = 2 }; 184 Token Tok = P.getCurToken(); 185 OpenMPDirectiveKindExWrapper DKind = 186 Tok.isAnnotation() 187 ? static_cast<unsigned>(OMPD_unknown) 188 : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok)); 189 if (DKind == OMPD_unknown) 190 return OMPD_unknown; 191 192 for (unsigned I = 0; I < llvm::array_lengthof(F); ++I) { 193 if (DKind != F[I][0]) 194 continue; 195 196 Tok = P.getPreprocessor().LookAhead(0); 197 OpenMPDirectiveKindExWrapper SDKind = 198 Tok.isAnnotation() 199 ? static_cast<unsigned>(OMPD_unknown) 200 : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok)); 201 if (SDKind == OMPD_unknown) 202 continue; 203 204 if (SDKind == F[I][1]) { 205 P.ConsumeToken(); 206 DKind = F[I][2]; 207 } 208 } 209 return unsigned(DKind) < llvm::omp::Directive_enumSize 210 ? static_cast<OpenMPDirectiveKind>(DKind) 211 : OMPD_unknown; 212 } 213 214 static DeclarationName parseOpenMPReductionId(Parser &P) { 215 Token Tok = P.getCurToken(); 216 Sema &Actions = P.getActions(); 217 OverloadedOperatorKind OOK = OO_None; 218 // Allow to use 'operator' keyword for C++ operators 219 bool WithOperator = false; 220 if (Tok.is(tok::kw_operator)) { 221 P.ConsumeToken(); 222 Tok = P.getCurToken(); 223 WithOperator = true; 224 } 225 switch (Tok.getKind()) { 226 case tok::plus: // '+' 227 OOK = OO_Plus; 228 break; 229 case tok::minus: // '-' 230 OOK = OO_Minus; 231 break; 232 case tok::star: // '*' 233 OOK = OO_Star; 234 break; 235 case tok::amp: // '&' 236 OOK = OO_Amp; 237 break; 238 case tok::pipe: // '|' 239 OOK = OO_Pipe; 240 break; 241 case tok::caret: // '^' 242 OOK = OO_Caret; 243 break; 244 case tok::ampamp: // '&&' 245 OOK = OO_AmpAmp; 246 break; 247 case tok::pipepipe: // '||' 248 OOK = OO_PipePipe; 249 break; 250 case tok::identifier: // identifier 251 if (!WithOperator) 252 break; 253 LLVM_FALLTHROUGH; 254 default: 255 P.Diag(Tok.getLocation(), diag::err_omp_expected_reduction_identifier); 256 P.SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 257 Parser::StopBeforeMatch); 258 return DeclarationName(); 259 } 260 P.ConsumeToken(); 261 auto &DeclNames = Actions.getASTContext().DeclarationNames; 262 return OOK == OO_None ? DeclNames.getIdentifier(Tok.getIdentifierInfo()) 263 : DeclNames.getCXXOperatorName(OOK); 264 } 265 266 /// Parse 'omp declare reduction' construct. 267 /// 268 /// declare-reduction-directive: 269 /// annot_pragma_openmp 'declare' 'reduction' 270 /// '(' <reduction_id> ':' <type> {',' <type>} ':' <expression> ')' 271 /// ['initializer' '(' ('omp_priv' '=' <expression>)|<function_call> ')'] 272 /// annot_pragma_openmp_end 273 /// <reduction_id> is either a base language identifier or one of the following 274 /// operators: '+', '-', '*', '&', '|', '^', '&&' and '||'. 275 /// 276 Parser::DeclGroupPtrTy 277 Parser::ParseOpenMPDeclareReductionDirective(AccessSpecifier AS) { 278 // Parse '('. 279 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 280 if (T.expectAndConsume( 281 diag::err_expected_lparen_after, 282 getOpenMPDirectiveName(OMPD_declare_reduction).data())) { 283 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 284 return DeclGroupPtrTy(); 285 } 286 287 DeclarationName Name = parseOpenMPReductionId(*this); 288 if (Name.isEmpty() && Tok.is(tok::annot_pragma_openmp_end)) 289 return DeclGroupPtrTy(); 290 291 // Consume ':'. 292 bool IsCorrect = !ExpectAndConsume(tok::colon); 293 294 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end)) 295 return DeclGroupPtrTy(); 296 297 IsCorrect = IsCorrect && !Name.isEmpty(); 298 299 if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end)) { 300 Diag(Tok.getLocation(), diag::err_expected_type); 301 IsCorrect = false; 302 } 303 304 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end)) 305 return DeclGroupPtrTy(); 306 307 SmallVector<std::pair<QualType, SourceLocation>, 8> ReductionTypes; 308 // Parse list of types until ':' token. 309 do { 310 ColonProtectionRAIIObject ColonRAII(*this); 311 SourceRange Range; 312 TypeResult TR = ParseTypeName(&Range, DeclaratorContext::Prototype, AS); 313 if (TR.isUsable()) { 314 QualType ReductionType = 315 Actions.ActOnOpenMPDeclareReductionType(Range.getBegin(), TR); 316 if (!ReductionType.isNull()) { 317 ReductionTypes.push_back( 318 std::make_pair(ReductionType, Range.getBegin())); 319 } 320 } else { 321 SkipUntil(tok::comma, tok::colon, tok::annot_pragma_openmp_end, 322 StopBeforeMatch); 323 } 324 325 if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end)) 326 break; 327 328 // Consume ','. 329 if (ExpectAndConsume(tok::comma)) { 330 IsCorrect = false; 331 if (Tok.is(tok::annot_pragma_openmp_end)) { 332 Diag(Tok.getLocation(), diag::err_expected_type); 333 return DeclGroupPtrTy(); 334 } 335 } 336 } while (Tok.isNot(tok::annot_pragma_openmp_end)); 337 338 if (ReductionTypes.empty()) { 339 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 340 return DeclGroupPtrTy(); 341 } 342 343 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end)) 344 return DeclGroupPtrTy(); 345 346 // Consume ':'. 347 if (ExpectAndConsume(tok::colon)) 348 IsCorrect = false; 349 350 if (Tok.is(tok::annot_pragma_openmp_end)) { 351 Diag(Tok.getLocation(), diag::err_expected_expression); 352 return DeclGroupPtrTy(); 353 } 354 355 DeclGroupPtrTy DRD = Actions.ActOnOpenMPDeclareReductionDirectiveStart( 356 getCurScope(), Actions.getCurLexicalContext(), Name, ReductionTypes, AS); 357 358 // Parse <combiner> expression and then parse initializer if any for each 359 // correct type. 360 unsigned I = 0, E = ReductionTypes.size(); 361 for (Decl *D : DRD.get()) { 362 TentativeParsingAction TPA(*this); 363 ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope | 364 Scope::CompoundStmtScope | 365 Scope::OpenMPDirectiveScope); 366 // Parse <combiner> expression. 367 Actions.ActOnOpenMPDeclareReductionCombinerStart(getCurScope(), D); 368 ExprResult CombinerResult = Actions.ActOnFinishFullExpr( 369 ParseExpression().get(), D->getLocation(), /*DiscardedValue*/ false); 370 Actions.ActOnOpenMPDeclareReductionCombinerEnd(D, CombinerResult.get()); 371 372 if (CombinerResult.isInvalid() && Tok.isNot(tok::r_paren) && 373 Tok.isNot(tok::annot_pragma_openmp_end)) { 374 TPA.Commit(); 375 IsCorrect = false; 376 break; 377 } 378 IsCorrect = !T.consumeClose() && IsCorrect && CombinerResult.isUsable(); 379 ExprResult InitializerResult; 380 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 381 // Parse <initializer> expression. 382 if (Tok.is(tok::identifier) && 383 Tok.getIdentifierInfo()->isStr("initializer")) { 384 ConsumeToken(); 385 } else { 386 Diag(Tok.getLocation(), diag::err_expected) << "'initializer'"; 387 TPA.Commit(); 388 IsCorrect = false; 389 break; 390 } 391 // Parse '('. 392 BalancedDelimiterTracker T(*this, tok::l_paren, 393 tok::annot_pragma_openmp_end); 394 IsCorrect = 395 !T.expectAndConsume(diag::err_expected_lparen_after, "initializer") && 396 IsCorrect; 397 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 398 ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope | 399 Scope::CompoundStmtScope | 400 Scope::OpenMPDirectiveScope); 401 // Parse expression. 402 VarDecl *OmpPrivParm = 403 Actions.ActOnOpenMPDeclareReductionInitializerStart(getCurScope(), 404 D); 405 // Check if initializer is omp_priv <init_expr> or something else. 406 if (Tok.is(tok::identifier) && 407 Tok.getIdentifierInfo()->isStr("omp_priv")) { 408 ConsumeToken(); 409 ParseOpenMPReductionInitializerForDecl(OmpPrivParm); 410 } else { 411 InitializerResult = Actions.ActOnFinishFullExpr( 412 ParseAssignmentExpression().get(), D->getLocation(), 413 /*DiscardedValue*/ false); 414 } 415 Actions.ActOnOpenMPDeclareReductionInitializerEnd( 416 D, InitializerResult.get(), OmpPrivParm); 417 if (InitializerResult.isInvalid() && Tok.isNot(tok::r_paren) && 418 Tok.isNot(tok::annot_pragma_openmp_end)) { 419 TPA.Commit(); 420 IsCorrect = false; 421 break; 422 } 423 IsCorrect = 424 !T.consumeClose() && IsCorrect && !InitializerResult.isInvalid(); 425 } 426 } 427 428 ++I; 429 // Revert parsing if not the last type, otherwise accept it, we're done with 430 // parsing. 431 if (I != E) 432 TPA.Revert(); 433 else 434 TPA.Commit(); 435 } 436 return Actions.ActOnOpenMPDeclareReductionDirectiveEnd(getCurScope(), DRD, 437 IsCorrect); 438 } 439 440 void Parser::ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm) { 441 // Parse declarator '=' initializer. 442 // If a '==' or '+=' is found, suggest a fixit to '='. 443 if (isTokenEqualOrEqualTypo()) { 444 ConsumeToken(); 445 446 if (Tok.is(tok::code_completion)) { 447 cutOffParsing(); 448 Actions.CodeCompleteInitializer(getCurScope(), OmpPrivParm); 449 Actions.FinalizeDeclaration(OmpPrivParm); 450 return; 451 } 452 453 PreferredType.enterVariableInit(Tok.getLocation(), OmpPrivParm); 454 ExprResult Init = ParseInitializer(); 455 456 if (Init.isInvalid()) { 457 SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch); 458 Actions.ActOnInitializerError(OmpPrivParm); 459 } else { 460 Actions.AddInitializerToDecl(OmpPrivParm, Init.get(), 461 /*DirectInit=*/false); 462 } 463 } else if (Tok.is(tok::l_paren)) { 464 // Parse C++ direct initializer: '(' expression-list ')' 465 BalancedDelimiterTracker T(*this, tok::l_paren); 466 T.consumeOpen(); 467 468 ExprVector Exprs; 469 CommaLocsTy CommaLocs; 470 471 SourceLocation LParLoc = T.getOpenLocation(); 472 auto RunSignatureHelp = [this, OmpPrivParm, LParLoc, &Exprs]() { 473 QualType PreferredType = Actions.ProduceConstructorSignatureHelp( 474 OmpPrivParm->getType()->getCanonicalTypeInternal(), 475 OmpPrivParm->getLocation(), Exprs, LParLoc, /*Braced=*/false); 476 CalledSignatureHelp = true; 477 return PreferredType; 478 }; 479 if (ParseExpressionList(Exprs, CommaLocs, [&] { 480 PreferredType.enterFunctionArgument(Tok.getLocation(), 481 RunSignatureHelp); 482 })) { 483 if (PP.isCodeCompletionReached() && !CalledSignatureHelp) 484 RunSignatureHelp(); 485 Actions.ActOnInitializerError(OmpPrivParm); 486 SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch); 487 } else { 488 // Match the ')'. 489 SourceLocation RLoc = Tok.getLocation(); 490 if (!T.consumeClose()) 491 RLoc = T.getCloseLocation(); 492 493 assert(!Exprs.empty() && Exprs.size() - 1 == CommaLocs.size() && 494 "Unexpected number of commas!"); 495 496 ExprResult Initializer = 497 Actions.ActOnParenListExpr(T.getOpenLocation(), RLoc, Exprs); 498 Actions.AddInitializerToDecl(OmpPrivParm, Initializer.get(), 499 /*DirectInit=*/true); 500 } 501 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 502 // Parse C++0x braced-init-list. 503 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 504 505 ExprResult Init(ParseBraceInitializer()); 506 507 if (Init.isInvalid()) { 508 Actions.ActOnInitializerError(OmpPrivParm); 509 } else { 510 Actions.AddInitializerToDecl(OmpPrivParm, Init.get(), 511 /*DirectInit=*/true); 512 } 513 } else { 514 Actions.ActOnUninitializedDecl(OmpPrivParm); 515 } 516 } 517 518 /// Parses 'omp declare mapper' directive. 519 /// 520 /// declare-mapper-directive: 521 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifier> ':'] 522 /// <type> <var> ')' [<clause>[[,] <clause>] ... ] 523 /// annot_pragma_openmp_end 524 /// <mapper-identifier> and <var> are base language identifiers. 525 /// 526 Parser::DeclGroupPtrTy 527 Parser::ParseOpenMPDeclareMapperDirective(AccessSpecifier AS) { 528 bool IsCorrect = true; 529 // Parse '(' 530 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 531 if (T.expectAndConsume(diag::err_expected_lparen_after, 532 getOpenMPDirectiveName(OMPD_declare_mapper).data())) { 533 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 534 return DeclGroupPtrTy(); 535 } 536 537 // Parse <mapper-identifier> 538 auto &DeclNames = Actions.getASTContext().DeclarationNames; 539 DeclarationName MapperId; 540 if (PP.LookAhead(0).is(tok::colon)) { 541 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) { 542 Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier); 543 IsCorrect = false; 544 } else { 545 MapperId = DeclNames.getIdentifier(Tok.getIdentifierInfo()); 546 } 547 ConsumeToken(); 548 // Consume ':'. 549 ExpectAndConsume(tok::colon); 550 } else { 551 // If no mapper identifier is provided, its name is "default" by default 552 MapperId = 553 DeclNames.getIdentifier(&Actions.getASTContext().Idents.get("default")); 554 } 555 556 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end)) 557 return DeclGroupPtrTy(); 558 559 // Parse <type> <var> 560 DeclarationName VName; 561 QualType MapperType; 562 SourceRange Range; 563 TypeResult ParsedType = parseOpenMPDeclareMapperVarDecl(Range, VName, AS); 564 if (ParsedType.isUsable()) 565 MapperType = 566 Actions.ActOnOpenMPDeclareMapperType(Range.getBegin(), ParsedType); 567 if (MapperType.isNull()) 568 IsCorrect = false; 569 if (!IsCorrect) { 570 SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch); 571 return DeclGroupPtrTy(); 572 } 573 574 // Consume ')'. 575 IsCorrect &= !T.consumeClose(); 576 if (!IsCorrect) { 577 SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch); 578 return DeclGroupPtrTy(); 579 } 580 581 // Enter scope. 582 DeclarationNameInfo DirName; 583 SourceLocation Loc = Tok.getLocation(); 584 unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope | 585 Scope::CompoundStmtScope | Scope::OpenMPDirectiveScope; 586 ParseScope OMPDirectiveScope(this, ScopeFlags); 587 Actions.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, getCurScope(), Loc); 588 589 // Add the mapper variable declaration. 590 ExprResult MapperVarRef = Actions.ActOnOpenMPDeclareMapperDirectiveVarDecl( 591 getCurScope(), MapperType, Range.getBegin(), VName); 592 593 // Parse map clauses. 594 SmallVector<OMPClause *, 6> Clauses; 595 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 596 OpenMPClauseKind CKind = Tok.isAnnotation() 597 ? OMPC_unknown 598 : getOpenMPClauseKind(PP.getSpelling(Tok)); 599 Actions.StartOpenMPClause(CKind); 600 OMPClause *Clause = 601 ParseOpenMPClause(OMPD_declare_mapper, CKind, Clauses.empty()); 602 if (Clause) 603 Clauses.push_back(Clause); 604 else 605 IsCorrect = false; 606 // Skip ',' if any. 607 if (Tok.is(tok::comma)) 608 ConsumeToken(); 609 Actions.EndOpenMPClause(); 610 } 611 if (Clauses.empty()) { 612 Diag(Tok, diag::err_omp_expected_clause) 613 << getOpenMPDirectiveName(OMPD_declare_mapper); 614 IsCorrect = false; 615 } 616 617 // Exit scope. 618 Actions.EndOpenMPDSABlock(nullptr); 619 OMPDirectiveScope.Exit(); 620 DeclGroupPtrTy DG = Actions.ActOnOpenMPDeclareMapperDirective( 621 getCurScope(), Actions.getCurLexicalContext(), MapperId, MapperType, 622 Range.getBegin(), VName, AS, MapperVarRef.get(), Clauses); 623 if (!IsCorrect) 624 return DeclGroupPtrTy(); 625 626 return DG; 627 } 628 629 TypeResult Parser::parseOpenMPDeclareMapperVarDecl(SourceRange &Range, 630 DeclarationName &Name, 631 AccessSpecifier AS) { 632 // Parse the common declaration-specifiers piece. 633 Parser::DeclSpecContext DSC = Parser::DeclSpecContext::DSC_type_specifier; 634 DeclSpec DS(AttrFactory); 635 ParseSpecifierQualifierList(DS, AS, DSC); 636 637 // Parse the declarator. 638 DeclaratorContext Context = DeclaratorContext::Prototype; 639 Declarator DeclaratorInfo(DS, Context); 640 ParseDeclarator(DeclaratorInfo); 641 Range = DeclaratorInfo.getSourceRange(); 642 if (DeclaratorInfo.getIdentifier() == nullptr) { 643 Diag(Tok.getLocation(), diag::err_omp_mapper_expected_declarator); 644 return true; 645 } 646 Name = Actions.GetNameForDeclarator(DeclaratorInfo).getName(); 647 648 return Actions.ActOnOpenMPDeclareMapperVarDecl(getCurScope(), DeclaratorInfo); 649 } 650 651 namespace { 652 /// RAII that recreates function context for correct parsing of clauses of 653 /// 'declare simd' construct. 654 /// OpenMP, 2.8.2 declare simd Construct 655 /// The expressions appearing in the clauses of this directive are evaluated in 656 /// the scope of the arguments of the function declaration or definition. 657 class FNContextRAII final { 658 Parser &P; 659 Sema::CXXThisScopeRAII *ThisScope; 660 Parser::MultiParseScope Scopes; 661 bool HasFunScope = false; 662 FNContextRAII() = delete; 663 FNContextRAII(const FNContextRAII &) = delete; 664 FNContextRAII &operator=(const FNContextRAII &) = delete; 665 666 public: 667 FNContextRAII(Parser &P, Parser::DeclGroupPtrTy Ptr) : P(P), Scopes(P) { 668 Decl *D = *Ptr.get().begin(); 669 NamedDecl *ND = dyn_cast<NamedDecl>(D); 670 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext()); 671 Sema &Actions = P.getActions(); 672 673 // Allow 'this' within late-parsed attributes. 674 ThisScope = new Sema::CXXThisScopeRAII(Actions, RD, Qualifiers(), 675 ND && ND->isCXXInstanceMember()); 676 677 // If the Decl is templatized, add template parameters to scope. 678 // FIXME: Track CurTemplateDepth? 679 P.ReenterTemplateScopes(Scopes, D); 680 681 // If the Decl is on a function, add function parameters to the scope. 682 if (D->isFunctionOrFunctionTemplate()) { 683 HasFunScope = true; 684 Scopes.Enter(Scope::FnScope | Scope::DeclScope | 685 Scope::CompoundStmtScope); 686 Actions.ActOnReenterFunctionContext(Actions.getCurScope(), D); 687 } 688 } 689 ~FNContextRAII() { 690 if (HasFunScope) 691 P.getActions().ActOnExitFunctionContext(); 692 delete ThisScope; 693 } 694 }; 695 } // namespace 696 697 /// Parses clauses for 'declare simd' directive. 698 /// clause: 699 /// 'inbranch' | 'notinbranch' 700 /// 'simdlen' '(' <expr> ')' 701 /// { 'uniform' '(' <argument_list> ')' } 702 /// { 'aligned '(' <argument_list> [ ':' <alignment> ] ')' } 703 /// { 'linear '(' <argument_list> [ ':' <step> ] ')' } 704 static bool parseDeclareSimdClauses( 705 Parser &P, OMPDeclareSimdDeclAttr::BranchStateTy &BS, ExprResult &SimdLen, 706 SmallVectorImpl<Expr *> &Uniforms, SmallVectorImpl<Expr *> &Aligneds, 707 SmallVectorImpl<Expr *> &Alignments, SmallVectorImpl<Expr *> &Linears, 708 SmallVectorImpl<unsigned> &LinModifiers, SmallVectorImpl<Expr *> &Steps) { 709 SourceRange BSRange; 710 const Token &Tok = P.getCurToken(); 711 bool IsError = false; 712 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 713 if (Tok.isNot(tok::identifier)) 714 break; 715 OMPDeclareSimdDeclAttr::BranchStateTy Out; 716 IdentifierInfo *II = Tok.getIdentifierInfo(); 717 StringRef ClauseName = II->getName(); 718 // Parse 'inranch|notinbranch' clauses. 719 if (OMPDeclareSimdDeclAttr::ConvertStrToBranchStateTy(ClauseName, Out)) { 720 if (BS != OMPDeclareSimdDeclAttr::BS_Undefined && BS != Out) { 721 P.Diag(Tok, diag::err_omp_declare_simd_inbranch_notinbranch) 722 << ClauseName 723 << OMPDeclareSimdDeclAttr::ConvertBranchStateTyToStr(BS) << BSRange; 724 IsError = true; 725 } 726 BS = Out; 727 BSRange = SourceRange(Tok.getLocation(), Tok.getEndLoc()); 728 P.ConsumeToken(); 729 } else if (ClauseName.equals("simdlen")) { 730 if (SimdLen.isUsable()) { 731 P.Diag(Tok, diag::err_omp_more_one_clause) 732 << getOpenMPDirectiveName(OMPD_declare_simd) << ClauseName << 0; 733 IsError = true; 734 } 735 P.ConsumeToken(); 736 SourceLocation RLoc; 737 SimdLen = P.ParseOpenMPParensExpr(ClauseName, RLoc); 738 if (SimdLen.isInvalid()) 739 IsError = true; 740 } else { 741 OpenMPClauseKind CKind = getOpenMPClauseKind(ClauseName); 742 if (CKind == OMPC_uniform || CKind == OMPC_aligned || 743 CKind == OMPC_linear) { 744 Parser::OpenMPVarListDataTy Data; 745 SmallVectorImpl<Expr *> *Vars = &Uniforms; 746 if (CKind == OMPC_aligned) { 747 Vars = &Aligneds; 748 } else if (CKind == OMPC_linear) { 749 Data.ExtraModifier = OMPC_LINEAR_val; 750 Vars = &Linears; 751 } 752 753 P.ConsumeToken(); 754 if (P.ParseOpenMPVarList(OMPD_declare_simd, 755 getOpenMPClauseKind(ClauseName), *Vars, Data)) 756 IsError = true; 757 if (CKind == OMPC_aligned) { 758 Alignments.append(Aligneds.size() - Alignments.size(), 759 Data.DepModOrTailExpr); 760 } else if (CKind == OMPC_linear) { 761 assert(0 <= Data.ExtraModifier && 762 Data.ExtraModifier <= OMPC_LINEAR_unknown && 763 "Unexpected linear modifier."); 764 if (P.getActions().CheckOpenMPLinearModifier( 765 static_cast<OpenMPLinearClauseKind>(Data.ExtraModifier), 766 Data.ExtraModifierLoc)) 767 Data.ExtraModifier = OMPC_LINEAR_val; 768 LinModifiers.append(Linears.size() - LinModifiers.size(), 769 Data.ExtraModifier); 770 Steps.append(Linears.size() - Steps.size(), Data.DepModOrTailExpr); 771 } 772 } else 773 // TODO: add parsing of other clauses. 774 break; 775 } 776 // Skip ',' if any. 777 if (Tok.is(tok::comma)) 778 P.ConsumeToken(); 779 } 780 return IsError; 781 } 782 783 /// Parse clauses for '#pragma omp declare simd'. 784 Parser::DeclGroupPtrTy 785 Parser::ParseOMPDeclareSimdClauses(Parser::DeclGroupPtrTy Ptr, 786 CachedTokens &Toks, SourceLocation Loc) { 787 PP.EnterToken(Tok, /*IsReinject*/ true); 788 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true, 789 /*IsReinject*/ true); 790 // Consume the previously pushed token. 791 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 792 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 793 794 FNContextRAII FnContext(*this, Ptr); 795 OMPDeclareSimdDeclAttr::BranchStateTy BS = 796 OMPDeclareSimdDeclAttr::BS_Undefined; 797 ExprResult Simdlen; 798 SmallVector<Expr *, 4> Uniforms; 799 SmallVector<Expr *, 4> Aligneds; 800 SmallVector<Expr *, 4> Alignments; 801 SmallVector<Expr *, 4> Linears; 802 SmallVector<unsigned, 4> LinModifiers; 803 SmallVector<Expr *, 4> Steps; 804 bool IsError = 805 parseDeclareSimdClauses(*this, BS, Simdlen, Uniforms, Aligneds, 806 Alignments, Linears, LinModifiers, Steps); 807 skipUntilPragmaOpenMPEnd(OMPD_declare_simd); 808 // Skip the last annot_pragma_openmp_end. 809 SourceLocation EndLoc = ConsumeAnnotationToken(); 810 if (IsError) 811 return Ptr; 812 return Actions.ActOnOpenMPDeclareSimdDirective( 813 Ptr, BS, Simdlen.get(), Uniforms, Aligneds, Alignments, Linears, 814 LinModifiers, Steps, SourceRange(Loc, EndLoc)); 815 } 816 817 namespace { 818 /// Constant used in the diagnostics to distinguish the levels in an OpenMP 819 /// contexts: selector-set={selector(trait, ...), ...}, .... 820 enum OMPContextLvl { 821 CONTEXT_SELECTOR_SET_LVL = 0, 822 CONTEXT_SELECTOR_LVL = 1, 823 CONTEXT_TRAIT_LVL = 2, 824 }; 825 826 static StringRef stringLiteralParser(Parser &P) { 827 ExprResult Res = P.ParseStringLiteralExpression(true); 828 return Res.isUsable() ? Res.getAs<StringLiteral>()->getString() : ""; 829 } 830 831 static StringRef getNameFromIdOrString(Parser &P, Token &Tok, 832 OMPContextLvl Lvl) { 833 if (Tok.is(tok::identifier) || Tok.is(tok::kw_for)) { 834 llvm::SmallString<16> Buffer; 835 StringRef Name = P.getPreprocessor().getSpelling(Tok, Buffer); 836 (void)P.ConsumeToken(); 837 return Name; 838 } 839 840 if (tok::isStringLiteral(Tok.getKind())) 841 return stringLiteralParser(P); 842 843 P.Diag(Tok.getLocation(), 844 diag::warn_omp_declare_variant_string_literal_or_identifier) 845 << Lvl; 846 return ""; 847 } 848 849 static bool checkForDuplicates(Parser &P, StringRef Name, 850 SourceLocation NameLoc, 851 llvm::StringMap<SourceLocation> &Seen, 852 OMPContextLvl Lvl) { 853 auto Res = Seen.try_emplace(Name, NameLoc); 854 if (Res.second) 855 return false; 856 857 // Each trait-set-selector-name, trait-selector-name and trait-name can 858 // only be specified once. 859 P.Diag(NameLoc, diag::warn_omp_declare_variant_ctx_mutiple_use) 860 << Lvl << Name; 861 P.Diag(Res.first->getValue(), diag::note_omp_declare_variant_ctx_used_here) 862 << Lvl << Name; 863 return true; 864 } 865 } // namespace 866 867 void Parser::parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty, 868 llvm::omp::TraitSet Set, 869 llvm::omp::TraitSelector Selector, 870 llvm::StringMap<SourceLocation> &Seen) { 871 TIProperty.Kind = TraitProperty::invalid; 872 873 SourceLocation NameLoc = Tok.getLocation(); 874 StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_TRAIT_LVL); 875 if (Name.empty()) { 876 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options) 877 << CONTEXT_TRAIT_LVL << listOpenMPContextTraitProperties(Set, Selector); 878 return; 879 } 880 881 TIProperty.RawString = Name; 882 TIProperty.Kind = getOpenMPContextTraitPropertyKind(Set, Selector, Name); 883 if (TIProperty.Kind != TraitProperty::invalid) { 884 if (checkForDuplicates(*this, Name, NameLoc, Seen, CONTEXT_TRAIT_LVL)) 885 TIProperty.Kind = TraitProperty::invalid; 886 return; 887 } 888 889 // It follows diagnosis and helping notes. 890 // FIXME: We should move the diagnosis string generation into libFrontend. 891 Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_property) 892 << Name << getOpenMPContextTraitSelectorName(Selector) 893 << getOpenMPContextTraitSetName(Set); 894 895 TraitSet SetForName = getOpenMPContextTraitSetKind(Name); 896 if (SetForName != TraitSet::invalid) { 897 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a) 898 << Name << CONTEXT_SELECTOR_SET_LVL << CONTEXT_TRAIT_LVL; 899 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try) 900 << Name << "<selector-name>" 901 << "(<property-name>)"; 902 return; 903 } 904 TraitSelector SelectorForName = getOpenMPContextTraitSelectorKind(Name); 905 if (SelectorForName != TraitSelector::invalid) { 906 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a) 907 << Name << CONTEXT_SELECTOR_LVL << CONTEXT_TRAIT_LVL; 908 bool AllowsTraitScore = false; 909 bool RequiresProperty = false; 910 isValidTraitSelectorForTraitSet( 911 SelectorForName, getOpenMPContextTraitSetForSelector(SelectorForName), 912 AllowsTraitScore, RequiresProperty); 913 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try) 914 << getOpenMPContextTraitSetName( 915 getOpenMPContextTraitSetForSelector(SelectorForName)) 916 << Name << (RequiresProperty ? "(<property-name>)" : ""); 917 return; 918 } 919 for (const auto &PotentialSet : 920 {TraitSet::construct, TraitSet::user, TraitSet::implementation, 921 TraitSet::device}) { 922 TraitProperty PropertyForName = 923 getOpenMPContextTraitPropertyKind(PotentialSet, Selector, Name); 924 if (PropertyForName == TraitProperty::invalid) 925 continue; 926 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try) 927 << getOpenMPContextTraitSetName( 928 getOpenMPContextTraitSetForProperty(PropertyForName)) 929 << getOpenMPContextTraitSelectorName( 930 getOpenMPContextTraitSelectorForProperty(PropertyForName)) 931 << ("(" + Name + ")").str(); 932 return; 933 } 934 Diag(NameLoc, diag::note_omp_declare_variant_ctx_options) 935 << CONTEXT_TRAIT_LVL << listOpenMPContextTraitProperties(Set, Selector); 936 } 937 938 static bool checkExtensionProperty(Parser &P, SourceLocation Loc, 939 OMPTraitProperty &TIProperty, 940 OMPTraitSelector &TISelector, 941 llvm::StringMap<SourceLocation> &Seen) { 942 assert(TISelector.Kind == 943 llvm::omp::TraitSelector::implementation_extension && 944 "Only for extension properties, e.g., " 945 "`implementation={extension(PROPERTY)}`"); 946 if (TIProperty.Kind == TraitProperty::invalid) 947 return false; 948 949 if (TIProperty.Kind == 950 TraitProperty::implementation_extension_disable_implicit_base) 951 return true; 952 953 if (TIProperty.Kind == 954 TraitProperty::implementation_extension_allow_templates) 955 return true; 956 957 auto IsMatchExtension = [](OMPTraitProperty &TP) { 958 return (TP.Kind == 959 llvm::omp::TraitProperty::implementation_extension_match_all || 960 TP.Kind == 961 llvm::omp::TraitProperty::implementation_extension_match_any || 962 TP.Kind == 963 llvm::omp::TraitProperty::implementation_extension_match_none); 964 }; 965 966 if (IsMatchExtension(TIProperty)) { 967 for (OMPTraitProperty &SeenProp : TISelector.Properties) 968 if (IsMatchExtension(SeenProp)) { 969 P.Diag(Loc, diag::err_omp_variant_ctx_second_match_extension); 970 StringRef SeenName = llvm::omp::getOpenMPContextTraitPropertyName( 971 SeenProp.Kind, SeenProp.RawString); 972 SourceLocation SeenLoc = Seen[SeenName]; 973 P.Diag(SeenLoc, diag::note_omp_declare_variant_ctx_used_here) 974 << CONTEXT_TRAIT_LVL << SeenName; 975 return false; 976 } 977 return true; 978 } 979 980 llvm_unreachable("Unknown extension property!"); 981 } 982 983 void Parser::parseOMPContextProperty(OMPTraitSelector &TISelector, 984 llvm::omp::TraitSet Set, 985 llvm::StringMap<SourceLocation> &Seen) { 986 assert(TISelector.Kind != TraitSelector::user_condition && 987 "User conditions are special properties not handled here!"); 988 989 SourceLocation PropertyLoc = Tok.getLocation(); 990 OMPTraitProperty TIProperty; 991 parseOMPTraitPropertyKind(TIProperty, Set, TISelector.Kind, Seen); 992 993 if (TISelector.Kind == llvm::omp::TraitSelector::implementation_extension) 994 if (!checkExtensionProperty(*this, Tok.getLocation(), TIProperty, 995 TISelector, Seen)) 996 TIProperty.Kind = TraitProperty::invalid; 997 998 // If we have an invalid property here we already issued a warning. 999 if (TIProperty.Kind == TraitProperty::invalid) { 1000 if (PropertyLoc != Tok.getLocation()) 1001 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here) 1002 << CONTEXT_TRAIT_LVL; 1003 return; 1004 } 1005 1006 if (isValidTraitPropertyForTraitSetAndSelector(TIProperty.Kind, 1007 TISelector.Kind, Set)) { 1008 1009 // If we make it here the property, selector, set, score, condition, ... are 1010 // all valid (or have been corrected). Thus we can record the property. 1011 TISelector.Properties.push_back(TIProperty); 1012 return; 1013 } 1014 1015 Diag(PropertyLoc, diag::warn_omp_ctx_incompatible_property_for_selector) 1016 << getOpenMPContextTraitPropertyName(TIProperty.Kind, 1017 TIProperty.RawString) 1018 << getOpenMPContextTraitSelectorName(TISelector.Kind) 1019 << getOpenMPContextTraitSetName(Set); 1020 Diag(PropertyLoc, diag::note_omp_ctx_compatible_set_and_selector_for_property) 1021 << getOpenMPContextTraitPropertyName(TIProperty.Kind, 1022 TIProperty.RawString) 1023 << getOpenMPContextTraitSelectorName( 1024 getOpenMPContextTraitSelectorForProperty(TIProperty.Kind)) 1025 << getOpenMPContextTraitSetName( 1026 getOpenMPContextTraitSetForProperty(TIProperty.Kind)); 1027 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here) 1028 << CONTEXT_TRAIT_LVL; 1029 } 1030 1031 void Parser::parseOMPTraitSelectorKind(OMPTraitSelector &TISelector, 1032 llvm::omp::TraitSet Set, 1033 llvm::StringMap<SourceLocation> &Seen) { 1034 TISelector.Kind = TraitSelector::invalid; 1035 1036 SourceLocation NameLoc = Tok.getLocation(); 1037 StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_SELECTOR_LVL); 1038 if (Name.empty()) { 1039 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options) 1040 << CONTEXT_SELECTOR_LVL << listOpenMPContextTraitSelectors(Set); 1041 return; 1042 } 1043 1044 TISelector.Kind = getOpenMPContextTraitSelectorKind(Name); 1045 if (TISelector.Kind != TraitSelector::invalid) { 1046 if (checkForDuplicates(*this, Name, NameLoc, Seen, CONTEXT_SELECTOR_LVL)) 1047 TISelector.Kind = TraitSelector::invalid; 1048 return; 1049 } 1050 1051 // It follows diagnosis and helping notes. 1052 Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_selector) 1053 << Name << getOpenMPContextTraitSetName(Set); 1054 1055 TraitSet SetForName = getOpenMPContextTraitSetKind(Name); 1056 if (SetForName != TraitSet::invalid) { 1057 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a) 1058 << Name << CONTEXT_SELECTOR_SET_LVL << CONTEXT_SELECTOR_LVL; 1059 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try) 1060 << Name << "<selector-name>" 1061 << "<property-name>"; 1062 return; 1063 } 1064 for (const auto &PotentialSet : 1065 {TraitSet::construct, TraitSet::user, TraitSet::implementation, 1066 TraitSet::device}) { 1067 TraitProperty PropertyForName = getOpenMPContextTraitPropertyKind( 1068 PotentialSet, TraitSelector::invalid, Name); 1069 if (PropertyForName == TraitProperty::invalid) 1070 continue; 1071 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a) 1072 << Name << CONTEXT_TRAIT_LVL << CONTEXT_SELECTOR_LVL; 1073 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try) 1074 << getOpenMPContextTraitSetName( 1075 getOpenMPContextTraitSetForProperty(PropertyForName)) 1076 << getOpenMPContextTraitSelectorName( 1077 getOpenMPContextTraitSelectorForProperty(PropertyForName)) 1078 << ("(" + Name + ")").str(); 1079 return; 1080 } 1081 Diag(NameLoc, diag::note_omp_declare_variant_ctx_options) 1082 << CONTEXT_SELECTOR_LVL << listOpenMPContextTraitSelectors(Set); 1083 } 1084 1085 /// Parse optional 'score' '(' <expr> ')' ':'. 1086 static ExprResult parseContextScore(Parser &P) { 1087 ExprResult ScoreExpr; 1088 llvm::SmallString<16> Buffer; 1089 StringRef SelectorName = 1090 P.getPreprocessor().getSpelling(P.getCurToken(), Buffer); 1091 if (!SelectorName.equals("score")) 1092 return ScoreExpr; 1093 (void)P.ConsumeToken(); 1094 SourceLocation RLoc; 1095 ScoreExpr = P.ParseOpenMPParensExpr(SelectorName, RLoc); 1096 // Parse ':' 1097 if (P.getCurToken().is(tok::colon)) 1098 (void)P.ConsumeAnyToken(); 1099 else 1100 P.Diag(P.getCurToken(), diag::warn_omp_declare_variant_expected) 1101 << "':'" 1102 << "score expression"; 1103 return ScoreExpr; 1104 } 1105 1106 /// Parses an OpenMP context selector. 1107 /// 1108 /// <trait-selector-name> ['('[<trait-score>] <trait-property> [, <t-p>]* ')'] 1109 void Parser::parseOMPContextSelector( 1110 OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, 1111 llvm::StringMap<SourceLocation> &SeenSelectors) { 1112 unsigned short OuterPC = ParenCount; 1113 1114 // If anything went wrong we issue an error or warning and then skip the rest 1115 // of the selector. However, commas are ambiguous so we look for the nesting 1116 // of parentheses here as well. 1117 auto FinishSelector = [OuterPC, this]() -> void { 1118 bool Done = false; 1119 while (!Done) { 1120 while (!SkipUntil({tok::r_brace, tok::r_paren, tok::comma, 1121 tok::annot_pragma_openmp_end}, 1122 StopBeforeMatch)) 1123 ; 1124 if (Tok.is(tok::r_paren) && OuterPC > ParenCount) 1125 (void)ConsumeParen(); 1126 if (OuterPC <= ParenCount) { 1127 Done = true; 1128 break; 1129 } 1130 if (!Tok.is(tok::comma) && !Tok.is(tok::r_paren)) { 1131 Done = true; 1132 break; 1133 } 1134 (void)ConsumeAnyToken(); 1135 } 1136 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here) 1137 << CONTEXT_SELECTOR_LVL; 1138 }; 1139 1140 SourceLocation SelectorLoc = Tok.getLocation(); 1141 parseOMPTraitSelectorKind(TISelector, Set, SeenSelectors); 1142 if (TISelector.Kind == TraitSelector::invalid) 1143 return FinishSelector(); 1144 1145 bool AllowsTraitScore = false; 1146 bool RequiresProperty = false; 1147 if (!isValidTraitSelectorForTraitSet(TISelector.Kind, Set, AllowsTraitScore, 1148 RequiresProperty)) { 1149 Diag(SelectorLoc, diag::warn_omp_ctx_incompatible_selector_for_set) 1150 << getOpenMPContextTraitSelectorName(TISelector.Kind) 1151 << getOpenMPContextTraitSetName(Set); 1152 Diag(SelectorLoc, diag::note_omp_ctx_compatible_set_for_selector) 1153 << getOpenMPContextTraitSelectorName(TISelector.Kind) 1154 << getOpenMPContextTraitSetName( 1155 getOpenMPContextTraitSetForSelector(TISelector.Kind)) 1156 << RequiresProperty; 1157 return FinishSelector(); 1158 } 1159 1160 if (!RequiresProperty) { 1161 TISelector.Properties.push_back( 1162 {getOpenMPContextTraitPropertyForSelector(TISelector.Kind), 1163 getOpenMPContextTraitSelectorName(TISelector.Kind)}); 1164 return; 1165 } 1166 1167 if (!Tok.is(tok::l_paren)) { 1168 Diag(SelectorLoc, diag::warn_omp_ctx_selector_without_properties) 1169 << getOpenMPContextTraitSelectorName(TISelector.Kind) 1170 << getOpenMPContextTraitSetName(Set); 1171 return FinishSelector(); 1172 } 1173 1174 if (TISelector.Kind == TraitSelector::user_condition) { 1175 SourceLocation RLoc; 1176 ExprResult Condition = ParseOpenMPParensExpr("user condition", RLoc); 1177 if (!Condition.isUsable()) 1178 return FinishSelector(); 1179 TISelector.ScoreOrCondition = Condition.get(); 1180 TISelector.Properties.push_back( 1181 {TraitProperty::user_condition_unknown, "<condition>"}); 1182 return; 1183 } 1184 1185 BalancedDelimiterTracker BDT(*this, tok::l_paren, 1186 tok::annot_pragma_openmp_end); 1187 // Parse '('. 1188 (void)BDT.consumeOpen(); 1189 1190 SourceLocation ScoreLoc = Tok.getLocation(); 1191 ExprResult Score = parseContextScore(*this); 1192 1193 if (!AllowsTraitScore && !Score.isUnset()) { 1194 if (Score.isUsable()) { 1195 Diag(ScoreLoc, diag::warn_omp_ctx_incompatible_score_for_property) 1196 << getOpenMPContextTraitSelectorName(TISelector.Kind) 1197 << getOpenMPContextTraitSetName(Set) << Score.get(); 1198 } else { 1199 Diag(ScoreLoc, diag::warn_omp_ctx_incompatible_score_for_property) 1200 << getOpenMPContextTraitSelectorName(TISelector.Kind) 1201 << getOpenMPContextTraitSetName(Set) << "<invalid>"; 1202 } 1203 Score = ExprResult(); 1204 } 1205 1206 if (Score.isUsable()) 1207 TISelector.ScoreOrCondition = Score.get(); 1208 1209 llvm::StringMap<SourceLocation> SeenProperties; 1210 do { 1211 parseOMPContextProperty(TISelector, Set, SeenProperties); 1212 } while (TryConsumeToken(tok::comma)); 1213 1214 // Parse ')'. 1215 BDT.consumeClose(); 1216 } 1217 1218 void Parser::parseOMPTraitSetKind(OMPTraitSet &TISet, 1219 llvm::StringMap<SourceLocation> &Seen) { 1220 TISet.Kind = TraitSet::invalid; 1221 1222 SourceLocation NameLoc = Tok.getLocation(); 1223 StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_SELECTOR_SET_LVL); 1224 if (Name.empty()) { 1225 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options) 1226 << CONTEXT_SELECTOR_SET_LVL << listOpenMPContextTraitSets(); 1227 return; 1228 } 1229 1230 TISet.Kind = getOpenMPContextTraitSetKind(Name); 1231 if (TISet.Kind != TraitSet::invalid) { 1232 if (checkForDuplicates(*this, Name, NameLoc, Seen, 1233 CONTEXT_SELECTOR_SET_LVL)) 1234 TISet.Kind = TraitSet::invalid; 1235 return; 1236 } 1237 1238 // It follows diagnosis and helping notes. 1239 Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_set) << Name; 1240 1241 TraitSelector SelectorForName = getOpenMPContextTraitSelectorKind(Name); 1242 if (SelectorForName != TraitSelector::invalid) { 1243 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a) 1244 << Name << CONTEXT_SELECTOR_LVL << CONTEXT_SELECTOR_SET_LVL; 1245 bool AllowsTraitScore = false; 1246 bool RequiresProperty = false; 1247 isValidTraitSelectorForTraitSet( 1248 SelectorForName, getOpenMPContextTraitSetForSelector(SelectorForName), 1249 AllowsTraitScore, RequiresProperty); 1250 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try) 1251 << getOpenMPContextTraitSetName( 1252 getOpenMPContextTraitSetForSelector(SelectorForName)) 1253 << Name << (RequiresProperty ? "(<property-name>)" : ""); 1254 return; 1255 } 1256 for (const auto &PotentialSet : 1257 {TraitSet::construct, TraitSet::user, TraitSet::implementation, 1258 TraitSet::device}) { 1259 TraitProperty PropertyForName = getOpenMPContextTraitPropertyKind( 1260 PotentialSet, TraitSelector::invalid, Name); 1261 if (PropertyForName == TraitProperty::invalid) 1262 continue; 1263 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a) 1264 << Name << CONTEXT_TRAIT_LVL << CONTEXT_SELECTOR_SET_LVL; 1265 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try) 1266 << getOpenMPContextTraitSetName( 1267 getOpenMPContextTraitSetForProperty(PropertyForName)) 1268 << getOpenMPContextTraitSelectorName( 1269 getOpenMPContextTraitSelectorForProperty(PropertyForName)) 1270 << ("(" + Name + ")").str(); 1271 return; 1272 } 1273 Diag(NameLoc, diag::note_omp_declare_variant_ctx_options) 1274 << CONTEXT_SELECTOR_SET_LVL << listOpenMPContextTraitSets(); 1275 } 1276 1277 /// Parses an OpenMP context selector set. 1278 /// 1279 /// <trait-set-selector-name> '=' '{' <trait-selector> [, <trait-selector>]* '}' 1280 void Parser::parseOMPContextSelectorSet( 1281 OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &SeenSets) { 1282 auto OuterBC = BraceCount; 1283 1284 // If anything went wrong we issue an error or warning and then skip the rest 1285 // of the set. However, commas are ambiguous so we look for the nesting 1286 // of braces here as well. 1287 auto FinishSelectorSet = [this, OuterBC]() -> void { 1288 bool Done = false; 1289 while (!Done) { 1290 while (!SkipUntil({tok::comma, tok::r_brace, tok::r_paren, 1291 tok::annot_pragma_openmp_end}, 1292 StopBeforeMatch)) 1293 ; 1294 if (Tok.is(tok::r_brace) && OuterBC > BraceCount) 1295 (void)ConsumeBrace(); 1296 if (OuterBC <= BraceCount) { 1297 Done = true; 1298 break; 1299 } 1300 if (!Tok.is(tok::comma) && !Tok.is(tok::r_brace)) { 1301 Done = true; 1302 break; 1303 } 1304 (void)ConsumeAnyToken(); 1305 } 1306 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here) 1307 << CONTEXT_SELECTOR_SET_LVL; 1308 }; 1309 1310 parseOMPTraitSetKind(TISet, SeenSets); 1311 if (TISet.Kind == TraitSet::invalid) 1312 return FinishSelectorSet(); 1313 1314 // Parse '='. 1315 if (!TryConsumeToken(tok::equal)) 1316 Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected) 1317 << "=" 1318 << ("context set name \"" + getOpenMPContextTraitSetName(TISet.Kind) + 1319 "\"") 1320 .str(); 1321 1322 // Parse '{'. 1323 if (Tok.is(tok::l_brace)) { 1324 (void)ConsumeBrace(); 1325 } else { 1326 Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected) 1327 << "{" 1328 << ("'=' that follows the context set name \"" + 1329 getOpenMPContextTraitSetName(TISet.Kind) + "\"") 1330 .str(); 1331 } 1332 1333 llvm::StringMap<SourceLocation> SeenSelectors; 1334 do { 1335 OMPTraitSelector TISelector; 1336 parseOMPContextSelector(TISelector, TISet.Kind, SeenSelectors); 1337 if (TISelector.Kind != TraitSelector::invalid && 1338 !TISelector.Properties.empty()) 1339 TISet.Selectors.push_back(TISelector); 1340 } while (TryConsumeToken(tok::comma)); 1341 1342 // Parse '}'. 1343 if (Tok.is(tok::r_brace)) { 1344 (void)ConsumeBrace(); 1345 } else { 1346 Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected) 1347 << "}" 1348 << ("context selectors for the context set \"" + 1349 getOpenMPContextTraitSetName(TISet.Kind) + "\"") 1350 .str(); 1351 } 1352 } 1353 1354 /// Parse OpenMP context selectors: 1355 /// 1356 /// <trait-set-selector> [, <trait-set-selector>]* 1357 bool Parser::parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI) { 1358 llvm::StringMap<SourceLocation> SeenSets; 1359 do { 1360 OMPTraitSet TISet; 1361 parseOMPContextSelectorSet(TISet, SeenSets); 1362 if (TISet.Kind != TraitSet::invalid && !TISet.Selectors.empty()) 1363 TI.Sets.push_back(TISet); 1364 } while (TryConsumeToken(tok::comma)); 1365 1366 return false; 1367 } 1368 1369 /// Parse clauses for '#pragma omp declare variant ( variant-func-id ) clause'. 1370 void Parser::ParseOMPDeclareVariantClauses(Parser::DeclGroupPtrTy Ptr, 1371 CachedTokens &Toks, 1372 SourceLocation Loc) { 1373 PP.EnterToken(Tok, /*IsReinject*/ true); 1374 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true, 1375 /*IsReinject*/ true); 1376 // Consume the previously pushed token. 1377 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 1378 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 1379 1380 FNContextRAII FnContext(*this, Ptr); 1381 // Parse function declaration id. 1382 SourceLocation RLoc; 1383 // Parse with IsAddressOfOperand set to true to parse methods as DeclRefExprs 1384 // instead of MemberExprs. 1385 ExprResult AssociatedFunction; 1386 { 1387 // Do not mark function as is used to prevent its emission if this is the 1388 // only place where it is used. 1389 EnterExpressionEvaluationContext Unevaluated( 1390 Actions, Sema::ExpressionEvaluationContext::Unevaluated); 1391 AssociatedFunction = ParseOpenMPParensExpr( 1392 getOpenMPDirectiveName(OMPD_declare_variant), RLoc, 1393 /*IsAddressOfOperand=*/true); 1394 } 1395 if (!AssociatedFunction.isUsable()) { 1396 if (!Tok.is(tok::annot_pragma_openmp_end)) 1397 while (!SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch)) 1398 ; 1399 // Skip the last annot_pragma_openmp_end. 1400 (void)ConsumeAnnotationToken(); 1401 return; 1402 } 1403 1404 OMPTraitInfo *ParentTI = Actions.getOMPTraitInfoForSurroundingScope(); 1405 ASTContext &ASTCtx = Actions.getASTContext(); 1406 OMPTraitInfo &TI = ASTCtx.getNewOMPTraitInfo(); 1407 SmallVector<Expr *, 6> AdjustNothing; 1408 SmallVector<Expr *, 6> AdjustNeedDevicePtr; 1409 SmallVector<OMPDeclareVariantAttr::InteropType, 3> AppendArgs; 1410 SourceLocation AdjustArgsLoc, AppendArgsLoc; 1411 1412 // At least one clause is required. 1413 if (Tok.is(tok::annot_pragma_openmp_end)) { 1414 Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause) 1415 << (getLangOpts().OpenMP < 51 ? 0 : 1); 1416 } 1417 1418 bool IsError = false; 1419 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 1420 OpenMPClauseKind CKind = Tok.isAnnotation() 1421 ? OMPC_unknown 1422 : getOpenMPClauseKind(PP.getSpelling(Tok)); 1423 if (!isAllowedClauseForDirective(OMPD_declare_variant, CKind, 1424 getLangOpts().OpenMP)) { 1425 Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause) 1426 << (getLangOpts().OpenMP < 51 ? 0 : 1); 1427 IsError = true; 1428 } 1429 if (!IsError) { 1430 switch (CKind) { 1431 case OMPC_match: 1432 IsError = parseOMPDeclareVariantMatchClause(Loc, TI, ParentTI); 1433 break; 1434 case OMPC_adjust_args: { 1435 AdjustArgsLoc = Tok.getLocation(); 1436 ConsumeToken(); 1437 Parser::OpenMPVarListDataTy Data; 1438 SmallVector<Expr *> Vars; 1439 IsError = ParseOpenMPVarList(OMPD_declare_variant, OMPC_adjust_args, 1440 Vars, Data); 1441 if (!IsError) 1442 llvm::append_range(Data.ExtraModifier == OMPC_ADJUST_ARGS_nothing 1443 ? AdjustNothing 1444 : AdjustNeedDevicePtr, 1445 Vars); 1446 break; 1447 } 1448 case OMPC_append_args: 1449 if (!AppendArgs.empty()) { 1450 Diag(AppendArgsLoc, diag::err_omp_more_one_clause) 1451 << getOpenMPDirectiveName(OMPD_declare_variant) 1452 << getOpenMPClauseName(CKind) << 0; 1453 IsError = true; 1454 } 1455 if (!IsError) { 1456 AppendArgsLoc = Tok.getLocation(); 1457 ConsumeToken(); 1458 IsError = parseOpenMPAppendArgs(AppendArgs); 1459 } 1460 break; 1461 default: 1462 llvm_unreachable("Unexpected clause for declare variant."); 1463 } 1464 } 1465 if (IsError) { 1466 while (!SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch)) 1467 ; 1468 // Skip the last annot_pragma_openmp_end. 1469 (void)ConsumeAnnotationToken(); 1470 return; 1471 } 1472 // Skip ',' if any. 1473 if (Tok.is(tok::comma)) 1474 ConsumeToken(); 1475 } 1476 1477 Optional<std::pair<FunctionDecl *, Expr *>> DeclVarData = 1478 Actions.checkOpenMPDeclareVariantFunction( 1479 Ptr, AssociatedFunction.get(), TI, AppendArgs.size(), 1480 SourceRange(Loc, Tok.getLocation())); 1481 1482 if (DeclVarData && !TI.Sets.empty()) 1483 Actions.ActOnOpenMPDeclareVariantDirective( 1484 DeclVarData->first, DeclVarData->second, TI, AdjustNothing, 1485 AdjustNeedDevicePtr, AppendArgs, AdjustArgsLoc, AppendArgsLoc, 1486 SourceRange(Loc, Tok.getLocation())); 1487 1488 // Skip the last annot_pragma_openmp_end. 1489 (void)ConsumeAnnotationToken(); 1490 } 1491 1492 /// Parse a list of interop-types. These are 'target' and 'targetsync'. Both 1493 /// are allowed but duplication of either is not meaningful. 1494 static Optional<OMPDeclareVariantAttr::InteropType> 1495 parseInteropTypeList(Parser &P) { 1496 const Token &Tok = P.getCurToken(); 1497 bool HasError = false; 1498 bool IsTarget = false; 1499 bool IsTargetSync = false; 1500 1501 while (Tok.is(tok::identifier)) { 1502 if (Tok.getIdentifierInfo()->isStr("target")) { 1503 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 1504 // Each interop-type may be specified on an action-clause at most 1505 // once. 1506 if (IsTarget) 1507 P.Diag(Tok, diag::warn_omp_more_one_interop_type) << "target"; 1508 IsTarget = true; 1509 } else if (Tok.getIdentifierInfo()->isStr("targetsync")) { 1510 if (IsTargetSync) 1511 P.Diag(Tok, diag::warn_omp_more_one_interop_type) << "targetsync"; 1512 IsTargetSync = true; 1513 } else { 1514 HasError = true; 1515 P.Diag(Tok, diag::err_omp_expected_interop_type); 1516 } 1517 P.ConsumeToken(); 1518 1519 if (!Tok.is(tok::comma)) 1520 break; 1521 P.ConsumeToken(); 1522 } 1523 if (HasError) 1524 return None; 1525 1526 if (!IsTarget && !IsTargetSync) { 1527 P.Diag(Tok, diag::err_omp_expected_interop_type); 1528 return None; 1529 } 1530 1531 // As of OpenMP 5.1,there are two interop-types, "target" and 1532 // "targetsync". Either or both are allowed for a single interop. 1533 if (IsTarget && IsTargetSync) 1534 return OMPDeclareVariantAttr::Target_TargetSync; 1535 if (IsTarget) 1536 return OMPDeclareVariantAttr::Target; 1537 return OMPDeclareVariantAttr::TargetSync; 1538 } 1539 1540 bool Parser::parseOpenMPAppendArgs( 1541 SmallVectorImpl<OMPDeclareVariantAttr::InteropType> &InterOpTypes) { 1542 bool HasError = false; 1543 // Parse '('. 1544 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 1545 if (T.expectAndConsume(diag::err_expected_lparen_after, 1546 getOpenMPClauseName(OMPC_append_args).data())) 1547 return true; 1548 1549 // Parse the list of append-ops, each is; 1550 // interop(interop-type[,interop-type]...) 1551 while (Tok.is(tok::identifier) && Tok.getIdentifierInfo()->isStr("interop")) { 1552 ConsumeToken(); 1553 BalancedDelimiterTracker IT(*this, tok::l_paren, 1554 tok::annot_pragma_openmp_end); 1555 if (IT.expectAndConsume(diag::err_expected_lparen_after, "interop")) 1556 return true; 1557 1558 // Parse the interop-types. 1559 if (Optional<OMPDeclareVariantAttr::InteropType> IType = 1560 parseInteropTypeList(*this)) 1561 InterOpTypes.push_back(IType.getValue()); 1562 else 1563 HasError = true; 1564 1565 IT.consumeClose(); 1566 if (Tok.is(tok::comma)) 1567 ConsumeToken(); 1568 } 1569 if (!HasError && InterOpTypes.empty()) { 1570 HasError = true; 1571 Diag(Tok.getLocation(), diag::err_omp_unexpected_append_op); 1572 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 1573 StopBeforeMatch); 1574 } 1575 HasError = T.consumeClose() || HasError; 1576 return HasError; 1577 } 1578 1579 bool Parser::parseOMPDeclareVariantMatchClause(SourceLocation Loc, 1580 OMPTraitInfo &TI, 1581 OMPTraitInfo *ParentTI) { 1582 // Parse 'match'. 1583 OpenMPClauseKind CKind = Tok.isAnnotation() 1584 ? OMPC_unknown 1585 : getOpenMPClauseKind(PP.getSpelling(Tok)); 1586 if (CKind != OMPC_match) { 1587 Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause) 1588 << (getLangOpts().OpenMP < 51 ? 0 : 1); 1589 return true; 1590 } 1591 (void)ConsumeToken(); 1592 // Parse '('. 1593 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 1594 if (T.expectAndConsume(diag::err_expected_lparen_after, 1595 getOpenMPClauseName(OMPC_match).data())) 1596 return true; 1597 1598 // Parse inner context selectors. 1599 parseOMPContextSelectors(Loc, TI); 1600 1601 // Parse ')' 1602 (void)T.consumeClose(); 1603 1604 if (!ParentTI) 1605 return false; 1606 1607 // Merge the parent/outer trait info into the one we just parsed and diagnose 1608 // problems. 1609 // TODO: Keep some source location in the TI to provide better diagnostics. 1610 // TODO: Perform some kind of equivalence check on the condition and score 1611 // expressions. 1612 for (const OMPTraitSet &ParentSet : ParentTI->Sets) { 1613 bool MergedSet = false; 1614 for (OMPTraitSet &Set : TI.Sets) { 1615 if (Set.Kind != ParentSet.Kind) 1616 continue; 1617 MergedSet = true; 1618 for (const OMPTraitSelector &ParentSelector : ParentSet.Selectors) { 1619 bool MergedSelector = false; 1620 for (OMPTraitSelector &Selector : Set.Selectors) { 1621 if (Selector.Kind != ParentSelector.Kind) 1622 continue; 1623 MergedSelector = true; 1624 for (const OMPTraitProperty &ParentProperty : 1625 ParentSelector.Properties) { 1626 bool MergedProperty = false; 1627 for (OMPTraitProperty &Property : Selector.Properties) { 1628 // Ignore "equivalent" properties. 1629 if (Property.Kind != ParentProperty.Kind) 1630 continue; 1631 1632 // If the kind is the same but the raw string not, we don't want 1633 // to skip out on the property. 1634 MergedProperty |= Property.RawString == ParentProperty.RawString; 1635 1636 if (Property.RawString == ParentProperty.RawString && 1637 Selector.ScoreOrCondition == ParentSelector.ScoreOrCondition) 1638 continue; 1639 1640 if (Selector.Kind == llvm::omp::TraitSelector::user_condition) { 1641 Diag(Loc, diag::err_omp_declare_variant_nested_user_condition); 1642 } else if (Selector.ScoreOrCondition != 1643 ParentSelector.ScoreOrCondition) { 1644 Diag(Loc, diag::err_omp_declare_variant_duplicate_nested_trait) 1645 << getOpenMPContextTraitPropertyName( 1646 ParentProperty.Kind, ParentProperty.RawString) 1647 << getOpenMPContextTraitSelectorName(ParentSelector.Kind) 1648 << getOpenMPContextTraitSetName(ParentSet.Kind); 1649 } 1650 } 1651 if (!MergedProperty) 1652 Selector.Properties.push_back(ParentProperty); 1653 } 1654 } 1655 if (!MergedSelector) 1656 Set.Selectors.push_back(ParentSelector); 1657 } 1658 } 1659 if (!MergedSet) 1660 TI.Sets.push_back(ParentSet); 1661 } 1662 1663 return false; 1664 } 1665 1666 /// `omp assumes` or `omp begin/end assumes` <clause> [[,]<clause>]... 1667 /// where 1668 /// 1669 /// clause: 1670 /// 'ext_IMPL_DEFINED' 1671 /// 'absent' '(' directive-name [, directive-name]* ')' 1672 /// 'contains' '(' directive-name [, directive-name]* ')' 1673 /// 'holds' '(' scalar-expression ')' 1674 /// 'no_openmp' 1675 /// 'no_openmp_routines' 1676 /// 'no_parallelism' 1677 /// 1678 void Parser::ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind, 1679 SourceLocation Loc) { 1680 SmallVector<std::string, 4> Assumptions; 1681 bool SkippedClauses = false; 1682 1683 auto SkipBraces = [&](llvm::StringRef Spelling, bool IssueNote) { 1684 BalancedDelimiterTracker T(*this, tok::l_paren, 1685 tok::annot_pragma_openmp_end); 1686 if (T.expectAndConsume(diag::err_expected_lparen_after, Spelling.data())) 1687 return; 1688 T.skipToEnd(); 1689 if (IssueNote && T.getCloseLocation().isValid()) 1690 Diag(T.getCloseLocation(), 1691 diag::note_omp_assumption_clause_continue_here); 1692 }; 1693 1694 /// Helper to determine which AssumptionClauseMapping (ACM) in the 1695 /// AssumptionClauseMappings table matches \p RawString. The return value is 1696 /// the index of the matching ACM into the table or -1 if there was no match. 1697 auto MatchACMClause = [&](StringRef RawString) { 1698 llvm::StringSwitch<int> SS(RawString); 1699 unsigned ACMIdx = 0; 1700 for (const AssumptionClauseMappingInfo &ACMI : AssumptionClauseMappings) { 1701 if (ACMI.StartsWith) 1702 SS.StartsWith(ACMI.Identifier, ACMIdx++); 1703 else 1704 SS.Case(ACMI.Identifier, ACMIdx++); 1705 } 1706 return SS.Default(-1); 1707 }; 1708 1709 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 1710 IdentifierInfo *II = nullptr; 1711 SourceLocation StartLoc = Tok.getLocation(); 1712 int Idx = -1; 1713 if (Tok.isAnyIdentifier()) { 1714 II = Tok.getIdentifierInfo(); 1715 Idx = MatchACMClause(II->getName()); 1716 } 1717 ConsumeAnyToken(); 1718 1719 bool NextIsLPar = Tok.is(tok::l_paren); 1720 // Handle unknown clauses by skipping them. 1721 if (Idx == -1) { 1722 Diag(StartLoc, diag::warn_omp_unknown_assumption_clause_missing_id) 1723 << llvm::omp::getOpenMPDirectiveName(DKind) 1724 << llvm::omp::getAllAssumeClauseOptions() << NextIsLPar; 1725 if (NextIsLPar) 1726 SkipBraces(II ? II->getName() : "", /* IssueNote */ true); 1727 SkippedClauses = true; 1728 continue; 1729 } 1730 const AssumptionClauseMappingInfo &ACMI = AssumptionClauseMappings[Idx]; 1731 if (ACMI.HasDirectiveList || ACMI.HasExpression) { 1732 // TODO: We ignore absent, contains, and holds assumptions for now. We 1733 // also do not verify the content in the parenthesis at all. 1734 SkippedClauses = true; 1735 SkipBraces(II->getName(), /* IssueNote */ false); 1736 continue; 1737 } 1738 1739 if (NextIsLPar) { 1740 Diag(Tok.getLocation(), 1741 diag::warn_omp_unknown_assumption_clause_without_args) 1742 << II; 1743 SkipBraces(II->getName(), /* IssueNote */ true); 1744 } 1745 1746 assert(II && "Expected an identifier clause!"); 1747 std::string Assumption = II->getName().str(); 1748 if (ACMI.StartsWith) 1749 Assumption = "ompx_" + Assumption.substr(ACMI.Identifier.size()); 1750 else 1751 Assumption = "omp_" + Assumption; 1752 Assumptions.push_back(Assumption); 1753 } 1754 1755 Actions.ActOnOpenMPAssumesDirective(Loc, DKind, Assumptions, SkippedClauses); 1756 } 1757 1758 void Parser::ParseOpenMPEndAssumesDirective(SourceLocation Loc) { 1759 if (Actions.isInOpenMPAssumeScope()) 1760 Actions.ActOnOpenMPEndAssumesDirective(); 1761 else 1762 Diag(Loc, diag::err_expected_begin_assumes); 1763 } 1764 1765 /// Parsing of simple OpenMP clauses like 'default' or 'proc_bind'. 1766 /// 1767 /// default-clause: 1768 /// 'default' '(' 'none' | 'shared' | 'firstprivate' ') 1769 /// 1770 /// proc_bind-clause: 1771 /// 'proc_bind' '(' 'master' | 'close' | 'spread' ') 1772 /// 1773 /// device_type-clause: 1774 /// 'device_type' '(' 'host' | 'nohost' | 'any' )' 1775 namespace { 1776 struct SimpleClauseData { 1777 unsigned Type; 1778 SourceLocation Loc; 1779 SourceLocation LOpen; 1780 SourceLocation TypeLoc; 1781 SourceLocation RLoc; 1782 SimpleClauseData(unsigned Type, SourceLocation Loc, SourceLocation LOpen, 1783 SourceLocation TypeLoc, SourceLocation RLoc) 1784 : Type(Type), Loc(Loc), LOpen(LOpen), TypeLoc(TypeLoc), RLoc(RLoc) {} 1785 }; 1786 } // anonymous namespace 1787 1788 static Optional<SimpleClauseData> 1789 parseOpenMPSimpleClause(Parser &P, OpenMPClauseKind Kind) { 1790 const Token &Tok = P.getCurToken(); 1791 SourceLocation Loc = Tok.getLocation(); 1792 SourceLocation LOpen = P.ConsumeToken(); 1793 // Parse '('. 1794 BalancedDelimiterTracker T(P, tok::l_paren, tok::annot_pragma_openmp_end); 1795 if (T.expectAndConsume(diag::err_expected_lparen_after, 1796 getOpenMPClauseName(Kind).data())) 1797 return llvm::None; 1798 1799 unsigned Type = getOpenMPSimpleClauseType( 1800 Kind, Tok.isAnnotation() ? "" : P.getPreprocessor().getSpelling(Tok), 1801 P.getLangOpts()); 1802 SourceLocation TypeLoc = Tok.getLocation(); 1803 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 1804 Tok.isNot(tok::annot_pragma_openmp_end)) 1805 P.ConsumeAnyToken(); 1806 1807 // Parse ')'. 1808 SourceLocation RLoc = Tok.getLocation(); 1809 if (!T.consumeClose()) 1810 RLoc = T.getCloseLocation(); 1811 1812 return SimpleClauseData(Type, Loc, LOpen, TypeLoc, RLoc); 1813 } 1814 1815 void Parser::ParseOMPDeclareTargetClauses( 1816 Sema::DeclareTargetContextInfo &DTCI) { 1817 SourceLocation DeviceTypeLoc; 1818 bool RequiresToOrLinkOrIndirectClause = false; 1819 bool HasToOrLinkOrIndirectClause = false; 1820 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 1821 OMPDeclareTargetDeclAttr::MapTypeTy MT = OMPDeclareTargetDeclAttr::MT_To; 1822 bool HasIdentifier = Tok.is(tok::identifier); 1823 if (HasIdentifier) { 1824 // If we see any clause we need a to or link clause. 1825 RequiresToOrLinkOrIndirectClause = true; 1826 IdentifierInfo *II = Tok.getIdentifierInfo(); 1827 StringRef ClauseName = II->getName(); 1828 bool IsDeviceTypeClause = 1829 getLangOpts().OpenMP >= 50 && 1830 getOpenMPClauseKind(ClauseName) == OMPC_device_type; 1831 1832 bool IsIndirectClause = getLangOpts().OpenMP >= 51 && 1833 getOpenMPClauseKind(ClauseName) == OMPC_indirect; 1834 if (DTCI.Indirect.hasValue() && IsIndirectClause) { 1835 Diag(Tok, diag::err_omp_more_one_clause) 1836 << getOpenMPDirectiveName(OMPD_declare_target) 1837 << getOpenMPClauseName(OMPC_indirect) << 0; 1838 break; 1839 } 1840 bool IsToOrLinkClause = 1841 OMPDeclareTargetDeclAttr::ConvertStrToMapTypeTy(ClauseName, MT); 1842 assert((!IsDeviceTypeClause || !IsToOrLinkClause) && "Cannot be both!"); 1843 1844 if (!IsDeviceTypeClause && !IsIndirectClause && 1845 DTCI.Kind == OMPD_begin_declare_target) { 1846 Diag(Tok, diag::err_omp_declare_target_unexpected_clause) 1847 << ClauseName << (getLangOpts().OpenMP >= 51 ? 3 : 0); 1848 break; 1849 } 1850 if (!IsDeviceTypeClause && !IsToOrLinkClause && !IsIndirectClause) { 1851 Diag(Tok, diag::err_omp_declare_target_unexpected_clause) 1852 << ClauseName 1853 << (getLangOpts().OpenMP >= 51 ? 4 1854 : getLangOpts().OpenMP >= 50 ? 2 1855 : 1); 1856 break; 1857 } 1858 1859 if (IsToOrLinkClause || IsIndirectClause) 1860 HasToOrLinkOrIndirectClause = true; 1861 1862 if (IsIndirectClause) { 1863 if (!ParseOpenMPIndirectClause(DTCI, /*ParseOnly*/ false)) 1864 break; 1865 continue; 1866 } 1867 // Parse 'device_type' clause and go to next clause if any. 1868 if (IsDeviceTypeClause) { 1869 Optional<SimpleClauseData> DevTypeData = 1870 parseOpenMPSimpleClause(*this, OMPC_device_type); 1871 if (DevTypeData.hasValue()) { 1872 if (DeviceTypeLoc.isValid()) { 1873 // We already saw another device_type clause, diagnose it. 1874 Diag(DevTypeData.getValue().Loc, 1875 diag::warn_omp_more_one_device_type_clause); 1876 break; 1877 } 1878 switch (static_cast<OpenMPDeviceType>(DevTypeData.getValue().Type)) { 1879 case OMPC_DEVICE_TYPE_any: 1880 DTCI.DT = OMPDeclareTargetDeclAttr::DT_Any; 1881 break; 1882 case OMPC_DEVICE_TYPE_host: 1883 DTCI.DT = OMPDeclareTargetDeclAttr::DT_Host; 1884 break; 1885 case OMPC_DEVICE_TYPE_nohost: 1886 DTCI.DT = OMPDeclareTargetDeclAttr::DT_NoHost; 1887 break; 1888 case OMPC_DEVICE_TYPE_unknown: 1889 llvm_unreachable("Unexpected device_type"); 1890 } 1891 DeviceTypeLoc = DevTypeData.getValue().Loc; 1892 } 1893 continue; 1894 } 1895 ConsumeToken(); 1896 } 1897 1898 if (DTCI.Kind == OMPD_declare_target || HasIdentifier) { 1899 auto &&Callback = [this, MT, &DTCI](CXXScopeSpec &SS, 1900 DeclarationNameInfo NameInfo) { 1901 NamedDecl *ND = 1902 Actions.lookupOpenMPDeclareTargetName(getCurScope(), SS, NameInfo); 1903 if (!ND) 1904 return; 1905 Sema::DeclareTargetContextInfo::MapInfo MI{MT, NameInfo.getLoc()}; 1906 bool FirstMapping = DTCI.ExplicitlyMapped.try_emplace(ND, MI).second; 1907 if (!FirstMapping) 1908 Diag(NameInfo.getLoc(), diag::err_omp_declare_target_multiple) 1909 << NameInfo.getName(); 1910 }; 1911 if (ParseOpenMPSimpleVarList(OMPD_declare_target, Callback, 1912 /*AllowScopeSpecifier=*/true)) 1913 break; 1914 } 1915 1916 if (Tok.is(tok::l_paren)) { 1917 Diag(Tok, 1918 diag::err_omp_begin_declare_target_unexpected_implicit_to_clause); 1919 break; 1920 } 1921 if (!HasIdentifier && Tok.isNot(tok::annot_pragma_openmp_end)) { 1922 Diag(Tok, 1923 diag::err_omp_declare_target_unexpected_clause_after_implicit_to); 1924 break; 1925 } 1926 1927 // Consume optional ','. 1928 if (Tok.is(tok::comma)) 1929 ConsumeToken(); 1930 } 1931 1932 if (DTCI.Indirect.hasValue() && DTCI.DT != OMPDeclareTargetDeclAttr::DT_Any) 1933 Diag(DeviceTypeLoc, diag::err_omp_declare_target_indirect_device_type); 1934 1935 // For declare target require at least 'to' or 'link' to be present. 1936 if (DTCI.Kind == OMPD_declare_target && RequiresToOrLinkOrIndirectClause && 1937 !HasToOrLinkOrIndirectClause) 1938 Diag(DTCI.Loc, diag::err_omp_declare_target_missing_to_or_link_clause) 1939 << (getLangOpts().OpenMP >= 51 ? 1 : 0); 1940 1941 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 1942 } 1943 1944 void Parser::skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind) { 1945 // The last seen token is annot_pragma_openmp_end - need to check for 1946 // extra tokens. 1947 if (Tok.is(tok::annot_pragma_openmp_end)) 1948 return; 1949 1950 Diag(Tok, diag::warn_omp_extra_tokens_at_eol) 1951 << getOpenMPDirectiveName(DKind); 1952 while (Tok.isNot(tok::annot_pragma_openmp_end)) 1953 ConsumeAnyToken(); 1954 } 1955 1956 void Parser::parseOMPEndDirective(OpenMPDirectiveKind BeginKind, 1957 OpenMPDirectiveKind ExpectedKind, 1958 OpenMPDirectiveKind FoundKind, 1959 SourceLocation BeginLoc, 1960 SourceLocation FoundLoc, 1961 bool SkipUntilOpenMPEnd) { 1962 int DiagSelection = ExpectedKind == OMPD_end_declare_target ? 0 : 1; 1963 1964 if (FoundKind == ExpectedKind) { 1965 ConsumeAnyToken(); 1966 skipUntilPragmaOpenMPEnd(ExpectedKind); 1967 return; 1968 } 1969 1970 Diag(FoundLoc, diag::err_expected_end_declare_target_or_variant) 1971 << DiagSelection; 1972 Diag(BeginLoc, diag::note_matching) 1973 << ("'#pragma omp " + getOpenMPDirectiveName(BeginKind) + "'").str(); 1974 if (SkipUntilOpenMPEnd) 1975 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 1976 } 1977 1978 void Parser::ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind BeginDKind, 1979 OpenMPDirectiveKind EndDKind, 1980 SourceLocation DKLoc) { 1981 parseOMPEndDirective(BeginDKind, OMPD_end_declare_target, EndDKind, DKLoc, 1982 Tok.getLocation(), 1983 /* SkipUntilOpenMPEnd */ false); 1984 // Skip the last annot_pragma_openmp_end. 1985 if (Tok.is(tok::annot_pragma_openmp_end)) 1986 ConsumeAnnotationToken(); 1987 } 1988 1989 /// Parsing of declarative OpenMP directives. 1990 /// 1991 /// threadprivate-directive: 1992 /// annot_pragma_openmp 'threadprivate' simple-variable-list 1993 /// annot_pragma_openmp_end 1994 /// 1995 /// allocate-directive: 1996 /// annot_pragma_openmp 'allocate' simple-variable-list [<clause>] 1997 /// annot_pragma_openmp_end 1998 /// 1999 /// declare-reduction-directive: 2000 /// annot_pragma_openmp 'declare' 'reduction' [...] 2001 /// annot_pragma_openmp_end 2002 /// 2003 /// declare-mapper-directive: 2004 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':'] 2005 /// <type> <var> ')' [<clause>[[,] <clause>] ... ] 2006 /// annot_pragma_openmp_end 2007 /// 2008 /// declare-simd-directive: 2009 /// annot_pragma_openmp 'declare simd' {<clause> [,]} 2010 /// annot_pragma_openmp_end 2011 /// <function declaration/definition> 2012 /// 2013 /// requires directive: 2014 /// annot_pragma_openmp 'requires' <clause> [[[,] <clause>] ... ] 2015 /// annot_pragma_openmp_end 2016 /// 2017 /// assumes directive: 2018 /// annot_pragma_openmp 'assumes' <clause> [[[,] <clause>] ... ] 2019 /// annot_pragma_openmp_end 2020 /// or 2021 /// annot_pragma_openmp 'begin assumes' <clause> [[[,] <clause>] ... ] 2022 /// annot_pragma_openmp 'end assumes' 2023 /// annot_pragma_openmp_end 2024 /// 2025 Parser::DeclGroupPtrTy Parser::ParseOpenMPDeclarativeDirectiveWithExtDecl( 2026 AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, bool Delayed, 2027 DeclSpec::TST TagType, Decl *Tag) { 2028 assert(Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp) && 2029 "Not an OpenMP directive!"); 2030 ParsingOpenMPDirectiveRAII DirScope(*this); 2031 ParenBraceBracketBalancer BalancerRAIIObj(*this); 2032 2033 SourceLocation Loc; 2034 OpenMPDirectiveKind DKind; 2035 if (Delayed) { 2036 TentativeParsingAction TPA(*this); 2037 Loc = ConsumeAnnotationToken(); 2038 DKind = parseOpenMPDirectiveKind(*this); 2039 if (DKind == OMPD_declare_reduction || DKind == OMPD_declare_mapper) { 2040 // Need to delay parsing until completion of the parent class. 2041 TPA.Revert(); 2042 CachedTokens Toks; 2043 unsigned Cnt = 1; 2044 Toks.push_back(Tok); 2045 while (Cnt && Tok.isNot(tok::eof)) { 2046 (void)ConsumeAnyToken(); 2047 if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) 2048 ++Cnt; 2049 else if (Tok.is(tok::annot_pragma_openmp_end)) 2050 --Cnt; 2051 Toks.push_back(Tok); 2052 } 2053 // Skip last annot_pragma_openmp_end. 2054 if (Cnt == 0) 2055 (void)ConsumeAnyToken(); 2056 auto *LP = new LateParsedPragma(this, AS); 2057 LP->takeToks(Toks); 2058 getCurrentClass().LateParsedDeclarations.push_back(LP); 2059 return nullptr; 2060 } 2061 TPA.Commit(); 2062 } else { 2063 Loc = ConsumeAnnotationToken(); 2064 DKind = parseOpenMPDirectiveKind(*this); 2065 } 2066 2067 switch (DKind) { 2068 case OMPD_threadprivate: { 2069 ConsumeToken(); 2070 DeclDirectiveListParserHelper Helper(this, DKind); 2071 if (!ParseOpenMPSimpleVarList(DKind, Helper, 2072 /*AllowScopeSpecifier=*/true)) { 2073 skipUntilPragmaOpenMPEnd(DKind); 2074 // Skip the last annot_pragma_openmp_end. 2075 ConsumeAnnotationToken(); 2076 return Actions.ActOnOpenMPThreadprivateDirective(Loc, 2077 Helper.getIdentifiers()); 2078 } 2079 break; 2080 } 2081 case OMPD_allocate: { 2082 ConsumeToken(); 2083 DeclDirectiveListParserHelper Helper(this, DKind); 2084 if (!ParseOpenMPSimpleVarList(DKind, Helper, 2085 /*AllowScopeSpecifier=*/true)) { 2086 SmallVector<OMPClause *, 1> Clauses; 2087 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 2088 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, 2089 llvm::omp::Clause_enumSize + 1> 2090 FirstClauses(llvm::omp::Clause_enumSize + 1); 2091 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 2092 OpenMPClauseKind CKind = 2093 Tok.isAnnotation() ? OMPC_unknown 2094 : getOpenMPClauseKind(PP.getSpelling(Tok)); 2095 Actions.StartOpenMPClause(CKind); 2096 OMPClause *Clause = ParseOpenMPClause( 2097 OMPD_allocate, CKind, !FirstClauses[unsigned(CKind)].getInt()); 2098 SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end, 2099 StopBeforeMatch); 2100 FirstClauses[unsigned(CKind)].setInt(true); 2101 if (Clause != nullptr) 2102 Clauses.push_back(Clause); 2103 if (Tok.is(tok::annot_pragma_openmp_end)) { 2104 Actions.EndOpenMPClause(); 2105 break; 2106 } 2107 // Skip ',' if any. 2108 if (Tok.is(tok::comma)) 2109 ConsumeToken(); 2110 Actions.EndOpenMPClause(); 2111 } 2112 skipUntilPragmaOpenMPEnd(DKind); 2113 } 2114 // Skip the last annot_pragma_openmp_end. 2115 ConsumeAnnotationToken(); 2116 return Actions.ActOnOpenMPAllocateDirective(Loc, Helper.getIdentifiers(), 2117 Clauses); 2118 } 2119 break; 2120 } 2121 case OMPD_requires: { 2122 SourceLocation StartLoc = ConsumeToken(); 2123 SmallVector<OMPClause *, 5> Clauses; 2124 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, 2125 llvm::omp::Clause_enumSize + 1> 2126 FirstClauses(llvm::omp::Clause_enumSize + 1); 2127 if (Tok.is(tok::annot_pragma_openmp_end)) { 2128 Diag(Tok, diag::err_omp_expected_clause) 2129 << getOpenMPDirectiveName(OMPD_requires); 2130 break; 2131 } 2132 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 2133 OpenMPClauseKind CKind = Tok.isAnnotation() 2134 ? OMPC_unknown 2135 : getOpenMPClauseKind(PP.getSpelling(Tok)); 2136 Actions.StartOpenMPClause(CKind); 2137 OMPClause *Clause = ParseOpenMPClause( 2138 OMPD_requires, CKind, !FirstClauses[unsigned(CKind)].getInt()); 2139 SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end, 2140 StopBeforeMatch); 2141 FirstClauses[unsigned(CKind)].setInt(true); 2142 if (Clause != nullptr) 2143 Clauses.push_back(Clause); 2144 if (Tok.is(tok::annot_pragma_openmp_end)) { 2145 Actions.EndOpenMPClause(); 2146 break; 2147 } 2148 // Skip ',' if any. 2149 if (Tok.is(tok::comma)) 2150 ConsumeToken(); 2151 Actions.EndOpenMPClause(); 2152 } 2153 // Consume final annot_pragma_openmp_end 2154 if (Clauses.empty()) { 2155 Diag(Tok, diag::err_omp_expected_clause) 2156 << getOpenMPDirectiveName(OMPD_requires); 2157 ConsumeAnnotationToken(); 2158 return nullptr; 2159 } 2160 ConsumeAnnotationToken(); 2161 return Actions.ActOnOpenMPRequiresDirective(StartLoc, Clauses); 2162 } 2163 case OMPD_assumes: 2164 case OMPD_begin_assumes: 2165 ParseOpenMPAssumesDirective(DKind, ConsumeToken()); 2166 break; 2167 case OMPD_end_assumes: 2168 ParseOpenMPEndAssumesDirective(ConsumeToken()); 2169 break; 2170 case OMPD_declare_reduction: 2171 ConsumeToken(); 2172 if (DeclGroupPtrTy Res = ParseOpenMPDeclareReductionDirective(AS)) { 2173 skipUntilPragmaOpenMPEnd(OMPD_declare_reduction); 2174 // Skip the last annot_pragma_openmp_end. 2175 ConsumeAnnotationToken(); 2176 return Res; 2177 } 2178 break; 2179 case OMPD_declare_mapper: { 2180 ConsumeToken(); 2181 if (DeclGroupPtrTy Res = ParseOpenMPDeclareMapperDirective(AS)) { 2182 // Skip the last annot_pragma_openmp_end. 2183 ConsumeAnnotationToken(); 2184 return Res; 2185 } 2186 break; 2187 } 2188 case OMPD_begin_declare_variant: { 2189 // The syntax is: 2190 // { #pragma omp begin declare variant clause } 2191 // <function-declaration-or-definition-sequence> 2192 // { #pragma omp end declare variant } 2193 // 2194 ConsumeToken(); 2195 OMPTraitInfo *ParentTI = Actions.getOMPTraitInfoForSurroundingScope(); 2196 ASTContext &ASTCtx = Actions.getASTContext(); 2197 OMPTraitInfo &TI = ASTCtx.getNewOMPTraitInfo(); 2198 if (parseOMPDeclareVariantMatchClause(Loc, TI, ParentTI)) { 2199 while (!SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch)) 2200 ; 2201 // Skip the last annot_pragma_openmp_end. 2202 (void)ConsumeAnnotationToken(); 2203 break; 2204 } 2205 2206 // Skip last tokens. 2207 skipUntilPragmaOpenMPEnd(OMPD_begin_declare_variant); 2208 2209 ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false); 2210 2211 VariantMatchInfo VMI; 2212 TI.getAsVariantMatchInfo(ASTCtx, VMI); 2213 2214 std::function<void(StringRef)> DiagUnknownTrait = 2215 [this, Loc](StringRef ISATrait) { 2216 // TODO Track the selector locations in a way that is accessible here 2217 // to improve the diagnostic location. 2218 Diag(Loc, diag::warn_unknown_declare_variant_isa_trait) << ISATrait; 2219 }; 2220 TargetOMPContext OMPCtx( 2221 ASTCtx, std::move(DiagUnknownTrait), 2222 /* CurrentFunctionDecl */ nullptr, 2223 /* ConstructTraits */ ArrayRef<llvm::omp::TraitProperty>()); 2224 2225 if (isVariantApplicableInContext(VMI, OMPCtx, /* DeviceSetOnly */ true)) { 2226 Actions.ActOnOpenMPBeginDeclareVariant(Loc, TI); 2227 break; 2228 } 2229 2230 // Elide all the code till the matching end declare variant was found. 2231 unsigned Nesting = 1; 2232 SourceLocation DKLoc; 2233 OpenMPDirectiveKind DK = OMPD_unknown; 2234 do { 2235 DKLoc = Tok.getLocation(); 2236 DK = parseOpenMPDirectiveKind(*this); 2237 if (DK == OMPD_end_declare_variant) 2238 --Nesting; 2239 else if (DK == OMPD_begin_declare_variant) 2240 ++Nesting; 2241 if (!Nesting || isEofOrEom()) 2242 break; 2243 ConsumeAnyToken(); 2244 } while (true); 2245 2246 parseOMPEndDirective(OMPD_begin_declare_variant, OMPD_end_declare_variant, 2247 DK, Loc, DKLoc, /* SkipUntilOpenMPEnd */ true); 2248 if (isEofOrEom()) 2249 return nullptr; 2250 break; 2251 } 2252 case OMPD_end_declare_variant: { 2253 if (Actions.isInOpenMPDeclareVariantScope()) 2254 Actions.ActOnOpenMPEndDeclareVariant(); 2255 else 2256 Diag(Loc, diag::err_expected_begin_declare_variant); 2257 ConsumeToken(); 2258 break; 2259 } 2260 case OMPD_declare_variant: 2261 case OMPD_declare_simd: { 2262 // The syntax is: 2263 // { #pragma omp declare {simd|variant} } 2264 // <function-declaration-or-definition> 2265 // 2266 CachedTokens Toks; 2267 Toks.push_back(Tok); 2268 ConsumeToken(); 2269 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 2270 Toks.push_back(Tok); 2271 ConsumeAnyToken(); 2272 } 2273 Toks.push_back(Tok); 2274 ConsumeAnyToken(); 2275 2276 DeclGroupPtrTy Ptr; 2277 if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) { 2278 Ptr = ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs, Delayed, 2279 TagType, Tag); 2280 } else if (Tok.isNot(tok::r_brace) && !isEofOrEom()) { 2281 // Here we expect to see some function declaration. 2282 if (AS == AS_none) { 2283 assert(TagType == DeclSpec::TST_unspecified); 2284 MaybeParseCXX11Attributes(Attrs); 2285 ParsingDeclSpec PDS(*this); 2286 Ptr = ParseExternalDeclaration(Attrs, &PDS); 2287 } else { 2288 Ptr = 2289 ParseCXXClassMemberDeclarationWithPragmas(AS, Attrs, TagType, Tag); 2290 } 2291 } 2292 if (!Ptr) { 2293 Diag(Loc, diag::err_omp_decl_in_declare_simd_variant) 2294 << (DKind == OMPD_declare_simd ? 0 : 1); 2295 return DeclGroupPtrTy(); 2296 } 2297 if (DKind == OMPD_declare_simd) 2298 return ParseOMPDeclareSimdClauses(Ptr, Toks, Loc); 2299 assert(DKind == OMPD_declare_variant && 2300 "Expected declare variant directive only"); 2301 ParseOMPDeclareVariantClauses(Ptr, Toks, Loc); 2302 return Ptr; 2303 } 2304 case OMPD_begin_declare_target: 2305 case OMPD_declare_target: { 2306 SourceLocation DTLoc = ConsumeAnyToken(); 2307 bool HasClauses = Tok.isNot(tok::annot_pragma_openmp_end); 2308 Sema::DeclareTargetContextInfo DTCI(DKind, DTLoc); 2309 if (HasClauses) 2310 ParseOMPDeclareTargetClauses(DTCI); 2311 bool HasImplicitMappings = 2312 DKind == OMPD_begin_declare_target || !HasClauses || 2313 (DTCI.ExplicitlyMapped.empty() && DTCI.Indirect.hasValue()); 2314 2315 // Skip the last annot_pragma_openmp_end. 2316 ConsumeAnyToken(); 2317 2318 if (HasImplicitMappings) { 2319 Actions.ActOnStartOpenMPDeclareTargetContext(DTCI); 2320 return nullptr; 2321 } 2322 2323 Actions.ActOnFinishedOpenMPDeclareTargetContext(DTCI); 2324 llvm::SmallVector<Decl *, 4> Decls; 2325 for (auto &It : DTCI.ExplicitlyMapped) 2326 Decls.push_back(It.first); 2327 return Actions.BuildDeclaratorGroup(Decls); 2328 } 2329 case OMPD_end_declare_target: { 2330 if (!Actions.isInOpenMPDeclareTargetContext()) { 2331 Diag(Tok, diag::err_omp_unexpected_directive) 2332 << 1 << getOpenMPDirectiveName(DKind); 2333 break; 2334 } 2335 const Sema::DeclareTargetContextInfo &DTCI = 2336 Actions.ActOnOpenMPEndDeclareTargetDirective(); 2337 ParseOMPEndDeclareTargetDirective(DTCI.Kind, DKind, DTCI.Loc); 2338 return nullptr; 2339 } 2340 case OMPD_unknown: 2341 Diag(Tok, diag::err_omp_unknown_directive); 2342 break; 2343 case OMPD_parallel: 2344 case OMPD_simd: 2345 case OMPD_tile: 2346 case OMPD_unroll: 2347 case OMPD_task: 2348 case OMPD_taskyield: 2349 case OMPD_barrier: 2350 case OMPD_taskwait: 2351 case OMPD_taskgroup: 2352 case OMPD_flush: 2353 case OMPD_depobj: 2354 case OMPD_scan: 2355 case OMPD_for: 2356 case OMPD_for_simd: 2357 case OMPD_sections: 2358 case OMPD_section: 2359 case OMPD_single: 2360 case OMPD_master: 2361 case OMPD_ordered: 2362 case OMPD_critical: 2363 case OMPD_parallel_for: 2364 case OMPD_parallel_for_simd: 2365 case OMPD_parallel_sections: 2366 case OMPD_parallel_master: 2367 case OMPD_atomic: 2368 case OMPD_target: 2369 case OMPD_teams: 2370 case OMPD_cancellation_point: 2371 case OMPD_cancel: 2372 case OMPD_target_data: 2373 case OMPD_target_enter_data: 2374 case OMPD_target_exit_data: 2375 case OMPD_target_parallel: 2376 case OMPD_target_parallel_for: 2377 case OMPD_taskloop: 2378 case OMPD_taskloop_simd: 2379 case OMPD_master_taskloop: 2380 case OMPD_master_taskloop_simd: 2381 case OMPD_parallel_master_taskloop: 2382 case OMPD_parallel_master_taskloop_simd: 2383 case OMPD_distribute: 2384 case OMPD_target_update: 2385 case OMPD_distribute_parallel_for: 2386 case OMPD_distribute_parallel_for_simd: 2387 case OMPD_distribute_simd: 2388 case OMPD_target_parallel_for_simd: 2389 case OMPD_target_simd: 2390 case OMPD_teams_distribute: 2391 case OMPD_teams_distribute_simd: 2392 case OMPD_teams_distribute_parallel_for_simd: 2393 case OMPD_teams_distribute_parallel_for: 2394 case OMPD_target_teams: 2395 case OMPD_target_teams_distribute: 2396 case OMPD_target_teams_distribute_parallel_for: 2397 case OMPD_target_teams_distribute_parallel_for_simd: 2398 case OMPD_target_teams_distribute_simd: 2399 case OMPD_dispatch: 2400 case OMPD_masked: 2401 case OMPD_metadirective: 2402 case OMPD_loop: 2403 case OMPD_teams_loop: 2404 Diag(Tok, diag::err_omp_unexpected_directive) 2405 << 1 << getOpenMPDirectiveName(DKind); 2406 break; 2407 default: 2408 break; 2409 } 2410 while (Tok.isNot(tok::annot_pragma_openmp_end)) 2411 ConsumeAnyToken(); 2412 ConsumeAnyToken(); 2413 return nullptr; 2414 } 2415 2416 /// Parsing of declarative or executable OpenMP directives. 2417 /// 2418 /// threadprivate-directive: 2419 /// annot_pragma_openmp 'threadprivate' simple-variable-list 2420 /// annot_pragma_openmp_end 2421 /// 2422 /// allocate-directive: 2423 /// annot_pragma_openmp 'allocate' simple-variable-list 2424 /// annot_pragma_openmp_end 2425 /// 2426 /// declare-reduction-directive: 2427 /// annot_pragma_openmp 'declare' 'reduction' '(' <reduction_id> ':' 2428 /// <type> {',' <type>} ':' <expression> ')' ['initializer' '(' 2429 /// ('omp_priv' '=' <expression>|<function_call>) ')'] 2430 /// annot_pragma_openmp_end 2431 /// 2432 /// declare-mapper-directive: 2433 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':'] 2434 /// <type> <var> ')' [<clause>[[,] <clause>] ... ] 2435 /// annot_pragma_openmp_end 2436 /// 2437 /// executable-directive: 2438 /// annot_pragma_openmp 'parallel' | 'simd' | 'for' | 'sections' | 2439 /// 'section' | 'single' | 'master' | 'critical' [ '(' <name> ')' ] | 2440 /// 'parallel for' | 'parallel sections' | 'parallel master' | 'task' | 2441 /// 'taskyield' | 'barrier' | 'taskwait' | 'flush' | 'ordered' | 2442 /// 'atomic' | 'for simd' | 'parallel for simd' | 'target' | 'target 2443 /// data' | 'taskgroup' | 'teams' | 'taskloop' | 'taskloop simd' | 2444 /// 'master taskloop' | 'master taskloop simd' | 'parallel master 2445 /// taskloop' | 'parallel master taskloop simd' | 'distribute' | 'target 2446 /// enter data' | 'target exit data' | 'target parallel' | 'target 2447 /// parallel for' | 'target update' | 'distribute parallel for' | 2448 /// 'distribute paralle for simd' | 'distribute simd' | 'target parallel 2449 /// for simd' | 'target simd' | 'teams distribute' | 'teams distribute 2450 /// simd' | 'teams distribute parallel for simd' | 'teams distribute 2451 /// parallel for' | 'target teams' | 'target teams distribute' | 'target 2452 /// teams distribute parallel for' | 'target teams distribute parallel 2453 /// for simd' | 'target teams distribute simd' | 'masked' {clause} 2454 /// annot_pragma_openmp_end 2455 /// 2456 StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective( 2457 ParsedStmtContext StmtCtx, bool ReadDirectiveWithinMetadirective) { 2458 if (!ReadDirectiveWithinMetadirective) 2459 assert(Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp) && 2460 "Not an OpenMP directive!"); 2461 ParsingOpenMPDirectiveRAII DirScope(*this); 2462 ParenBraceBracketBalancer BalancerRAIIObj(*this); 2463 SmallVector<OMPClause *, 5> Clauses; 2464 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, 2465 llvm::omp::Clause_enumSize + 1> 2466 FirstClauses(llvm::omp::Clause_enumSize + 1); 2467 unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope | 2468 Scope::CompoundStmtScope | Scope::OpenMPDirectiveScope; 2469 SourceLocation Loc = ReadDirectiveWithinMetadirective 2470 ? Tok.getLocation() 2471 : ConsumeAnnotationToken(), 2472 EndLoc; 2473 OpenMPDirectiveKind DKind = parseOpenMPDirectiveKind(*this); 2474 if (ReadDirectiveWithinMetadirective && DKind == OMPD_unknown) { 2475 Diag(Tok, diag::err_omp_unknown_directive); 2476 return StmtError(); 2477 } 2478 OpenMPDirectiveKind CancelRegion = OMPD_unknown; 2479 // Name of critical directive. 2480 DeclarationNameInfo DirName; 2481 StmtResult Directive = StmtError(); 2482 bool HasAssociatedStatement = true; 2483 2484 switch (DKind) { 2485 case OMPD_metadirective: { 2486 ConsumeToken(); 2487 SmallVector<VariantMatchInfo, 4> VMIs; 2488 2489 // First iteration of parsing all clauses of metadirective. 2490 // This iteration only parses and collects all context selector ignoring the 2491 // associated directives. 2492 TentativeParsingAction TPA(*this); 2493 ASTContext &ASTContext = Actions.getASTContext(); 2494 2495 BalancedDelimiterTracker T(*this, tok::l_paren, 2496 tok::annot_pragma_openmp_end); 2497 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 2498 OpenMPClauseKind CKind = Tok.isAnnotation() 2499 ? OMPC_unknown 2500 : getOpenMPClauseKind(PP.getSpelling(Tok)); 2501 SourceLocation Loc = ConsumeToken(); 2502 2503 // Parse '('. 2504 if (T.expectAndConsume(diag::err_expected_lparen_after, 2505 getOpenMPClauseName(CKind).data())) 2506 return Directive; 2507 2508 OMPTraitInfo &TI = Actions.getASTContext().getNewOMPTraitInfo(); 2509 if (CKind == OMPC_when) { 2510 // parse and get OMPTraitInfo to pass to the When clause 2511 parseOMPContextSelectors(Loc, TI); 2512 if (TI.Sets.size() == 0) { 2513 Diag(Tok, diag::err_omp_expected_context_selector) << "when clause"; 2514 TPA.Commit(); 2515 return Directive; 2516 } 2517 2518 // Parse ':' 2519 if (Tok.is(tok::colon)) 2520 ConsumeAnyToken(); 2521 else { 2522 Diag(Tok, diag::err_omp_expected_colon) << "when clause"; 2523 TPA.Commit(); 2524 return Directive; 2525 } 2526 } 2527 // Skip Directive for now. We will parse directive in the second iteration 2528 int paren = 0; 2529 while (Tok.isNot(tok::r_paren) || paren != 0) { 2530 if (Tok.is(tok::l_paren)) 2531 paren++; 2532 if (Tok.is(tok::r_paren)) 2533 paren--; 2534 if (Tok.is(tok::annot_pragma_openmp_end)) { 2535 Diag(Tok, diag::err_omp_expected_punc) 2536 << getOpenMPClauseName(CKind) << 0; 2537 TPA.Commit(); 2538 return Directive; 2539 } 2540 ConsumeAnyToken(); 2541 } 2542 // Parse ')' 2543 if (Tok.is(tok::r_paren)) 2544 T.consumeClose(); 2545 2546 VariantMatchInfo VMI; 2547 TI.getAsVariantMatchInfo(ASTContext, VMI); 2548 2549 VMIs.push_back(VMI); 2550 } 2551 2552 TPA.Revert(); 2553 // End of the first iteration. Parser is reset to the start of metadirective 2554 2555 std::function<void(StringRef)> DiagUnknownTrait = 2556 [this, Loc](StringRef ISATrait) { 2557 // TODO Track the selector locations in a way that is accessible here 2558 // to improve the diagnostic location. 2559 Diag(Loc, diag::warn_unknown_declare_variant_isa_trait) << ISATrait; 2560 }; 2561 TargetOMPContext OMPCtx(ASTContext, std::move(DiagUnknownTrait), 2562 /* CurrentFunctionDecl */ nullptr, 2563 ArrayRef<llvm::omp::TraitProperty>()); 2564 2565 // A single match is returned for OpenMP 5.0 2566 int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx); 2567 2568 int Idx = 0; 2569 // In OpenMP 5.0 metadirective is either replaced by another directive or 2570 // ignored. 2571 // TODO: In OpenMP 5.1 generate multiple directives based upon the matches 2572 // found by getBestWhenMatchForContext. 2573 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 2574 // OpenMP 5.0 implementation - Skip to the best index found. 2575 if (Idx++ != BestIdx) { 2576 ConsumeToken(); // Consume clause name 2577 T.consumeOpen(); // Consume '(' 2578 int paren = 0; 2579 // Skip everything inside the clause 2580 while (Tok.isNot(tok::r_paren) || paren != 0) { 2581 if (Tok.is(tok::l_paren)) 2582 paren++; 2583 if (Tok.is(tok::r_paren)) 2584 paren--; 2585 ConsumeAnyToken(); 2586 } 2587 // Parse ')' 2588 if (Tok.is(tok::r_paren)) 2589 T.consumeClose(); 2590 continue; 2591 } 2592 2593 OpenMPClauseKind CKind = Tok.isAnnotation() 2594 ? OMPC_unknown 2595 : getOpenMPClauseKind(PP.getSpelling(Tok)); 2596 SourceLocation Loc = ConsumeToken(); 2597 2598 // Parse '('. 2599 T.consumeOpen(); 2600 2601 // Skip ContextSelectors for when clause 2602 if (CKind == OMPC_when) { 2603 OMPTraitInfo &TI = Actions.getASTContext().getNewOMPTraitInfo(); 2604 // parse and skip the ContextSelectors 2605 parseOMPContextSelectors(Loc, TI); 2606 2607 // Parse ':' 2608 ConsumeAnyToken(); 2609 } 2610 2611 // If no directive is passed, skip in OpenMP 5.0. 2612 // TODO: Generate nothing directive from OpenMP 5.1. 2613 if (Tok.is(tok::r_paren)) { 2614 SkipUntil(tok::annot_pragma_openmp_end); 2615 break; 2616 } 2617 2618 // Parse Directive 2619 Directive = ParseOpenMPDeclarativeOrExecutableDirective( 2620 StmtCtx, 2621 /*ReadDirectiveWithinMetadirective=*/true); 2622 break; 2623 } 2624 break; 2625 } 2626 case OMPD_threadprivate: { 2627 // FIXME: Should this be permitted in C++? 2628 if ((StmtCtx & ParsedStmtContext::AllowDeclarationsInC) == 2629 ParsedStmtContext()) { 2630 Diag(Tok, diag::err_omp_immediate_directive) 2631 << getOpenMPDirectiveName(DKind) << 0; 2632 } 2633 ConsumeToken(); 2634 DeclDirectiveListParserHelper Helper(this, DKind); 2635 if (!ParseOpenMPSimpleVarList(DKind, Helper, 2636 /*AllowScopeSpecifier=*/false)) { 2637 skipUntilPragmaOpenMPEnd(DKind); 2638 DeclGroupPtrTy Res = Actions.ActOnOpenMPThreadprivateDirective( 2639 Loc, Helper.getIdentifiers()); 2640 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation()); 2641 } 2642 SkipUntil(tok::annot_pragma_openmp_end); 2643 break; 2644 } 2645 case OMPD_allocate: { 2646 // FIXME: Should this be permitted in C++? 2647 if ((StmtCtx & ParsedStmtContext::AllowDeclarationsInC) == 2648 ParsedStmtContext()) { 2649 Diag(Tok, diag::err_omp_immediate_directive) 2650 << getOpenMPDirectiveName(DKind) << 0; 2651 } 2652 ConsumeToken(); 2653 DeclDirectiveListParserHelper Helper(this, DKind); 2654 if (!ParseOpenMPSimpleVarList(DKind, Helper, 2655 /*AllowScopeSpecifier=*/false)) { 2656 SmallVector<OMPClause *, 1> Clauses; 2657 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 2658 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, 2659 llvm::omp::Clause_enumSize + 1> 2660 FirstClauses(llvm::omp::Clause_enumSize + 1); 2661 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 2662 OpenMPClauseKind CKind = 2663 Tok.isAnnotation() ? OMPC_unknown 2664 : getOpenMPClauseKind(PP.getSpelling(Tok)); 2665 Actions.StartOpenMPClause(CKind); 2666 OMPClause *Clause = ParseOpenMPClause( 2667 OMPD_allocate, CKind, !FirstClauses[unsigned(CKind)].getInt()); 2668 SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end, 2669 StopBeforeMatch); 2670 FirstClauses[unsigned(CKind)].setInt(true); 2671 if (Clause != nullptr) 2672 Clauses.push_back(Clause); 2673 if (Tok.is(tok::annot_pragma_openmp_end)) { 2674 Actions.EndOpenMPClause(); 2675 break; 2676 } 2677 // Skip ',' if any. 2678 if (Tok.is(tok::comma)) 2679 ConsumeToken(); 2680 Actions.EndOpenMPClause(); 2681 } 2682 skipUntilPragmaOpenMPEnd(DKind); 2683 } 2684 DeclGroupPtrTy Res = Actions.ActOnOpenMPAllocateDirective( 2685 Loc, Helper.getIdentifiers(), Clauses); 2686 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation()); 2687 } 2688 SkipUntil(tok::annot_pragma_openmp_end); 2689 break; 2690 } 2691 case OMPD_declare_reduction: 2692 ConsumeToken(); 2693 if (DeclGroupPtrTy Res = 2694 ParseOpenMPDeclareReductionDirective(/*AS=*/AS_none)) { 2695 skipUntilPragmaOpenMPEnd(OMPD_declare_reduction); 2696 ConsumeAnyToken(); 2697 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation()); 2698 } else { 2699 SkipUntil(tok::annot_pragma_openmp_end); 2700 } 2701 break; 2702 case OMPD_declare_mapper: { 2703 ConsumeToken(); 2704 if (DeclGroupPtrTy Res = 2705 ParseOpenMPDeclareMapperDirective(/*AS=*/AS_none)) { 2706 // Skip the last annot_pragma_openmp_end. 2707 ConsumeAnnotationToken(); 2708 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation()); 2709 } else { 2710 SkipUntil(tok::annot_pragma_openmp_end); 2711 } 2712 break; 2713 } 2714 case OMPD_flush: 2715 case OMPD_depobj: 2716 case OMPD_scan: 2717 case OMPD_taskyield: 2718 case OMPD_barrier: 2719 case OMPD_taskwait: 2720 case OMPD_cancellation_point: 2721 case OMPD_cancel: 2722 case OMPD_target_enter_data: 2723 case OMPD_target_exit_data: 2724 case OMPD_target_update: 2725 case OMPD_interop: 2726 if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) == 2727 ParsedStmtContext()) { 2728 Diag(Tok, diag::err_omp_immediate_directive) 2729 << getOpenMPDirectiveName(DKind) << 0; 2730 } 2731 HasAssociatedStatement = false; 2732 // Fall through for further analysis. 2733 LLVM_FALLTHROUGH; 2734 case OMPD_parallel: 2735 case OMPD_simd: 2736 case OMPD_tile: 2737 case OMPD_unroll: 2738 case OMPD_for: 2739 case OMPD_for_simd: 2740 case OMPD_sections: 2741 case OMPD_single: 2742 case OMPD_section: 2743 case OMPD_master: 2744 case OMPD_critical: 2745 case OMPD_parallel_for: 2746 case OMPD_parallel_for_simd: 2747 case OMPD_parallel_sections: 2748 case OMPD_parallel_master: 2749 case OMPD_task: 2750 case OMPD_ordered: 2751 case OMPD_atomic: 2752 case OMPD_target: 2753 case OMPD_teams: 2754 case OMPD_taskgroup: 2755 case OMPD_target_data: 2756 case OMPD_target_parallel: 2757 case OMPD_target_parallel_for: 2758 case OMPD_loop: 2759 case OMPD_teams_loop: 2760 case OMPD_taskloop: 2761 case OMPD_taskloop_simd: 2762 case OMPD_master_taskloop: 2763 case OMPD_master_taskloop_simd: 2764 case OMPD_parallel_master_taskloop: 2765 case OMPD_parallel_master_taskloop_simd: 2766 case OMPD_distribute: 2767 case OMPD_distribute_parallel_for: 2768 case OMPD_distribute_parallel_for_simd: 2769 case OMPD_distribute_simd: 2770 case OMPD_target_parallel_for_simd: 2771 case OMPD_target_simd: 2772 case OMPD_teams_distribute: 2773 case OMPD_teams_distribute_simd: 2774 case OMPD_teams_distribute_parallel_for_simd: 2775 case OMPD_teams_distribute_parallel_for: 2776 case OMPD_target_teams: 2777 case OMPD_target_teams_distribute: 2778 case OMPD_target_teams_distribute_parallel_for: 2779 case OMPD_target_teams_distribute_parallel_for_simd: 2780 case OMPD_target_teams_distribute_simd: 2781 case OMPD_dispatch: 2782 case OMPD_masked: { 2783 // Special processing for flush and depobj clauses. 2784 Token ImplicitTok; 2785 bool ImplicitClauseAllowed = false; 2786 if (DKind == OMPD_flush || DKind == OMPD_depobj) { 2787 ImplicitTok = Tok; 2788 ImplicitClauseAllowed = true; 2789 } 2790 ConsumeToken(); 2791 // Parse directive name of the 'critical' directive if any. 2792 if (DKind == OMPD_critical) { 2793 BalancedDelimiterTracker T(*this, tok::l_paren, 2794 tok::annot_pragma_openmp_end); 2795 if (!T.consumeOpen()) { 2796 if (Tok.isAnyIdentifier()) { 2797 DirName = 2798 DeclarationNameInfo(Tok.getIdentifierInfo(), Tok.getLocation()); 2799 ConsumeAnyToken(); 2800 } else { 2801 Diag(Tok, diag::err_omp_expected_identifier_for_critical); 2802 } 2803 T.consumeClose(); 2804 } 2805 } else if (DKind == OMPD_cancellation_point || DKind == OMPD_cancel) { 2806 CancelRegion = parseOpenMPDirectiveKind(*this); 2807 if (Tok.isNot(tok::annot_pragma_openmp_end)) 2808 ConsumeToken(); 2809 } 2810 2811 if (isOpenMPLoopDirective(DKind)) 2812 ScopeFlags |= Scope::OpenMPLoopDirectiveScope; 2813 if (isOpenMPSimdDirective(DKind)) 2814 ScopeFlags |= Scope::OpenMPSimdDirectiveScope; 2815 ParseScope OMPDirectiveScope(this, ScopeFlags); 2816 Actions.StartOpenMPDSABlock(DKind, DirName, Actions.getCurScope(), Loc); 2817 2818 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 2819 // If we are parsing for a directive within a metadirective, the directive 2820 // ends with a ')'. 2821 if (ReadDirectiveWithinMetadirective && Tok.is(tok::r_paren)) { 2822 while (Tok.isNot(tok::annot_pragma_openmp_end)) 2823 ConsumeAnyToken(); 2824 break; 2825 } 2826 bool HasImplicitClause = false; 2827 if (ImplicitClauseAllowed && Tok.is(tok::l_paren)) { 2828 HasImplicitClause = true; 2829 // Push copy of the current token back to stream to properly parse 2830 // pseudo-clause OMPFlushClause or OMPDepobjClause. 2831 PP.EnterToken(Tok, /*IsReinject*/ true); 2832 PP.EnterToken(ImplicitTok, /*IsReinject*/ true); 2833 ConsumeAnyToken(); 2834 } 2835 OpenMPClauseKind CKind = Tok.isAnnotation() 2836 ? OMPC_unknown 2837 : getOpenMPClauseKind(PP.getSpelling(Tok)); 2838 if (HasImplicitClause) { 2839 assert(CKind == OMPC_unknown && "Must be unknown implicit clause."); 2840 if (DKind == OMPD_flush) { 2841 CKind = OMPC_flush; 2842 } else { 2843 assert(DKind == OMPD_depobj && 2844 "Expected flush or depobj directives."); 2845 CKind = OMPC_depobj; 2846 } 2847 } 2848 // No more implicit clauses allowed. 2849 ImplicitClauseAllowed = false; 2850 Actions.StartOpenMPClause(CKind); 2851 HasImplicitClause = false; 2852 OMPClause *Clause = ParseOpenMPClause( 2853 DKind, CKind, !FirstClauses[unsigned(CKind)].getInt()); 2854 FirstClauses[unsigned(CKind)].setInt(true); 2855 if (Clause) { 2856 FirstClauses[unsigned(CKind)].setPointer(Clause); 2857 Clauses.push_back(Clause); 2858 } 2859 2860 // Skip ',' if any. 2861 if (Tok.is(tok::comma)) 2862 ConsumeToken(); 2863 Actions.EndOpenMPClause(); 2864 } 2865 // End location of the directive. 2866 EndLoc = Tok.getLocation(); 2867 // Consume final annot_pragma_openmp_end. 2868 ConsumeAnnotationToken(); 2869 2870 // OpenMP [2.13.8, ordered Construct, Syntax] 2871 // If the depend clause is specified, the ordered construct is a stand-alone 2872 // directive. 2873 if (DKind == OMPD_ordered && FirstClauses[unsigned(OMPC_depend)].getInt()) { 2874 if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) == 2875 ParsedStmtContext()) { 2876 Diag(Loc, diag::err_omp_immediate_directive) 2877 << getOpenMPDirectiveName(DKind) << 1 2878 << getOpenMPClauseName(OMPC_depend); 2879 } 2880 HasAssociatedStatement = false; 2881 } 2882 2883 if (DKind == OMPD_tile && !FirstClauses[unsigned(OMPC_sizes)].getInt()) { 2884 Diag(Loc, diag::err_omp_required_clause) 2885 << getOpenMPDirectiveName(OMPD_tile) << "sizes"; 2886 } 2887 2888 StmtResult AssociatedStmt; 2889 if (HasAssociatedStatement) { 2890 // The body is a block scope like in Lambdas and Blocks. 2891 Actions.ActOnOpenMPRegionStart(DKind, getCurScope()); 2892 // FIXME: We create a bogus CompoundStmt scope to hold the contents of 2893 // the captured region. Code elsewhere assumes that any FunctionScopeInfo 2894 // should have at least one compound statement scope within it. 2895 ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false); 2896 { 2897 Sema::CompoundScopeRAII Scope(Actions); 2898 AssociatedStmt = ParseStatement(); 2899 2900 if (AssociatedStmt.isUsable() && isOpenMPLoopDirective(DKind) && 2901 getLangOpts().OpenMPIRBuilder) 2902 AssociatedStmt = Actions.ActOnOpenMPLoopnest(AssociatedStmt.get()); 2903 } 2904 AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses); 2905 } else if (DKind == OMPD_target_update || DKind == OMPD_target_enter_data || 2906 DKind == OMPD_target_exit_data) { 2907 Actions.ActOnOpenMPRegionStart(DKind, getCurScope()); 2908 AssociatedStmt = (Sema::CompoundScopeRAII(Actions), 2909 Actions.ActOnCompoundStmt(Loc, Loc, llvm::None, 2910 /*isStmtExpr=*/false)); 2911 AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses); 2912 } 2913 Directive = Actions.ActOnOpenMPExecutableDirective( 2914 DKind, DirName, CancelRegion, Clauses, AssociatedStmt.get(), Loc, 2915 EndLoc); 2916 2917 // Exit scope. 2918 Actions.EndOpenMPDSABlock(Directive.get()); 2919 OMPDirectiveScope.Exit(); 2920 break; 2921 } 2922 case OMPD_declare_simd: 2923 case OMPD_declare_target: 2924 case OMPD_begin_declare_target: 2925 case OMPD_end_declare_target: 2926 case OMPD_requires: 2927 case OMPD_begin_declare_variant: 2928 case OMPD_end_declare_variant: 2929 case OMPD_declare_variant: 2930 Diag(Tok, diag::err_omp_unexpected_directive) 2931 << 1 << getOpenMPDirectiveName(DKind); 2932 SkipUntil(tok::annot_pragma_openmp_end); 2933 break; 2934 case OMPD_unknown: 2935 default: 2936 Diag(Tok, diag::err_omp_unknown_directive); 2937 SkipUntil(tok::annot_pragma_openmp_end); 2938 break; 2939 } 2940 return Directive; 2941 } 2942 2943 // Parses simple list: 2944 // simple-variable-list: 2945 // '(' id-expression {, id-expression} ')' 2946 // 2947 bool Parser::ParseOpenMPSimpleVarList( 2948 OpenMPDirectiveKind Kind, 2949 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> 2950 &Callback, 2951 bool AllowScopeSpecifier) { 2952 // Parse '('. 2953 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 2954 if (T.expectAndConsume(diag::err_expected_lparen_after, 2955 getOpenMPDirectiveName(Kind).data())) 2956 return true; 2957 bool IsCorrect = true; 2958 bool NoIdentIsFound = true; 2959 2960 // Read tokens while ')' or annot_pragma_openmp_end is not found. 2961 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) { 2962 CXXScopeSpec SS; 2963 UnqualifiedId Name; 2964 // Read var name. 2965 Token PrevTok = Tok; 2966 NoIdentIsFound = false; 2967 2968 if (AllowScopeSpecifier && getLangOpts().CPlusPlus && 2969 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr, 2970 /*ObjectHasErrors=*/false, false)) { 2971 IsCorrect = false; 2972 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 2973 StopBeforeMatch); 2974 } else if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr, 2975 /*ObjectHadErrors=*/false, false, false, 2976 false, false, nullptr, Name)) { 2977 IsCorrect = false; 2978 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 2979 StopBeforeMatch); 2980 } else if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren) && 2981 Tok.isNot(tok::annot_pragma_openmp_end)) { 2982 IsCorrect = false; 2983 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 2984 StopBeforeMatch); 2985 Diag(PrevTok.getLocation(), diag::err_expected) 2986 << tok::identifier 2987 << SourceRange(PrevTok.getLocation(), PrevTokLocation); 2988 } else { 2989 Callback(SS, Actions.GetNameFromUnqualifiedId(Name)); 2990 } 2991 // Consume ','. 2992 if (Tok.is(tok::comma)) { 2993 ConsumeToken(); 2994 } 2995 } 2996 2997 if (NoIdentIsFound) { 2998 Diag(Tok, diag::err_expected) << tok::identifier; 2999 IsCorrect = false; 3000 } 3001 3002 // Parse ')'. 3003 IsCorrect = !T.consumeClose() && IsCorrect; 3004 3005 return !IsCorrect; 3006 } 3007 3008 OMPClause *Parser::ParseOpenMPSizesClause() { 3009 SourceLocation ClauseNameLoc = ConsumeToken(); 3010 SmallVector<Expr *, 4> ValExprs; 3011 3012 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 3013 if (T.consumeOpen()) { 3014 Diag(Tok, diag::err_expected) << tok::l_paren; 3015 return nullptr; 3016 } 3017 3018 while (true) { 3019 ExprResult Val = ParseConstantExpression(); 3020 if (!Val.isUsable()) { 3021 T.skipToEnd(); 3022 return nullptr; 3023 } 3024 3025 ValExprs.push_back(Val.get()); 3026 3027 if (Tok.is(tok::r_paren) || Tok.is(tok::annot_pragma_openmp_end)) 3028 break; 3029 3030 ExpectAndConsume(tok::comma); 3031 } 3032 3033 T.consumeClose(); 3034 3035 return Actions.ActOnOpenMPSizesClause( 3036 ValExprs, ClauseNameLoc, T.getOpenLocation(), T.getCloseLocation()); 3037 } 3038 3039 OMPClause *Parser::ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind) { 3040 SourceLocation Loc = Tok.getLocation(); 3041 ConsumeAnyToken(); 3042 3043 // Parse '('. 3044 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 3045 if (T.expectAndConsume(diag::err_expected_lparen_after, "uses_allocator")) 3046 return nullptr; 3047 SmallVector<Sema::UsesAllocatorsData, 4> Data; 3048 do { 3049 ExprResult Allocator = 3050 getLangOpts().CPlusPlus ? ParseCXXIdExpression() : ParseExpression(); 3051 if (Allocator.isInvalid()) { 3052 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 3053 StopBeforeMatch); 3054 break; 3055 } 3056 Sema::UsesAllocatorsData &D = Data.emplace_back(); 3057 D.Allocator = Allocator.get(); 3058 if (Tok.is(tok::l_paren)) { 3059 BalancedDelimiterTracker T(*this, tok::l_paren, 3060 tok::annot_pragma_openmp_end); 3061 T.consumeOpen(); 3062 ExprResult AllocatorTraits = 3063 getLangOpts().CPlusPlus ? ParseCXXIdExpression() : ParseExpression(); 3064 T.consumeClose(); 3065 if (AllocatorTraits.isInvalid()) { 3066 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 3067 StopBeforeMatch); 3068 break; 3069 } 3070 D.AllocatorTraits = AllocatorTraits.get(); 3071 D.LParenLoc = T.getOpenLocation(); 3072 D.RParenLoc = T.getCloseLocation(); 3073 } 3074 if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren)) 3075 Diag(Tok, diag::err_omp_expected_punc) << "uses_allocators" << 0; 3076 // Parse ',' 3077 if (Tok.is(tok::comma)) 3078 ConsumeAnyToken(); 3079 } while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)); 3080 T.consumeClose(); 3081 return Actions.ActOnOpenMPUsesAllocatorClause(Loc, T.getOpenLocation(), 3082 T.getCloseLocation(), Data); 3083 } 3084 3085 /// Parsing of OpenMP clauses. 3086 /// 3087 /// clause: 3088 /// if-clause | final-clause | num_threads-clause | safelen-clause | 3089 /// default-clause | private-clause | firstprivate-clause | shared-clause 3090 /// | linear-clause | aligned-clause | collapse-clause | bind-clause | 3091 /// lastprivate-clause | reduction-clause | proc_bind-clause | 3092 /// schedule-clause | copyin-clause | copyprivate-clause | untied-clause | 3093 /// mergeable-clause | flush-clause | read-clause | write-clause | 3094 /// update-clause | capture-clause | seq_cst-clause | device-clause | 3095 /// simdlen-clause | threads-clause | simd-clause | num_teams-clause | 3096 /// thread_limit-clause | priority-clause | grainsize-clause | 3097 /// nogroup-clause | num_tasks-clause | hint-clause | to-clause | 3098 /// from-clause | is_device_ptr-clause | task_reduction-clause | 3099 /// in_reduction-clause | allocator-clause | allocate-clause | 3100 /// acq_rel-clause | acquire-clause | release-clause | relaxed-clause | 3101 /// depobj-clause | destroy-clause | detach-clause | inclusive-clause | 3102 /// exclusive-clause | uses_allocators-clause | use_device_addr-clause 3103 /// 3104 OMPClause *Parser::ParseOpenMPClause(OpenMPDirectiveKind DKind, 3105 OpenMPClauseKind CKind, bool FirstClause) { 3106 OMPClauseKind = CKind; 3107 OMPClause *Clause = nullptr; 3108 bool ErrorFound = false; 3109 bool WrongDirective = false; 3110 // Check if clause is allowed for the given directive. 3111 if (CKind != OMPC_unknown && 3112 !isAllowedClauseForDirective(DKind, CKind, getLangOpts().OpenMP)) { 3113 Diag(Tok, diag::err_omp_unexpected_clause) 3114 << getOpenMPClauseName(CKind) << getOpenMPDirectiveName(DKind); 3115 ErrorFound = true; 3116 WrongDirective = true; 3117 } 3118 3119 switch (CKind) { 3120 case OMPC_final: 3121 case OMPC_num_threads: 3122 case OMPC_safelen: 3123 case OMPC_simdlen: 3124 case OMPC_collapse: 3125 case OMPC_ordered: 3126 case OMPC_num_teams: 3127 case OMPC_thread_limit: 3128 case OMPC_priority: 3129 case OMPC_grainsize: 3130 case OMPC_num_tasks: 3131 case OMPC_hint: 3132 case OMPC_allocator: 3133 case OMPC_depobj: 3134 case OMPC_detach: 3135 case OMPC_novariants: 3136 case OMPC_nocontext: 3137 case OMPC_filter: 3138 case OMPC_partial: 3139 case OMPC_align: 3140 // OpenMP [2.5, Restrictions] 3141 // At most one num_threads clause can appear on the directive. 3142 // OpenMP [2.8.1, simd construct, Restrictions] 3143 // Only one safelen clause can appear on a simd directive. 3144 // Only one simdlen clause can appear on a simd directive. 3145 // Only one collapse clause can appear on a simd directive. 3146 // OpenMP [2.11.1, task Construct, Restrictions] 3147 // At most one if clause can appear on the directive. 3148 // At most one final clause can appear on the directive. 3149 // OpenMP [teams Construct, Restrictions] 3150 // At most one num_teams clause can appear on the directive. 3151 // At most one thread_limit clause can appear on the directive. 3152 // OpenMP [2.9.1, task Construct, Restrictions] 3153 // At most one priority clause can appear on the directive. 3154 // OpenMP [2.9.2, taskloop Construct, Restrictions] 3155 // At most one grainsize clause can appear on the directive. 3156 // OpenMP [2.9.2, taskloop Construct, Restrictions] 3157 // At most one num_tasks clause can appear on the directive. 3158 // OpenMP [2.11.3, allocate Directive, Restrictions] 3159 // At most one allocator clause can appear on the directive. 3160 // OpenMP 5.0, 2.10.1 task Construct, Restrictions. 3161 // At most one detach clause can appear on the directive. 3162 // OpenMP 5.1, 2.3.6 dispatch Construct, Restrictions. 3163 // At most one novariants clause can appear on a dispatch directive. 3164 // At most one nocontext clause can appear on a dispatch directive. 3165 if (!FirstClause) { 3166 Diag(Tok, diag::err_omp_more_one_clause) 3167 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 3168 ErrorFound = true; 3169 } 3170 3171 if ((CKind == OMPC_ordered || CKind == OMPC_partial) && 3172 PP.LookAhead(/*N=*/0).isNot(tok::l_paren)) 3173 Clause = ParseOpenMPClause(CKind, WrongDirective); 3174 else 3175 Clause = ParseOpenMPSingleExprClause(CKind, WrongDirective); 3176 break; 3177 case OMPC_default: 3178 case OMPC_proc_bind: 3179 case OMPC_atomic_default_mem_order: 3180 case OMPC_order: 3181 case OMPC_bind: 3182 // OpenMP [2.14.3.1, Restrictions] 3183 // Only a single default clause may be specified on a parallel, task or 3184 // teams directive. 3185 // OpenMP [2.5, parallel Construct, Restrictions] 3186 // At most one proc_bind clause can appear on the directive. 3187 // OpenMP [5.0, Requires directive, Restrictions] 3188 // At most one atomic_default_mem_order clause can appear 3189 // on the directive 3190 // OpenMP 5.1, 2.11.7 loop Construct, Restrictions. 3191 // At most one bind clause can appear on a loop directive. 3192 if (!FirstClause && CKind != OMPC_order) { 3193 Diag(Tok, diag::err_omp_more_one_clause) 3194 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 3195 ErrorFound = true; 3196 } 3197 3198 Clause = ParseOpenMPSimpleClause(CKind, WrongDirective); 3199 break; 3200 case OMPC_device: 3201 case OMPC_schedule: 3202 case OMPC_dist_schedule: 3203 case OMPC_defaultmap: 3204 // OpenMP [2.7.1, Restrictions, p. 3] 3205 // Only one schedule clause can appear on a loop directive. 3206 // OpenMP 4.5 [2.10.4, Restrictions, p. 106] 3207 // At most one defaultmap clause can appear on the directive. 3208 // OpenMP 5.0 [2.12.5, target construct, Restrictions] 3209 // At most one device clause can appear on the directive. 3210 if ((getLangOpts().OpenMP < 50 || CKind != OMPC_defaultmap) && 3211 !FirstClause) { 3212 Diag(Tok, diag::err_omp_more_one_clause) 3213 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 3214 ErrorFound = true; 3215 } 3216 LLVM_FALLTHROUGH; 3217 case OMPC_if: 3218 Clause = ParseOpenMPSingleExprWithArgClause(DKind, CKind, WrongDirective); 3219 break; 3220 case OMPC_nowait: 3221 case OMPC_untied: 3222 case OMPC_mergeable: 3223 case OMPC_read: 3224 case OMPC_write: 3225 case OMPC_capture: 3226 case OMPC_compare: 3227 case OMPC_seq_cst: 3228 case OMPC_acq_rel: 3229 case OMPC_acquire: 3230 case OMPC_release: 3231 case OMPC_relaxed: 3232 case OMPC_threads: 3233 case OMPC_simd: 3234 case OMPC_nogroup: 3235 case OMPC_unified_address: 3236 case OMPC_unified_shared_memory: 3237 case OMPC_reverse_offload: 3238 case OMPC_dynamic_allocators: 3239 case OMPC_full: 3240 // OpenMP [2.7.1, Restrictions, p. 9] 3241 // Only one ordered clause can appear on a loop directive. 3242 // OpenMP [2.7.1, Restrictions, C/C++, p. 4] 3243 // Only one nowait clause can appear on a for directive. 3244 // OpenMP [5.0, Requires directive, Restrictions] 3245 // Each of the requires clauses can appear at most once on the directive. 3246 if (!FirstClause) { 3247 Diag(Tok, diag::err_omp_more_one_clause) 3248 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 3249 ErrorFound = true; 3250 } 3251 3252 Clause = ParseOpenMPClause(CKind, WrongDirective); 3253 break; 3254 case OMPC_update: 3255 if (!FirstClause) { 3256 Diag(Tok, diag::err_omp_more_one_clause) 3257 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 3258 ErrorFound = true; 3259 } 3260 3261 Clause = (DKind == OMPD_depobj) 3262 ? ParseOpenMPSimpleClause(CKind, WrongDirective) 3263 : ParseOpenMPClause(CKind, WrongDirective); 3264 break; 3265 case OMPC_private: 3266 case OMPC_firstprivate: 3267 case OMPC_lastprivate: 3268 case OMPC_shared: 3269 case OMPC_reduction: 3270 case OMPC_task_reduction: 3271 case OMPC_in_reduction: 3272 case OMPC_linear: 3273 case OMPC_aligned: 3274 case OMPC_copyin: 3275 case OMPC_copyprivate: 3276 case OMPC_flush: 3277 case OMPC_depend: 3278 case OMPC_map: 3279 case OMPC_to: 3280 case OMPC_from: 3281 case OMPC_use_device_ptr: 3282 case OMPC_use_device_addr: 3283 case OMPC_is_device_ptr: 3284 case OMPC_allocate: 3285 case OMPC_nontemporal: 3286 case OMPC_inclusive: 3287 case OMPC_exclusive: 3288 case OMPC_affinity: 3289 Clause = ParseOpenMPVarListClause(DKind, CKind, WrongDirective); 3290 break; 3291 case OMPC_sizes: 3292 if (!FirstClause) { 3293 Diag(Tok, diag::err_omp_more_one_clause) 3294 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 3295 ErrorFound = true; 3296 } 3297 3298 Clause = ParseOpenMPSizesClause(); 3299 break; 3300 case OMPC_uses_allocators: 3301 Clause = ParseOpenMPUsesAllocatorClause(DKind); 3302 break; 3303 case OMPC_destroy: 3304 if (DKind != OMPD_interop) { 3305 if (!FirstClause) { 3306 Diag(Tok, diag::err_omp_more_one_clause) 3307 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 3308 ErrorFound = true; 3309 } 3310 Clause = ParseOpenMPClause(CKind, WrongDirective); 3311 break; 3312 } 3313 LLVM_FALLTHROUGH; 3314 case OMPC_init: 3315 case OMPC_use: 3316 Clause = ParseOpenMPInteropClause(CKind, WrongDirective); 3317 break; 3318 case OMPC_device_type: 3319 case OMPC_unknown: 3320 skipUntilPragmaOpenMPEnd(DKind); 3321 break; 3322 case OMPC_threadprivate: 3323 case OMPC_uniform: 3324 case OMPC_match: 3325 if (!WrongDirective) 3326 Diag(Tok, diag::err_omp_unexpected_clause) 3327 << getOpenMPClauseName(CKind) << getOpenMPDirectiveName(DKind); 3328 SkipUntil(tok::comma, tok::annot_pragma_openmp_end, StopBeforeMatch); 3329 break; 3330 default: 3331 break; 3332 } 3333 return ErrorFound ? nullptr : Clause; 3334 } 3335 3336 /// Parses simple expression in parens for single-expression clauses of OpenMP 3337 /// constructs. 3338 /// \param RLoc Returned location of right paren. 3339 ExprResult Parser::ParseOpenMPParensExpr(StringRef ClauseName, 3340 SourceLocation &RLoc, 3341 bool IsAddressOfOperand) { 3342 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 3343 if (T.expectAndConsume(diag::err_expected_lparen_after, ClauseName.data())) 3344 return ExprError(); 3345 3346 SourceLocation ELoc = Tok.getLocation(); 3347 ExprResult LHS( 3348 ParseCastExpression(AnyCastExpr, IsAddressOfOperand, NotTypeCast)); 3349 ExprResult Val(ParseRHSOfBinaryExpression(LHS, prec::Conditional)); 3350 Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false); 3351 3352 // Parse ')'. 3353 RLoc = Tok.getLocation(); 3354 if (!T.consumeClose()) 3355 RLoc = T.getCloseLocation(); 3356 3357 return Val; 3358 } 3359 3360 /// Parsing of OpenMP clauses with single expressions like 'final', 3361 /// 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams', 3362 /// 'thread_limit', 'simdlen', 'priority', 'grainsize', 'num_tasks', 'hint' or 3363 /// 'detach'. 3364 /// 3365 /// final-clause: 3366 /// 'final' '(' expression ')' 3367 /// 3368 /// num_threads-clause: 3369 /// 'num_threads' '(' expression ')' 3370 /// 3371 /// safelen-clause: 3372 /// 'safelen' '(' expression ')' 3373 /// 3374 /// simdlen-clause: 3375 /// 'simdlen' '(' expression ')' 3376 /// 3377 /// collapse-clause: 3378 /// 'collapse' '(' expression ')' 3379 /// 3380 /// priority-clause: 3381 /// 'priority' '(' expression ')' 3382 /// 3383 /// grainsize-clause: 3384 /// 'grainsize' '(' expression ')' 3385 /// 3386 /// num_tasks-clause: 3387 /// 'num_tasks' '(' expression ')' 3388 /// 3389 /// hint-clause: 3390 /// 'hint' '(' expression ')' 3391 /// 3392 /// allocator-clause: 3393 /// 'allocator' '(' expression ')' 3394 /// 3395 /// detach-clause: 3396 /// 'detach' '(' event-handler-expression ')' 3397 /// 3398 /// align-clause 3399 /// 'align' '(' positive-integer-constant ')' 3400 /// 3401 OMPClause *Parser::ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, 3402 bool ParseOnly) { 3403 SourceLocation Loc = ConsumeToken(); 3404 SourceLocation LLoc = Tok.getLocation(); 3405 SourceLocation RLoc; 3406 3407 ExprResult Val = ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc); 3408 3409 if (Val.isInvalid()) 3410 return nullptr; 3411 3412 if (ParseOnly) 3413 return nullptr; 3414 return Actions.ActOnOpenMPSingleExprClause(Kind, Val.get(), Loc, LLoc, RLoc); 3415 } 3416 3417 /// Parse indirect clause for '#pragma omp declare target' directive. 3418 /// 'indirect' '[' '(' invoked-by-fptr ')' ']' 3419 /// where invoked-by-fptr is a constant boolean expression that evaluates to 3420 /// true or false at compile time. 3421 bool Parser::ParseOpenMPIndirectClause(Sema::DeclareTargetContextInfo &DTCI, 3422 bool ParseOnly) { 3423 SourceLocation Loc = ConsumeToken(); 3424 SourceLocation RLoc; 3425 3426 if (Tok.isNot(tok::l_paren)) { 3427 if (ParseOnly) 3428 return false; 3429 DTCI.Indirect = nullptr; 3430 return true; 3431 } 3432 3433 ExprResult Val = 3434 ParseOpenMPParensExpr(getOpenMPClauseName(OMPC_indirect), RLoc); 3435 if (Val.isInvalid()) 3436 return false; 3437 3438 if (ParseOnly) 3439 return false; 3440 3441 if (!Val.get()->isValueDependent() && !Val.get()->isTypeDependent() && 3442 !Val.get()->isInstantiationDependent() && 3443 !Val.get()->containsUnexpandedParameterPack()) { 3444 ExprResult Ret = Actions.CheckBooleanCondition(Loc, Val.get()); 3445 if (Ret.isInvalid()) 3446 return false; 3447 llvm::APSInt Result; 3448 Ret = Actions.VerifyIntegerConstantExpression(Val.get(), &Result, 3449 Sema::AllowFold); 3450 if (Ret.isInvalid()) 3451 return false; 3452 DTCI.Indirect = Val.get(); 3453 return true; 3454 } 3455 return false; 3456 } 3457 3458 /// Parsing of OpenMP clauses that use an interop-var. 3459 /// 3460 /// init-clause: 3461 /// init([interop-modifier, ]interop-type[[, interop-type] ... ]:interop-var) 3462 /// 3463 /// destroy-clause: 3464 /// destroy(interop-var) 3465 /// 3466 /// use-clause: 3467 /// use(interop-var) 3468 /// 3469 /// interop-modifier: 3470 /// prefer_type(preference-list) 3471 /// 3472 /// preference-list: 3473 /// foreign-runtime-id [, foreign-runtime-id]... 3474 /// 3475 /// foreign-runtime-id: 3476 /// <string-literal> | <constant-integral-expression> 3477 /// 3478 /// interop-type: 3479 /// target | targetsync 3480 /// 3481 OMPClause *Parser::ParseOpenMPInteropClause(OpenMPClauseKind Kind, 3482 bool ParseOnly) { 3483 SourceLocation Loc = ConsumeToken(); 3484 // Parse '('. 3485 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 3486 if (T.expectAndConsume(diag::err_expected_lparen_after, 3487 getOpenMPClauseName(Kind).data())) 3488 return nullptr; 3489 3490 bool IsTarget = false; 3491 bool IsTargetSync = false; 3492 SmallVector<Expr *, 4> Prefs; 3493 3494 if (Kind == OMPC_init) { 3495 3496 // Parse optional interop-modifier. 3497 if (Tok.is(tok::identifier) && PP.getSpelling(Tok) == "prefer_type") { 3498 ConsumeToken(); 3499 BalancedDelimiterTracker PT(*this, tok::l_paren, 3500 tok::annot_pragma_openmp_end); 3501 if (PT.expectAndConsume(diag::err_expected_lparen_after, "prefer_type")) 3502 return nullptr; 3503 3504 while (Tok.isNot(tok::r_paren)) { 3505 SourceLocation Loc = Tok.getLocation(); 3506 ExprResult LHS = ParseCastExpression(AnyCastExpr); 3507 ExprResult PTExpr = Actions.CorrectDelayedTyposInExpr( 3508 ParseRHSOfBinaryExpression(LHS, prec::Conditional)); 3509 PTExpr = Actions.ActOnFinishFullExpr(PTExpr.get(), Loc, 3510 /*DiscardedValue=*/false); 3511 if (PTExpr.isUsable()) 3512 Prefs.push_back(PTExpr.get()); 3513 else 3514 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 3515 StopBeforeMatch); 3516 3517 if (Tok.is(tok::comma)) 3518 ConsumeToken(); 3519 } 3520 PT.consumeClose(); 3521 } 3522 3523 if (!Prefs.empty()) { 3524 if (Tok.is(tok::comma)) 3525 ConsumeToken(); 3526 else 3527 Diag(Tok, diag::err_omp_expected_punc_after_interop_mod); 3528 } 3529 3530 // Parse the interop-types. 3531 if (Optional<OMPDeclareVariantAttr::InteropType> IType = 3532 parseInteropTypeList(*this)) { 3533 IsTarget = IType != OMPDeclareVariantAttr::TargetSync; 3534 IsTargetSync = IType != OMPDeclareVariantAttr::Target; 3535 if (Tok.isNot(tok::colon)) 3536 Diag(Tok, diag::warn_pragma_expected_colon) << "interop types"; 3537 } 3538 if (Tok.is(tok::colon)) 3539 ConsumeToken(); 3540 } 3541 3542 // Parse the variable. 3543 SourceLocation VarLoc = Tok.getLocation(); 3544 ExprResult InteropVarExpr = 3545 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()); 3546 if (!InteropVarExpr.isUsable()) { 3547 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 3548 StopBeforeMatch); 3549 } 3550 3551 // Parse ')'. 3552 SourceLocation RLoc = Tok.getLocation(); 3553 if (!T.consumeClose()) 3554 RLoc = T.getCloseLocation(); 3555 3556 if (ParseOnly || !InteropVarExpr.isUsable() || 3557 (Kind == OMPC_init && !IsTarget && !IsTargetSync)) 3558 return nullptr; 3559 3560 if (Kind == OMPC_init) 3561 return Actions.ActOnOpenMPInitClause(InteropVarExpr.get(), Prefs, IsTarget, 3562 IsTargetSync, Loc, T.getOpenLocation(), 3563 VarLoc, RLoc); 3564 if (Kind == OMPC_use) 3565 return Actions.ActOnOpenMPUseClause(InteropVarExpr.get(), Loc, 3566 T.getOpenLocation(), VarLoc, RLoc); 3567 3568 if (Kind == OMPC_destroy) 3569 return Actions.ActOnOpenMPDestroyClause(InteropVarExpr.get(), Loc, 3570 T.getOpenLocation(), VarLoc, RLoc); 3571 3572 llvm_unreachable("Unexpected interop variable clause."); 3573 } 3574 3575 /// Parsing of simple OpenMP clauses like 'default' or 'proc_bind'. 3576 /// 3577 /// default-clause: 3578 /// 'default' '(' 'none' | 'shared' | 'firstprivate' ')' 3579 /// 3580 /// proc_bind-clause: 3581 /// 'proc_bind' '(' 'master' | 'close' | 'spread' ')' 3582 /// 3583 /// bind-clause: 3584 /// 'bind' '(' 'teams' | 'parallel' | 'thread' ')' 3585 /// 3586 /// update-clause: 3587 /// 'update' '(' 'in' | 'out' | 'inout' | 'mutexinoutset' | 3588 /// 'inoutset' ')' 3589 /// 3590 OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind, 3591 bool ParseOnly) { 3592 llvm::Optional<SimpleClauseData> Val = parseOpenMPSimpleClause(*this, Kind); 3593 if (!Val || ParseOnly) 3594 return nullptr; 3595 if (getLangOpts().OpenMP < 51 && Kind == OMPC_default && 3596 static_cast<DefaultKind>(Val.getValue().Type) == 3597 OMP_DEFAULT_firstprivate) { 3598 Diag(Val.getValue().LOpen, diag::err_omp_invalid_dsa) 3599 << getOpenMPClauseName(OMPC_firstprivate) 3600 << getOpenMPClauseName(OMPC_default) << "5.1"; 3601 return nullptr; 3602 } 3603 return Actions.ActOnOpenMPSimpleClause( 3604 Kind, Val.getValue().Type, Val.getValue().TypeLoc, Val.getValue().LOpen, 3605 Val.getValue().Loc, Val.getValue().RLoc); 3606 } 3607 3608 /// Parsing of OpenMP clauses like 'ordered'. 3609 /// 3610 /// ordered-clause: 3611 /// 'ordered' 3612 /// 3613 /// nowait-clause: 3614 /// 'nowait' 3615 /// 3616 /// untied-clause: 3617 /// 'untied' 3618 /// 3619 /// mergeable-clause: 3620 /// 'mergeable' 3621 /// 3622 /// read-clause: 3623 /// 'read' 3624 /// 3625 /// threads-clause: 3626 /// 'threads' 3627 /// 3628 /// simd-clause: 3629 /// 'simd' 3630 /// 3631 /// nogroup-clause: 3632 /// 'nogroup' 3633 /// 3634 OMPClause *Parser::ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly) { 3635 SourceLocation Loc = Tok.getLocation(); 3636 ConsumeAnyToken(); 3637 3638 if (ParseOnly) 3639 return nullptr; 3640 return Actions.ActOnOpenMPClause(Kind, Loc, Tok.getLocation()); 3641 } 3642 3643 /// Parsing of OpenMP clauses with single expressions and some additional 3644 /// argument like 'schedule' or 'dist_schedule'. 3645 /// 3646 /// schedule-clause: 3647 /// 'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression ] 3648 /// ')' 3649 /// 3650 /// if-clause: 3651 /// 'if' '(' [ directive-name-modifier ':' ] expression ')' 3652 /// 3653 /// defaultmap: 3654 /// 'defaultmap' '(' modifier [ ':' kind ] ')' 3655 /// 3656 /// device-clause: 3657 /// 'device' '(' [ device-modifier ':' ] expression ')' 3658 /// 3659 OMPClause *Parser::ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind, 3660 OpenMPClauseKind Kind, 3661 bool ParseOnly) { 3662 SourceLocation Loc = ConsumeToken(); 3663 SourceLocation DelimLoc; 3664 // Parse '('. 3665 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 3666 if (T.expectAndConsume(diag::err_expected_lparen_after, 3667 getOpenMPClauseName(Kind).data())) 3668 return nullptr; 3669 3670 ExprResult Val; 3671 SmallVector<unsigned, 4> Arg; 3672 SmallVector<SourceLocation, 4> KLoc; 3673 if (Kind == OMPC_schedule) { 3674 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 3675 Arg.resize(NumberOfElements); 3676 KLoc.resize(NumberOfElements); 3677 Arg[Modifier1] = OMPC_SCHEDULE_MODIFIER_unknown; 3678 Arg[Modifier2] = OMPC_SCHEDULE_MODIFIER_unknown; 3679 Arg[ScheduleKind] = OMPC_SCHEDULE_unknown; 3680 unsigned KindModifier = getOpenMPSimpleClauseType( 3681 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()); 3682 if (KindModifier > OMPC_SCHEDULE_unknown) { 3683 // Parse 'modifier' 3684 Arg[Modifier1] = KindModifier; 3685 KLoc[Modifier1] = Tok.getLocation(); 3686 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 3687 Tok.isNot(tok::annot_pragma_openmp_end)) 3688 ConsumeAnyToken(); 3689 if (Tok.is(tok::comma)) { 3690 // Parse ',' 'modifier' 3691 ConsumeAnyToken(); 3692 KindModifier = getOpenMPSimpleClauseType( 3693 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()); 3694 Arg[Modifier2] = KindModifier > OMPC_SCHEDULE_unknown 3695 ? KindModifier 3696 : (unsigned)OMPC_SCHEDULE_unknown; 3697 KLoc[Modifier2] = Tok.getLocation(); 3698 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 3699 Tok.isNot(tok::annot_pragma_openmp_end)) 3700 ConsumeAnyToken(); 3701 } 3702 // Parse ':' 3703 if (Tok.is(tok::colon)) 3704 ConsumeAnyToken(); 3705 else 3706 Diag(Tok, diag::warn_pragma_expected_colon) << "schedule modifier"; 3707 KindModifier = getOpenMPSimpleClauseType( 3708 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()); 3709 } 3710 Arg[ScheduleKind] = KindModifier; 3711 KLoc[ScheduleKind] = Tok.getLocation(); 3712 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 3713 Tok.isNot(tok::annot_pragma_openmp_end)) 3714 ConsumeAnyToken(); 3715 if ((Arg[ScheduleKind] == OMPC_SCHEDULE_static || 3716 Arg[ScheduleKind] == OMPC_SCHEDULE_dynamic || 3717 Arg[ScheduleKind] == OMPC_SCHEDULE_guided) && 3718 Tok.is(tok::comma)) 3719 DelimLoc = ConsumeAnyToken(); 3720 } else if (Kind == OMPC_dist_schedule) { 3721 Arg.push_back(getOpenMPSimpleClauseType( 3722 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts())); 3723 KLoc.push_back(Tok.getLocation()); 3724 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 3725 Tok.isNot(tok::annot_pragma_openmp_end)) 3726 ConsumeAnyToken(); 3727 if (Arg.back() == OMPC_DIST_SCHEDULE_static && Tok.is(tok::comma)) 3728 DelimLoc = ConsumeAnyToken(); 3729 } else if (Kind == OMPC_defaultmap) { 3730 // Get a defaultmap modifier 3731 unsigned Modifier = getOpenMPSimpleClauseType( 3732 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()); 3733 // Set defaultmap modifier to unknown if it is either scalar, aggregate, or 3734 // pointer 3735 if (Modifier < OMPC_DEFAULTMAP_MODIFIER_unknown) 3736 Modifier = OMPC_DEFAULTMAP_MODIFIER_unknown; 3737 Arg.push_back(Modifier); 3738 KLoc.push_back(Tok.getLocation()); 3739 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 3740 Tok.isNot(tok::annot_pragma_openmp_end)) 3741 ConsumeAnyToken(); 3742 // Parse ':' 3743 if (Tok.is(tok::colon) || getLangOpts().OpenMP < 50) { 3744 if (Tok.is(tok::colon)) 3745 ConsumeAnyToken(); 3746 else if (Arg.back() != OMPC_DEFAULTMAP_MODIFIER_unknown) 3747 Diag(Tok, diag::warn_pragma_expected_colon) << "defaultmap modifier"; 3748 // Get a defaultmap kind 3749 Arg.push_back(getOpenMPSimpleClauseType( 3750 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts())); 3751 KLoc.push_back(Tok.getLocation()); 3752 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 3753 Tok.isNot(tok::annot_pragma_openmp_end)) 3754 ConsumeAnyToken(); 3755 } else { 3756 Arg.push_back(OMPC_DEFAULTMAP_unknown); 3757 KLoc.push_back(SourceLocation()); 3758 } 3759 } else if (Kind == OMPC_device) { 3760 // Only target executable directives support extended device construct. 3761 if (isOpenMPTargetExecutionDirective(DKind) && getLangOpts().OpenMP >= 50 && 3762 NextToken().is(tok::colon)) { 3763 // Parse optional <device modifier> ':' 3764 Arg.push_back(getOpenMPSimpleClauseType( 3765 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts())); 3766 KLoc.push_back(Tok.getLocation()); 3767 ConsumeAnyToken(); 3768 // Parse ':' 3769 ConsumeAnyToken(); 3770 } else { 3771 Arg.push_back(OMPC_DEVICE_unknown); 3772 KLoc.emplace_back(); 3773 } 3774 } else { 3775 assert(Kind == OMPC_if); 3776 KLoc.push_back(Tok.getLocation()); 3777 TentativeParsingAction TPA(*this); 3778 auto DK = parseOpenMPDirectiveKind(*this); 3779 Arg.push_back(DK); 3780 if (DK != OMPD_unknown) { 3781 ConsumeToken(); 3782 if (Tok.is(tok::colon) && getLangOpts().OpenMP > 40) { 3783 TPA.Commit(); 3784 DelimLoc = ConsumeToken(); 3785 } else { 3786 TPA.Revert(); 3787 Arg.back() = unsigned(OMPD_unknown); 3788 } 3789 } else { 3790 TPA.Revert(); 3791 } 3792 } 3793 3794 bool NeedAnExpression = (Kind == OMPC_schedule && DelimLoc.isValid()) || 3795 (Kind == OMPC_dist_schedule && DelimLoc.isValid()) || 3796 Kind == OMPC_if || Kind == OMPC_device; 3797 if (NeedAnExpression) { 3798 SourceLocation ELoc = Tok.getLocation(); 3799 ExprResult LHS(ParseCastExpression(AnyCastExpr, false, NotTypeCast)); 3800 Val = ParseRHSOfBinaryExpression(LHS, prec::Conditional); 3801 Val = 3802 Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false); 3803 } 3804 3805 // Parse ')'. 3806 SourceLocation RLoc = Tok.getLocation(); 3807 if (!T.consumeClose()) 3808 RLoc = T.getCloseLocation(); 3809 3810 if (NeedAnExpression && Val.isInvalid()) 3811 return nullptr; 3812 3813 if (ParseOnly) 3814 return nullptr; 3815 return Actions.ActOnOpenMPSingleExprWithArgClause( 3816 Kind, Arg, Val.get(), Loc, T.getOpenLocation(), KLoc, DelimLoc, RLoc); 3817 } 3818 3819 static bool ParseReductionId(Parser &P, CXXScopeSpec &ReductionIdScopeSpec, 3820 UnqualifiedId &ReductionId) { 3821 if (ReductionIdScopeSpec.isEmpty()) { 3822 auto OOK = OO_None; 3823 switch (P.getCurToken().getKind()) { 3824 case tok::plus: 3825 OOK = OO_Plus; 3826 break; 3827 case tok::minus: 3828 OOK = OO_Minus; 3829 break; 3830 case tok::star: 3831 OOK = OO_Star; 3832 break; 3833 case tok::amp: 3834 OOK = OO_Amp; 3835 break; 3836 case tok::pipe: 3837 OOK = OO_Pipe; 3838 break; 3839 case tok::caret: 3840 OOK = OO_Caret; 3841 break; 3842 case tok::ampamp: 3843 OOK = OO_AmpAmp; 3844 break; 3845 case tok::pipepipe: 3846 OOK = OO_PipePipe; 3847 break; 3848 default: 3849 break; 3850 } 3851 if (OOK != OO_None) { 3852 SourceLocation OpLoc = P.ConsumeToken(); 3853 SourceLocation SymbolLocations[] = {OpLoc, OpLoc, SourceLocation()}; 3854 ReductionId.setOperatorFunctionId(OpLoc, OOK, SymbolLocations); 3855 return false; 3856 } 3857 } 3858 return P.ParseUnqualifiedId( 3859 ReductionIdScopeSpec, /*ObjectType=*/nullptr, 3860 /*ObjectHadErrors=*/false, /*EnteringContext*/ false, 3861 /*AllowDestructorName*/ false, 3862 /*AllowConstructorName*/ false, 3863 /*AllowDeductionGuide*/ false, nullptr, ReductionId); 3864 } 3865 3866 /// Checks if the token is a valid map-type-modifier. 3867 /// FIXME: It will return an OpenMPMapClauseKind if that's what it parses. 3868 static OpenMPMapModifierKind isMapModifier(Parser &P) { 3869 Token Tok = P.getCurToken(); 3870 if (!Tok.is(tok::identifier)) 3871 return OMPC_MAP_MODIFIER_unknown; 3872 3873 Preprocessor &PP = P.getPreprocessor(); 3874 OpenMPMapModifierKind TypeModifier = 3875 static_cast<OpenMPMapModifierKind>(getOpenMPSimpleClauseType( 3876 OMPC_map, PP.getSpelling(Tok), P.getLangOpts())); 3877 return TypeModifier; 3878 } 3879 3880 /// Parse the mapper modifier in map, to, and from clauses. 3881 bool Parser::parseMapperModifier(OpenMPVarListDataTy &Data) { 3882 // Parse '('. 3883 BalancedDelimiterTracker T(*this, tok::l_paren, tok::colon); 3884 if (T.expectAndConsume(diag::err_expected_lparen_after, "mapper")) { 3885 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 3886 StopBeforeMatch); 3887 return true; 3888 } 3889 // Parse mapper-identifier 3890 if (getLangOpts().CPlusPlus) 3891 ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec, 3892 /*ObjectType=*/nullptr, 3893 /*ObjectHasErrors=*/false, 3894 /*EnteringContext=*/false); 3895 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) { 3896 Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier); 3897 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 3898 StopBeforeMatch); 3899 return true; 3900 } 3901 auto &DeclNames = Actions.getASTContext().DeclarationNames; 3902 Data.ReductionOrMapperId = DeclarationNameInfo( 3903 DeclNames.getIdentifier(Tok.getIdentifierInfo()), Tok.getLocation()); 3904 ConsumeToken(); 3905 // Parse ')'. 3906 return T.consumeClose(); 3907 } 3908 3909 /// Parse map-type-modifiers in map clause. 3910 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) 3911 /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) | 3912 /// present 3913 bool Parser::parseMapTypeModifiers(OpenMPVarListDataTy &Data) { 3914 while (getCurToken().isNot(tok::colon)) { 3915 OpenMPMapModifierKind TypeModifier = isMapModifier(*this); 3916 if (TypeModifier == OMPC_MAP_MODIFIER_always || 3917 TypeModifier == OMPC_MAP_MODIFIER_close || 3918 TypeModifier == OMPC_MAP_MODIFIER_present || 3919 TypeModifier == OMPC_MAP_MODIFIER_ompx_hold) { 3920 Data.MapTypeModifiers.push_back(TypeModifier); 3921 Data.MapTypeModifiersLoc.push_back(Tok.getLocation()); 3922 ConsumeToken(); 3923 } else if (TypeModifier == OMPC_MAP_MODIFIER_mapper) { 3924 Data.MapTypeModifiers.push_back(TypeModifier); 3925 Data.MapTypeModifiersLoc.push_back(Tok.getLocation()); 3926 ConsumeToken(); 3927 if (parseMapperModifier(Data)) 3928 return true; 3929 } else { 3930 // For the case of unknown map-type-modifier or a map-type. 3931 // Map-type is followed by a colon; the function returns when it 3932 // encounters a token followed by a colon. 3933 if (Tok.is(tok::comma)) { 3934 Diag(Tok, diag::err_omp_map_type_modifier_missing); 3935 ConsumeToken(); 3936 continue; 3937 } 3938 // Potential map-type token as it is followed by a colon. 3939 if (PP.LookAhead(0).is(tok::colon)) 3940 return false; 3941 Diag(Tok, diag::err_omp_unknown_map_type_modifier) 3942 << (getLangOpts().OpenMP >= 51 ? 1 : 0) 3943 << getLangOpts().OpenMPExtensions; 3944 ConsumeToken(); 3945 } 3946 if (getCurToken().is(tok::comma)) 3947 ConsumeToken(); 3948 } 3949 return false; 3950 } 3951 3952 /// Checks if the token is a valid map-type. 3953 /// FIXME: It will return an OpenMPMapModifierKind if that's what it parses. 3954 static OpenMPMapClauseKind isMapType(Parser &P) { 3955 Token Tok = P.getCurToken(); 3956 // The map-type token can be either an identifier or the C++ delete keyword. 3957 if (!Tok.isOneOf(tok::identifier, tok::kw_delete)) 3958 return OMPC_MAP_unknown; 3959 Preprocessor &PP = P.getPreprocessor(); 3960 OpenMPMapClauseKind MapType = 3961 static_cast<OpenMPMapClauseKind>(getOpenMPSimpleClauseType( 3962 OMPC_map, PP.getSpelling(Tok), P.getLangOpts())); 3963 return MapType; 3964 } 3965 3966 /// Parse map-type in map clause. 3967 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) 3968 /// where, map-type ::= to | from | tofrom | alloc | release | delete 3969 static void parseMapType(Parser &P, Parser::OpenMPVarListDataTy &Data) { 3970 Token Tok = P.getCurToken(); 3971 if (Tok.is(tok::colon)) { 3972 P.Diag(Tok, diag::err_omp_map_type_missing); 3973 return; 3974 } 3975 Data.ExtraModifier = isMapType(P); 3976 if (Data.ExtraModifier == OMPC_MAP_unknown) 3977 P.Diag(Tok, diag::err_omp_unknown_map_type); 3978 P.ConsumeToken(); 3979 } 3980 3981 /// Parses simple expression in parens for single-expression clauses of OpenMP 3982 /// constructs. 3983 ExprResult Parser::ParseOpenMPIteratorsExpr() { 3984 assert(Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator" && 3985 "Expected 'iterator' token."); 3986 SourceLocation IteratorKwLoc = ConsumeToken(); 3987 3988 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 3989 if (T.expectAndConsume(diag::err_expected_lparen_after, "iterator")) 3990 return ExprError(); 3991 3992 SourceLocation LLoc = T.getOpenLocation(); 3993 SmallVector<Sema::OMPIteratorData, 4> Data; 3994 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) { 3995 // Check if the type parsing is required. 3996 ParsedType IteratorType; 3997 if (Tok.isNot(tok::identifier) || NextToken().isNot(tok::equal)) { 3998 // identifier '=' is not found - parse type. 3999 TypeResult TR = ParseTypeName(); 4000 if (TR.isInvalid()) { 4001 T.skipToEnd(); 4002 return ExprError(); 4003 } 4004 IteratorType = TR.get(); 4005 } 4006 4007 // Parse identifier. 4008 IdentifierInfo *II = nullptr; 4009 SourceLocation IdLoc; 4010 if (Tok.is(tok::identifier)) { 4011 II = Tok.getIdentifierInfo(); 4012 IdLoc = ConsumeToken(); 4013 } else { 4014 Diag(Tok, diag::err_expected_unqualified_id) << 0; 4015 } 4016 4017 // Parse '='. 4018 SourceLocation AssignLoc; 4019 if (Tok.is(tok::equal)) 4020 AssignLoc = ConsumeToken(); 4021 else 4022 Diag(Tok, diag::err_omp_expected_equal_in_iterator); 4023 4024 // Parse range-specification - <begin> ':' <end> [ ':' <step> ] 4025 ColonProtectionRAIIObject ColonRAII(*this); 4026 // Parse <begin> 4027 SourceLocation Loc = Tok.getLocation(); 4028 ExprResult LHS = ParseCastExpression(AnyCastExpr); 4029 ExprResult Begin = Actions.CorrectDelayedTyposInExpr( 4030 ParseRHSOfBinaryExpression(LHS, prec::Conditional)); 4031 Begin = Actions.ActOnFinishFullExpr(Begin.get(), Loc, 4032 /*DiscardedValue=*/false); 4033 // Parse ':'. 4034 SourceLocation ColonLoc; 4035 if (Tok.is(tok::colon)) 4036 ColonLoc = ConsumeToken(); 4037 4038 // Parse <end> 4039 Loc = Tok.getLocation(); 4040 LHS = ParseCastExpression(AnyCastExpr); 4041 ExprResult End = Actions.CorrectDelayedTyposInExpr( 4042 ParseRHSOfBinaryExpression(LHS, prec::Conditional)); 4043 End = Actions.ActOnFinishFullExpr(End.get(), Loc, 4044 /*DiscardedValue=*/false); 4045 4046 SourceLocation SecColonLoc; 4047 ExprResult Step; 4048 // Parse optional step. 4049 if (Tok.is(tok::colon)) { 4050 // Parse ':' 4051 SecColonLoc = ConsumeToken(); 4052 // Parse <step> 4053 Loc = Tok.getLocation(); 4054 LHS = ParseCastExpression(AnyCastExpr); 4055 Step = Actions.CorrectDelayedTyposInExpr( 4056 ParseRHSOfBinaryExpression(LHS, prec::Conditional)); 4057 Step = Actions.ActOnFinishFullExpr(Step.get(), Loc, 4058 /*DiscardedValue=*/false); 4059 } 4060 4061 // Parse ',' or ')' 4062 if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren)) 4063 Diag(Tok, diag::err_omp_expected_punc_after_iterator); 4064 if (Tok.is(tok::comma)) 4065 ConsumeToken(); 4066 4067 Sema::OMPIteratorData &D = Data.emplace_back(); 4068 D.DeclIdent = II; 4069 D.DeclIdentLoc = IdLoc; 4070 D.Type = IteratorType; 4071 D.AssignLoc = AssignLoc; 4072 D.ColonLoc = ColonLoc; 4073 D.SecColonLoc = SecColonLoc; 4074 D.Range.Begin = Begin.get(); 4075 D.Range.End = End.get(); 4076 D.Range.Step = Step.get(); 4077 } 4078 4079 // Parse ')'. 4080 SourceLocation RLoc = Tok.getLocation(); 4081 if (!T.consumeClose()) 4082 RLoc = T.getCloseLocation(); 4083 4084 return Actions.ActOnOMPIteratorExpr(getCurScope(), IteratorKwLoc, LLoc, RLoc, 4085 Data); 4086 } 4087 4088 /// Parses clauses with list. 4089 bool Parser::ParseOpenMPVarList(OpenMPDirectiveKind DKind, 4090 OpenMPClauseKind Kind, 4091 SmallVectorImpl<Expr *> &Vars, 4092 OpenMPVarListDataTy &Data) { 4093 UnqualifiedId UnqualifiedReductionId; 4094 bool InvalidReductionId = false; 4095 bool IsInvalidMapperModifier = false; 4096 4097 // Parse '('. 4098 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 4099 if (T.expectAndConsume(diag::err_expected_lparen_after, 4100 getOpenMPClauseName(Kind).data())) 4101 return true; 4102 4103 bool HasIterator = false; 4104 bool NeedRParenForLinear = false; 4105 BalancedDelimiterTracker LinearT(*this, tok::l_paren, 4106 tok::annot_pragma_openmp_end); 4107 // Handle reduction-identifier for reduction clause. 4108 if (Kind == OMPC_reduction || Kind == OMPC_task_reduction || 4109 Kind == OMPC_in_reduction) { 4110 Data.ExtraModifier = OMPC_REDUCTION_unknown; 4111 if (Kind == OMPC_reduction && getLangOpts().OpenMP >= 50 && 4112 (Tok.is(tok::identifier) || Tok.is(tok::kw_default)) && 4113 NextToken().is(tok::comma)) { 4114 // Parse optional reduction modifier. 4115 Data.ExtraModifier = 4116 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts()); 4117 Data.ExtraModifierLoc = Tok.getLocation(); 4118 ConsumeToken(); 4119 assert(Tok.is(tok::comma) && "Expected comma."); 4120 (void)ConsumeToken(); 4121 } 4122 ColonProtectionRAIIObject ColonRAII(*this); 4123 if (getLangOpts().CPlusPlus) 4124 ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec, 4125 /*ObjectType=*/nullptr, 4126 /*ObjectHasErrors=*/false, 4127 /*EnteringContext=*/false); 4128 InvalidReductionId = ParseReductionId( 4129 *this, Data.ReductionOrMapperIdScopeSpec, UnqualifiedReductionId); 4130 if (InvalidReductionId) { 4131 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 4132 StopBeforeMatch); 4133 } 4134 if (Tok.is(tok::colon)) 4135 Data.ColonLoc = ConsumeToken(); 4136 else 4137 Diag(Tok, diag::warn_pragma_expected_colon) << "reduction identifier"; 4138 if (!InvalidReductionId) 4139 Data.ReductionOrMapperId = 4140 Actions.GetNameFromUnqualifiedId(UnqualifiedReductionId); 4141 } else if (Kind == OMPC_depend) { 4142 if (getLangOpts().OpenMP >= 50) { 4143 if (Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator") { 4144 // Handle optional dependence modifier. 4145 // iterator(iterators-definition) 4146 // where iterators-definition is iterator-specifier [, 4147 // iterators-definition ] 4148 // where iterator-specifier is [ iterator-type ] identifier = 4149 // range-specification 4150 HasIterator = true; 4151 EnterScope(Scope::OpenMPDirectiveScope | Scope::DeclScope); 4152 ExprResult IteratorRes = ParseOpenMPIteratorsExpr(); 4153 Data.DepModOrTailExpr = IteratorRes.get(); 4154 // Parse ',' 4155 ExpectAndConsume(tok::comma); 4156 } 4157 } 4158 // Handle dependency type for depend clause. 4159 ColonProtectionRAIIObject ColonRAII(*this); 4160 Data.ExtraModifier = getOpenMPSimpleClauseType( 4161 Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "", 4162 getLangOpts()); 4163 Data.ExtraModifierLoc = Tok.getLocation(); 4164 if (Data.ExtraModifier == OMPC_DEPEND_unknown) { 4165 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 4166 StopBeforeMatch); 4167 } else { 4168 ConsumeToken(); 4169 // Special processing for depend(source) clause. 4170 if (DKind == OMPD_ordered && Data.ExtraModifier == OMPC_DEPEND_source) { 4171 // Parse ')'. 4172 T.consumeClose(); 4173 return false; 4174 } 4175 } 4176 if (Tok.is(tok::colon)) { 4177 Data.ColonLoc = ConsumeToken(); 4178 } else { 4179 Diag(Tok, DKind == OMPD_ordered ? diag::warn_pragma_expected_colon_r_paren 4180 : diag::warn_pragma_expected_colon) 4181 << "dependency type"; 4182 } 4183 } else if (Kind == OMPC_linear) { 4184 // Try to parse modifier if any. 4185 Data.ExtraModifier = OMPC_LINEAR_val; 4186 if (Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::l_paren)) { 4187 Data.ExtraModifier = 4188 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts()); 4189 Data.ExtraModifierLoc = ConsumeToken(); 4190 LinearT.consumeOpen(); 4191 NeedRParenForLinear = true; 4192 } 4193 } else if (Kind == OMPC_lastprivate) { 4194 // Try to parse modifier if any. 4195 Data.ExtraModifier = OMPC_LASTPRIVATE_unknown; 4196 // Conditional modifier allowed only in OpenMP 5.0 and not supported in 4197 // distribute and taskloop based directives. 4198 if ((getLangOpts().OpenMP >= 50 && !isOpenMPDistributeDirective(DKind) && 4199 !isOpenMPTaskLoopDirective(DKind)) && 4200 Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::colon)) { 4201 Data.ExtraModifier = 4202 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts()); 4203 Data.ExtraModifierLoc = Tok.getLocation(); 4204 ConsumeToken(); 4205 assert(Tok.is(tok::colon) && "Expected colon."); 4206 Data.ColonLoc = ConsumeToken(); 4207 } 4208 } else if (Kind == OMPC_map) { 4209 // Handle map type for map clause. 4210 ColonProtectionRAIIObject ColonRAII(*this); 4211 4212 // The first identifier may be a list item, a map-type or a 4213 // map-type-modifier. The map-type can also be delete which has the same 4214 // spelling of the C++ delete keyword. 4215 Data.ExtraModifier = OMPC_MAP_unknown; 4216 Data.ExtraModifierLoc = Tok.getLocation(); 4217 4218 // Check for presence of a colon in the map clause. 4219 TentativeParsingAction TPA(*this); 4220 bool ColonPresent = false; 4221 if (SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 4222 StopBeforeMatch)) { 4223 if (Tok.is(tok::colon)) 4224 ColonPresent = true; 4225 } 4226 TPA.Revert(); 4227 // Only parse map-type-modifier[s] and map-type if a colon is present in 4228 // the map clause. 4229 if (ColonPresent) { 4230 IsInvalidMapperModifier = parseMapTypeModifiers(Data); 4231 if (!IsInvalidMapperModifier) 4232 parseMapType(*this, Data); 4233 else 4234 SkipUntil(tok::colon, tok::annot_pragma_openmp_end, StopBeforeMatch); 4235 } 4236 if (Data.ExtraModifier == OMPC_MAP_unknown) { 4237 Data.ExtraModifier = OMPC_MAP_tofrom; 4238 Data.IsMapTypeImplicit = true; 4239 } 4240 4241 if (Tok.is(tok::colon)) 4242 Data.ColonLoc = ConsumeToken(); 4243 } else if (Kind == OMPC_to || Kind == OMPC_from) { 4244 while (Tok.is(tok::identifier)) { 4245 auto Modifier = static_cast<OpenMPMotionModifierKind>( 4246 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts())); 4247 if (Modifier == OMPC_MOTION_MODIFIER_unknown) 4248 break; 4249 Data.MotionModifiers.push_back(Modifier); 4250 Data.MotionModifiersLoc.push_back(Tok.getLocation()); 4251 ConsumeToken(); 4252 if (Modifier == OMPC_MOTION_MODIFIER_mapper) { 4253 IsInvalidMapperModifier = parseMapperModifier(Data); 4254 if (IsInvalidMapperModifier) 4255 break; 4256 } 4257 // OpenMP < 5.1 doesn't permit a ',' or additional modifiers. 4258 if (getLangOpts().OpenMP < 51) 4259 break; 4260 // OpenMP 5.1 accepts an optional ',' even if the next character is ':'. 4261 // TODO: Is that intentional? 4262 if (Tok.is(tok::comma)) 4263 ConsumeToken(); 4264 } 4265 if (!Data.MotionModifiers.empty() && Tok.isNot(tok::colon)) { 4266 if (!IsInvalidMapperModifier) { 4267 if (getLangOpts().OpenMP < 51) 4268 Diag(Tok, diag::warn_pragma_expected_colon) << ")"; 4269 else 4270 Diag(Tok, diag::warn_pragma_expected_colon) << "motion modifier"; 4271 } 4272 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 4273 StopBeforeMatch); 4274 } 4275 // OpenMP 5.1 permits a ':' even without a preceding modifier. TODO: Is 4276 // that intentional? 4277 if ((!Data.MotionModifiers.empty() || getLangOpts().OpenMP >= 51) && 4278 Tok.is(tok::colon)) 4279 Data.ColonLoc = ConsumeToken(); 4280 } else if (Kind == OMPC_allocate || 4281 (Kind == OMPC_affinity && Tok.is(tok::identifier) && 4282 PP.getSpelling(Tok) == "iterator")) { 4283 // Handle optional allocator expression followed by colon delimiter. 4284 ColonProtectionRAIIObject ColonRAII(*this); 4285 TentativeParsingAction TPA(*this); 4286 // OpenMP 5.0, 2.10.1, task Construct. 4287 // where aff-modifier is one of the following: 4288 // iterator(iterators-definition) 4289 ExprResult Tail; 4290 if (Kind == OMPC_allocate) { 4291 Tail = ParseAssignmentExpression(); 4292 } else { 4293 HasIterator = true; 4294 EnterScope(Scope::OpenMPDirectiveScope | Scope::DeclScope); 4295 Tail = ParseOpenMPIteratorsExpr(); 4296 } 4297 Tail = Actions.CorrectDelayedTyposInExpr(Tail); 4298 Tail = Actions.ActOnFinishFullExpr(Tail.get(), T.getOpenLocation(), 4299 /*DiscardedValue=*/false); 4300 if (Tail.isUsable()) { 4301 if (Tok.is(tok::colon)) { 4302 Data.DepModOrTailExpr = Tail.get(); 4303 Data.ColonLoc = ConsumeToken(); 4304 TPA.Commit(); 4305 } else { 4306 // Colon not found, parse only list of variables. 4307 TPA.Revert(); 4308 } 4309 } else { 4310 // Parsing was unsuccessfull, revert and skip to the end of clause or 4311 // directive. 4312 TPA.Revert(); 4313 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 4314 StopBeforeMatch); 4315 } 4316 } else if (Kind == OMPC_adjust_args) { 4317 // Handle adjust-op for adjust_args clause. 4318 ColonProtectionRAIIObject ColonRAII(*this); 4319 Data.ExtraModifier = getOpenMPSimpleClauseType( 4320 Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "", 4321 getLangOpts()); 4322 Data.ExtraModifierLoc = Tok.getLocation(); 4323 if (Data.ExtraModifier == OMPC_ADJUST_ARGS_unknown) { 4324 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 4325 StopBeforeMatch); 4326 } else { 4327 ConsumeToken(); 4328 if (Tok.is(tok::colon)) 4329 Data.ColonLoc = Tok.getLocation(); 4330 ExpectAndConsume(tok::colon, diag::warn_pragma_expected_colon, 4331 "adjust-op"); 4332 } 4333 } 4334 4335 bool IsComma = 4336 (Kind != OMPC_reduction && Kind != OMPC_task_reduction && 4337 Kind != OMPC_in_reduction && Kind != OMPC_depend && Kind != OMPC_map) || 4338 (Kind == OMPC_reduction && !InvalidReductionId) || 4339 (Kind == OMPC_map && Data.ExtraModifier != OMPC_MAP_unknown) || 4340 (Kind == OMPC_depend && Data.ExtraModifier != OMPC_DEPEND_unknown) || 4341 (Kind == OMPC_adjust_args && 4342 Data.ExtraModifier != OMPC_ADJUST_ARGS_unknown); 4343 const bool MayHaveTail = (Kind == OMPC_linear || Kind == OMPC_aligned); 4344 while (IsComma || (Tok.isNot(tok::r_paren) && Tok.isNot(tok::colon) && 4345 Tok.isNot(tok::annot_pragma_openmp_end))) { 4346 ParseScope OMPListScope(this, Scope::OpenMPDirectiveScope); 4347 ColonProtectionRAIIObject ColonRAII(*this, MayHaveTail); 4348 // Parse variable 4349 ExprResult VarExpr = 4350 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()); 4351 if (VarExpr.isUsable()) { 4352 Vars.push_back(VarExpr.get()); 4353 } else { 4354 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 4355 StopBeforeMatch); 4356 } 4357 // Skip ',' if any 4358 IsComma = Tok.is(tok::comma); 4359 if (IsComma) 4360 ConsumeToken(); 4361 else if (Tok.isNot(tok::r_paren) && 4362 Tok.isNot(tok::annot_pragma_openmp_end) && 4363 (!MayHaveTail || Tok.isNot(tok::colon))) 4364 Diag(Tok, diag::err_omp_expected_punc) 4365 << ((Kind == OMPC_flush) ? getOpenMPDirectiveName(OMPD_flush) 4366 : getOpenMPClauseName(Kind)) 4367 << (Kind == OMPC_flush); 4368 } 4369 4370 // Parse ')' for linear clause with modifier. 4371 if (NeedRParenForLinear) 4372 LinearT.consumeClose(); 4373 4374 // Parse ':' linear-step (or ':' alignment). 4375 const bool MustHaveTail = MayHaveTail && Tok.is(tok::colon); 4376 if (MustHaveTail) { 4377 Data.ColonLoc = Tok.getLocation(); 4378 SourceLocation ELoc = ConsumeToken(); 4379 ExprResult Tail = ParseAssignmentExpression(); 4380 Tail = 4381 Actions.ActOnFinishFullExpr(Tail.get(), ELoc, /*DiscardedValue*/ false); 4382 if (Tail.isUsable()) 4383 Data.DepModOrTailExpr = Tail.get(); 4384 else 4385 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 4386 StopBeforeMatch); 4387 } 4388 4389 // Parse ')'. 4390 Data.RLoc = Tok.getLocation(); 4391 if (!T.consumeClose()) 4392 Data.RLoc = T.getCloseLocation(); 4393 // Exit from scope when the iterator is used in depend clause. 4394 if (HasIterator) 4395 ExitScope(); 4396 return (Kind != OMPC_depend && Kind != OMPC_map && Vars.empty()) || 4397 (MustHaveTail && !Data.DepModOrTailExpr) || InvalidReductionId || 4398 IsInvalidMapperModifier; 4399 } 4400 4401 /// Parsing of OpenMP clause 'private', 'firstprivate', 'lastprivate', 4402 /// 'shared', 'copyin', 'copyprivate', 'flush', 'reduction', 'task_reduction', 4403 /// 'in_reduction', 'nontemporal', 'exclusive' or 'inclusive'. 4404 /// 4405 /// private-clause: 4406 /// 'private' '(' list ')' 4407 /// firstprivate-clause: 4408 /// 'firstprivate' '(' list ')' 4409 /// lastprivate-clause: 4410 /// 'lastprivate' '(' list ')' 4411 /// shared-clause: 4412 /// 'shared' '(' list ')' 4413 /// linear-clause: 4414 /// 'linear' '(' linear-list [ ':' linear-step ] ')' 4415 /// aligned-clause: 4416 /// 'aligned' '(' list [ ':' alignment ] ')' 4417 /// reduction-clause: 4418 /// 'reduction' '(' [ modifier ',' ] reduction-identifier ':' list ')' 4419 /// task_reduction-clause: 4420 /// 'task_reduction' '(' reduction-identifier ':' list ')' 4421 /// in_reduction-clause: 4422 /// 'in_reduction' '(' reduction-identifier ':' list ')' 4423 /// copyprivate-clause: 4424 /// 'copyprivate' '(' list ')' 4425 /// flush-clause: 4426 /// 'flush' '(' list ')' 4427 /// depend-clause: 4428 /// 'depend' '(' in | out | inout : list | source ')' 4429 /// map-clause: 4430 /// 'map' '(' [ [ always [,] ] [ close [,] ] 4431 /// [ mapper '(' mapper-identifier ')' [,] ] 4432 /// to | from | tofrom | alloc | release | delete ':' ] list ')'; 4433 /// to-clause: 4434 /// 'to' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')' 4435 /// from-clause: 4436 /// 'from' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')' 4437 /// use_device_ptr-clause: 4438 /// 'use_device_ptr' '(' list ')' 4439 /// use_device_addr-clause: 4440 /// 'use_device_addr' '(' list ')' 4441 /// is_device_ptr-clause: 4442 /// 'is_device_ptr' '(' list ')' 4443 /// allocate-clause: 4444 /// 'allocate' '(' [ allocator ':' ] list ')' 4445 /// nontemporal-clause: 4446 /// 'nontemporal' '(' list ')' 4447 /// inclusive-clause: 4448 /// 'inclusive' '(' list ')' 4449 /// exclusive-clause: 4450 /// 'exclusive' '(' list ')' 4451 /// 4452 /// For 'linear' clause linear-list may have the following forms: 4453 /// list 4454 /// modifier(list) 4455 /// where modifier is 'val' (C) or 'ref', 'val' or 'uval'(C++). 4456 OMPClause *Parser::ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, 4457 OpenMPClauseKind Kind, 4458 bool ParseOnly) { 4459 SourceLocation Loc = Tok.getLocation(); 4460 SourceLocation LOpen = ConsumeToken(); 4461 SmallVector<Expr *, 4> Vars; 4462 OpenMPVarListDataTy Data; 4463 4464 if (ParseOpenMPVarList(DKind, Kind, Vars, Data)) 4465 return nullptr; 4466 4467 if (ParseOnly) 4468 return nullptr; 4469 OMPVarListLocTy Locs(Loc, LOpen, Data.RLoc); 4470 return Actions.ActOnOpenMPVarListClause( 4471 Kind, Vars, Data.DepModOrTailExpr, Locs, Data.ColonLoc, 4472 Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId, 4473 Data.ExtraModifier, Data.MapTypeModifiers, Data.MapTypeModifiersLoc, 4474 Data.IsMapTypeImplicit, Data.ExtraModifierLoc, Data.MotionModifiers, 4475 Data.MotionModifiersLoc); 4476 } 4477