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