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/StmtOpenMP.h" 15 #include "clang/Parse/ParseDiagnostic.h" 16 #include "clang/Parse/Parser.h" 17 #include "clang/Parse/RAIIObjectsForParser.h" 18 #include "clang/Sema/Scope.h" 19 #include "llvm/ADT/PointerIntPair.h" 20 #include "llvm/ADT/UniqueVector.h" 21 22 using namespace clang; 23 using namespace llvm::omp; 24 25 //===----------------------------------------------------------------------===// 26 // OpenMP declarative directives. 27 //===----------------------------------------------------------------------===// 28 29 namespace { 30 enum OpenMPDirectiveKindEx { 31 OMPD_cancellation = unsigned(OMPD_unknown) + 1, 32 OMPD_data, 33 OMPD_declare, 34 OMPD_end, 35 OMPD_end_declare, 36 OMPD_enter, 37 OMPD_exit, 38 OMPD_point, 39 OMPD_reduction, 40 OMPD_target_enter, 41 OMPD_target_exit, 42 OMPD_update, 43 OMPD_distribute_parallel, 44 OMPD_teams_distribute_parallel, 45 OMPD_target_teams_distribute_parallel, 46 OMPD_mapper, 47 OMPD_variant, 48 }; 49 50 // Helper to unify the enum class OpenMPDirectiveKind with its extension 51 // the OpenMPDirectiveKindEx enum which allows to use them together as if they 52 // are unsigned values. 53 struct OpenMPDirectiveKindExWrapper { 54 OpenMPDirectiveKindExWrapper(unsigned Value) : Value(Value) {} 55 OpenMPDirectiveKindExWrapper(OpenMPDirectiveKind DK) : Value(unsigned(DK)) {} 56 bool operator==(OpenMPDirectiveKind V) const { return Value == unsigned(V); } 57 bool operator!=(OpenMPDirectiveKind V) const { return Value != unsigned(V); } 58 bool operator<(OpenMPDirectiveKind V) const { return Value < unsigned(V); } 59 operator unsigned() const { return Value; } 60 operator OpenMPDirectiveKind() const { return OpenMPDirectiveKind(Value); } 61 unsigned Value; 62 }; 63 64 class DeclDirectiveListParserHelper final { 65 SmallVector<Expr *, 4> Identifiers; 66 Parser *P; 67 OpenMPDirectiveKind Kind; 68 69 public: 70 DeclDirectiveListParserHelper(Parser *P, OpenMPDirectiveKind Kind) 71 : P(P), Kind(Kind) {} 72 void operator()(CXXScopeSpec &SS, DeclarationNameInfo NameInfo) { 73 ExprResult Res = P->getActions().ActOnOpenMPIdExpression( 74 P->getCurScope(), SS, NameInfo, Kind); 75 if (Res.isUsable()) 76 Identifiers.push_back(Res.get()); 77 } 78 llvm::ArrayRef<Expr *> getIdentifiers() const { return Identifiers; } 79 }; 80 } // namespace 81 82 // Map token string to extended OMP token kind that are 83 // OpenMPDirectiveKind + OpenMPDirectiveKindEx. 84 static unsigned getOpenMPDirectiveKindEx(StringRef S) { 85 OpenMPDirectiveKindExWrapper DKind = getOpenMPDirectiveKind(S); 86 if (DKind != OMPD_unknown) 87 return DKind; 88 89 return llvm::StringSwitch<OpenMPDirectiveKindExWrapper>(S) 90 .Case("cancellation", OMPD_cancellation) 91 .Case("data", OMPD_data) 92 .Case("declare", OMPD_declare) 93 .Case("end", OMPD_end) 94 .Case("enter", OMPD_enter) 95 .Case("exit", OMPD_exit) 96 .Case("point", OMPD_point) 97 .Case("reduction", OMPD_reduction) 98 .Case("update", OMPD_update) 99 .Case("mapper", OMPD_mapper) 100 .Case("variant", OMPD_variant) 101 .Default(OMPD_unknown); 102 } 103 104 static OpenMPDirectiveKindExWrapper parseOpenMPDirectiveKind(Parser &P) { 105 // Array of foldings: F[i][0] F[i][1] ===> F[i][2]. 106 // E.g.: OMPD_for OMPD_simd ===> OMPD_for_simd 107 // TODO: add other combined directives in topological order. 108 static const OpenMPDirectiveKindExWrapper F[][3] = { 109 {OMPD_cancellation, OMPD_point, OMPD_cancellation_point}, 110 {OMPD_declare, OMPD_reduction, OMPD_declare_reduction}, 111 {OMPD_declare, OMPD_mapper, OMPD_declare_mapper}, 112 {OMPD_declare, OMPD_simd, OMPD_declare_simd}, 113 {OMPD_declare, OMPD_target, OMPD_declare_target}, 114 {OMPD_declare, OMPD_variant, OMPD_declare_variant}, 115 {OMPD_distribute, OMPD_parallel, OMPD_distribute_parallel}, 116 {OMPD_distribute_parallel, OMPD_for, OMPD_distribute_parallel_for}, 117 {OMPD_distribute_parallel_for, OMPD_simd, 118 OMPD_distribute_parallel_for_simd}, 119 {OMPD_distribute, OMPD_simd, OMPD_distribute_simd}, 120 {OMPD_end, OMPD_declare, OMPD_end_declare}, 121 {OMPD_end_declare, OMPD_target, OMPD_end_declare_target}, 122 {OMPD_target, OMPD_data, OMPD_target_data}, 123 {OMPD_target, OMPD_enter, OMPD_target_enter}, 124 {OMPD_target, OMPD_exit, OMPD_target_exit}, 125 {OMPD_target, OMPD_update, OMPD_target_update}, 126 {OMPD_target_enter, OMPD_data, OMPD_target_enter_data}, 127 {OMPD_target_exit, OMPD_data, OMPD_target_exit_data}, 128 {OMPD_for, OMPD_simd, OMPD_for_simd}, 129 {OMPD_parallel, OMPD_for, OMPD_parallel_for}, 130 {OMPD_parallel_for, OMPD_simd, OMPD_parallel_for_simd}, 131 {OMPD_parallel, OMPD_sections, OMPD_parallel_sections}, 132 {OMPD_taskloop, OMPD_simd, OMPD_taskloop_simd}, 133 {OMPD_target, OMPD_parallel, OMPD_target_parallel}, 134 {OMPD_target, OMPD_simd, OMPD_target_simd}, 135 {OMPD_target_parallel, OMPD_for, OMPD_target_parallel_for}, 136 {OMPD_target_parallel_for, OMPD_simd, OMPD_target_parallel_for_simd}, 137 {OMPD_teams, OMPD_distribute, OMPD_teams_distribute}, 138 {OMPD_teams_distribute, OMPD_simd, OMPD_teams_distribute_simd}, 139 {OMPD_teams_distribute, OMPD_parallel, OMPD_teams_distribute_parallel}, 140 {OMPD_teams_distribute_parallel, OMPD_for, 141 OMPD_teams_distribute_parallel_for}, 142 {OMPD_teams_distribute_parallel_for, OMPD_simd, 143 OMPD_teams_distribute_parallel_for_simd}, 144 {OMPD_target, OMPD_teams, OMPD_target_teams}, 145 {OMPD_target_teams, OMPD_distribute, OMPD_target_teams_distribute}, 146 {OMPD_target_teams_distribute, OMPD_parallel, 147 OMPD_target_teams_distribute_parallel}, 148 {OMPD_target_teams_distribute, OMPD_simd, 149 OMPD_target_teams_distribute_simd}, 150 {OMPD_target_teams_distribute_parallel, OMPD_for, 151 OMPD_target_teams_distribute_parallel_for}, 152 {OMPD_target_teams_distribute_parallel_for, OMPD_simd, 153 OMPD_target_teams_distribute_parallel_for_simd}, 154 {OMPD_master, OMPD_taskloop, OMPD_master_taskloop}, 155 {OMPD_master_taskloop, OMPD_simd, OMPD_master_taskloop_simd}, 156 {OMPD_parallel, OMPD_master, OMPD_parallel_master}, 157 {OMPD_parallel_master, OMPD_taskloop, OMPD_parallel_master_taskloop}, 158 {OMPD_parallel_master_taskloop, OMPD_simd, 159 OMPD_parallel_master_taskloop_simd}}; 160 enum { CancellationPoint = 0, DeclareReduction = 1, TargetData = 2 }; 161 Token Tok = P.getCurToken(); 162 OpenMPDirectiveKindExWrapper DKind = 163 Tok.isAnnotation() 164 ? static_cast<unsigned>(OMPD_unknown) 165 : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok)); 166 if (DKind == OMPD_unknown) 167 return OMPD_unknown; 168 169 for (unsigned I = 0; I < llvm::array_lengthof(F); ++I) { 170 if (DKind != F[I][0]) 171 continue; 172 173 Tok = P.getPreprocessor().LookAhead(0); 174 OpenMPDirectiveKindExWrapper SDKind = 175 Tok.isAnnotation() 176 ? static_cast<unsigned>(OMPD_unknown) 177 : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok)); 178 if (SDKind == OMPD_unknown) 179 continue; 180 181 if (SDKind == F[I][1]) { 182 P.ConsumeToken(); 183 DKind = F[I][2]; 184 } 185 } 186 return DKind < OMPD_unknown ? static_cast<OpenMPDirectiveKind>(DKind) 187 : OMPD_unknown; 188 } 189 190 static DeclarationName parseOpenMPReductionId(Parser &P) { 191 Token Tok = P.getCurToken(); 192 Sema &Actions = P.getActions(); 193 OverloadedOperatorKind OOK = OO_None; 194 // Allow to use 'operator' keyword for C++ operators 195 bool WithOperator = false; 196 if (Tok.is(tok::kw_operator)) { 197 P.ConsumeToken(); 198 Tok = P.getCurToken(); 199 WithOperator = true; 200 } 201 switch (Tok.getKind()) { 202 case tok::plus: // '+' 203 OOK = OO_Plus; 204 break; 205 case tok::minus: // '-' 206 OOK = OO_Minus; 207 break; 208 case tok::star: // '*' 209 OOK = OO_Star; 210 break; 211 case tok::amp: // '&' 212 OOK = OO_Amp; 213 break; 214 case tok::pipe: // '|' 215 OOK = OO_Pipe; 216 break; 217 case tok::caret: // '^' 218 OOK = OO_Caret; 219 break; 220 case tok::ampamp: // '&&' 221 OOK = OO_AmpAmp; 222 break; 223 case tok::pipepipe: // '||' 224 OOK = OO_PipePipe; 225 break; 226 case tok::identifier: // identifier 227 if (!WithOperator) 228 break; 229 LLVM_FALLTHROUGH; 230 default: 231 P.Diag(Tok.getLocation(), diag::err_omp_expected_reduction_identifier); 232 P.SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 233 Parser::StopBeforeMatch); 234 return DeclarationName(); 235 } 236 P.ConsumeToken(); 237 auto &DeclNames = Actions.getASTContext().DeclarationNames; 238 return OOK == OO_None ? DeclNames.getIdentifier(Tok.getIdentifierInfo()) 239 : DeclNames.getCXXOperatorName(OOK); 240 } 241 242 /// Parse 'omp declare reduction' construct. 243 /// 244 /// declare-reduction-directive: 245 /// annot_pragma_openmp 'declare' 'reduction' 246 /// '(' <reduction_id> ':' <type> {',' <type>} ':' <expression> ')' 247 /// ['initializer' '(' ('omp_priv' '=' <expression>)|<function_call> ')'] 248 /// annot_pragma_openmp_end 249 /// <reduction_id> is either a base language identifier or one of the following 250 /// operators: '+', '-', '*', '&', '|', '^', '&&' and '||'. 251 /// 252 Parser::DeclGroupPtrTy 253 Parser::ParseOpenMPDeclareReductionDirective(AccessSpecifier AS) { 254 // Parse '('. 255 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 256 if (T.expectAndConsume( 257 diag::err_expected_lparen_after, 258 getOpenMPDirectiveName(OMPD_declare_reduction).data())) { 259 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 260 return DeclGroupPtrTy(); 261 } 262 263 DeclarationName Name = parseOpenMPReductionId(*this); 264 if (Name.isEmpty() && Tok.is(tok::annot_pragma_openmp_end)) 265 return DeclGroupPtrTy(); 266 267 // Consume ':'. 268 bool IsCorrect = !ExpectAndConsume(tok::colon); 269 270 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end)) 271 return DeclGroupPtrTy(); 272 273 IsCorrect = IsCorrect && !Name.isEmpty(); 274 275 if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end)) { 276 Diag(Tok.getLocation(), diag::err_expected_type); 277 IsCorrect = false; 278 } 279 280 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end)) 281 return DeclGroupPtrTy(); 282 283 SmallVector<std::pair<QualType, SourceLocation>, 8> ReductionTypes; 284 // Parse list of types until ':' token. 285 do { 286 ColonProtectionRAIIObject ColonRAII(*this); 287 SourceRange Range; 288 TypeResult TR = 289 ParseTypeName(&Range, DeclaratorContext::PrototypeContext, AS); 290 if (TR.isUsable()) { 291 QualType ReductionType = 292 Actions.ActOnOpenMPDeclareReductionType(Range.getBegin(), TR); 293 if (!ReductionType.isNull()) { 294 ReductionTypes.push_back( 295 std::make_pair(ReductionType, Range.getBegin())); 296 } 297 } else { 298 SkipUntil(tok::comma, tok::colon, tok::annot_pragma_openmp_end, 299 StopBeforeMatch); 300 } 301 302 if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end)) 303 break; 304 305 // Consume ','. 306 if (ExpectAndConsume(tok::comma)) { 307 IsCorrect = false; 308 if (Tok.is(tok::annot_pragma_openmp_end)) { 309 Diag(Tok.getLocation(), diag::err_expected_type); 310 return DeclGroupPtrTy(); 311 } 312 } 313 } while (Tok.isNot(tok::annot_pragma_openmp_end)); 314 315 if (ReductionTypes.empty()) { 316 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 317 return DeclGroupPtrTy(); 318 } 319 320 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end)) 321 return DeclGroupPtrTy(); 322 323 // Consume ':'. 324 if (ExpectAndConsume(tok::colon)) 325 IsCorrect = false; 326 327 if (Tok.is(tok::annot_pragma_openmp_end)) { 328 Diag(Tok.getLocation(), diag::err_expected_expression); 329 return DeclGroupPtrTy(); 330 } 331 332 DeclGroupPtrTy DRD = Actions.ActOnOpenMPDeclareReductionDirectiveStart( 333 getCurScope(), Actions.getCurLexicalContext(), Name, ReductionTypes, AS); 334 335 // Parse <combiner> expression and then parse initializer if any for each 336 // correct type. 337 unsigned I = 0, E = ReductionTypes.size(); 338 for (Decl *D : DRD.get()) { 339 TentativeParsingAction TPA(*this); 340 ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope | 341 Scope::CompoundStmtScope | 342 Scope::OpenMPDirectiveScope); 343 // Parse <combiner> expression. 344 Actions.ActOnOpenMPDeclareReductionCombinerStart(getCurScope(), D); 345 ExprResult CombinerResult = 346 Actions.ActOnFinishFullExpr(ParseAssignmentExpression().get(), 347 D->getLocation(), /*DiscardedValue*/ false); 348 Actions.ActOnOpenMPDeclareReductionCombinerEnd(D, CombinerResult.get()); 349 350 if (CombinerResult.isInvalid() && Tok.isNot(tok::r_paren) && 351 Tok.isNot(tok::annot_pragma_openmp_end)) { 352 TPA.Commit(); 353 IsCorrect = false; 354 break; 355 } 356 IsCorrect = !T.consumeClose() && IsCorrect && CombinerResult.isUsable(); 357 ExprResult InitializerResult; 358 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 359 // Parse <initializer> expression. 360 if (Tok.is(tok::identifier) && 361 Tok.getIdentifierInfo()->isStr("initializer")) { 362 ConsumeToken(); 363 } else { 364 Diag(Tok.getLocation(), diag::err_expected) << "'initializer'"; 365 TPA.Commit(); 366 IsCorrect = false; 367 break; 368 } 369 // Parse '('. 370 BalancedDelimiterTracker T(*this, tok::l_paren, 371 tok::annot_pragma_openmp_end); 372 IsCorrect = 373 !T.expectAndConsume(diag::err_expected_lparen_after, "initializer") && 374 IsCorrect; 375 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 376 ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope | 377 Scope::CompoundStmtScope | 378 Scope::OpenMPDirectiveScope); 379 // Parse expression. 380 VarDecl *OmpPrivParm = 381 Actions.ActOnOpenMPDeclareReductionInitializerStart(getCurScope(), 382 D); 383 // Check if initializer is omp_priv <init_expr> or something else. 384 if (Tok.is(tok::identifier) && 385 Tok.getIdentifierInfo()->isStr("omp_priv")) { 386 ConsumeToken(); 387 ParseOpenMPReductionInitializerForDecl(OmpPrivParm); 388 } else { 389 InitializerResult = Actions.ActOnFinishFullExpr( 390 ParseAssignmentExpression().get(), D->getLocation(), 391 /*DiscardedValue*/ false); 392 } 393 Actions.ActOnOpenMPDeclareReductionInitializerEnd( 394 D, InitializerResult.get(), OmpPrivParm); 395 if (InitializerResult.isInvalid() && Tok.isNot(tok::r_paren) && 396 Tok.isNot(tok::annot_pragma_openmp_end)) { 397 TPA.Commit(); 398 IsCorrect = false; 399 break; 400 } 401 IsCorrect = 402 !T.consumeClose() && IsCorrect && !InitializerResult.isInvalid(); 403 } 404 } 405 406 ++I; 407 // Revert parsing if not the last type, otherwise accept it, we're done with 408 // parsing. 409 if (I != E) 410 TPA.Revert(); 411 else 412 TPA.Commit(); 413 } 414 return Actions.ActOnOpenMPDeclareReductionDirectiveEnd(getCurScope(), DRD, 415 IsCorrect); 416 } 417 418 void Parser::ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm) { 419 // Parse declarator '=' initializer. 420 // If a '==' or '+=' is found, suggest a fixit to '='. 421 if (isTokenEqualOrEqualTypo()) { 422 ConsumeToken(); 423 424 if (Tok.is(tok::code_completion)) { 425 Actions.CodeCompleteInitializer(getCurScope(), OmpPrivParm); 426 Actions.FinalizeDeclaration(OmpPrivParm); 427 cutOffParsing(); 428 return; 429 } 430 431 PreferredType.enterVariableInit(Tok.getLocation(), OmpPrivParm); 432 ExprResult Init = ParseAssignmentExpression(); 433 434 if (Init.isInvalid()) { 435 SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch); 436 Actions.ActOnInitializerError(OmpPrivParm); 437 } else { 438 Actions.AddInitializerToDecl(OmpPrivParm, Init.get(), 439 /*DirectInit=*/false); 440 } 441 } else if (Tok.is(tok::l_paren)) { 442 // Parse C++ direct initializer: '(' expression-list ')' 443 BalancedDelimiterTracker T(*this, tok::l_paren); 444 T.consumeOpen(); 445 446 ExprVector Exprs; 447 CommaLocsTy CommaLocs; 448 449 SourceLocation LParLoc = T.getOpenLocation(); 450 auto RunSignatureHelp = [this, OmpPrivParm, LParLoc, &Exprs]() { 451 QualType PreferredType = Actions.ProduceConstructorSignatureHelp( 452 getCurScope(), OmpPrivParm->getType()->getCanonicalTypeInternal(), 453 OmpPrivParm->getLocation(), Exprs, LParLoc); 454 CalledSignatureHelp = true; 455 return PreferredType; 456 }; 457 if (ParseExpressionList(Exprs, CommaLocs, [&] { 458 PreferredType.enterFunctionArgument(Tok.getLocation(), 459 RunSignatureHelp); 460 })) { 461 if (PP.isCodeCompletionReached() && !CalledSignatureHelp) 462 RunSignatureHelp(); 463 Actions.ActOnInitializerError(OmpPrivParm); 464 SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch); 465 } else { 466 // Match the ')'. 467 SourceLocation RLoc = Tok.getLocation(); 468 if (!T.consumeClose()) 469 RLoc = T.getCloseLocation(); 470 471 assert(!Exprs.empty() && Exprs.size() - 1 == CommaLocs.size() && 472 "Unexpected number of commas!"); 473 474 ExprResult Initializer = 475 Actions.ActOnParenListExpr(T.getOpenLocation(), RLoc, Exprs); 476 Actions.AddInitializerToDecl(OmpPrivParm, Initializer.get(), 477 /*DirectInit=*/true); 478 } 479 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { 480 // Parse C++0x braced-init-list. 481 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); 482 483 ExprResult Init(ParseBraceInitializer()); 484 485 if (Init.isInvalid()) { 486 Actions.ActOnInitializerError(OmpPrivParm); 487 } else { 488 Actions.AddInitializerToDecl(OmpPrivParm, Init.get(), 489 /*DirectInit=*/true); 490 } 491 } else { 492 Actions.ActOnUninitializedDecl(OmpPrivParm); 493 } 494 } 495 496 /// Parses 'omp declare mapper' directive. 497 /// 498 /// declare-mapper-directive: 499 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifier> ':'] 500 /// <type> <var> ')' [<clause>[[,] <clause>] ... ] 501 /// annot_pragma_openmp_end 502 /// <mapper-identifier> and <var> are base language identifiers. 503 /// 504 Parser::DeclGroupPtrTy 505 Parser::ParseOpenMPDeclareMapperDirective(AccessSpecifier AS) { 506 bool IsCorrect = true; 507 // Parse '(' 508 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 509 if (T.expectAndConsume(diag::err_expected_lparen_after, 510 getOpenMPDirectiveName(OMPD_declare_mapper).data())) { 511 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 512 return DeclGroupPtrTy(); 513 } 514 515 // Parse <mapper-identifier> 516 auto &DeclNames = Actions.getASTContext().DeclarationNames; 517 DeclarationName MapperId; 518 if (PP.LookAhead(0).is(tok::colon)) { 519 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) { 520 Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier); 521 IsCorrect = false; 522 } else { 523 MapperId = DeclNames.getIdentifier(Tok.getIdentifierInfo()); 524 } 525 ConsumeToken(); 526 // Consume ':'. 527 ExpectAndConsume(tok::colon); 528 } else { 529 // If no mapper identifier is provided, its name is "default" by default 530 MapperId = 531 DeclNames.getIdentifier(&Actions.getASTContext().Idents.get("default")); 532 } 533 534 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end)) 535 return DeclGroupPtrTy(); 536 537 // Parse <type> <var> 538 DeclarationName VName; 539 QualType MapperType; 540 SourceRange Range; 541 TypeResult ParsedType = parseOpenMPDeclareMapperVarDecl(Range, VName, AS); 542 if (ParsedType.isUsable()) 543 MapperType = 544 Actions.ActOnOpenMPDeclareMapperType(Range.getBegin(), ParsedType); 545 if (MapperType.isNull()) 546 IsCorrect = false; 547 if (!IsCorrect) { 548 SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch); 549 return DeclGroupPtrTy(); 550 } 551 552 // Consume ')'. 553 IsCorrect &= !T.consumeClose(); 554 if (!IsCorrect) { 555 SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch); 556 return DeclGroupPtrTy(); 557 } 558 559 // Enter scope. 560 OMPDeclareMapperDecl *DMD = Actions.ActOnOpenMPDeclareMapperDirectiveStart( 561 getCurScope(), Actions.getCurLexicalContext(), MapperId, MapperType, 562 Range.getBegin(), VName, AS); 563 DeclarationNameInfo DirName; 564 SourceLocation Loc = Tok.getLocation(); 565 unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope | 566 Scope::CompoundStmtScope | Scope::OpenMPDirectiveScope; 567 ParseScope OMPDirectiveScope(this, ScopeFlags); 568 Actions.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, getCurScope(), Loc); 569 570 // Add the mapper variable declaration. 571 Actions.ActOnOpenMPDeclareMapperDirectiveVarDecl( 572 DMD, getCurScope(), MapperType, Range.getBegin(), VName); 573 574 // Parse map clauses. 575 SmallVector<OMPClause *, 6> Clauses; 576 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 577 OpenMPClauseKind CKind = Tok.isAnnotation() 578 ? OMPC_unknown 579 : getOpenMPClauseKind(PP.getSpelling(Tok)); 580 Actions.StartOpenMPClause(CKind); 581 OMPClause *Clause = 582 ParseOpenMPClause(OMPD_declare_mapper, CKind, Clauses.size() == 0); 583 if (Clause) 584 Clauses.push_back(Clause); 585 else 586 IsCorrect = false; 587 // Skip ',' if any. 588 if (Tok.is(tok::comma)) 589 ConsumeToken(); 590 Actions.EndOpenMPClause(); 591 } 592 if (Clauses.empty()) { 593 Diag(Tok, diag::err_omp_expected_clause) 594 << getOpenMPDirectiveName(OMPD_declare_mapper); 595 IsCorrect = false; 596 } 597 598 // Exit scope. 599 Actions.EndOpenMPDSABlock(nullptr); 600 OMPDirectiveScope.Exit(); 601 602 DeclGroupPtrTy DGP = 603 Actions.ActOnOpenMPDeclareMapperDirectiveEnd(DMD, getCurScope(), Clauses); 604 if (!IsCorrect) 605 return DeclGroupPtrTy(); 606 return DGP; 607 } 608 609 TypeResult Parser::parseOpenMPDeclareMapperVarDecl(SourceRange &Range, 610 DeclarationName &Name, 611 AccessSpecifier AS) { 612 // Parse the common declaration-specifiers piece. 613 Parser::DeclSpecContext DSC = Parser::DeclSpecContext::DSC_type_specifier; 614 DeclSpec DS(AttrFactory); 615 ParseSpecifierQualifierList(DS, AS, DSC); 616 617 // Parse the declarator. 618 DeclaratorContext Context = DeclaratorContext::PrototypeContext; 619 Declarator DeclaratorInfo(DS, Context); 620 ParseDeclarator(DeclaratorInfo); 621 Range = DeclaratorInfo.getSourceRange(); 622 if (DeclaratorInfo.getIdentifier() == nullptr) { 623 Diag(Tok.getLocation(), diag::err_omp_mapper_expected_declarator); 624 return true; 625 } 626 Name = Actions.GetNameForDeclarator(DeclaratorInfo).getName(); 627 628 return Actions.ActOnOpenMPDeclareMapperVarDecl(getCurScope(), DeclaratorInfo); 629 } 630 631 namespace { 632 /// RAII that recreates function context for correct parsing of clauses of 633 /// 'declare simd' construct. 634 /// OpenMP, 2.8.2 declare simd Construct 635 /// The expressions appearing in the clauses of this directive are evaluated in 636 /// the scope of the arguments of the function declaration or definition. 637 class FNContextRAII final { 638 Parser &P; 639 Sema::CXXThisScopeRAII *ThisScope; 640 Parser::ParseScope *TempScope; 641 Parser::ParseScope *FnScope; 642 bool HasTemplateScope = false; 643 bool HasFunScope = false; 644 FNContextRAII() = delete; 645 FNContextRAII(const FNContextRAII &) = delete; 646 FNContextRAII &operator=(const FNContextRAII &) = delete; 647 648 public: 649 FNContextRAII(Parser &P, Parser::DeclGroupPtrTy Ptr) : P(P) { 650 Decl *D = *Ptr.get().begin(); 651 NamedDecl *ND = dyn_cast<NamedDecl>(D); 652 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext()); 653 Sema &Actions = P.getActions(); 654 655 // Allow 'this' within late-parsed attributes. 656 ThisScope = new Sema::CXXThisScopeRAII(Actions, RD, Qualifiers(), 657 ND && ND->isCXXInstanceMember()); 658 659 // If the Decl is templatized, add template parameters to scope. 660 HasTemplateScope = D->isTemplateDecl(); 661 TempScope = 662 new Parser::ParseScope(&P, Scope::TemplateParamScope, HasTemplateScope); 663 if (HasTemplateScope) 664 Actions.ActOnReenterTemplateScope(Actions.getCurScope(), D); 665 666 // If the Decl is on a function, add function parameters to the scope. 667 HasFunScope = D->isFunctionOrFunctionTemplate(); 668 FnScope = new Parser::ParseScope( 669 &P, Scope::FnScope | Scope::DeclScope | Scope::CompoundStmtScope, 670 HasFunScope); 671 if (HasFunScope) 672 Actions.ActOnReenterFunctionContext(Actions.getCurScope(), D); 673 } 674 ~FNContextRAII() { 675 if (HasFunScope) { 676 P.getActions().ActOnExitFunctionContext(); 677 FnScope->Exit(); // Pop scope, and remove Decls from IdResolver 678 } 679 if (HasTemplateScope) 680 TempScope->Exit(); 681 delete FnScope; 682 delete TempScope; 683 delete ThisScope; 684 } 685 }; 686 } // namespace 687 688 /// Parses clauses for 'declare simd' directive. 689 /// clause: 690 /// 'inbranch' | 'notinbranch' 691 /// 'simdlen' '(' <expr> ')' 692 /// { 'uniform' '(' <argument_list> ')' } 693 /// { 'aligned '(' <argument_list> [ ':' <alignment> ] ')' } 694 /// { 'linear '(' <argument_list> [ ':' <step> ] ')' } 695 static bool parseDeclareSimdClauses( 696 Parser &P, OMPDeclareSimdDeclAttr::BranchStateTy &BS, ExprResult &SimdLen, 697 SmallVectorImpl<Expr *> &Uniforms, SmallVectorImpl<Expr *> &Aligneds, 698 SmallVectorImpl<Expr *> &Alignments, SmallVectorImpl<Expr *> &Linears, 699 SmallVectorImpl<unsigned> &LinModifiers, SmallVectorImpl<Expr *> &Steps) { 700 SourceRange BSRange; 701 const Token &Tok = P.getCurToken(); 702 bool IsError = false; 703 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 704 if (Tok.isNot(tok::identifier)) 705 break; 706 OMPDeclareSimdDeclAttr::BranchStateTy Out; 707 IdentifierInfo *II = Tok.getIdentifierInfo(); 708 StringRef ClauseName = II->getName(); 709 // Parse 'inranch|notinbranch' clauses. 710 if (OMPDeclareSimdDeclAttr::ConvertStrToBranchStateTy(ClauseName, Out)) { 711 if (BS != OMPDeclareSimdDeclAttr::BS_Undefined && BS != Out) { 712 P.Diag(Tok, diag::err_omp_declare_simd_inbranch_notinbranch) 713 << ClauseName 714 << OMPDeclareSimdDeclAttr::ConvertBranchStateTyToStr(BS) << BSRange; 715 IsError = true; 716 } 717 BS = Out; 718 BSRange = SourceRange(Tok.getLocation(), Tok.getEndLoc()); 719 P.ConsumeToken(); 720 } else if (ClauseName.equals("simdlen")) { 721 if (SimdLen.isUsable()) { 722 P.Diag(Tok, diag::err_omp_more_one_clause) 723 << getOpenMPDirectiveName(OMPD_declare_simd) << ClauseName << 0; 724 IsError = true; 725 } 726 P.ConsumeToken(); 727 SourceLocation RLoc; 728 SimdLen = P.ParseOpenMPParensExpr(ClauseName, RLoc); 729 if (SimdLen.isInvalid()) 730 IsError = true; 731 } else { 732 OpenMPClauseKind CKind = getOpenMPClauseKind(ClauseName); 733 if (CKind == OMPC_uniform || CKind == OMPC_aligned || 734 CKind == OMPC_linear) { 735 Parser::OpenMPVarListDataTy Data; 736 SmallVectorImpl<Expr *> *Vars = &Uniforms; 737 if (CKind == OMPC_aligned) 738 Vars = &Aligneds; 739 else if (CKind == OMPC_linear) 740 Vars = &Linears; 741 742 P.ConsumeToken(); 743 if (P.ParseOpenMPVarList(OMPD_declare_simd, 744 getOpenMPClauseKind(ClauseName), *Vars, Data)) 745 IsError = true; 746 if (CKind == OMPC_aligned) { 747 Alignments.append(Aligneds.size() - Alignments.size(), Data.TailExpr); 748 } else if (CKind == OMPC_linear) { 749 if (P.getActions().CheckOpenMPLinearModifier(Data.LinKind, 750 Data.DepLinMapLoc)) 751 Data.LinKind = OMPC_LINEAR_val; 752 LinModifiers.append(Linears.size() - LinModifiers.size(), 753 Data.LinKind); 754 Steps.append(Linears.size() - Steps.size(), Data.TailExpr); 755 } 756 } else 757 // TODO: add parsing of other clauses. 758 break; 759 } 760 // Skip ',' if any. 761 if (Tok.is(tok::comma)) 762 P.ConsumeToken(); 763 } 764 return IsError; 765 } 766 767 /// Parse clauses for '#pragma omp declare simd'. 768 Parser::DeclGroupPtrTy 769 Parser::ParseOMPDeclareSimdClauses(Parser::DeclGroupPtrTy Ptr, 770 CachedTokens &Toks, SourceLocation Loc) { 771 PP.EnterToken(Tok, /*IsReinject*/ true); 772 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true, 773 /*IsReinject*/ true); 774 // Consume the previously pushed token. 775 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 776 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 777 778 FNContextRAII FnContext(*this, Ptr); 779 OMPDeclareSimdDeclAttr::BranchStateTy BS = 780 OMPDeclareSimdDeclAttr::BS_Undefined; 781 ExprResult Simdlen; 782 SmallVector<Expr *, 4> Uniforms; 783 SmallVector<Expr *, 4> Aligneds; 784 SmallVector<Expr *, 4> Alignments; 785 SmallVector<Expr *, 4> Linears; 786 SmallVector<unsigned, 4> LinModifiers; 787 SmallVector<Expr *, 4> Steps; 788 bool IsError = 789 parseDeclareSimdClauses(*this, BS, Simdlen, Uniforms, Aligneds, 790 Alignments, Linears, LinModifiers, Steps); 791 // Need to check for extra tokens. 792 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 793 Diag(Tok, diag::warn_omp_extra_tokens_at_eol) 794 << getOpenMPDirectiveName(OMPD_declare_simd); 795 while (Tok.isNot(tok::annot_pragma_openmp_end)) 796 ConsumeAnyToken(); 797 } 798 // Skip the last annot_pragma_openmp_end. 799 SourceLocation EndLoc = ConsumeAnnotationToken(); 800 if (IsError) 801 return Ptr; 802 return Actions.ActOnOpenMPDeclareSimdDirective( 803 Ptr, BS, Simdlen.get(), Uniforms, Aligneds, Alignments, Linears, 804 LinModifiers, Steps, SourceRange(Loc, EndLoc)); 805 } 806 807 /// Parse optional 'score' '(' <expr> ')' ':'. 808 static ExprResult parseContextScore(Parser &P) { 809 ExprResult ScoreExpr; 810 Sema::OMPCtxStringType Buffer; 811 StringRef SelectorName = 812 P.getPreprocessor().getSpelling(P.getCurToken(), Buffer); 813 if (!SelectorName.equals("score")) 814 return ScoreExpr; 815 (void)P.ConsumeToken(); 816 SourceLocation RLoc; 817 ScoreExpr = P.ParseOpenMPParensExpr(SelectorName, RLoc); 818 // Parse ':' 819 if (P.getCurToken().is(tok::colon)) 820 (void)P.ConsumeAnyToken(); 821 else 822 P.Diag(P.getCurToken(), diag::warn_pragma_expected_colon) 823 << "context selector score clause"; 824 return ScoreExpr; 825 } 826 827 /// Parse context selector for 'implementation' selector set: 828 /// 'vendor' '(' [ 'score' '(' <score _expr> ')' ':' ] <vendor> { ',' <vendor> } 829 /// ')' 830 static void 831 parseImplementationSelector(Parser &P, SourceLocation Loc, 832 llvm::StringMap<SourceLocation> &UsedCtx, 833 SmallVectorImpl<Sema::OMPCtxSelectorData> &Data) { 834 const Token &Tok = P.getCurToken(); 835 // Parse inner context selector set name, if any. 836 if (!Tok.is(tok::identifier)) { 837 P.Diag(Tok.getLocation(), diag::warn_omp_declare_variant_cs_name_expected) 838 << "implementation"; 839 // Skip until either '}', ')', or end of directive. 840 while (!P.SkipUntil(tok::r_brace, tok::r_paren, 841 tok::annot_pragma_openmp_end, Parser::StopBeforeMatch)) 842 ; 843 return; 844 } 845 Sema::OMPCtxStringType Buffer; 846 StringRef CtxSelectorName = P.getPreprocessor().getSpelling(Tok, Buffer); 847 auto Res = UsedCtx.try_emplace(CtxSelectorName, Tok.getLocation()); 848 if (!Res.second) { 849 // OpenMP 5.0, 2.3.2 Context Selectors, Restrictions. 850 // Each trait-selector-name can only be specified once. 851 P.Diag(Tok.getLocation(), diag::err_omp_declare_variant_ctx_mutiple_use) 852 << CtxSelectorName << "implementation"; 853 P.Diag(Res.first->getValue(), diag::note_omp_declare_variant_ctx_used_here) 854 << CtxSelectorName; 855 } 856 OpenMPContextSelectorKind CSKind = getOpenMPContextSelector(CtxSelectorName); 857 (void)P.ConsumeToken(); 858 switch (CSKind) { 859 case OMP_CTX_vendor: { 860 // Parse '('. 861 BalancedDelimiterTracker T(P, tok::l_paren, tok::annot_pragma_openmp_end); 862 (void)T.expectAndConsume(diag::err_expected_lparen_after, 863 CtxSelectorName.data()); 864 ExprResult Score = parseContextScore(P); 865 llvm::UniqueVector<Sema::OMPCtxStringType> Vendors; 866 do { 867 // Parse <vendor>. 868 StringRef VendorName; 869 if (Tok.is(tok::identifier)) { 870 Buffer.clear(); 871 VendorName = P.getPreprocessor().getSpelling(P.getCurToken(), Buffer); 872 (void)P.ConsumeToken(); 873 if (!VendorName.empty()) 874 Vendors.insert(VendorName); 875 } else { 876 P.Diag(Tok.getLocation(), diag::err_omp_declare_variant_item_expected) 877 << "vendor identifier" 878 << "vendor" 879 << "implementation"; 880 } 881 if (!P.TryConsumeToken(tok::comma) && Tok.isNot(tok::r_paren)) { 882 P.Diag(Tok, diag::err_expected_punc) 883 << (VendorName.empty() ? "vendor name" : VendorName); 884 } 885 } while (Tok.is(tok::identifier)); 886 // Parse ')'. 887 (void)T.consumeClose(); 888 if (!Vendors.empty()) 889 Data.emplace_back(OMP_CTX_SET_implementation, CSKind, Score, Vendors); 890 break; 891 } 892 case OMP_CTX_kind: 893 case OMP_CTX_unknown: 894 P.Diag(Tok.getLocation(), diag::warn_omp_declare_variant_cs_name_expected) 895 << "implementation"; 896 // Skip until either '}', ')', or end of directive. 897 while (!P.SkipUntil(tok::r_brace, tok::r_paren, 898 tok::annot_pragma_openmp_end, Parser::StopBeforeMatch)) 899 ; 900 return; 901 } 902 } 903 904 /// Parse context selector for 'device' selector set: 905 /// 'kind' '(' <kind> { ',' <kind> } ')' 906 static void 907 parseDeviceSelector(Parser &P, SourceLocation Loc, 908 llvm::StringMap<SourceLocation> &UsedCtx, 909 SmallVectorImpl<Sema::OMPCtxSelectorData> &Data) { 910 const Token &Tok = P.getCurToken(); 911 // Parse inner context selector set name, if any. 912 if (!Tok.is(tok::identifier)) { 913 P.Diag(Tok.getLocation(), diag::warn_omp_declare_variant_cs_name_expected) 914 << "device"; 915 // Skip until either '}', ')', or end of directive. 916 while (!P.SkipUntil(tok::r_brace, tok::r_paren, 917 tok::annot_pragma_openmp_end, Parser::StopBeforeMatch)) 918 ; 919 return; 920 } 921 Sema::OMPCtxStringType Buffer; 922 StringRef CtxSelectorName = P.getPreprocessor().getSpelling(Tok, Buffer); 923 auto Res = UsedCtx.try_emplace(CtxSelectorName, Tok.getLocation()); 924 if (!Res.second) { 925 // OpenMP 5.0, 2.3.2 Context Selectors, Restrictions. 926 // Each trait-selector-name can only be specified once. 927 P.Diag(Tok.getLocation(), diag::err_omp_declare_variant_ctx_mutiple_use) 928 << CtxSelectorName << "device"; 929 P.Diag(Res.first->getValue(), diag::note_omp_declare_variant_ctx_used_here) 930 << CtxSelectorName; 931 } 932 OpenMPContextSelectorKind CSKind = getOpenMPContextSelector(CtxSelectorName); 933 (void)P.ConsumeToken(); 934 switch (CSKind) { 935 case OMP_CTX_kind: { 936 // Parse '('. 937 BalancedDelimiterTracker T(P, tok::l_paren, tok::annot_pragma_openmp_end); 938 (void)T.expectAndConsume(diag::err_expected_lparen_after, 939 CtxSelectorName.data()); 940 llvm::UniqueVector<Sema::OMPCtxStringType> Kinds; 941 do { 942 // Parse <kind>. 943 StringRef KindName; 944 if (Tok.is(tok::identifier)) { 945 Buffer.clear(); 946 KindName = P.getPreprocessor().getSpelling(P.getCurToken(), Buffer); 947 SourceLocation SLoc = P.getCurToken().getLocation(); 948 (void)P.ConsumeToken(); 949 if (llvm::StringSwitch<bool>(KindName) 950 .Case("host", false) 951 .Case("nohost", false) 952 .Case("cpu", false) 953 .Case("gpu", false) 954 .Case("fpga", false) 955 .Default(true)) { 956 P.Diag(SLoc, diag::err_omp_wrong_device_kind_trait) << KindName; 957 } else { 958 Kinds.insert(KindName); 959 } 960 } else { 961 P.Diag(Tok.getLocation(), diag::err_omp_declare_variant_item_expected) 962 << "'host', 'nohost', 'cpu', 'gpu', or 'fpga'" 963 << "kind" 964 << "device"; 965 } 966 if (!P.TryConsumeToken(tok::comma) && Tok.isNot(tok::r_paren)) { 967 P.Diag(Tok, diag::err_expected_punc) 968 << (KindName.empty() ? "kind of device" : KindName); 969 } 970 } while (Tok.is(tok::identifier)); 971 // Parse ')'. 972 (void)T.consumeClose(); 973 if (!Kinds.empty()) 974 Data.emplace_back(OMP_CTX_SET_device, CSKind, ExprResult(), Kinds); 975 break; 976 } 977 case OMP_CTX_vendor: 978 case OMP_CTX_unknown: 979 P.Diag(Tok.getLocation(), diag::warn_omp_declare_variant_cs_name_expected) 980 << "device"; 981 // Skip until either '}', ')', or end of directive. 982 while (!P.SkipUntil(tok::r_brace, tok::r_paren, 983 tok::annot_pragma_openmp_end, Parser::StopBeforeMatch)) 984 ; 985 return; 986 } 987 } 988 989 /// Parses clauses for 'declare variant' directive. 990 /// clause: 991 /// <selector_set_name> '=' '{' <context_selectors> '}' 992 /// [ ',' <selector_set_name> '=' '{' <context_selectors> '}' ] 993 bool Parser::parseOpenMPContextSelectors( 994 SourceLocation Loc, SmallVectorImpl<Sema::OMPCtxSelectorData> &Data) { 995 llvm::StringMap<SourceLocation> UsedCtxSets; 996 do { 997 // Parse inner context selector set name. 998 if (!Tok.is(tok::identifier)) { 999 Diag(Tok.getLocation(), diag::err_omp_declare_variant_no_ctx_selector) 1000 << getOpenMPClauseName(OMPC_match); 1001 return true; 1002 } 1003 Sema::OMPCtxStringType Buffer; 1004 StringRef CtxSelectorSetName = PP.getSpelling(Tok, Buffer); 1005 auto Res = UsedCtxSets.try_emplace(CtxSelectorSetName, Tok.getLocation()); 1006 if (!Res.second) { 1007 // OpenMP 5.0, 2.3.2 Context Selectors, Restrictions. 1008 // Each trait-set-selector-name can only be specified once. 1009 Diag(Tok.getLocation(), diag::err_omp_declare_variant_ctx_set_mutiple_use) 1010 << CtxSelectorSetName; 1011 Diag(Res.first->getValue(), 1012 diag::note_omp_declare_variant_ctx_set_used_here) 1013 << CtxSelectorSetName; 1014 } 1015 // Parse '='. 1016 (void)ConsumeToken(); 1017 if (Tok.isNot(tok::equal)) { 1018 Diag(Tok.getLocation(), diag::err_omp_declare_variant_equal_expected) 1019 << CtxSelectorSetName; 1020 return true; 1021 } 1022 (void)ConsumeToken(); 1023 // TBD: add parsing of known context selectors. 1024 // Unknown selector - just ignore it completely. 1025 { 1026 // Parse '{'. 1027 BalancedDelimiterTracker TBr(*this, tok::l_brace, 1028 tok::annot_pragma_openmp_end); 1029 if (TBr.expectAndConsume(diag::err_expected_lbrace_after, "=")) 1030 return true; 1031 OpenMPContextSelectorSetKind CSSKind = 1032 getOpenMPContextSelectorSet(CtxSelectorSetName); 1033 llvm::StringMap<SourceLocation> UsedCtx; 1034 do { 1035 switch (CSSKind) { 1036 case OMP_CTX_SET_implementation: 1037 parseImplementationSelector(*this, Loc, UsedCtx, Data); 1038 break; 1039 case OMP_CTX_SET_device: 1040 parseDeviceSelector(*this, Loc, UsedCtx, Data); 1041 break; 1042 case OMP_CTX_SET_unknown: 1043 // Skip until either '}', ')', or end of directive. 1044 while (!SkipUntil(tok::r_brace, tok::r_paren, 1045 tok::annot_pragma_openmp_end, StopBeforeMatch)) 1046 ; 1047 break; 1048 } 1049 const Token PrevTok = Tok; 1050 if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace)) 1051 Diag(Tok, diag::err_omp_expected_comma_brace) 1052 << (PrevTok.isAnnotation() ? "context selector trait" 1053 : PP.getSpelling(PrevTok)); 1054 } while (Tok.is(tok::identifier)); 1055 // Parse '}'. 1056 (void)TBr.consumeClose(); 1057 } 1058 // Consume ',' 1059 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) 1060 (void)ExpectAndConsume(tok::comma); 1061 } while (Tok.isAnyIdentifier()); 1062 return false; 1063 } 1064 1065 /// Parse clauses for '#pragma omp declare variant ( variant-func-id ) clause'. 1066 void Parser::ParseOMPDeclareVariantClauses(Parser::DeclGroupPtrTy Ptr, 1067 CachedTokens &Toks, 1068 SourceLocation Loc) { 1069 PP.EnterToken(Tok, /*IsReinject*/ true); 1070 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true, 1071 /*IsReinject*/ true); 1072 // Consume the previously pushed token. 1073 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 1074 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); 1075 1076 FNContextRAII FnContext(*this, Ptr); 1077 // Parse function declaration id. 1078 SourceLocation RLoc; 1079 // Parse with IsAddressOfOperand set to true to parse methods as DeclRefExprs 1080 // instead of MemberExprs. 1081 ExprResult AssociatedFunction = 1082 ParseOpenMPParensExpr(getOpenMPDirectiveName(OMPD_declare_variant), RLoc, 1083 /*IsAddressOfOperand=*/true); 1084 if (!AssociatedFunction.isUsable()) { 1085 if (!Tok.is(tok::annot_pragma_openmp_end)) 1086 while (!SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch)) 1087 ; 1088 // Skip the last annot_pragma_openmp_end. 1089 (void)ConsumeAnnotationToken(); 1090 return; 1091 } 1092 Optional<std::pair<FunctionDecl *, Expr *>> DeclVarData = 1093 Actions.checkOpenMPDeclareVariantFunction( 1094 Ptr, AssociatedFunction.get(), SourceRange(Loc, Tok.getLocation())); 1095 1096 // Parse 'match'. 1097 OpenMPClauseKind CKind = Tok.isAnnotation() 1098 ? OMPC_unknown 1099 : getOpenMPClauseKind(PP.getSpelling(Tok)); 1100 if (CKind != OMPC_match) { 1101 Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause) 1102 << getOpenMPClauseName(OMPC_match); 1103 while (!SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch)) 1104 ; 1105 // Skip the last annot_pragma_openmp_end. 1106 (void)ConsumeAnnotationToken(); 1107 return; 1108 } 1109 (void)ConsumeToken(); 1110 // Parse '('. 1111 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 1112 if (T.expectAndConsume(diag::err_expected_lparen_after, 1113 getOpenMPClauseName(OMPC_match))) { 1114 while (!SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch)) 1115 ; 1116 // Skip the last annot_pragma_openmp_end. 1117 (void)ConsumeAnnotationToken(); 1118 return; 1119 } 1120 1121 // Parse inner context selectors. 1122 SmallVector<Sema::OMPCtxSelectorData, 4> Data; 1123 if (!parseOpenMPContextSelectors(Loc, Data)) { 1124 // Parse ')'. 1125 (void)T.consumeClose(); 1126 // Need to check for extra tokens. 1127 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 1128 Diag(Tok, diag::warn_omp_extra_tokens_at_eol) 1129 << getOpenMPDirectiveName(OMPD_declare_variant); 1130 } 1131 } 1132 1133 // Skip last tokens. 1134 while (Tok.isNot(tok::annot_pragma_openmp_end)) 1135 ConsumeAnyToken(); 1136 if (DeclVarData.hasValue()) 1137 Actions.ActOnOpenMPDeclareVariantDirective( 1138 DeclVarData.getValue().first, DeclVarData.getValue().second, 1139 SourceRange(Loc, Tok.getLocation()), Data); 1140 // Skip the last annot_pragma_openmp_end. 1141 (void)ConsumeAnnotationToken(); 1142 } 1143 1144 /// Parsing of simple OpenMP clauses like 'default' or 'proc_bind'. 1145 /// 1146 /// default-clause: 1147 /// 'default' '(' 'none' | 'shared' ') 1148 /// 1149 /// proc_bind-clause: 1150 /// 'proc_bind' '(' 'master' | 'close' | 'spread' ') 1151 /// 1152 /// device_type-clause: 1153 /// 'device_type' '(' 'host' | 'nohost' | 'any' )' 1154 namespace { 1155 struct SimpleClauseData { 1156 unsigned Type; 1157 SourceLocation Loc; 1158 SourceLocation LOpen; 1159 SourceLocation TypeLoc; 1160 SourceLocation RLoc; 1161 SimpleClauseData(unsigned Type, SourceLocation Loc, SourceLocation LOpen, 1162 SourceLocation TypeLoc, SourceLocation RLoc) 1163 : Type(Type), Loc(Loc), LOpen(LOpen), TypeLoc(TypeLoc), RLoc(RLoc) {} 1164 }; 1165 } // anonymous namespace 1166 1167 static Optional<SimpleClauseData> 1168 parseOpenMPSimpleClause(Parser &P, OpenMPClauseKind Kind) { 1169 const Token &Tok = P.getCurToken(); 1170 SourceLocation Loc = Tok.getLocation(); 1171 SourceLocation LOpen = P.ConsumeToken(); 1172 // Parse '('. 1173 BalancedDelimiterTracker T(P, tok::l_paren, tok::annot_pragma_openmp_end); 1174 if (T.expectAndConsume(diag::err_expected_lparen_after, 1175 getOpenMPClauseName(Kind))) 1176 return llvm::None; 1177 1178 unsigned Type = getOpenMPSimpleClauseType( 1179 Kind, Tok.isAnnotation() ? "" : P.getPreprocessor().getSpelling(Tok)); 1180 SourceLocation TypeLoc = Tok.getLocation(); 1181 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 1182 Tok.isNot(tok::annot_pragma_openmp_end)) 1183 P.ConsumeAnyToken(); 1184 1185 // Parse ')'. 1186 SourceLocation RLoc = Tok.getLocation(); 1187 if (!T.consumeClose()) 1188 RLoc = T.getCloseLocation(); 1189 1190 return SimpleClauseData(Type, Loc, LOpen, TypeLoc, RLoc); 1191 } 1192 1193 Parser::DeclGroupPtrTy Parser::ParseOMPDeclareTargetClauses() { 1194 // OpenMP 4.5 syntax with list of entities. 1195 Sema::NamedDeclSetType SameDirectiveDecls; 1196 SmallVector<std::tuple<OMPDeclareTargetDeclAttr::MapTypeTy, SourceLocation, 1197 NamedDecl *>, 1198 4> 1199 DeclareTargetDecls; 1200 OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any; 1201 SourceLocation DeviceTypeLoc; 1202 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 1203 OMPDeclareTargetDeclAttr::MapTypeTy MT = OMPDeclareTargetDeclAttr::MT_To; 1204 if (Tok.is(tok::identifier)) { 1205 IdentifierInfo *II = Tok.getIdentifierInfo(); 1206 StringRef ClauseName = II->getName(); 1207 bool IsDeviceTypeClause = 1208 getLangOpts().OpenMP >= 50 && 1209 getOpenMPClauseKind(ClauseName) == OMPC_device_type; 1210 // Parse 'to|link|device_type' clauses. 1211 if (!OMPDeclareTargetDeclAttr::ConvertStrToMapTypeTy(ClauseName, MT) && 1212 !IsDeviceTypeClause) { 1213 Diag(Tok, diag::err_omp_declare_target_unexpected_clause) 1214 << ClauseName << (getLangOpts().OpenMP >= 50 ? 1 : 0); 1215 break; 1216 } 1217 // Parse 'device_type' clause and go to next clause if any. 1218 if (IsDeviceTypeClause) { 1219 Optional<SimpleClauseData> DevTypeData = 1220 parseOpenMPSimpleClause(*this, OMPC_device_type); 1221 if (DevTypeData.hasValue()) { 1222 if (DeviceTypeLoc.isValid()) { 1223 // We already saw another device_type clause, diagnose it. 1224 Diag(DevTypeData.getValue().Loc, 1225 diag::warn_omp_more_one_device_type_clause); 1226 } 1227 switch(static_cast<OpenMPDeviceType>(DevTypeData.getValue().Type)) { 1228 case OMPC_DEVICE_TYPE_any: 1229 DT = OMPDeclareTargetDeclAttr::DT_Any; 1230 break; 1231 case OMPC_DEVICE_TYPE_host: 1232 DT = OMPDeclareTargetDeclAttr::DT_Host; 1233 break; 1234 case OMPC_DEVICE_TYPE_nohost: 1235 DT = OMPDeclareTargetDeclAttr::DT_NoHost; 1236 break; 1237 case OMPC_DEVICE_TYPE_unknown: 1238 llvm_unreachable("Unexpected device_type"); 1239 } 1240 DeviceTypeLoc = DevTypeData.getValue().Loc; 1241 } 1242 continue; 1243 } 1244 ConsumeToken(); 1245 } 1246 auto &&Callback = [this, MT, &DeclareTargetDecls, &SameDirectiveDecls]( 1247 CXXScopeSpec &SS, DeclarationNameInfo NameInfo) { 1248 NamedDecl *ND = Actions.lookupOpenMPDeclareTargetName( 1249 getCurScope(), SS, NameInfo, SameDirectiveDecls); 1250 if (ND) 1251 DeclareTargetDecls.emplace_back(MT, NameInfo.getLoc(), ND); 1252 }; 1253 if (ParseOpenMPSimpleVarList(OMPD_declare_target, Callback, 1254 /*AllowScopeSpecifier=*/true)) 1255 break; 1256 1257 // Consume optional ','. 1258 if (Tok.is(tok::comma)) 1259 ConsumeToken(); 1260 } 1261 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 1262 ConsumeAnyToken(); 1263 for (auto &MTLocDecl : DeclareTargetDecls) { 1264 OMPDeclareTargetDeclAttr::MapTypeTy MT; 1265 SourceLocation Loc; 1266 NamedDecl *ND; 1267 std::tie(MT, Loc, ND) = MTLocDecl; 1268 // device_type clause is applied only to functions. 1269 Actions.ActOnOpenMPDeclareTargetName( 1270 ND, Loc, MT, isa<VarDecl>(ND) ? OMPDeclareTargetDeclAttr::DT_Any : DT); 1271 } 1272 SmallVector<Decl *, 4> Decls(SameDirectiveDecls.begin(), 1273 SameDirectiveDecls.end()); 1274 if (Decls.empty()) 1275 return DeclGroupPtrTy(); 1276 return Actions.BuildDeclaratorGroup(Decls); 1277 } 1278 1279 void Parser::ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind, 1280 SourceLocation DTLoc) { 1281 if (DKind != OMPD_end_declare_target) { 1282 Diag(Tok, diag::err_expected_end_declare_target); 1283 Diag(DTLoc, diag::note_matching) << "'#pragma omp declare target'"; 1284 return; 1285 } 1286 ConsumeAnyToken(); 1287 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 1288 Diag(Tok, diag::warn_omp_extra_tokens_at_eol) 1289 << getOpenMPDirectiveName(OMPD_end_declare_target); 1290 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 1291 } 1292 // Skip the last annot_pragma_openmp_end. 1293 ConsumeAnyToken(); 1294 } 1295 1296 /// Parsing of declarative OpenMP directives. 1297 /// 1298 /// threadprivate-directive: 1299 /// annot_pragma_openmp 'threadprivate' simple-variable-list 1300 /// annot_pragma_openmp_end 1301 /// 1302 /// allocate-directive: 1303 /// annot_pragma_openmp 'allocate' simple-variable-list [<clause>] 1304 /// annot_pragma_openmp_end 1305 /// 1306 /// declare-reduction-directive: 1307 /// annot_pragma_openmp 'declare' 'reduction' [...] 1308 /// annot_pragma_openmp_end 1309 /// 1310 /// declare-mapper-directive: 1311 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':'] 1312 /// <type> <var> ')' [<clause>[[,] <clause>] ... ] 1313 /// annot_pragma_openmp_end 1314 /// 1315 /// declare-simd-directive: 1316 /// annot_pragma_openmp 'declare simd' {<clause> [,]} 1317 /// annot_pragma_openmp_end 1318 /// <function declaration/definition> 1319 /// 1320 /// requires directive: 1321 /// annot_pragma_openmp 'requires' <clause> [[[,] <clause>] ... ] 1322 /// annot_pragma_openmp_end 1323 /// 1324 Parser::DeclGroupPtrTy Parser::ParseOpenMPDeclarativeDirectiveWithExtDecl( 1325 AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, 1326 DeclSpec::TST TagType, Decl *Tag) { 1327 assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!"); 1328 ParenBraceBracketBalancer BalancerRAIIObj(*this); 1329 1330 SourceLocation Loc = ConsumeAnnotationToken(); 1331 OpenMPDirectiveKind DKind = parseOpenMPDirectiveKind(*this); 1332 1333 switch (DKind) { 1334 case OMPD_threadprivate: { 1335 ConsumeToken(); 1336 DeclDirectiveListParserHelper Helper(this, DKind); 1337 if (!ParseOpenMPSimpleVarList(DKind, Helper, 1338 /*AllowScopeSpecifier=*/true)) { 1339 // The last seen token is annot_pragma_openmp_end - need to check for 1340 // extra tokens. 1341 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 1342 Diag(Tok, diag::warn_omp_extra_tokens_at_eol) 1343 << getOpenMPDirectiveName(DKind); 1344 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 1345 } 1346 // Skip the last annot_pragma_openmp_end. 1347 ConsumeAnnotationToken(); 1348 return Actions.ActOnOpenMPThreadprivateDirective(Loc, 1349 Helper.getIdentifiers()); 1350 } 1351 break; 1352 } 1353 case OMPD_allocate: { 1354 ConsumeToken(); 1355 DeclDirectiveListParserHelper Helper(this, DKind); 1356 if (!ParseOpenMPSimpleVarList(DKind, Helper, 1357 /*AllowScopeSpecifier=*/true)) { 1358 SmallVector<OMPClause *, 1> Clauses; 1359 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 1360 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, 1361 OMPC_unknown + 1> 1362 FirstClauses(OMPC_unknown + 1); 1363 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 1364 OpenMPClauseKind CKind = 1365 Tok.isAnnotation() ? OMPC_unknown 1366 : getOpenMPClauseKind(PP.getSpelling(Tok)); 1367 Actions.StartOpenMPClause(CKind); 1368 OMPClause *Clause = ParseOpenMPClause(OMPD_allocate, CKind, 1369 !FirstClauses[CKind].getInt()); 1370 SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end, 1371 StopBeforeMatch); 1372 FirstClauses[CKind].setInt(true); 1373 if (Clause != nullptr) 1374 Clauses.push_back(Clause); 1375 if (Tok.is(tok::annot_pragma_openmp_end)) { 1376 Actions.EndOpenMPClause(); 1377 break; 1378 } 1379 // Skip ',' if any. 1380 if (Tok.is(tok::comma)) 1381 ConsumeToken(); 1382 Actions.EndOpenMPClause(); 1383 } 1384 // The last seen token is annot_pragma_openmp_end - need to check for 1385 // extra tokens. 1386 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 1387 Diag(Tok, diag::warn_omp_extra_tokens_at_eol) 1388 << getOpenMPDirectiveName(DKind); 1389 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 1390 } 1391 } 1392 // Skip the last annot_pragma_openmp_end. 1393 ConsumeAnnotationToken(); 1394 return Actions.ActOnOpenMPAllocateDirective(Loc, Helper.getIdentifiers(), 1395 Clauses); 1396 } 1397 break; 1398 } 1399 case OMPD_requires: { 1400 SourceLocation StartLoc = ConsumeToken(); 1401 SmallVector<OMPClause *, 5> Clauses; 1402 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, OMPC_unknown + 1> 1403 FirstClauses(OMPC_unknown + 1); 1404 if (Tok.is(tok::annot_pragma_openmp_end)) { 1405 Diag(Tok, diag::err_omp_expected_clause) 1406 << getOpenMPDirectiveName(OMPD_requires); 1407 break; 1408 } 1409 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 1410 OpenMPClauseKind CKind = Tok.isAnnotation() 1411 ? OMPC_unknown 1412 : getOpenMPClauseKind(PP.getSpelling(Tok)); 1413 Actions.StartOpenMPClause(CKind); 1414 OMPClause *Clause = ParseOpenMPClause(OMPD_requires, CKind, 1415 !FirstClauses[CKind].getInt()); 1416 SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end, 1417 StopBeforeMatch); 1418 FirstClauses[CKind].setInt(true); 1419 if (Clause != nullptr) 1420 Clauses.push_back(Clause); 1421 if (Tok.is(tok::annot_pragma_openmp_end)) { 1422 Actions.EndOpenMPClause(); 1423 break; 1424 } 1425 // Skip ',' if any. 1426 if (Tok.is(tok::comma)) 1427 ConsumeToken(); 1428 Actions.EndOpenMPClause(); 1429 } 1430 // Consume final annot_pragma_openmp_end 1431 if (Clauses.size() == 0) { 1432 Diag(Tok, diag::err_omp_expected_clause) 1433 << getOpenMPDirectiveName(OMPD_requires); 1434 ConsumeAnnotationToken(); 1435 return nullptr; 1436 } 1437 ConsumeAnnotationToken(); 1438 return Actions.ActOnOpenMPRequiresDirective(StartLoc, Clauses); 1439 } 1440 case OMPD_declare_reduction: 1441 ConsumeToken(); 1442 if (DeclGroupPtrTy Res = ParseOpenMPDeclareReductionDirective(AS)) { 1443 // The last seen token is annot_pragma_openmp_end - need to check for 1444 // extra tokens. 1445 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 1446 Diag(Tok, diag::warn_omp_extra_tokens_at_eol) 1447 << getOpenMPDirectiveName(OMPD_declare_reduction); 1448 while (Tok.isNot(tok::annot_pragma_openmp_end)) 1449 ConsumeAnyToken(); 1450 } 1451 // Skip the last annot_pragma_openmp_end. 1452 ConsumeAnnotationToken(); 1453 return Res; 1454 } 1455 break; 1456 case OMPD_declare_mapper: { 1457 ConsumeToken(); 1458 if (DeclGroupPtrTy Res = ParseOpenMPDeclareMapperDirective(AS)) { 1459 // Skip the last annot_pragma_openmp_end. 1460 ConsumeAnnotationToken(); 1461 return Res; 1462 } 1463 break; 1464 } 1465 case OMPD_declare_variant: 1466 case OMPD_declare_simd: { 1467 // The syntax is: 1468 // { #pragma omp declare {simd|variant} } 1469 // <function-declaration-or-definition> 1470 // 1471 CachedTokens Toks; 1472 Toks.push_back(Tok); 1473 ConsumeToken(); 1474 while(Tok.isNot(tok::annot_pragma_openmp_end)) { 1475 Toks.push_back(Tok); 1476 ConsumeAnyToken(); 1477 } 1478 Toks.push_back(Tok); 1479 ConsumeAnyToken(); 1480 1481 DeclGroupPtrTy Ptr; 1482 if (Tok.is(tok::annot_pragma_openmp)) { 1483 Ptr = ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs, TagType, Tag); 1484 } else if (Tok.isNot(tok::r_brace) && !isEofOrEom()) { 1485 // Here we expect to see some function declaration. 1486 if (AS == AS_none) { 1487 assert(TagType == DeclSpec::TST_unspecified); 1488 MaybeParseCXX11Attributes(Attrs); 1489 ParsingDeclSpec PDS(*this); 1490 Ptr = ParseExternalDeclaration(Attrs, &PDS); 1491 } else { 1492 Ptr = 1493 ParseCXXClassMemberDeclarationWithPragmas(AS, Attrs, TagType, Tag); 1494 } 1495 } 1496 if (!Ptr) { 1497 Diag(Loc, diag::err_omp_decl_in_declare_simd_variant) 1498 << (DKind == OMPD_declare_simd ? 0 : 1); 1499 return DeclGroupPtrTy(); 1500 } 1501 if (DKind == OMPD_declare_simd) 1502 return ParseOMPDeclareSimdClauses(Ptr, Toks, Loc); 1503 assert(DKind == OMPD_declare_variant && 1504 "Expected declare variant directive only"); 1505 ParseOMPDeclareVariantClauses(Ptr, Toks, Loc); 1506 return Ptr; 1507 } 1508 case OMPD_declare_target: { 1509 SourceLocation DTLoc = ConsumeAnyToken(); 1510 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 1511 return ParseOMPDeclareTargetClauses(); 1512 } 1513 1514 // Skip the last annot_pragma_openmp_end. 1515 ConsumeAnyToken(); 1516 1517 if (!Actions.ActOnStartOpenMPDeclareTargetDirective(DTLoc)) 1518 return DeclGroupPtrTy(); 1519 1520 llvm::SmallVector<Decl *, 4> Decls; 1521 DKind = parseOpenMPDirectiveKind(*this); 1522 while (DKind != OMPD_end_declare_target && Tok.isNot(tok::eof) && 1523 Tok.isNot(tok::r_brace)) { 1524 DeclGroupPtrTy Ptr; 1525 // Here we expect to see some function declaration. 1526 if (AS == AS_none) { 1527 assert(TagType == DeclSpec::TST_unspecified); 1528 MaybeParseCXX11Attributes(Attrs); 1529 ParsingDeclSpec PDS(*this); 1530 Ptr = ParseExternalDeclaration(Attrs, &PDS); 1531 } else { 1532 Ptr = 1533 ParseCXXClassMemberDeclarationWithPragmas(AS, Attrs, TagType, Tag); 1534 } 1535 if (Ptr) { 1536 DeclGroupRef Ref = Ptr.get(); 1537 Decls.append(Ref.begin(), Ref.end()); 1538 } 1539 if (Tok.isAnnotation() && Tok.is(tok::annot_pragma_openmp)) { 1540 TentativeParsingAction TPA(*this); 1541 ConsumeAnnotationToken(); 1542 DKind = parseOpenMPDirectiveKind(*this); 1543 if (DKind != OMPD_end_declare_target) 1544 TPA.Revert(); 1545 else 1546 TPA.Commit(); 1547 } 1548 } 1549 1550 ParseOMPEndDeclareTargetDirective(DKind, DTLoc); 1551 Actions.ActOnFinishOpenMPDeclareTargetDirective(); 1552 return Actions.BuildDeclaratorGroup(Decls); 1553 } 1554 case OMPD_unknown: 1555 Diag(Tok, diag::err_omp_unknown_directive); 1556 break; 1557 case OMPD_parallel: 1558 case OMPD_simd: 1559 case OMPD_task: 1560 case OMPD_taskyield: 1561 case OMPD_barrier: 1562 case OMPD_taskwait: 1563 case OMPD_taskgroup: 1564 case OMPD_flush: 1565 case OMPD_for: 1566 case OMPD_for_simd: 1567 case OMPD_sections: 1568 case OMPD_section: 1569 case OMPD_single: 1570 case OMPD_master: 1571 case OMPD_ordered: 1572 case OMPD_critical: 1573 case OMPD_parallel_for: 1574 case OMPD_parallel_for_simd: 1575 case OMPD_parallel_sections: 1576 case OMPD_parallel_master: 1577 case OMPD_atomic: 1578 case OMPD_target: 1579 case OMPD_teams: 1580 case OMPD_cancellation_point: 1581 case OMPD_cancel: 1582 case OMPD_target_data: 1583 case OMPD_target_enter_data: 1584 case OMPD_target_exit_data: 1585 case OMPD_target_parallel: 1586 case OMPD_target_parallel_for: 1587 case OMPD_taskloop: 1588 case OMPD_taskloop_simd: 1589 case OMPD_master_taskloop: 1590 case OMPD_master_taskloop_simd: 1591 case OMPD_parallel_master_taskloop: 1592 case OMPD_parallel_master_taskloop_simd: 1593 case OMPD_distribute: 1594 case OMPD_end_declare_target: 1595 case OMPD_target_update: 1596 case OMPD_distribute_parallel_for: 1597 case OMPD_distribute_parallel_for_simd: 1598 case OMPD_distribute_simd: 1599 case OMPD_target_parallel_for_simd: 1600 case OMPD_target_simd: 1601 case OMPD_teams_distribute: 1602 case OMPD_teams_distribute_simd: 1603 case OMPD_teams_distribute_parallel_for_simd: 1604 case OMPD_teams_distribute_parallel_for: 1605 case OMPD_target_teams: 1606 case OMPD_target_teams_distribute: 1607 case OMPD_target_teams_distribute_parallel_for: 1608 case OMPD_target_teams_distribute_parallel_for_simd: 1609 case OMPD_target_teams_distribute_simd: 1610 Diag(Tok, diag::err_omp_unexpected_directive) 1611 << 1 << getOpenMPDirectiveName(DKind); 1612 break; 1613 } 1614 while (Tok.isNot(tok::annot_pragma_openmp_end)) 1615 ConsumeAnyToken(); 1616 ConsumeAnyToken(); 1617 return nullptr; 1618 } 1619 1620 /// Parsing of declarative or executable OpenMP directives. 1621 /// 1622 /// threadprivate-directive: 1623 /// annot_pragma_openmp 'threadprivate' simple-variable-list 1624 /// annot_pragma_openmp_end 1625 /// 1626 /// allocate-directive: 1627 /// annot_pragma_openmp 'allocate' simple-variable-list 1628 /// annot_pragma_openmp_end 1629 /// 1630 /// declare-reduction-directive: 1631 /// annot_pragma_openmp 'declare' 'reduction' '(' <reduction_id> ':' 1632 /// <type> {',' <type>} ':' <expression> ')' ['initializer' '(' 1633 /// ('omp_priv' '=' <expression>|<function_call>) ')'] 1634 /// annot_pragma_openmp_end 1635 /// 1636 /// declare-mapper-directive: 1637 /// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':'] 1638 /// <type> <var> ')' [<clause>[[,] <clause>] ... ] 1639 /// annot_pragma_openmp_end 1640 /// 1641 /// executable-directive: 1642 /// annot_pragma_openmp 'parallel' | 'simd' | 'for' | 'sections' | 1643 /// 'section' | 'single' | 'master' | 'critical' [ '(' <name> ')' ] | 1644 /// 'parallel for' | 'parallel sections' | 'parallel master' | 'task' | 1645 /// 'taskyield' | 'barrier' | 'taskwait' | 'flush' | 'ordered' | 1646 /// 'atomic' | 'for simd' | 'parallel for simd' | 'target' | 'target 1647 /// data' | 'taskgroup' | 'teams' | 'taskloop' | 'taskloop simd' | 1648 /// 'master taskloop' | 'master taskloop simd' | 'parallel master 1649 /// taskloop' | 'parallel master taskloop simd' | 'distribute' | 'target 1650 /// enter data' | 'target exit data' | 'target parallel' | 'target 1651 /// parallel for' | 'target update' | 'distribute parallel for' | 1652 /// 'distribute paralle for simd' | 'distribute simd' | 'target parallel 1653 /// for simd' | 'target simd' | 'teams distribute' | 'teams distribute 1654 /// simd' | 'teams distribute parallel for simd' | 'teams distribute 1655 /// parallel for' | 'target teams' | 'target teams distribute' | 'target 1656 /// teams distribute parallel for' | 'target teams distribute parallel 1657 /// for simd' | 'target teams distribute simd' {clause} 1658 /// annot_pragma_openmp_end 1659 /// 1660 StmtResult 1661 Parser::ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx) { 1662 assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!"); 1663 ParenBraceBracketBalancer BalancerRAIIObj(*this); 1664 SmallVector<OMPClause *, 5> Clauses; 1665 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, OMPC_unknown + 1> 1666 FirstClauses(OMPC_unknown + 1); 1667 unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope | 1668 Scope::CompoundStmtScope | Scope::OpenMPDirectiveScope; 1669 SourceLocation Loc = ConsumeAnnotationToken(), EndLoc; 1670 OpenMPDirectiveKind DKind = parseOpenMPDirectiveKind(*this); 1671 OpenMPDirectiveKind CancelRegion = OMPD_unknown; 1672 // Name of critical directive. 1673 DeclarationNameInfo DirName; 1674 StmtResult Directive = StmtError(); 1675 bool HasAssociatedStatement = true; 1676 bool FlushHasClause = false; 1677 1678 switch (DKind) { 1679 case OMPD_threadprivate: { 1680 // FIXME: Should this be permitted in C++? 1681 if ((StmtCtx & ParsedStmtContext::AllowDeclarationsInC) == 1682 ParsedStmtContext()) { 1683 Diag(Tok, diag::err_omp_immediate_directive) 1684 << getOpenMPDirectiveName(DKind) << 0; 1685 } 1686 ConsumeToken(); 1687 DeclDirectiveListParserHelper Helper(this, DKind); 1688 if (!ParseOpenMPSimpleVarList(DKind, Helper, 1689 /*AllowScopeSpecifier=*/false)) { 1690 // The last seen token is annot_pragma_openmp_end - need to check for 1691 // extra tokens. 1692 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 1693 Diag(Tok, diag::warn_omp_extra_tokens_at_eol) 1694 << getOpenMPDirectiveName(DKind); 1695 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 1696 } 1697 DeclGroupPtrTy Res = Actions.ActOnOpenMPThreadprivateDirective( 1698 Loc, Helper.getIdentifiers()); 1699 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation()); 1700 } 1701 SkipUntil(tok::annot_pragma_openmp_end); 1702 break; 1703 } 1704 case OMPD_allocate: { 1705 // FIXME: Should this be permitted in C++? 1706 if ((StmtCtx & ParsedStmtContext::AllowDeclarationsInC) == 1707 ParsedStmtContext()) { 1708 Diag(Tok, diag::err_omp_immediate_directive) 1709 << getOpenMPDirectiveName(DKind) << 0; 1710 } 1711 ConsumeToken(); 1712 DeclDirectiveListParserHelper Helper(this, DKind); 1713 if (!ParseOpenMPSimpleVarList(DKind, Helper, 1714 /*AllowScopeSpecifier=*/false)) { 1715 SmallVector<OMPClause *, 1> Clauses; 1716 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 1717 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, 1718 OMPC_unknown + 1> 1719 FirstClauses(OMPC_unknown + 1); 1720 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 1721 OpenMPClauseKind CKind = 1722 Tok.isAnnotation() ? OMPC_unknown 1723 : getOpenMPClauseKind(PP.getSpelling(Tok)); 1724 Actions.StartOpenMPClause(CKind); 1725 OMPClause *Clause = ParseOpenMPClause(OMPD_allocate, CKind, 1726 !FirstClauses[CKind].getInt()); 1727 SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end, 1728 StopBeforeMatch); 1729 FirstClauses[CKind].setInt(true); 1730 if (Clause != nullptr) 1731 Clauses.push_back(Clause); 1732 if (Tok.is(tok::annot_pragma_openmp_end)) { 1733 Actions.EndOpenMPClause(); 1734 break; 1735 } 1736 // Skip ',' if any. 1737 if (Tok.is(tok::comma)) 1738 ConsumeToken(); 1739 Actions.EndOpenMPClause(); 1740 } 1741 // The last seen token is annot_pragma_openmp_end - need to check for 1742 // extra tokens. 1743 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 1744 Diag(Tok, diag::warn_omp_extra_tokens_at_eol) 1745 << getOpenMPDirectiveName(DKind); 1746 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 1747 } 1748 } 1749 DeclGroupPtrTy Res = Actions.ActOnOpenMPAllocateDirective( 1750 Loc, Helper.getIdentifiers(), Clauses); 1751 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation()); 1752 } 1753 SkipUntil(tok::annot_pragma_openmp_end); 1754 break; 1755 } 1756 case OMPD_declare_reduction: 1757 ConsumeToken(); 1758 if (DeclGroupPtrTy Res = 1759 ParseOpenMPDeclareReductionDirective(/*AS=*/AS_none)) { 1760 // The last seen token is annot_pragma_openmp_end - need to check for 1761 // extra tokens. 1762 if (Tok.isNot(tok::annot_pragma_openmp_end)) { 1763 Diag(Tok, diag::warn_omp_extra_tokens_at_eol) 1764 << getOpenMPDirectiveName(OMPD_declare_reduction); 1765 while (Tok.isNot(tok::annot_pragma_openmp_end)) 1766 ConsumeAnyToken(); 1767 } 1768 ConsumeAnyToken(); 1769 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation()); 1770 } else { 1771 SkipUntil(tok::annot_pragma_openmp_end); 1772 } 1773 break; 1774 case OMPD_declare_mapper: { 1775 ConsumeToken(); 1776 if (DeclGroupPtrTy Res = 1777 ParseOpenMPDeclareMapperDirective(/*AS=*/AS_none)) { 1778 // Skip the last annot_pragma_openmp_end. 1779 ConsumeAnnotationToken(); 1780 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation()); 1781 } else { 1782 SkipUntil(tok::annot_pragma_openmp_end); 1783 } 1784 break; 1785 } 1786 case OMPD_flush: 1787 if (PP.LookAhead(0).is(tok::l_paren)) { 1788 FlushHasClause = true; 1789 // Push copy of the current token back to stream to properly parse 1790 // pseudo-clause OMPFlushClause. 1791 PP.EnterToken(Tok, /*IsReinject*/ true); 1792 } 1793 LLVM_FALLTHROUGH; 1794 case OMPD_taskyield: 1795 case OMPD_barrier: 1796 case OMPD_taskwait: 1797 case OMPD_cancellation_point: 1798 case OMPD_cancel: 1799 case OMPD_target_enter_data: 1800 case OMPD_target_exit_data: 1801 case OMPD_target_update: 1802 if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) == 1803 ParsedStmtContext()) { 1804 Diag(Tok, diag::err_omp_immediate_directive) 1805 << getOpenMPDirectiveName(DKind) << 0; 1806 } 1807 HasAssociatedStatement = false; 1808 // Fall through for further analysis. 1809 LLVM_FALLTHROUGH; 1810 case OMPD_parallel: 1811 case OMPD_simd: 1812 case OMPD_for: 1813 case OMPD_for_simd: 1814 case OMPD_sections: 1815 case OMPD_single: 1816 case OMPD_section: 1817 case OMPD_master: 1818 case OMPD_critical: 1819 case OMPD_parallel_for: 1820 case OMPD_parallel_for_simd: 1821 case OMPD_parallel_sections: 1822 case OMPD_parallel_master: 1823 case OMPD_task: 1824 case OMPD_ordered: 1825 case OMPD_atomic: 1826 case OMPD_target: 1827 case OMPD_teams: 1828 case OMPD_taskgroup: 1829 case OMPD_target_data: 1830 case OMPD_target_parallel: 1831 case OMPD_target_parallel_for: 1832 case OMPD_taskloop: 1833 case OMPD_taskloop_simd: 1834 case OMPD_master_taskloop: 1835 case OMPD_master_taskloop_simd: 1836 case OMPD_parallel_master_taskloop: 1837 case OMPD_parallel_master_taskloop_simd: 1838 case OMPD_distribute: 1839 case OMPD_distribute_parallel_for: 1840 case OMPD_distribute_parallel_for_simd: 1841 case OMPD_distribute_simd: 1842 case OMPD_target_parallel_for_simd: 1843 case OMPD_target_simd: 1844 case OMPD_teams_distribute: 1845 case OMPD_teams_distribute_simd: 1846 case OMPD_teams_distribute_parallel_for_simd: 1847 case OMPD_teams_distribute_parallel_for: 1848 case OMPD_target_teams: 1849 case OMPD_target_teams_distribute: 1850 case OMPD_target_teams_distribute_parallel_for: 1851 case OMPD_target_teams_distribute_parallel_for_simd: 1852 case OMPD_target_teams_distribute_simd: { 1853 ConsumeToken(); 1854 // Parse directive name of the 'critical' directive if any. 1855 if (DKind == OMPD_critical) { 1856 BalancedDelimiterTracker T(*this, tok::l_paren, 1857 tok::annot_pragma_openmp_end); 1858 if (!T.consumeOpen()) { 1859 if (Tok.isAnyIdentifier()) { 1860 DirName = 1861 DeclarationNameInfo(Tok.getIdentifierInfo(), Tok.getLocation()); 1862 ConsumeAnyToken(); 1863 } else { 1864 Diag(Tok, diag::err_omp_expected_identifier_for_critical); 1865 } 1866 T.consumeClose(); 1867 } 1868 } else if (DKind == OMPD_cancellation_point || DKind == OMPD_cancel) { 1869 CancelRegion = parseOpenMPDirectiveKind(*this); 1870 if (Tok.isNot(tok::annot_pragma_openmp_end)) 1871 ConsumeToken(); 1872 } 1873 1874 if (isOpenMPLoopDirective(DKind)) 1875 ScopeFlags |= Scope::OpenMPLoopDirectiveScope; 1876 if (isOpenMPSimdDirective(DKind)) 1877 ScopeFlags |= Scope::OpenMPSimdDirectiveScope; 1878 ParseScope OMPDirectiveScope(this, ScopeFlags); 1879 Actions.StartOpenMPDSABlock(DKind, DirName, Actions.getCurScope(), Loc); 1880 1881 while (Tok.isNot(tok::annot_pragma_openmp_end)) { 1882 OpenMPClauseKind CKind = 1883 Tok.isAnnotation() 1884 ? OMPC_unknown 1885 : FlushHasClause ? OMPC_flush 1886 : getOpenMPClauseKind(PP.getSpelling(Tok)); 1887 Actions.StartOpenMPClause(CKind); 1888 FlushHasClause = false; 1889 OMPClause *Clause = 1890 ParseOpenMPClause(DKind, CKind, !FirstClauses[CKind].getInt()); 1891 FirstClauses[CKind].setInt(true); 1892 if (Clause) { 1893 FirstClauses[CKind].setPointer(Clause); 1894 Clauses.push_back(Clause); 1895 } 1896 1897 // Skip ',' if any. 1898 if (Tok.is(tok::comma)) 1899 ConsumeToken(); 1900 Actions.EndOpenMPClause(); 1901 } 1902 // End location of the directive. 1903 EndLoc = Tok.getLocation(); 1904 // Consume final annot_pragma_openmp_end. 1905 ConsumeAnnotationToken(); 1906 1907 // OpenMP [2.13.8, ordered Construct, Syntax] 1908 // If the depend clause is specified, the ordered construct is a stand-alone 1909 // directive. 1910 if (DKind == OMPD_ordered && FirstClauses[OMPC_depend].getInt()) { 1911 if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) == 1912 ParsedStmtContext()) { 1913 Diag(Loc, diag::err_omp_immediate_directive) 1914 << getOpenMPDirectiveName(DKind) << 1 1915 << getOpenMPClauseName(OMPC_depend); 1916 } 1917 HasAssociatedStatement = false; 1918 } 1919 1920 StmtResult AssociatedStmt; 1921 if (HasAssociatedStatement) { 1922 // The body is a block scope like in Lambdas and Blocks. 1923 Actions.ActOnOpenMPRegionStart(DKind, getCurScope()); 1924 // FIXME: We create a bogus CompoundStmt scope to hold the contents of 1925 // the captured region. Code elsewhere assumes that any FunctionScopeInfo 1926 // should have at least one compound statement scope within it. 1927 AssociatedStmt = (Sema::CompoundScopeRAII(Actions), ParseStatement()); 1928 AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses); 1929 } else if (DKind == OMPD_target_update || DKind == OMPD_target_enter_data || 1930 DKind == OMPD_target_exit_data) { 1931 Actions.ActOnOpenMPRegionStart(DKind, getCurScope()); 1932 AssociatedStmt = (Sema::CompoundScopeRAII(Actions), 1933 Actions.ActOnCompoundStmt(Loc, Loc, llvm::None, 1934 /*isStmtExpr=*/false)); 1935 AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses); 1936 } 1937 Directive = Actions.ActOnOpenMPExecutableDirective( 1938 DKind, DirName, CancelRegion, Clauses, AssociatedStmt.get(), Loc, 1939 EndLoc); 1940 1941 // Exit scope. 1942 Actions.EndOpenMPDSABlock(Directive.get()); 1943 OMPDirectiveScope.Exit(); 1944 break; 1945 } 1946 case OMPD_declare_simd: 1947 case OMPD_declare_target: 1948 case OMPD_end_declare_target: 1949 case OMPD_requires: 1950 case OMPD_declare_variant: 1951 Diag(Tok, diag::err_omp_unexpected_directive) 1952 << 1 << getOpenMPDirectiveName(DKind); 1953 SkipUntil(tok::annot_pragma_openmp_end); 1954 break; 1955 case OMPD_unknown: 1956 Diag(Tok, diag::err_omp_unknown_directive); 1957 SkipUntil(tok::annot_pragma_openmp_end); 1958 break; 1959 } 1960 return Directive; 1961 } 1962 1963 // Parses simple list: 1964 // simple-variable-list: 1965 // '(' id-expression {, id-expression} ')' 1966 // 1967 bool Parser::ParseOpenMPSimpleVarList( 1968 OpenMPDirectiveKind Kind, 1969 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> & 1970 Callback, 1971 bool AllowScopeSpecifier) { 1972 // Parse '('. 1973 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 1974 if (T.expectAndConsume(diag::err_expected_lparen_after, 1975 getOpenMPDirectiveName(Kind).data())) 1976 return true; 1977 bool IsCorrect = true; 1978 bool NoIdentIsFound = true; 1979 1980 // Read tokens while ')' or annot_pragma_openmp_end is not found. 1981 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) { 1982 CXXScopeSpec SS; 1983 UnqualifiedId Name; 1984 // Read var name. 1985 Token PrevTok = Tok; 1986 NoIdentIsFound = false; 1987 1988 if (AllowScopeSpecifier && getLangOpts().CPlusPlus && 1989 ParseOptionalCXXScopeSpecifier(SS, nullptr, false)) { 1990 IsCorrect = false; 1991 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 1992 StopBeforeMatch); 1993 } else if (ParseUnqualifiedId(SS, false, false, false, false, nullptr, 1994 nullptr, Name)) { 1995 IsCorrect = false; 1996 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 1997 StopBeforeMatch); 1998 } else if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren) && 1999 Tok.isNot(tok::annot_pragma_openmp_end)) { 2000 IsCorrect = false; 2001 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 2002 StopBeforeMatch); 2003 Diag(PrevTok.getLocation(), diag::err_expected) 2004 << tok::identifier 2005 << SourceRange(PrevTok.getLocation(), PrevTokLocation); 2006 } else { 2007 Callback(SS, Actions.GetNameFromUnqualifiedId(Name)); 2008 } 2009 // Consume ','. 2010 if (Tok.is(tok::comma)) { 2011 ConsumeToken(); 2012 } 2013 } 2014 2015 if (NoIdentIsFound) { 2016 Diag(Tok, diag::err_expected) << tok::identifier; 2017 IsCorrect = false; 2018 } 2019 2020 // Parse ')'. 2021 IsCorrect = !T.consumeClose() && IsCorrect; 2022 2023 return !IsCorrect; 2024 } 2025 2026 /// Parsing of OpenMP clauses. 2027 /// 2028 /// clause: 2029 /// if-clause | final-clause | num_threads-clause | safelen-clause | 2030 /// default-clause | private-clause | firstprivate-clause | shared-clause 2031 /// | linear-clause | aligned-clause | collapse-clause | 2032 /// lastprivate-clause | reduction-clause | proc_bind-clause | 2033 /// schedule-clause | copyin-clause | copyprivate-clause | untied-clause | 2034 /// mergeable-clause | flush-clause | read-clause | write-clause | 2035 /// update-clause | capture-clause | seq_cst-clause | device-clause | 2036 /// simdlen-clause | threads-clause | simd-clause | num_teams-clause | 2037 /// thread_limit-clause | priority-clause | grainsize-clause | 2038 /// nogroup-clause | num_tasks-clause | hint-clause | to-clause | 2039 /// from-clause | is_device_ptr-clause | task_reduction-clause | 2040 /// in_reduction-clause | allocator-clause | allocate-clause 2041 /// 2042 OMPClause *Parser::ParseOpenMPClause(OpenMPDirectiveKind DKind, 2043 OpenMPClauseKind CKind, bool FirstClause) { 2044 OMPClause *Clause = nullptr; 2045 bool ErrorFound = false; 2046 bool WrongDirective = false; 2047 // Check if clause is allowed for the given directive. 2048 if (CKind != OMPC_unknown && 2049 !isAllowedClauseForDirective(DKind, CKind, getLangOpts().OpenMP)) { 2050 Diag(Tok, diag::err_omp_unexpected_clause) << getOpenMPClauseName(CKind) 2051 << getOpenMPDirectiveName(DKind); 2052 ErrorFound = true; 2053 WrongDirective = true; 2054 } 2055 2056 switch (CKind) { 2057 case OMPC_final: 2058 case OMPC_num_threads: 2059 case OMPC_safelen: 2060 case OMPC_simdlen: 2061 case OMPC_collapse: 2062 case OMPC_ordered: 2063 case OMPC_device: 2064 case OMPC_num_teams: 2065 case OMPC_thread_limit: 2066 case OMPC_priority: 2067 case OMPC_grainsize: 2068 case OMPC_num_tasks: 2069 case OMPC_hint: 2070 case OMPC_allocator: 2071 // OpenMP [2.5, Restrictions] 2072 // At most one num_threads clause can appear on the directive. 2073 // OpenMP [2.8.1, simd construct, Restrictions] 2074 // Only one safelen clause can appear on a simd directive. 2075 // Only one simdlen clause can appear on a simd directive. 2076 // Only one collapse clause can appear on a simd directive. 2077 // OpenMP [2.9.1, target data construct, Restrictions] 2078 // At most one device clause can appear on the directive. 2079 // OpenMP [2.11.1, task Construct, Restrictions] 2080 // At most one if clause can appear on the directive. 2081 // At most one final clause can appear on the directive. 2082 // OpenMP [teams Construct, Restrictions] 2083 // At most one num_teams clause can appear on the directive. 2084 // At most one thread_limit clause can appear on the directive. 2085 // OpenMP [2.9.1, task Construct, Restrictions] 2086 // At most one priority clause can appear on the directive. 2087 // OpenMP [2.9.2, taskloop Construct, Restrictions] 2088 // At most one grainsize clause can appear on the directive. 2089 // OpenMP [2.9.2, taskloop Construct, Restrictions] 2090 // At most one num_tasks clause can appear on the directive. 2091 // OpenMP [2.11.3, allocate Directive, Restrictions] 2092 // At most one allocator clause can appear on the directive. 2093 if (!FirstClause) { 2094 Diag(Tok, diag::err_omp_more_one_clause) 2095 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 2096 ErrorFound = true; 2097 } 2098 2099 if (CKind == OMPC_ordered && PP.LookAhead(/*N=*/0).isNot(tok::l_paren)) 2100 Clause = ParseOpenMPClause(CKind, WrongDirective); 2101 else 2102 Clause = ParseOpenMPSingleExprClause(CKind, WrongDirective); 2103 break; 2104 case OMPC_default: 2105 case OMPC_proc_bind: 2106 case OMPC_atomic_default_mem_order: 2107 // OpenMP [2.14.3.1, Restrictions] 2108 // Only a single default clause may be specified on a parallel, task or 2109 // teams directive. 2110 // OpenMP [2.5, parallel Construct, Restrictions] 2111 // At most one proc_bind clause can appear on the directive. 2112 // OpenMP [5.0, Requires directive, Restrictions] 2113 // At most one atomic_default_mem_order clause can appear 2114 // on the directive 2115 if (!FirstClause) { 2116 Diag(Tok, diag::err_omp_more_one_clause) 2117 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 2118 ErrorFound = true; 2119 } 2120 2121 Clause = ParseOpenMPSimpleClause(CKind, WrongDirective); 2122 break; 2123 case OMPC_schedule: 2124 case OMPC_dist_schedule: 2125 case OMPC_defaultmap: 2126 // OpenMP [2.7.1, Restrictions, p. 3] 2127 // Only one schedule clause can appear on a loop directive. 2128 // OpenMP 4.5 [2.10.4, Restrictions, p. 106] 2129 // At most one defaultmap clause can appear on the directive. 2130 if ((getLangOpts().OpenMP < 50 || CKind != OMPC_defaultmap) && 2131 !FirstClause) { 2132 Diag(Tok, diag::err_omp_more_one_clause) 2133 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 2134 ErrorFound = true; 2135 } 2136 LLVM_FALLTHROUGH; 2137 case OMPC_if: 2138 Clause = ParseOpenMPSingleExprWithArgClause(CKind, WrongDirective); 2139 break; 2140 case OMPC_nowait: 2141 case OMPC_untied: 2142 case OMPC_mergeable: 2143 case OMPC_read: 2144 case OMPC_write: 2145 case OMPC_update: 2146 case OMPC_capture: 2147 case OMPC_seq_cst: 2148 case OMPC_threads: 2149 case OMPC_simd: 2150 case OMPC_nogroup: 2151 case OMPC_unified_address: 2152 case OMPC_unified_shared_memory: 2153 case OMPC_reverse_offload: 2154 case OMPC_dynamic_allocators: 2155 // OpenMP [2.7.1, Restrictions, p. 9] 2156 // Only one ordered clause can appear on a loop directive. 2157 // OpenMP [2.7.1, Restrictions, C/C++, p. 4] 2158 // Only one nowait clause can appear on a for directive. 2159 // OpenMP [5.0, Requires directive, Restrictions] 2160 // Each of the requires clauses can appear at most once on the directive. 2161 if (!FirstClause) { 2162 Diag(Tok, diag::err_omp_more_one_clause) 2163 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0; 2164 ErrorFound = true; 2165 } 2166 2167 Clause = ParseOpenMPClause(CKind, WrongDirective); 2168 break; 2169 case OMPC_private: 2170 case OMPC_firstprivate: 2171 case OMPC_lastprivate: 2172 case OMPC_shared: 2173 case OMPC_reduction: 2174 case OMPC_task_reduction: 2175 case OMPC_in_reduction: 2176 case OMPC_linear: 2177 case OMPC_aligned: 2178 case OMPC_copyin: 2179 case OMPC_copyprivate: 2180 case OMPC_flush: 2181 case OMPC_depend: 2182 case OMPC_map: 2183 case OMPC_to: 2184 case OMPC_from: 2185 case OMPC_use_device_ptr: 2186 case OMPC_is_device_ptr: 2187 case OMPC_allocate: 2188 Clause = ParseOpenMPVarListClause(DKind, CKind, WrongDirective); 2189 break; 2190 case OMPC_device_type: 2191 case OMPC_unknown: 2192 Diag(Tok, diag::warn_omp_extra_tokens_at_eol) 2193 << getOpenMPDirectiveName(DKind); 2194 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); 2195 break; 2196 case OMPC_threadprivate: 2197 case OMPC_uniform: 2198 case OMPC_match: 2199 if (!WrongDirective) 2200 Diag(Tok, diag::err_omp_unexpected_clause) 2201 << getOpenMPClauseName(CKind) << getOpenMPDirectiveName(DKind); 2202 SkipUntil(tok::comma, tok::annot_pragma_openmp_end, StopBeforeMatch); 2203 break; 2204 } 2205 return ErrorFound ? nullptr : Clause; 2206 } 2207 2208 /// Parses simple expression in parens for single-expression clauses of OpenMP 2209 /// constructs. 2210 /// \param RLoc Returned location of right paren. 2211 ExprResult Parser::ParseOpenMPParensExpr(StringRef ClauseName, 2212 SourceLocation &RLoc, 2213 bool IsAddressOfOperand) { 2214 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 2215 if (T.expectAndConsume(diag::err_expected_lparen_after, ClauseName.data())) 2216 return ExprError(); 2217 2218 SourceLocation ELoc = Tok.getLocation(); 2219 ExprResult LHS(ParseCastExpression( 2220 /*isUnaryExpression=*/false, IsAddressOfOperand, NotTypeCast)); 2221 ExprResult Val(ParseRHSOfBinaryExpression(LHS, prec::Conditional)); 2222 Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false); 2223 2224 // Parse ')'. 2225 RLoc = Tok.getLocation(); 2226 if (!T.consumeClose()) 2227 RLoc = T.getCloseLocation(); 2228 2229 return Val; 2230 } 2231 2232 /// Parsing of OpenMP clauses with single expressions like 'final', 2233 /// 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams', 2234 /// 'thread_limit', 'simdlen', 'priority', 'grainsize', 'num_tasks' or 'hint'. 2235 /// 2236 /// final-clause: 2237 /// 'final' '(' expression ')' 2238 /// 2239 /// num_threads-clause: 2240 /// 'num_threads' '(' expression ')' 2241 /// 2242 /// safelen-clause: 2243 /// 'safelen' '(' expression ')' 2244 /// 2245 /// simdlen-clause: 2246 /// 'simdlen' '(' expression ')' 2247 /// 2248 /// collapse-clause: 2249 /// 'collapse' '(' expression ')' 2250 /// 2251 /// priority-clause: 2252 /// 'priority' '(' expression ')' 2253 /// 2254 /// grainsize-clause: 2255 /// 'grainsize' '(' expression ')' 2256 /// 2257 /// num_tasks-clause: 2258 /// 'num_tasks' '(' expression ')' 2259 /// 2260 /// hint-clause: 2261 /// 'hint' '(' expression ')' 2262 /// 2263 /// allocator-clause: 2264 /// 'allocator' '(' expression ')' 2265 /// 2266 OMPClause *Parser::ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, 2267 bool ParseOnly) { 2268 SourceLocation Loc = ConsumeToken(); 2269 SourceLocation LLoc = Tok.getLocation(); 2270 SourceLocation RLoc; 2271 2272 ExprResult Val = ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc); 2273 2274 if (Val.isInvalid()) 2275 return nullptr; 2276 2277 if (ParseOnly) 2278 return nullptr; 2279 return Actions.ActOnOpenMPSingleExprClause(Kind, Val.get(), Loc, LLoc, RLoc); 2280 } 2281 2282 /// Parsing of simple OpenMP clauses like 'default' or 'proc_bind'. 2283 /// 2284 /// default-clause: 2285 /// 'default' '(' 'none' | 'shared' ') 2286 /// 2287 /// proc_bind-clause: 2288 /// 'proc_bind' '(' 'master' | 'close' | 'spread' ') 2289 /// 2290 OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind, 2291 bool ParseOnly) { 2292 llvm::Optional<SimpleClauseData> Val = parseOpenMPSimpleClause(*this, Kind); 2293 if (!Val || ParseOnly) 2294 return nullptr; 2295 return Actions.ActOnOpenMPSimpleClause( 2296 Kind, Val.getValue().Type, Val.getValue().TypeLoc, Val.getValue().LOpen, 2297 Val.getValue().Loc, Val.getValue().RLoc); 2298 } 2299 2300 /// Parsing of OpenMP clauses like 'ordered'. 2301 /// 2302 /// ordered-clause: 2303 /// 'ordered' 2304 /// 2305 /// nowait-clause: 2306 /// 'nowait' 2307 /// 2308 /// untied-clause: 2309 /// 'untied' 2310 /// 2311 /// mergeable-clause: 2312 /// 'mergeable' 2313 /// 2314 /// read-clause: 2315 /// 'read' 2316 /// 2317 /// threads-clause: 2318 /// 'threads' 2319 /// 2320 /// simd-clause: 2321 /// 'simd' 2322 /// 2323 /// nogroup-clause: 2324 /// 'nogroup' 2325 /// 2326 OMPClause *Parser::ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly) { 2327 SourceLocation Loc = Tok.getLocation(); 2328 ConsumeAnyToken(); 2329 2330 if (ParseOnly) 2331 return nullptr; 2332 return Actions.ActOnOpenMPClause(Kind, Loc, Tok.getLocation()); 2333 } 2334 2335 2336 /// Parsing of OpenMP clauses with single expressions and some additional 2337 /// argument like 'schedule' or 'dist_schedule'. 2338 /// 2339 /// schedule-clause: 2340 /// 'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression ] 2341 /// ')' 2342 /// 2343 /// if-clause: 2344 /// 'if' '(' [ directive-name-modifier ':' ] expression ')' 2345 /// 2346 /// defaultmap: 2347 /// 'defaultmap' '(' modifier ':' kind ')' 2348 /// 2349 OMPClause *Parser::ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind, 2350 bool ParseOnly) { 2351 SourceLocation Loc = ConsumeToken(); 2352 SourceLocation DelimLoc; 2353 // Parse '('. 2354 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 2355 if (T.expectAndConsume(diag::err_expected_lparen_after, 2356 getOpenMPClauseName(Kind))) 2357 return nullptr; 2358 2359 ExprResult Val; 2360 SmallVector<unsigned, 4> Arg; 2361 SmallVector<SourceLocation, 4> KLoc; 2362 if (Kind == OMPC_schedule) { 2363 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 2364 Arg.resize(NumberOfElements); 2365 KLoc.resize(NumberOfElements); 2366 Arg[Modifier1] = OMPC_SCHEDULE_MODIFIER_unknown; 2367 Arg[Modifier2] = OMPC_SCHEDULE_MODIFIER_unknown; 2368 Arg[ScheduleKind] = OMPC_SCHEDULE_unknown; 2369 unsigned KindModifier = getOpenMPSimpleClauseType( 2370 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)); 2371 if (KindModifier > OMPC_SCHEDULE_unknown) { 2372 // Parse 'modifier' 2373 Arg[Modifier1] = KindModifier; 2374 KLoc[Modifier1] = Tok.getLocation(); 2375 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 2376 Tok.isNot(tok::annot_pragma_openmp_end)) 2377 ConsumeAnyToken(); 2378 if (Tok.is(tok::comma)) { 2379 // Parse ',' 'modifier' 2380 ConsumeAnyToken(); 2381 KindModifier = getOpenMPSimpleClauseType( 2382 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)); 2383 Arg[Modifier2] = KindModifier > OMPC_SCHEDULE_unknown 2384 ? KindModifier 2385 : (unsigned)OMPC_SCHEDULE_unknown; 2386 KLoc[Modifier2] = Tok.getLocation(); 2387 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 2388 Tok.isNot(tok::annot_pragma_openmp_end)) 2389 ConsumeAnyToken(); 2390 } 2391 // Parse ':' 2392 if (Tok.is(tok::colon)) 2393 ConsumeAnyToken(); 2394 else 2395 Diag(Tok, diag::warn_pragma_expected_colon) << "schedule modifier"; 2396 KindModifier = getOpenMPSimpleClauseType( 2397 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)); 2398 } 2399 Arg[ScheduleKind] = KindModifier; 2400 KLoc[ScheduleKind] = Tok.getLocation(); 2401 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 2402 Tok.isNot(tok::annot_pragma_openmp_end)) 2403 ConsumeAnyToken(); 2404 if ((Arg[ScheduleKind] == OMPC_SCHEDULE_static || 2405 Arg[ScheduleKind] == OMPC_SCHEDULE_dynamic || 2406 Arg[ScheduleKind] == OMPC_SCHEDULE_guided) && 2407 Tok.is(tok::comma)) 2408 DelimLoc = ConsumeAnyToken(); 2409 } else if (Kind == OMPC_dist_schedule) { 2410 Arg.push_back(getOpenMPSimpleClauseType( 2411 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok))); 2412 KLoc.push_back(Tok.getLocation()); 2413 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 2414 Tok.isNot(tok::annot_pragma_openmp_end)) 2415 ConsumeAnyToken(); 2416 if (Arg.back() == OMPC_DIST_SCHEDULE_static && Tok.is(tok::comma)) 2417 DelimLoc = ConsumeAnyToken(); 2418 } else if (Kind == OMPC_defaultmap) { 2419 // Get a defaultmap modifier 2420 unsigned Modifier = getOpenMPSimpleClauseType( 2421 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)); 2422 // Set defaultmap modifier to unknown if it is either scalar, aggregate, or 2423 // pointer 2424 if (Modifier < OMPC_DEFAULTMAP_MODIFIER_unknown) 2425 Modifier = OMPC_DEFAULTMAP_MODIFIER_unknown; 2426 Arg.push_back(Modifier); 2427 KLoc.push_back(Tok.getLocation()); 2428 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 2429 Tok.isNot(tok::annot_pragma_openmp_end)) 2430 ConsumeAnyToken(); 2431 // Parse ':' 2432 if (Tok.is(tok::colon)) 2433 ConsumeAnyToken(); 2434 else if (Arg.back() != OMPC_DEFAULTMAP_MODIFIER_unknown) 2435 Diag(Tok, diag::warn_pragma_expected_colon) << "defaultmap modifier"; 2436 // Get a defaultmap kind 2437 Arg.push_back(getOpenMPSimpleClauseType( 2438 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok))); 2439 KLoc.push_back(Tok.getLocation()); 2440 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && 2441 Tok.isNot(tok::annot_pragma_openmp_end)) 2442 ConsumeAnyToken(); 2443 } else { 2444 assert(Kind == OMPC_if); 2445 KLoc.push_back(Tok.getLocation()); 2446 TentativeParsingAction TPA(*this); 2447 auto DK = parseOpenMPDirectiveKind(*this); 2448 Arg.push_back(DK); 2449 if (DK != OMPD_unknown) { 2450 ConsumeToken(); 2451 if (Tok.is(tok::colon) && getLangOpts().OpenMP > 40) { 2452 TPA.Commit(); 2453 DelimLoc = ConsumeToken(); 2454 } else { 2455 TPA.Revert(); 2456 Arg.back() = unsigned(OMPD_unknown); 2457 } 2458 } else { 2459 TPA.Revert(); 2460 } 2461 } 2462 2463 bool NeedAnExpression = (Kind == OMPC_schedule && DelimLoc.isValid()) || 2464 (Kind == OMPC_dist_schedule && DelimLoc.isValid()) || 2465 Kind == OMPC_if; 2466 if (NeedAnExpression) { 2467 SourceLocation ELoc = Tok.getLocation(); 2468 ExprResult LHS(ParseCastExpression(false, false, NotTypeCast)); 2469 Val = ParseRHSOfBinaryExpression(LHS, prec::Conditional); 2470 Val = 2471 Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false); 2472 } 2473 2474 // Parse ')'. 2475 SourceLocation RLoc = Tok.getLocation(); 2476 if (!T.consumeClose()) 2477 RLoc = T.getCloseLocation(); 2478 2479 if (NeedAnExpression && Val.isInvalid()) 2480 return nullptr; 2481 2482 if (ParseOnly) 2483 return nullptr; 2484 return Actions.ActOnOpenMPSingleExprWithArgClause( 2485 Kind, Arg, Val.get(), Loc, T.getOpenLocation(), KLoc, DelimLoc, RLoc); 2486 } 2487 2488 static bool ParseReductionId(Parser &P, CXXScopeSpec &ReductionIdScopeSpec, 2489 UnqualifiedId &ReductionId) { 2490 if (ReductionIdScopeSpec.isEmpty()) { 2491 auto OOK = OO_None; 2492 switch (P.getCurToken().getKind()) { 2493 case tok::plus: 2494 OOK = OO_Plus; 2495 break; 2496 case tok::minus: 2497 OOK = OO_Minus; 2498 break; 2499 case tok::star: 2500 OOK = OO_Star; 2501 break; 2502 case tok::amp: 2503 OOK = OO_Amp; 2504 break; 2505 case tok::pipe: 2506 OOK = OO_Pipe; 2507 break; 2508 case tok::caret: 2509 OOK = OO_Caret; 2510 break; 2511 case tok::ampamp: 2512 OOK = OO_AmpAmp; 2513 break; 2514 case tok::pipepipe: 2515 OOK = OO_PipePipe; 2516 break; 2517 default: 2518 break; 2519 } 2520 if (OOK != OO_None) { 2521 SourceLocation OpLoc = P.ConsumeToken(); 2522 SourceLocation SymbolLocations[] = {OpLoc, OpLoc, SourceLocation()}; 2523 ReductionId.setOperatorFunctionId(OpLoc, OOK, SymbolLocations); 2524 return false; 2525 } 2526 } 2527 return P.ParseUnqualifiedId(ReductionIdScopeSpec, /*EnteringContext*/ false, 2528 /*AllowDestructorName*/ false, 2529 /*AllowConstructorName*/ false, 2530 /*AllowDeductionGuide*/ false, 2531 nullptr, nullptr, ReductionId); 2532 } 2533 2534 /// Checks if the token is a valid map-type-modifier. 2535 static OpenMPMapModifierKind isMapModifier(Parser &P) { 2536 Token Tok = P.getCurToken(); 2537 if (!Tok.is(tok::identifier)) 2538 return OMPC_MAP_MODIFIER_unknown; 2539 2540 Preprocessor &PP = P.getPreprocessor(); 2541 OpenMPMapModifierKind TypeModifier = static_cast<OpenMPMapModifierKind>( 2542 getOpenMPSimpleClauseType(OMPC_map, PP.getSpelling(Tok))); 2543 return TypeModifier; 2544 } 2545 2546 /// Parse the mapper modifier in map, to, and from clauses. 2547 bool Parser::parseMapperModifier(OpenMPVarListDataTy &Data) { 2548 // Parse '('. 2549 BalancedDelimiterTracker T(*this, tok::l_paren, tok::colon); 2550 if (T.expectAndConsume(diag::err_expected_lparen_after, "mapper")) { 2551 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 2552 StopBeforeMatch); 2553 return true; 2554 } 2555 // Parse mapper-identifier 2556 if (getLangOpts().CPlusPlus) 2557 ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec, 2558 /*ObjectType=*/nullptr, 2559 /*EnteringContext=*/false); 2560 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) { 2561 Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier); 2562 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 2563 StopBeforeMatch); 2564 return true; 2565 } 2566 auto &DeclNames = Actions.getASTContext().DeclarationNames; 2567 Data.ReductionOrMapperId = DeclarationNameInfo( 2568 DeclNames.getIdentifier(Tok.getIdentifierInfo()), Tok.getLocation()); 2569 ConsumeToken(); 2570 // Parse ')'. 2571 return T.consumeClose(); 2572 } 2573 2574 /// Parse map-type-modifiers in map clause. 2575 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) 2576 /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) 2577 bool Parser::parseMapTypeModifiers(OpenMPVarListDataTy &Data) { 2578 while (getCurToken().isNot(tok::colon)) { 2579 OpenMPMapModifierKind TypeModifier = isMapModifier(*this); 2580 if (TypeModifier == OMPC_MAP_MODIFIER_always || 2581 TypeModifier == OMPC_MAP_MODIFIER_close) { 2582 Data.MapTypeModifiers.push_back(TypeModifier); 2583 Data.MapTypeModifiersLoc.push_back(Tok.getLocation()); 2584 ConsumeToken(); 2585 } else if (TypeModifier == OMPC_MAP_MODIFIER_mapper) { 2586 Data.MapTypeModifiers.push_back(TypeModifier); 2587 Data.MapTypeModifiersLoc.push_back(Tok.getLocation()); 2588 ConsumeToken(); 2589 if (parseMapperModifier(Data)) 2590 return true; 2591 } else { 2592 // For the case of unknown map-type-modifier or a map-type. 2593 // Map-type is followed by a colon; the function returns when it 2594 // encounters a token followed by a colon. 2595 if (Tok.is(tok::comma)) { 2596 Diag(Tok, diag::err_omp_map_type_modifier_missing); 2597 ConsumeToken(); 2598 continue; 2599 } 2600 // Potential map-type token as it is followed by a colon. 2601 if (PP.LookAhead(0).is(tok::colon)) 2602 return false; 2603 Diag(Tok, diag::err_omp_unknown_map_type_modifier); 2604 ConsumeToken(); 2605 } 2606 if (getCurToken().is(tok::comma)) 2607 ConsumeToken(); 2608 } 2609 return false; 2610 } 2611 2612 /// Checks if the token is a valid map-type. 2613 static OpenMPMapClauseKind isMapType(Parser &P) { 2614 Token Tok = P.getCurToken(); 2615 // The map-type token can be either an identifier or the C++ delete keyword. 2616 if (!Tok.isOneOf(tok::identifier, tok::kw_delete)) 2617 return OMPC_MAP_unknown; 2618 Preprocessor &PP = P.getPreprocessor(); 2619 OpenMPMapClauseKind MapType = static_cast<OpenMPMapClauseKind>( 2620 getOpenMPSimpleClauseType(OMPC_map, PP.getSpelling(Tok))); 2621 return MapType; 2622 } 2623 2624 /// Parse map-type in map clause. 2625 /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) 2626 /// where, map-type ::= to | from | tofrom | alloc | release | delete 2627 static void parseMapType(Parser &P, Parser::OpenMPVarListDataTy &Data) { 2628 Token Tok = P.getCurToken(); 2629 if (Tok.is(tok::colon)) { 2630 P.Diag(Tok, diag::err_omp_map_type_missing); 2631 return; 2632 } 2633 Data.MapType = isMapType(P); 2634 if (Data.MapType == OMPC_MAP_unknown) 2635 P.Diag(Tok, diag::err_omp_unknown_map_type); 2636 P.ConsumeToken(); 2637 } 2638 2639 /// Parses clauses with list. 2640 bool Parser::ParseOpenMPVarList(OpenMPDirectiveKind DKind, 2641 OpenMPClauseKind Kind, 2642 SmallVectorImpl<Expr *> &Vars, 2643 OpenMPVarListDataTy &Data) { 2644 UnqualifiedId UnqualifiedReductionId; 2645 bool InvalidReductionId = false; 2646 bool IsInvalidMapperModifier = false; 2647 2648 // Parse '('. 2649 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); 2650 if (T.expectAndConsume(diag::err_expected_lparen_after, 2651 getOpenMPClauseName(Kind))) 2652 return true; 2653 2654 bool NeedRParenForLinear = false; 2655 BalancedDelimiterTracker LinearT(*this, tok::l_paren, 2656 tok::annot_pragma_openmp_end); 2657 // Handle reduction-identifier for reduction clause. 2658 if (Kind == OMPC_reduction || Kind == OMPC_task_reduction || 2659 Kind == OMPC_in_reduction) { 2660 ColonProtectionRAIIObject ColonRAII(*this); 2661 if (getLangOpts().CPlusPlus) 2662 ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec, 2663 /*ObjectType=*/nullptr, 2664 /*EnteringContext=*/false); 2665 InvalidReductionId = ParseReductionId( 2666 *this, Data.ReductionOrMapperIdScopeSpec, UnqualifiedReductionId); 2667 if (InvalidReductionId) { 2668 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 2669 StopBeforeMatch); 2670 } 2671 if (Tok.is(tok::colon)) 2672 Data.ColonLoc = ConsumeToken(); 2673 else 2674 Diag(Tok, diag::warn_pragma_expected_colon) << "reduction identifier"; 2675 if (!InvalidReductionId) 2676 Data.ReductionOrMapperId = 2677 Actions.GetNameFromUnqualifiedId(UnqualifiedReductionId); 2678 } else if (Kind == OMPC_depend) { 2679 // Handle dependency type for depend clause. 2680 ColonProtectionRAIIObject ColonRAII(*this); 2681 Data.DepKind = 2682 static_cast<OpenMPDependClauseKind>(getOpenMPSimpleClauseType( 2683 Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "")); 2684 Data.DepLinMapLoc = Tok.getLocation(); 2685 2686 if (Data.DepKind == OMPC_DEPEND_unknown) { 2687 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 2688 StopBeforeMatch); 2689 } else { 2690 ConsumeToken(); 2691 // Special processing for depend(source) clause. 2692 if (DKind == OMPD_ordered && Data.DepKind == OMPC_DEPEND_source) { 2693 // Parse ')'. 2694 T.consumeClose(); 2695 return false; 2696 } 2697 } 2698 if (Tok.is(tok::colon)) { 2699 Data.ColonLoc = ConsumeToken(); 2700 } else { 2701 Diag(Tok, DKind == OMPD_ordered ? diag::warn_pragma_expected_colon_r_paren 2702 : diag::warn_pragma_expected_colon) 2703 << "dependency type"; 2704 } 2705 } else if (Kind == OMPC_linear) { 2706 // Try to parse modifier if any. 2707 if (Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::l_paren)) { 2708 Data.LinKind = static_cast<OpenMPLinearClauseKind>( 2709 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok))); 2710 Data.DepLinMapLoc = ConsumeToken(); 2711 LinearT.consumeOpen(); 2712 NeedRParenForLinear = true; 2713 } 2714 } else if (Kind == OMPC_map) { 2715 // Handle map type for map clause. 2716 ColonProtectionRAIIObject ColonRAII(*this); 2717 2718 // The first identifier may be a list item, a map-type or a 2719 // map-type-modifier. The map-type can also be delete which has the same 2720 // spelling of the C++ delete keyword. 2721 Data.DepLinMapLoc = Tok.getLocation(); 2722 2723 // Check for presence of a colon in the map clause. 2724 TentativeParsingAction TPA(*this); 2725 bool ColonPresent = false; 2726 if (SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 2727 StopBeforeMatch)) { 2728 if (Tok.is(tok::colon)) 2729 ColonPresent = true; 2730 } 2731 TPA.Revert(); 2732 // Only parse map-type-modifier[s] and map-type if a colon is present in 2733 // the map clause. 2734 if (ColonPresent) { 2735 IsInvalidMapperModifier = parseMapTypeModifiers(Data); 2736 if (!IsInvalidMapperModifier) 2737 parseMapType(*this, Data); 2738 else 2739 SkipUntil(tok::colon, tok::annot_pragma_openmp_end, StopBeforeMatch); 2740 } 2741 if (Data.MapType == OMPC_MAP_unknown) { 2742 Data.MapType = OMPC_MAP_tofrom; 2743 Data.IsMapTypeImplicit = true; 2744 } 2745 2746 if (Tok.is(tok::colon)) 2747 Data.ColonLoc = ConsumeToken(); 2748 } else if (Kind == OMPC_to || Kind == OMPC_from) { 2749 if (Tok.is(tok::identifier)) { 2750 bool IsMapperModifier = false; 2751 if (Kind == OMPC_to) { 2752 auto Modifier = static_cast<OpenMPToModifierKind>( 2753 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok))); 2754 if (Modifier == OMPC_TO_MODIFIER_mapper) 2755 IsMapperModifier = true; 2756 } else { 2757 auto Modifier = static_cast<OpenMPFromModifierKind>( 2758 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok))); 2759 if (Modifier == OMPC_FROM_MODIFIER_mapper) 2760 IsMapperModifier = true; 2761 } 2762 if (IsMapperModifier) { 2763 // Parse the mapper modifier. 2764 ConsumeToken(); 2765 IsInvalidMapperModifier = parseMapperModifier(Data); 2766 if (Tok.isNot(tok::colon)) { 2767 if (!IsInvalidMapperModifier) 2768 Diag(Tok, diag::warn_pragma_expected_colon) << ")"; 2769 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, 2770 StopBeforeMatch); 2771 } 2772 // Consume ':'. 2773 if (Tok.is(tok::colon)) 2774 ConsumeToken(); 2775 } 2776 } 2777 } else if (Kind == OMPC_allocate) { 2778 // Handle optional allocator expression followed by colon delimiter. 2779 ColonProtectionRAIIObject ColonRAII(*this); 2780 TentativeParsingAction TPA(*this); 2781 ExprResult Tail = 2782 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()); 2783 Tail = Actions.ActOnFinishFullExpr(Tail.get(), T.getOpenLocation(), 2784 /*DiscardedValue=*/false); 2785 if (Tail.isUsable()) { 2786 if (Tok.is(tok::colon)) { 2787 Data.TailExpr = Tail.get(); 2788 Data.ColonLoc = ConsumeToken(); 2789 TPA.Commit(); 2790 } else { 2791 // colon not found, no allocator specified, parse only list of 2792 // variables. 2793 TPA.Revert(); 2794 } 2795 } else { 2796 // Parsing was unsuccessfull, revert and skip to the end of clause or 2797 // directive. 2798 TPA.Revert(); 2799 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 2800 StopBeforeMatch); 2801 } 2802 } 2803 2804 bool IsComma = 2805 (Kind != OMPC_reduction && Kind != OMPC_task_reduction && 2806 Kind != OMPC_in_reduction && Kind != OMPC_depend && Kind != OMPC_map) || 2807 (Kind == OMPC_reduction && !InvalidReductionId) || 2808 (Kind == OMPC_map && Data.MapType != OMPC_MAP_unknown) || 2809 (Kind == OMPC_depend && Data.DepKind != OMPC_DEPEND_unknown); 2810 const bool MayHaveTail = (Kind == OMPC_linear || Kind == OMPC_aligned); 2811 while (IsComma || (Tok.isNot(tok::r_paren) && Tok.isNot(tok::colon) && 2812 Tok.isNot(tok::annot_pragma_openmp_end))) { 2813 ColonProtectionRAIIObject ColonRAII(*this, MayHaveTail); 2814 // Parse variable 2815 ExprResult VarExpr = 2816 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()); 2817 if (VarExpr.isUsable()) { 2818 Vars.push_back(VarExpr.get()); 2819 } else { 2820 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 2821 StopBeforeMatch); 2822 } 2823 // Skip ',' if any 2824 IsComma = Tok.is(tok::comma); 2825 if (IsComma) 2826 ConsumeToken(); 2827 else if (Tok.isNot(tok::r_paren) && 2828 Tok.isNot(tok::annot_pragma_openmp_end) && 2829 (!MayHaveTail || Tok.isNot(tok::colon))) 2830 Diag(Tok, diag::err_omp_expected_punc) 2831 << ((Kind == OMPC_flush) ? getOpenMPDirectiveName(OMPD_flush) 2832 : getOpenMPClauseName(Kind)) 2833 << (Kind == OMPC_flush); 2834 } 2835 2836 // Parse ')' for linear clause with modifier. 2837 if (NeedRParenForLinear) 2838 LinearT.consumeClose(); 2839 2840 // Parse ':' linear-step (or ':' alignment). 2841 const bool MustHaveTail = MayHaveTail && Tok.is(tok::colon); 2842 if (MustHaveTail) { 2843 Data.ColonLoc = Tok.getLocation(); 2844 SourceLocation ELoc = ConsumeToken(); 2845 ExprResult Tail = ParseAssignmentExpression(); 2846 Tail = 2847 Actions.ActOnFinishFullExpr(Tail.get(), ELoc, /*DiscardedValue*/ false); 2848 if (Tail.isUsable()) 2849 Data.TailExpr = Tail.get(); 2850 else 2851 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, 2852 StopBeforeMatch); 2853 } 2854 2855 // Parse ')'. 2856 Data.RLoc = Tok.getLocation(); 2857 if (!T.consumeClose()) 2858 Data.RLoc = T.getCloseLocation(); 2859 return (Kind == OMPC_depend && Data.DepKind != OMPC_DEPEND_unknown && 2860 Vars.empty()) || 2861 (Kind != OMPC_depend && Kind != OMPC_map && Vars.empty()) || 2862 (MustHaveTail && !Data.TailExpr) || InvalidReductionId || 2863 IsInvalidMapperModifier; 2864 } 2865 2866 /// Parsing of OpenMP clause 'private', 'firstprivate', 'lastprivate', 2867 /// 'shared', 'copyin', 'copyprivate', 'flush', 'reduction', 'task_reduction' or 2868 /// 'in_reduction'. 2869 /// 2870 /// private-clause: 2871 /// 'private' '(' list ')' 2872 /// firstprivate-clause: 2873 /// 'firstprivate' '(' list ')' 2874 /// lastprivate-clause: 2875 /// 'lastprivate' '(' list ')' 2876 /// shared-clause: 2877 /// 'shared' '(' list ')' 2878 /// linear-clause: 2879 /// 'linear' '(' linear-list [ ':' linear-step ] ')' 2880 /// aligned-clause: 2881 /// 'aligned' '(' list [ ':' alignment ] ')' 2882 /// reduction-clause: 2883 /// 'reduction' '(' reduction-identifier ':' list ')' 2884 /// task_reduction-clause: 2885 /// 'task_reduction' '(' reduction-identifier ':' list ')' 2886 /// in_reduction-clause: 2887 /// 'in_reduction' '(' reduction-identifier ':' list ')' 2888 /// copyprivate-clause: 2889 /// 'copyprivate' '(' list ')' 2890 /// flush-clause: 2891 /// 'flush' '(' list ')' 2892 /// depend-clause: 2893 /// 'depend' '(' in | out | inout : list | source ')' 2894 /// map-clause: 2895 /// 'map' '(' [ [ always [,] ] [ close [,] ] 2896 /// [ mapper '(' mapper-identifier ')' [,] ] 2897 /// to | from | tofrom | alloc | release | delete ':' ] list ')'; 2898 /// to-clause: 2899 /// 'to' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')' 2900 /// from-clause: 2901 /// 'from' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')' 2902 /// use_device_ptr-clause: 2903 /// 'use_device_ptr' '(' list ')' 2904 /// is_device_ptr-clause: 2905 /// 'is_device_ptr' '(' list ')' 2906 /// allocate-clause: 2907 /// 'allocate' '(' [ allocator ':' ] list ')' 2908 /// 2909 /// For 'linear' clause linear-list may have the following forms: 2910 /// list 2911 /// modifier(list) 2912 /// where modifier is 'val' (C) or 'ref', 'val' or 'uval'(C++). 2913 OMPClause *Parser::ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, 2914 OpenMPClauseKind Kind, 2915 bool ParseOnly) { 2916 SourceLocation Loc = Tok.getLocation(); 2917 SourceLocation LOpen = ConsumeToken(); 2918 SmallVector<Expr *, 4> Vars; 2919 OpenMPVarListDataTy Data; 2920 2921 if (ParseOpenMPVarList(DKind, Kind, Vars, Data)) 2922 return nullptr; 2923 2924 if (ParseOnly) 2925 return nullptr; 2926 OMPVarListLocTy Locs(Loc, LOpen, Data.RLoc); 2927 return Actions.ActOnOpenMPVarListClause( 2928 Kind, Vars, Data.TailExpr, Locs, Data.ColonLoc, 2929 Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId, Data.DepKind, 2930 Data.LinKind, Data.MapTypeModifiers, Data.MapTypeModifiersLoc, 2931 Data.MapType, Data.IsMapTypeImplicit, Data.DepLinMapLoc); 2932 } 2933 2934