]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Parse/ParseOpenMP.cpp
Update clang to trunk r290819 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Parse / ParseOpenMP.cpp
1 //===--- ParseOpenMP.cpp - OpenMP directives parsing ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 /// \brief This file implements parsing of all OpenMP directives and clauses.
11 ///
12 //===----------------------------------------------------------------------===//
13
14 #include "RAIIObjectsForParser.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/StmtOpenMP.h"
17 #include "clang/Parse/ParseDiagnostic.h"
18 #include "clang/Parse/Parser.h"
19 #include "clang/Sema/Scope.h"
20 #include "llvm/ADT/PointerIntPair.h"
21
22 using namespace clang;
23
24 //===----------------------------------------------------------------------===//
25 // OpenMP declarative directives.
26 //===----------------------------------------------------------------------===//
27
28 namespace {
29 enum OpenMPDirectiveKindEx {
30   OMPD_cancellation = OMPD_unknown + 1,
31   OMPD_data,
32   OMPD_declare,
33   OMPD_end,
34   OMPD_end_declare,
35   OMPD_enter,
36   OMPD_exit,
37   OMPD_point,
38   OMPD_reduction,
39   OMPD_target_enter,
40   OMPD_target_exit,
41   OMPD_update,
42   OMPD_distribute_parallel,
43   OMPD_teams_distribute_parallel,
44   OMPD_target_teams_distribute_parallel
45 };
46
47 class ThreadprivateListParserHelper final {
48   SmallVector<Expr *, 4> Identifiers;
49   Parser *P;
50
51 public:
52   ThreadprivateListParserHelper(Parser *P) : P(P) {}
53   void operator()(CXXScopeSpec &SS, DeclarationNameInfo NameInfo) {
54     ExprResult Res =
55         P->getActions().ActOnOpenMPIdExpression(P->getCurScope(), SS, NameInfo);
56     if (Res.isUsable())
57       Identifiers.push_back(Res.get());
58   }
59   llvm::ArrayRef<Expr *> getIdentifiers() const { return Identifiers; }
60 };
61 } // namespace
62
63 // Map token string to extended OMP token kind that are
64 // OpenMPDirectiveKind + OpenMPDirectiveKindEx.
65 static unsigned getOpenMPDirectiveKindEx(StringRef S) {
66   auto DKind = getOpenMPDirectiveKind(S);
67   if (DKind != OMPD_unknown)
68     return DKind;
69
70   return llvm::StringSwitch<unsigned>(S)
71       .Case("cancellation", OMPD_cancellation)
72       .Case("data", OMPD_data)
73       .Case("declare", OMPD_declare)
74       .Case("end", OMPD_end)
75       .Case("enter", OMPD_enter)
76       .Case("exit", OMPD_exit)
77       .Case("point", OMPD_point)
78       .Case("reduction", OMPD_reduction)
79       .Case("update", OMPD_update)
80       .Default(OMPD_unknown);
81 }
82
83 static OpenMPDirectiveKind ParseOpenMPDirectiveKind(Parser &P) {
84   // Array of foldings: F[i][0] F[i][1] ===> F[i][2].
85   // E.g.: OMPD_for OMPD_simd ===> OMPD_for_simd
86   // TODO: add other combined directives in topological order.
87   static const unsigned F[][3] = {
88     { OMPD_cancellation, OMPD_point, OMPD_cancellation_point },
89     { OMPD_declare, OMPD_reduction, OMPD_declare_reduction },
90     { OMPD_declare, OMPD_simd, OMPD_declare_simd },
91     { OMPD_declare, OMPD_target, OMPD_declare_target },
92     { OMPD_distribute, OMPD_parallel, OMPD_distribute_parallel },
93     { OMPD_distribute_parallel, OMPD_for, OMPD_distribute_parallel_for },
94     { OMPD_distribute_parallel_for, OMPD_simd, 
95       OMPD_distribute_parallel_for_simd },
96     { OMPD_distribute, OMPD_simd, OMPD_distribute_simd },
97     { OMPD_end, OMPD_declare, OMPD_end_declare },
98     { OMPD_end_declare, OMPD_target, OMPD_end_declare_target },
99     { OMPD_target, OMPD_data, OMPD_target_data },
100     { OMPD_target, OMPD_enter, OMPD_target_enter },
101     { OMPD_target, OMPD_exit, OMPD_target_exit },
102     { OMPD_target, OMPD_update, OMPD_target_update },
103     { OMPD_target_enter, OMPD_data, OMPD_target_enter_data },
104     { OMPD_target_exit, OMPD_data, OMPD_target_exit_data },
105     { OMPD_for, OMPD_simd, OMPD_for_simd },
106     { OMPD_parallel, OMPD_for, OMPD_parallel_for },
107     { OMPD_parallel_for, OMPD_simd, OMPD_parallel_for_simd },
108     { OMPD_parallel, OMPD_sections, OMPD_parallel_sections },
109     { OMPD_taskloop, OMPD_simd, OMPD_taskloop_simd },
110     { OMPD_target, OMPD_parallel, OMPD_target_parallel },
111     { OMPD_target, OMPD_simd, OMPD_target_simd },
112     { OMPD_target_parallel, OMPD_for, OMPD_target_parallel_for },
113     { OMPD_target_parallel_for, OMPD_simd, OMPD_target_parallel_for_simd },
114     { OMPD_teams, OMPD_distribute, OMPD_teams_distribute },
115     { OMPD_teams_distribute, OMPD_simd, OMPD_teams_distribute_simd },
116     { OMPD_teams_distribute, OMPD_parallel, OMPD_teams_distribute_parallel },
117     { OMPD_teams_distribute_parallel, OMPD_for, OMPD_teams_distribute_parallel_for },
118     { OMPD_teams_distribute_parallel_for, OMPD_simd, OMPD_teams_distribute_parallel_for_simd },
119     { OMPD_target, OMPD_teams, OMPD_target_teams },
120     { OMPD_target_teams, OMPD_distribute, OMPD_target_teams_distribute },
121     { OMPD_target_teams_distribute, OMPD_parallel, OMPD_target_teams_distribute_parallel },
122     { OMPD_target_teams_distribute_parallel, OMPD_for, OMPD_target_teams_distribute_parallel_for }
123   };
124   enum { CancellationPoint = 0, DeclareReduction = 1, TargetData = 2 };
125   auto Tok = P.getCurToken();
126   unsigned DKind =
127       Tok.isAnnotation()
128           ? static_cast<unsigned>(OMPD_unknown)
129           : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
130   if (DKind == OMPD_unknown)
131     return OMPD_unknown;
132
133   for (unsigned i = 0; i < llvm::array_lengthof(F); ++i) {
134     if (DKind != F[i][0])
135       continue;
136
137     Tok = P.getPreprocessor().LookAhead(0);
138     unsigned SDKind =
139         Tok.isAnnotation()
140             ? static_cast<unsigned>(OMPD_unknown)
141             : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
142     if (SDKind == OMPD_unknown)
143       continue;
144
145     if (SDKind == F[i][1]) {
146       P.ConsumeToken();
147       DKind = F[i][2];
148     }
149   }
150   return DKind < OMPD_unknown ? static_cast<OpenMPDirectiveKind>(DKind)
151                               : OMPD_unknown;
152 }
153
154 static DeclarationName parseOpenMPReductionId(Parser &P) {
155   Token Tok = P.getCurToken();
156   Sema &Actions = P.getActions();
157   OverloadedOperatorKind OOK = OO_None;
158   // Allow to use 'operator' keyword for C++ operators
159   bool WithOperator = false;
160   if (Tok.is(tok::kw_operator)) {
161     P.ConsumeToken();
162     Tok = P.getCurToken();
163     WithOperator = true;
164   }
165   switch (Tok.getKind()) {
166   case tok::plus: // '+'
167     OOK = OO_Plus;
168     break;
169   case tok::minus: // '-'
170     OOK = OO_Minus;
171     break;
172   case tok::star: // '*'
173     OOK = OO_Star;
174     break;
175   case tok::amp: // '&'
176     OOK = OO_Amp;
177     break;
178   case tok::pipe: // '|'
179     OOK = OO_Pipe;
180     break;
181   case tok::caret: // '^'
182     OOK = OO_Caret;
183     break;
184   case tok::ampamp: // '&&'
185     OOK = OO_AmpAmp;
186     break;
187   case tok::pipepipe: // '||'
188     OOK = OO_PipePipe;
189     break;
190   case tok::identifier: // identifier
191     if (!WithOperator)
192       break;
193   default:
194     P.Diag(Tok.getLocation(), diag::err_omp_expected_reduction_identifier);
195     P.SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
196                 Parser::StopBeforeMatch);
197     return DeclarationName();
198   }
199   P.ConsumeToken();
200   auto &DeclNames = Actions.getASTContext().DeclarationNames;
201   return OOK == OO_None ? DeclNames.getIdentifier(Tok.getIdentifierInfo())
202                         : DeclNames.getCXXOperatorName(OOK);
203 }
204
205 /// \brief Parse 'omp declare reduction' construct.
206 ///
207 ///       declare-reduction-directive:
208 ///        annot_pragma_openmp 'declare' 'reduction'
209 ///        '(' <reduction_id> ':' <type> {',' <type>} ':' <expression> ')'
210 ///        ['initializer' '(' ('omp_priv' '=' <expression>)|<function_call> ')']
211 ///        annot_pragma_openmp_end
212 /// <reduction_id> is either a base language identifier or one of the following
213 /// operators: '+', '-', '*', '&', '|', '^', '&&' and '||'.
214 ///
215 Parser::DeclGroupPtrTy
216 Parser::ParseOpenMPDeclareReductionDirective(AccessSpecifier AS) {
217   // Parse '('.
218   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
219   if (T.expectAndConsume(diag::err_expected_lparen_after,
220                          getOpenMPDirectiveName(OMPD_declare_reduction))) {
221     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
222     return DeclGroupPtrTy();
223   }
224
225   DeclarationName Name = parseOpenMPReductionId(*this);
226   if (Name.isEmpty() && Tok.is(tok::annot_pragma_openmp_end))
227     return DeclGroupPtrTy();
228
229   // Consume ':'.
230   bool IsCorrect = !ExpectAndConsume(tok::colon);
231
232   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
233     return DeclGroupPtrTy();
234
235   IsCorrect = IsCorrect && !Name.isEmpty();
236
237   if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end)) {
238     Diag(Tok.getLocation(), diag::err_expected_type);
239     IsCorrect = false;
240   }
241
242   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
243     return DeclGroupPtrTy();
244
245   SmallVector<std::pair<QualType, SourceLocation>, 8> ReductionTypes;
246   // Parse list of types until ':' token.
247   do {
248     ColonProtectionRAIIObject ColonRAII(*this);
249     SourceRange Range;
250     TypeResult TR = ParseTypeName(&Range, Declarator::PrototypeContext, AS);
251     if (TR.isUsable()) {
252       auto ReductionType =
253           Actions.ActOnOpenMPDeclareReductionType(Range.getBegin(), TR);
254       if (!ReductionType.isNull()) {
255         ReductionTypes.push_back(
256             std::make_pair(ReductionType, Range.getBegin()));
257       }
258     } else {
259       SkipUntil(tok::comma, tok::colon, tok::annot_pragma_openmp_end,
260                 StopBeforeMatch);
261     }
262
263     if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end))
264       break;
265
266     // Consume ','.
267     if (ExpectAndConsume(tok::comma)) {
268       IsCorrect = false;
269       if (Tok.is(tok::annot_pragma_openmp_end)) {
270         Diag(Tok.getLocation(), diag::err_expected_type);
271         return DeclGroupPtrTy();
272       }
273     }
274   } while (Tok.isNot(tok::annot_pragma_openmp_end));
275
276   if (ReductionTypes.empty()) {
277     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
278     return DeclGroupPtrTy();
279   }
280
281   if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
282     return DeclGroupPtrTy();
283
284   // Consume ':'.
285   if (ExpectAndConsume(tok::colon))
286     IsCorrect = false;
287
288   if (Tok.is(tok::annot_pragma_openmp_end)) {
289     Diag(Tok.getLocation(), diag::err_expected_expression);
290     return DeclGroupPtrTy();
291   }
292
293   DeclGroupPtrTy DRD = Actions.ActOnOpenMPDeclareReductionDirectiveStart(
294       getCurScope(), Actions.getCurLexicalContext(), Name, ReductionTypes, AS);
295
296   // Parse <combiner> expression and then parse initializer if any for each
297   // correct type.
298   unsigned I = 0, E = ReductionTypes.size();
299   for (auto *D : DRD.get()) {
300     TentativeParsingAction TPA(*this);
301     ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
302                                     Scope::OpenMPDirectiveScope);
303     // Parse <combiner> expression.
304     Actions.ActOnOpenMPDeclareReductionCombinerStart(getCurScope(), D);
305     ExprResult CombinerResult =
306         Actions.ActOnFinishFullExpr(ParseAssignmentExpression().get(),
307                                     D->getLocation(), /*DiscardedValue=*/true);
308     Actions.ActOnOpenMPDeclareReductionCombinerEnd(D, CombinerResult.get());
309
310     if (CombinerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
311         Tok.isNot(tok::annot_pragma_openmp_end)) {
312       TPA.Commit();
313       IsCorrect = false;
314       break;
315     }
316     IsCorrect = !T.consumeClose() && IsCorrect && CombinerResult.isUsable();
317     ExprResult InitializerResult;
318     if (Tok.isNot(tok::annot_pragma_openmp_end)) {
319       // Parse <initializer> expression.
320       if (Tok.is(tok::identifier) &&
321           Tok.getIdentifierInfo()->isStr("initializer"))
322         ConsumeToken();
323       else {
324         Diag(Tok.getLocation(), diag::err_expected) << "'initializer'";
325         TPA.Commit();
326         IsCorrect = false;
327         break;
328       }
329       // Parse '('.
330       BalancedDelimiterTracker T(*this, tok::l_paren,
331                                  tok::annot_pragma_openmp_end);
332       IsCorrect =
333           !T.expectAndConsume(diag::err_expected_lparen_after, "initializer") &&
334           IsCorrect;
335       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
336         ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
337                                         Scope::OpenMPDirectiveScope);
338         // Parse expression.
339         Actions.ActOnOpenMPDeclareReductionInitializerStart(getCurScope(), D);
340         InitializerResult = Actions.ActOnFinishFullExpr(
341             ParseAssignmentExpression().get(), D->getLocation(),
342             /*DiscardedValue=*/true);
343         Actions.ActOnOpenMPDeclareReductionInitializerEnd(
344             D, InitializerResult.get());
345         if (InitializerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
346             Tok.isNot(tok::annot_pragma_openmp_end)) {
347           TPA.Commit();
348           IsCorrect = false;
349           break;
350         }
351         IsCorrect =
352             !T.consumeClose() && IsCorrect && !InitializerResult.isInvalid();
353       }
354     }
355
356     ++I;
357     // Revert parsing if not the last type, otherwise accept it, we're done with
358     // parsing.
359     if (I != E)
360       TPA.Revert();
361     else
362       TPA.Commit();
363   }
364   return Actions.ActOnOpenMPDeclareReductionDirectiveEnd(getCurScope(), DRD,
365                                                          IsCorrect);
366 }
367
368 namespace {
369 /// RAII that recreates function context for correct parsing of clauses of
370 /// 'declare simd' construct.
371 /// OpenMP, 2.8.2 declare simd Construct
372 /// The expressions appearing in the clauses of this directive are evaluated in
373 /// the scope of the arguments of the function declaration or definition.
374 class FNContextRAII final {
375   Parser &P;
376   Sema::CXXThisScopeRAII *ThisScope;
377   Parser::ParseScope *TempScope;
378   Parser::ParseScope *FnScope;
379   bool HasTemplateScope = false;
380   bool HasFunScope = false;
381   FNContextRAII() = delete;
382   FNContextRAII(const FNContextRAII &) = delete;
383   FNContextRAII &operator=(const FNContextRAII &) = delete;
384
385 public:
386   FNContextRAII(Parser &P, Parser::DeclGroupPtrTy Ptr) : P(P) {
387     Decl *D = *Ptr.get().begin();
388     NamedDecl *ND = dyn_cast<NamedDecl>(D);
389     RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
390     Sema &Actions = P.getActions();
391
392     // Allow 'this' within late-parsed attributes.
393     ThisScope = new Sema::CXXThisScopeRAII(Actions, RD, /*TypeQuals=*/0,
394                                            ND && ND->isCXXInstanceMember());
395
396     // If the Decl is templatized, add template parameters to scope.
397     HasTemplateScope = D->isTemplateDecl();
398     TempScope =
399         new Parser::ParseScope(&P, Scope::TemplateParamScope, HasTemplateScope);
400     if (HasTemplateScope)
401       Actions.ActOnReenterTemplateScope(Actions.getCurScope(), D);
402
403     // If the Decl is on a function, add function parameters to the scope.
404     HasFunScope = D->isFunctionOrFunctionTemplate();
405     FnScope = new Parser::ParseScope(&P, Scope::FnScope | Scope::DeclScope,
406                                      HasFunScope);
407     if (HasFunScope)
408       Actions.ActOnReenterFunctionContext(Actions.getCurScope(), D);
409   }
410   ~FNContextRAII() {
411     if (HasFunScope) {
412       P.getActions().ActOnExitFunctionContext();
413       FnScope->Exit(); // Pop scope, and remove Decls from IdResolver
414     }
415     if (HasTemplateScope)
416       TempScope->Exit();
417     delete FnScope;
418     delete TempScope;
419     delete ThisScope;
420   }
421 };
422 } // namespace
423
424 /// Parses clauses for 'declare simd' directive.
425 ///    clause:
426 ///      'inbranch' | 'notinbranch'
427 ///      'simdlen' '(' <expr> ')'
428 ///      { 'uniform' '(' <argument_list> ')' }
429 ///      { 'aligned '(' <argument_list> [ ':' <alignment> ] ')' }
430 ///      { 'linear '(' <argument_list> [ ':' <step> ] ')' }
431 static bool parseDeclareSimdClauses(
432     Parser &P, OMPDeclareSimdDeclAttr::BranchStateTy &BS, ExprResult &SimdLen,
433     SmallVectorImpl<Expr *> &Uniforms, SmallVectorImpl<Expr *> &Aligneds,
434     SmallVectorImpl<Expr *> &Alignments, SmallVectorImpl<Expr *> &Linears,
435     SmallVectorImpl<unsigned> &LinModifiers, SmallVectorImpl<Expr *> &Steps) {
436   SourceRange BSRange;
437   const Token &Tok = P.getCurToken();
438   bool IsError = false;
439   while (Tok.isNot(tok::annot_pragma_openmp_end)) {
440     if (Tok.isNot(tok::identifier))
441       break;
442     OMPDeclareSimdDeclAttr::BranchStateTy Out;
443     IdentifierInfo *II = Tok.getIdentifierInfo();
444     StringRef ClauseName = II->getName();
445     // Parse 'inranch|notinbranch' clauses.
446     if (OMPDeclareSimdDeclAttr::ConvertStrToBranchStateTy(ClauseName, Out)) {
447       if (BS != OMPDeclareSimdDeclAttr::BS_Undefined && BS != Out) {
448         P.Diag(Tok, diag::err_omp_declare_simd_inbranch_notinbranch)
449             << ClauseName
450             << OMPDeclareSimdDeclAttr::ConvertBranchStateTyToStr(BS) << BSRange;
451         IsError = true;
452       }
453       BS = Out;
454       BSRange = SourceRange(Tok.getLocation(), Tok.getEndLoc());
455       P.ConsumeToken();
456     } else if (ClauseName.equals("simdlen")) {
457       if (SimdLen.isUsable()) {
458         P.Diag(Tok, diag::err_omp_more_one_clause)
459             << getOpenMPDirectiveName(OMPD_declare_simd) << ClauseName << 0;
460         IsError = true;
461       }
462       P.ConsumeToken();
463       SourceLocation RLoc;
464       SimdLen = P.ParseOpenMPParensExpr(ClauseName, RLoc);
465       if (SimdLen.isInvalid())
466         IsError = true;
467     } else {
468       OpenMPClauseKind CKind = getOpenMPClauseKind(ClauseName);
469       if (CKind == OMPC_uniform || CKind == OMPC_aligned ||
470           CKind == OMPC_linear) {
471         Parser::OpenMPVarListDataTy Data;
472         auto *Vars = &Uniforms;
473         if (CKind == OMPC_aligned)
474           Vars = &Aligneds;
475         else if (CKind == OMPC_linear)
476           Vars = &Linears;
477
478         P.ConsumeToken();
479         if (P.ParseOpenMPVarList(OMPD_declare_simd,
480                                  getOpenMPClauseKind(ClauseName), *Vars, Data))
481           IsError = true;
482         if (CKind == OMPC_aligned)
483           Alignments.append(Aligneds.size() - Alignments.size(), Data.TailExpr);
484         else if (CKind == OMPC_linear) {
485           if (P.getActions().CheckOpenMPLinearModifier(Data.LinKind,
486                                                        Data.DepLinMapLoc))
487             Data.LinKind = OMPC_LINEAR_val;
488           LinModifiers.append(Linears.size() - LinModifiers.size(),
489                               Data.LinKind);
490           Steps.append(Linears.size() - Steps.size(), Data.TailExpr);
491         }
492       } else
493         // TODO: add parsing of other clauses.
494         break;
495     }
496     // Skip ',' if any.
497     if (Tok.is(tok::comma))
498       P.ConsumeToken();
499   }
500   return IsError;
501 }
502
503 /// Parse clauses for '#pragma omp declare simd'.
504 Parser::DeclGroupPtrTy
505 Parser::ParseOMPDeclareSimdClauses(Parser::DeclGroupPtrTy Ptr,
506                                    CachedTokens &Toks, SourceLocation Loc) {
507   PP.EnterToken(Tok);
508   PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
509   // Consume the previously pushed token.
510   ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
511
512   FNContextRAII FnContext(*this, Ptr);
513   OMPDeclareSimdDeclAttr::BranchStateTy BS =
514       OMPDeclareSimdDeclAttr::BS_Undefined;
515   ExprResult Simdlen;
516   SmallVector<Expr *, 4> Uniforms;
517   SmallVector<Expr *, 4> Aligneds;
518   SmallVector<Expr *, 4> Alignments;
519   SmallVector<Expr *, 4> Linears;
520   SmallVector<unsigned, 4> LinModifiers;
521   SmallVector<Expr *, 4> Steps;
522   bool IsError =
523       parseDeclareSimdClauses(*this, BS, Simdlen, Uniforms, Aligneds,
524                               Alignments, Linears, LinModifiers, Steps);
525   // Need to check for extra tokens.
526   if (Tok.isNot(tok::annot_pragma_openmp_end)) {
527     Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
528         << getOpenMPDirectiveName(OMPD_declare_simd);
529     while (Tok.isNot(tok::annot_pragma_openmp_end))
530       ConsumeAnyToken();
531   }
532   // Skip the last annot_pragma_openmp_end.
533   SourceLocation EndLoc = ConsumeToken();
534   if (!IsError) {
535     return Actions.ActOnOpenMPDeclareSimdDirective(
536         Ptr, BS, Simdlen.get(), Uniforms, Aligneds, Alignments, Linears,
537         LinModifiers, Steps, SourceRange(Loc, EndLoc));
538   }
539   return Ptr;
540 }
541
542 /// \brief Parsing of declarative OpenMP directives.
543 ///
544 ///       threadprivate-directive:
545 ///         annot_pragma_openmp 'threadprivate' simple-variable-list
546 ///         annot_pragma_openmp_end
547 ///
548 ///       declare-reduction-directive:
549 ///        annot_pragma_openmp 'declare' 'reduction' [...]
550 ///        annot_pragma_openmp_end
551 ///
552 ///       declare-simd-directive:
553 ///         annot_pragma_openmp 'declare simd' {<clause> [,]}
554 ///         annot_pragma_openmp_end
555 ///         <function declaration/definition>
556 ///
557 Parser::DeclGroupPtrTy Parser::ParseOpenMPDeclarativeDirectiveWithExtDecl(
558     AccessSpecifier &AS, ParsedAttributesWithRange &Attrs,
559     DeclSpec::TST TagType, Decl *Tag) {
560   assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!");
561   ParenBraceBracketBalancer BalancerRAIIObj(*this);
562
563   SourceLocation Loc = ConsumeToken();
564   auto DKind = ParseOpenMPDirectiveKind(*this);
565
566   switch (DKind) {
567   case OMPD_threadprivate: {
568     ConsumeToken();
569     ThreadprivateListParserHelper Helper(this);
570     if (!ParseOpenMPSimpleVarList(OMPD_threadprivate, Helper, true)) {
571       // The last seen token is annot_pragma_openmp_end - need to check for
572       // extra tokens.
573       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
574         Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
575             << getOpenMPDirectiveName(OMPD_threadprivate);
576         SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
577       }
578       // Skip the last annot_pragma_openmp_end.
579       ConsumeToken();
580       return Actions.ActOnOpenMPThreadprivateDirective(Loc,
581                                                        Helper.getIdentifiers());
582     }
583     break;
584   }
585   case OMPD_declare_reduction:
586     ConsumeToken();
587     if (auto Res = ParseOpenMPDeclareReductionDirective(AS)) {
588       // The last seen token is annot_pragma_openmp_end - need to check for
589       // extra tokens.
590       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
591         Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
592             << getOpenMPDirectiveName(OMPD_declare_reduction);
593         while (Tok.isNot(tok::annot_pragma_openmp_end))
594           ConsumeAnyToken();
595       }
596       // Skip the last annot_pragma_openmp_end.
597       ConsumeToken();
598       return Res;
599     }
600     break;
601   case OMPD_declare_simd: {
602     // The syntax is:
603     // { #pragma omp declare simd }
604     // <function-declaration-or-definition>
605     //
606     ConsumeToken();
607     CachedTokens Toks;
608     while(Tok.isNot(tok::annot_pragma_openmp_end)) {
609       Toks.push_back(Tok);
610       ConsumeAnyToken();
611     }
612     Toks.push_back(Tok);
613     ConsumeAnyToken();
614
615     DeclGroupPtrTy Ptr;
616     if (Tok.is(tok::annot_pragma_openmp))
617       Ptr = ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs, TagType, Tag);
618     else if (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
619       // Here we expect to see some function declaration.
620       if (AS == AS_none) {
621         assert(TagType == DeclSpec::TST_unspecified);
622         MaybeParseCXX11Attributes(Attrs);
623         ParsingDeclSpec PDS(*this);
624         Ptr = ParseExternalDeclaration(Attrs, &PDS);
625       } else {
626         Ptr =
627             ParseCXXClassMemberDeclarationWithPragmas(AS, Attrs, TagType, Tag);
628       }
629     }
630     if (!Ptr) {
631       Diag(Loc, diag::err_omp_decl_in_declare_simd);
632       return DeclGroupPtrTy();
633     }
634     return ParseOMPDeclareSimdClauses(Ptr, Toks, Loc);
635   }
636   case OMPD_declare_target: {
637     SourceLocation DTLoc = ConsumeAnyToken();
638     if (Tok.isNot(tok::annot_pragma_openmp_end)) {
639       // OpenMP 4.5 syntax with list of entities.
640       llvm::SmallSetVector<const NamedDecl*, 16> SameDirectiveDecls;
641       while (Tok.isNot(tok::annot_pragma_openmp_end)) {
642         OMPDeclareTargetDeclAttr::MapTypeTy MT =
643             OMPDeclareTargetDeclAttr::MT_To;
644         if (Tok.is(tok::identifier)) {
645           IdentifierInfo *II = Tok.getIdentifierInfo();
646           StringRef ClauseName = II->getName();
647           // Parse 'to|link' clauses.
648           if (!OMPDeclareTargetDeclAttr::ConvertStrToMapTypeTy(ClauseName,
649                                                                MT)) {
650             Diag(Tok, diag::err_omp_declare_target_unexpected_clause)
651                 << ClauseName;
652             break;
653           }
654           ConsumeToken();
655         }
656         auto Callback = [this, MT, &SameDirectiveDecls](
657             CXXScopeSpec &SS, DeclarationNameInfo NameInfo) {
658           Actions.ActOnOpenMPDeclareTargetName(getCurScope(), SS, NameInfo, MT,
659                                                SameDirectiveDecls);
660         };
661         if (ParseOpenMPSimpleVarList(OMPD_declare_target, Callback, true))
662           break;
663
664         // Consume optional ','.
665         if (Tok.is(tok::comma))
666           ConsumeToken();
667       }
668       SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
669       ConsumeAnyToken();
670       return DeclGroupPtrTy();
671     }
672
673     // Skip the last annot_pragma_openmp_end.
674     ConsumeAnyToken();
675
676     if (!Actions.ActOnStartOpenMPDeclareTargetDirective(DTLoc))
677       return DeclGroupPtrTy();
678
679     DKind = ParseOpenMPDirectiveKind(*this);
680     while (DKind != OMPD_end_declare_target && DKind != OMPD_declare_target &&
681            Tok.isNot(tok::eof) && Tok.isNot(tok::r_brace)) {
682       ParsedAttributesWithRange attrs(AttrFactory);
683       MaybeParseCXX11Attributes(attrs);
684       ParseExternalDeclaration(attrs);
685       if (Tok.isAnnotation() && Tok.is(tok::annot_pragma_openmp)) {
686         TentativeParsingAction TPA(*this);
687         ConsumeToken();
688         DKind = ParseOpenMPDirectiveKind(*this);
689         if (DKind != OMPD_end_declare_target)
690           TPA.Revert();
691         else
692           TPA.Commit();
693       }
694     }
695
696     if (DKind == OMPD_end_declare_target) {
697       ConsumeAnyToken();
698       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
699         Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
700             << getOpenMPDirectiveName(OMPD_end_declare_target);
701         SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
702       }
703       // Skip the last annot_pragma_openmp_end.
704       ConsumeAnyToken();
705     } else {
706       Diag(Tok, diag::err_expected_end_declare_target);
707       Diag(DTLoc, diag::note_matching) << "'#pragma omp declare target'";
708     }
709     Actions.ActOnFinishOpenMPDeclareTargetDirective();
710     return DeclGroupPtrTy();
711   }
712   case OMPD_unknown:
713     Diag(Tok, diag::err_omp_unknown_directive);
714     break;
715   case OMPD_parallel:
716   case OMPD_simd:
717   case OMPD_task:
718   case OMPD_taskyield:
719   case OMPD_barrier:
720   case OMPD_taskwait:
721   case OMPD_taskgroup:
722   case OMPD_flush:
723   case OMPD_for:
724   case OMPD_for_simd:
725   case OMPD_sections:
726   case OMPD_section:
727   case OMPD_single:
728   case OMPD_master:
729   case OMPD_ordered:
730   case OMPD_critical:
731   case OMPD_parallel_for:
732   case OMPD_parallel_for_simd:
733   case OMPD_parallel_sections:
734   case OMPD_atomic:
735   case OMPD_target:
736   case OMPD_teams:
737   case OMPD_cancellation_point:
738   case OMPD_cancel:
739   case OMPD_target_data:
740   case OMPD_target_enter_data:
741   case OMPD_target_exit_data:
742   case OMPD_target_parallel:
743   case OMPD_target_parallel_for:
744   case OMPD_taskloop:
745   case OMPD_taskloop_simd:
746   case OMPD_distribute:
747   case OMPD_end_declare_target:
748   case OMPD_target_update:
749   case OMPD_distribute_parallel_for:
750   case OMPD_distribute_parallel_for_simd:
751   case OMPD_distribute_simd:
752   case OMPD_target_parallel_for_simd:
753   case OMPD_target_simd:
754   case OMPD_teams_distribute:
755   case OMPD_teams_distribute_simd:
756   case OMPD_teams_distribute_parallel_for_simd:
757   case OMPD_teams_distribute_parallel_for:
758   case OMPD_target_teams:
759   case OMPD_target_teams_distribute:
760   case OMPD_target_teams_distribute_parallel_for:
761     Diag(Tok, diag::err_omp_unexpected_directive)
762         << getOpenMPDirectiveName(DKind);
763     break;
764   }
765   while (Tok.isNot(tok::annot_pragma_openmp_end))
766     ConsumeAnyToken();
767   ConsumeAnyToken();
768   return nullptr;
769 }
770
771 /// \brief Parsing of declarative or executable OpenMP directives.
772 ///
773 ///       threadprivate-directive:
774 ///         annot_pragma_openmp 'threadprivate' simple-variable-list
775 ///         annot_pragma_openmp_end
776 ///
777 ///       declare-reduction-directive:
778 ///         annot_pragma_openmp 'declare' 'reduction' '(' <reduction_id> ':'
779 ///         <type> {',' <type>} ':' <expression> ')' ['initializer' '('
780 ///         ('omp_priv' '=' <expression>|<function_call>) ')']
781 ///         annot_pragma_openmp_end
782 ///
783 ///       executable-directive:
784 ///         annot_pragma_openmp 'parallel' | 'simd' | 'for' | 'sections' |
785 ///         'section' | 'single' | 'master' | 'critical' [ '(' <name> ')' ] |
786 ///         'parallel for' | 'parallel sections' | 'task' | 'taskyield' |
787 ///         'barrier' | 'taskwait' | 'flush' | 'ordered' | 'atomic' |
788 ///         'for simd' | 'parallel for simd' | 'target' | 'target data' |
789 ///         'taskgroup' | 'teams' | 'taskloop' | 'taskloop simd' |
790 ///         'distribute' | 'target enter data' | 'target exit data' |
791 ///         'target parallel' | 'target parallel for' |
792 ///         'target update' | 'distribute parallel for' |
793 ///         'distribute paralle for simd' | 'distribute simd' |
794 ///         'target parallel for simd' | 'target simd' |
795 ///         'teams distribute' | 'teams distribute simd' |
796 ///         'teams distribute parallel for simd' |
797 ///         'teams distribute parallel for' | 'target teams' |
798 ///         'target teams distribute' |
799 ///         'target teams distribute parallel for' {clause}
800 ///         annot_pragma_openmp_end
801 ///
802 StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective(
803     AllowedContsructsKind Allowed) {
804   assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!");
805   ParenBraceBracketBalancer BalancerRAIIObj(*this);
806   SmallVector<OMPClause *, 5> Clauses;
807   SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, OMPC_unknown + 1>
808   FirstClauses(OMPC_unknown + 1);
809   unsigned ScopeFlags =
810       Scope::FnScope | Scope::DeclScope | Scope::OpenMPDirectiveScope;
811   SourceLocation Loc = ConsumeToken(), EndLoc;
812   auto DKind = ParseOpenMPDirectiveKind(*this);
813   OpenMPDirectiveKind CancelRegion = OMPD_unknown;
814   // Name of critical directive.
815   DeclarationNameInfo DirName;
816   StmtResult Directive = StmtError();
817   bool HasAssociatedStatement = true;
818   bool FlushHasClause = false;
819
820   switch (DKind) {
821   case OMPD_threadprivate: {
822     if (Allowed != ACK_Any) {
823       Diag(Tok, diag::err_omp_immediate_directive)
824           << getOpenMPDirectiveName(DKind) << 0;
825     }
826     ConsumeToken();
827     ThreadprivateListParserHelper Helper(this);
828     if (!ParseOpenMPSimpleVarList(OMPD_threadprivate, Helper, false)) {
829       // The last seen token is annot_pragma_openmp_end - need to check for
830       // extra tokens.
831       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
832         Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
833             << getOpenMPDirectiveName(OMPD_threadprivate);
834         SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
835       }
836       DeclGroupPtrTy Res = Actions.ActOnOpenMPThreadprivateDirective(
837           Loc, Helper.getIdentifiers());
838       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
839     }
840     SkipUntil(tok::annot_pragma_openmp_end);
841     break;
842   }
843   case OMPD_declare_reduction:
844     ConsumeToken();
845     if (auto Res = ParseOpenMPDeclareReductionDirective(/*AS=*/AS_none)) {
846       // The last seen token is annot_pragma_openmp_end - need to check for
847       // extra tokens.
848       if (Tok.isNot(tok::annot_pragma_openmp_end)) {
849         Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
850             << getOpenMPDirectiveName(OMPD_declare_reduction);
851         while (Tok.isNot(tok::annot_pragma_openmp_end))
852           ConsumeAnyToken();
853       }
854       ConsumeAnyToken();
855       Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
856     } else
857       SkipUntil(tok::annot_pragma_openmp_end);
858     break;
859   case OMPD_flush:
860     if (PP.LookAhead(0).is(tok::l_paren)) {
861       FlushHasClause = true;
862       // Push copy of the current token back to stream to properly parse
863       // pseudo-clause OMPFlushClause.
864       PP.EnterToken(Tok);
865     }
866   case OMPD_taskyield:
867   case OMPD_barrier:
868   case OMPD_taskwait:
869   case OMPD_cancellation_point:
870   case OMPD_cancel:
871   case OMPD_target_enter_data:
872   case OMPD_target_exit_data:
873   case OMPD_target_update:
874     if (Allowed == ACK_StatementsOpenMPNonStandalone) {
875       Diag(Tok, diag::err_omp_immediate_directive)
876           << getOpenMPDirectiveName(DKind) << 0;
877     }
878     HasAssociatedStatement = false;
879     // Fall through for further analysis.
880   case OMPD_parallel:
881   case OMPD_simd:
882   case OMPD_for:
883   case OMPD_for_simd:
884   case OMPD_sections:
885   case OMPD_single:
886   case OMPD_section:
887   case OMPD_master:
888   case OMPD_critical:
889   case OMPD_parallel_for:
890   case OMPD_parallel_for_simd:
891   case OMPD_parallel_sections:
892   case OMPD_task:
893   case OMPD_ordered:
894   case OMPD_atomic:
895   case OMPD_target:
896   case OMPD_teams:
897   case OMPD_taskgroup:
898   case OMPD_target_data:
899   case OMPD_target_parallel:
900   case OMPD_target_parallel_for:
901   case OMPD_taskloop:
902   case OMPD_taskloop_simd:
903   case OMPD_distribute:
904   case OMPD_distribute_parallel_for:
905   case OMPD_distribute_parallel_for_simd:
906   case OMPD_distribute_simd:
907   case OMPD_target_parallel_for_simd:
908   case OMPD_target_simd:
909   case OMPD_teams_distribute:
910   case OMPD_teams_distribute_simd:
911   case OMPD_teams_distribute_parallel_for_simd:
912   case OMPD_teams_distribute_parallel_for:
913   case OMPD_target_teams:
914   case OMPD_target_teams_distribute:
915   case OMPD_target_teams_distribute_parallel_for: {
916     ConsumeToken();
917     // Parse directive name of the 'critical' directive if any.
918     if (DKind == OMPD_critical) {
919       BalancedDelimiterTracker T(*this, tok::l_paren,
920                                  tok::annot_pragma_openmp_end);
921       if (!T.consumeOpen()) {
922         if (Tok.isAnyIdentifier()) {
923           DirName =
924               DeclarationNameInfo(Tok.getIdentifierInfo(), Tok.getLocation());
925           ConsumeAnyToken();
926         } else {
927           Diag(Tok, diag::err_omp_expected_identifier_for_critical);
928         }
929         T.consumeClose();
930       }
931     } else if (DKind == OMPD_cancellation_point || DKind == OMPD_cancel) {
932       CancelRegion = ParseOpenMPDirectiveKind(*this);
933       if (Tok.isNot(tok::annot_pragma_openmp_end))
934         ConsumeToken();
935     }
936
937     if (isOpenMPLoopDirective(DKind))
938       ScopeFlags |= Scope::OpenMPLoopDirectiveScope;
939     if (isOpenMPSimdDirective(DKind))
940       ScopeFlags |= Scope::OpenMPSimdDirectiveScope;
941     ParseScope OMPDirectiveScope(this, ScopeFlags);
942     Actions.StartOpenMPDSABlock(DKind, DirName, Actions.getCurScope(), Loc);
943
944     while (Tok.isNot(tok::annot_pragma_openmp_end)) {
945       OpenMPClauseKind CKind =
946           Tok.isAnnotation()
947               ? OMPC_unknown
948               : FlushHasClause ? OMPC_flush
949                                : getOpenMPClauseKind(PP.getSpelling(Tok));
950       Actions.StartOpenMPClause(CKind);
951       FlushHasClause = false;
952       OMPClause *Clause =
953           ParseOpenMPClause(DKind, CKind, !FirstClauses[CKind].getInt());
954       FirstClauses[CKind].setInt(true);
955       if (Clause) {
956         FirstClauses[CKind].setPointer(Clause);
957         Clauses.push_back(Clause);
958       }
959
960       // Skip ',' if any.
961       if (Tok.is(tok::comma))
962         ConsumeToken();
963       Actions.EndOpenMPClause();
964     }
965     // End location of the directive.
966     EndLoc = Tok.getLocation();
967     // Consume final annot_pragma_openmp_end.
968     ConsumeToken();
969
970     // OpenMP [2.13.8, ordered Construct, Syntax]
971     // If the depend clause is specified, the ordered construct is a stand-alone
972     // directive.
973     if (DKind == OMPD_ordered && FirstClauses[OMPC_depend].getInt()) {
974       if (Allowed == ACK_StatementsOpenMPNonStandalone) {
975         Diag(Loc, diag::err_omp_immediate_directive)
976             << getOpenMPDirectiveName(DKind) << 1
977             << getOpenMPClauseName(OMPC_depend);
978       }
979       HasAssociatedStatement = false;
980     }
981
982     StmtResult AssociatedStmt;
983     if (HasAssociatedStatement) {
984       // The body is a block scope like in Lambdas and Blocks.
985       Sema::CompoundScopeRAII CompoundScope(Actions);
986       Actions.ActOnOpenMPRegionStart(DKind, getCurScope());
987       Actions.ActOnStartOfCompoundStmt();
988       // Parse statement
989       AssociatedStmt = ParseStatement();
990       Actions.ActOnFinishOfCompoundStmt();
991       AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
992     }
993     Directive = Actions.ActOnOpenMPExecutableDirective(
994         DKind, DirName, CancelRegion, Clauses, AssociatedStmt.get(), Loc,
995         EndLoc);
996
997     // Exit scope.
998     Actions.EndOpenMPDSABlock(Directive.get());
999     OMPDirectiveScope.Exit();
1000     break;
1001   }
1002   case OMPD_declare_simd:
1003   case OMPD_declare_target:
1004   case OMPD_end_declare_target:
1005     Diag(Tok, diag::err_omp_unexpected_directive)
1006         << getOpenMPDirectiveName(DKind);
1007     SkipUntil(tok::annot_pragma_openmp_end);
1008     break;
1009   case OMPD_unknown:
1010     Diag(Tok, diag::err_omp_unknown_directive);
1011     SkipUntil(tok::annot_pragma_openmp_end);
1012     break;
1013   }
1014   return Directive;
1015 }
1016
1017 // Parses simple list:
1018 //   simple-variable-list:
1019 //         '(' id-expression {, id-expression} ')'
1020 //
1021 bool Parser::ParseOpenMPSimpleVarList(
1022     OpenMPDirectiveKind Kind,
1023     const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> &
1024         Callback,
1025     bool AllowScopeSpecifier) {
1026   // Parse '('.
1027   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1028   if (T.expectAndConsume(diag::err_expected_lparen_after,
1029                          getOpenMPDirectiveName(Kind)))
1030     return true;
1031   bool IsCorrect = true;
1032   bool NoIdentIsFound = true;
1033
1034   // Read tokens while ')' or annot_pragma_openmp_end is not found.
1035   while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
1036     CXXScopeSpec SS;
1037     SourceLocation TemplateKWLoc;
1038     UnqualifiedId Name;
1039     // Read var name.
1040     Token PrevTok = Tok;
1041     NoIdentIsFound = false;
1042
1043     if (AllowScopeSpecifier && getLangOpts().CPlusPlus &&
1044         ParseOptionalCXXScopeSpecifier(SS, nullptr, false)) {
1045       IsCorrect = false;
1046       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1047                 StopBeforeMatch);
1048     } else if (ParseUnqualifiedId(SS, false, false, false, nullptr,
1049                                   TemplateKWLoc, Name)) {
1050       IsCorrect = false;
1051       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1052                 StopBeforeMatch);
1053     } else if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren) &&
1054                Tok.isNot(tok::annot_pragma_openmp_end)) {
1055       IsCorrect = false;
1056       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1057                 StopBeforeMatch);
1058       Diag(PrevTok.getLocation(), diag::err_expected)
1059           << tok::identifier
1060           << SourceRange(PrevTok.getLocation(), PrevTokLocation);
1061     } else {
1062       Callback(SS, Actions.GetNameFromUnqualifiedId(Name));
1063     }
1064     // Consume ','.
1065     if (Tok.is(tok::comma)) {
1066       ConsumeToken();
1067     }
1068   }
1069
1070   if (NoIdentIsFound) {
1071     Diag(Tok, diag::err_expected) << tok::identifier;
1072     IsCorrect = false;
1073   }
1074
1075   // Parse ')'.
1076   IsCorrect = !T.consumeClose() && IsCorrect;
1077
1078   return !IsCorrect;
1079 }
1080
1081 /// \brief Parsing of OpenMP clauses.
1082 ///
1083 ///    clause:
1084 ///       if-clause | final-clause | num_threads-clause | safelen-clause |
1085 ///       default-clause | private-clause | firstprivate-clause | shared-clause
1086 ///       | linear-clause | aligned-clause | collapse-clause |
1087 ///       lastprivate-clause | reduction-clause | proc_bind-clause |
1088 ///       schedule-clause | copyin-clause | copyprivate-clause | untied-clause |
1089 ///       mergeable-clause | flush-clause | read-clause | write-clause |
1090 ///       update-clause | capture-clause | seq_cst-clause | device-clause |
1091 ///       simdlen-clause | threads-clause | simd-clause | num_teams-clause |
1092 ///       thread_limit-clause | priority-clause | grainsize-clause |
1093 ///       nogroup-clause | num_tasks-clause | hint-clause | to-clause |
1094 ///       from-clause | is_device_ptr-clause
1095 ///
1096 OMPClause *Parser::ParseOpenMPClause(OpenMPDirectiveKind DKind,
1097                                      OpenMPClauseKind CKind, bool FirstClause) {
1098   OMPClause *Clause = nullptr;
1099   bool ErrorFound = false;
1100   // Check if clause is allowed for the given directive.
1101   if (CKind != OMPC_unknown && !isAllowedClauseForDirective(DKind, CKind)) {
1102     Diag(Tok, diag::err_omp_unexpected_clause) << getOpenMPClauseName(CKind)
1103                                                << getOpenMPDirectiveName(DKind);
1104     ErrorFound = true;
1105   }
1106
1107   switch (CKind) {
1108   case OMPC_final:
1109   case OMPC_num_threads:
1110   case OMPC_safelen:
1111   case OMPC_simdlen:
1112   case OMPC_collapse:
1113   case OMPC_ordered:
1114   case OMPC_device:
1115   case OMPC_num_teams:
1116   case OMPC_thread_limit:
1117   case OMPC_priority:
1118   case OMPC_grainsize:
1119   case OMPC_num_tasks:
1120   case OMPC_hint:
1121     // OpenMP [2.5, Restrictions]
1122     //  At most one num_threads clause can appear on the directive.
1123     // OpenMP [2.8.1, simd construct, Restrictions]
1124     //  Only one safelen  clause can appear on a simd directive.
1125     //  Only one simdlen  clause can appear on a simd directive.
1126     //  Only one collapse clause can appear on a simd directive.
1127     // OpenMP [2.9.1, target data construct, Restrictions]
1128     //  At most one device clause can appear on the directive.
1129     // OpenMP [2.11.1, task Construct, Restrictions]
1130     //  At most one if clause can appear on the directive.
1131     //  At most one final clause can appear on the directive.
1132     // OpenMP [teams Construct, Restrictions]
1133     //  At most one num_teams clause can appear on the directive.
1134     //  At most one thread_limit clause can appear on the directive.
1135     // OpenMP [2.9.1, task Construct, Restrictions]
1136     // At most one priority clause can appear on the directive.
1137     // OpenMP [2.9.2, taskloop Construct, Restrictions]
1138     // At most one grainsize clause can appear on the directive.
1139     // OpenMP [2.9.2, taskloop Construct, Restrictions]
1140     // At most one num_tasks clause can appear on the directive.
1141     if (!FirstClause) {
1142       Diag(Tok, diag::err_omp_more_one_clause)
1143           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1144       ErrorFound = true;
1145     }
1146
1147     if (CKind == OMPC_ordered && PP.LookAhead(/*N=*/0).isNot(tok::l_paren))
1148       Clause = ParseOpenMPClause(CKind);
1149     else
1150       Clause = ParseOpenMPSingleExprClause(CKind);
1151     break;
1152   case OMPC_default:
1153   case OMPC_proc_bind:
1154     // OpenMP [2.14.3.1, Restrictions]
1155     //  Only a single default clause may be specified on a parallel, task or
1156     //  teams directive.
1157     // OpenMP [2.5, parallel Construct, Restrictions]
1158     //  At most one proc_bind clause can appear on the directive.
1159     if (!FirstClause) {
1160       Diag(Tok, diag::err_omp_more_one_clause)
1161           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1162       ErrorFound = true;
1163     }
1164
1165     Clause = ParseOpenMPSimpleClause(CKind);
1166     break;
1167   case OMPC_schedule:
1168   case OMPC_dist_schedule:
1169   case OMPC_defaultmap:
1170     // OpenMP [2.7.1, Restrictions, p. 3]
1171     //  Only one schedule clause can appear on a loop directive.
1172     // OpenMP [2.10.4, Restrictions, p. 106]
1173     //  At most one defaultmap clause can appear on the directive.
1174     if (!FirstClause) {
1175       Diag(Tok, diag::err_omp_more_one_clause)
1176           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1177       ErrorFound = true;
1178     }
1179
1180   case OMPC_if:
1181     Clause = ParseOpenMPSingleExprWithArgClause(CKind);
1182     break;
1183   case OMPC_nowait:
1184   case OMPC_untied:
1185   case OMPC_mergeable:
1186   case OMPC_read:
1187   case OMPC_write:
1188   case OMPC_update:
1189   case OMPC_capture:
1190   case OMPC_seq_cst:
1191   case OMPC_threads:
1192   case OMPC_simd:
1193   case OMPC_nogroup:
1194     // OpenMP [2.7.1, Restrictions, p. 9]
1195     //  Only one ordered clause can appear on a loop directive.
1196     // OpenMP [2.7.1, Restrictions, C/C++, p. 4]
1197     //  Only one nowait clause can appear on a for directive.
1198     if (!FirstClause) {
1199       Diag(Tok, diag::err_omp_more_one_clause)
1200           << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
1201       ErrorFound = true;
1202     }
1203
1204     Clause = ParseOpenMPClause(CKind);
1205     break;
1206   case OMPC_private:
1207   case OMPC_firstprivate:
1208   case OMPC_lastprivate:
1209   case OMPC_shared:
1210   case OMPC_reduction:
1211   case OMPC_linear:
1212   case OMPC_aligned:
1213   case OMPC_copyin:
1214   case OMPC_copyprivate:
1215   case OMPC_flush:
1216   case OMPC_depend:
1217   case OMPC_map:
1218   case OMPC_to:
1219   case OMPC_from:
1220   case OMPC_use_device_ptr:
1221   case OMPC_is_device_ptr:
1222     Clause = ParseOpenMPVarListClause(DKind, CKind);
1223     break;
1224   case OMPC_unknown:
1225     Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
1226         << getOpenMPDirectiveName(DKind);
1227     SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
1228     break;
1229   case OMPC_threadprivate:
1230   case OMPC_uniform:
1231     Diag(Tok, diag::err_omp_unexpected_clause) << getOpenMPClauseName(CKind)
1232                                                << getOpenMPDirectiveName(DKind);
1233     SkipUntil(tok::comma, tok::annot_pragma_openmp_end, StopBeforeMatch);
1234     break;
1235   }
1236   return ErrorFound ? nullptr : Clause;
1237 }
1238
1239 /// Parses simple expression in parens for single-expression clauses of OpenMP
1240 /// constructs.
1241 /// \param RLoc Returned location of right paren.
1242 ExprResult Parser::ParseOpenMPParensExpr(StringRef ClauseName,
1243                                          SourceLocation &RLoc) {
1244   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1245   if (T.expectAndConsume(diag::err_expected_lparen_after, ClauseName.data()))
1246     return ExprError();
1247
1248   SourceLocation ELoc = Tok.getLocation();
1249   ExprResult LHS(ParseCastExpression(
1250       /*isUnaryExpression=*/false, /*isAddressOfOperand=*/false, NotTypeCast));
1251   ExprResult Val(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
1252   Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc);
1253
1254   // Parse ')'.
1255   T.consumeClose();
1256
1257   RLoc = T.getCloseLocation();
1258   return Val;
1259 }
1260
1261 /// \brief Parsing of OpenMP clauses with single expressions like 'final',
1262 /// 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams',
1263 /// 'thread_limit', 'simdlen', 'priority', 'grainsize', 'num_tasks' or 'hint'.
1264 ///
1265 ///    final-clause:
1266 ///      'final' '(' expression ')'
1267 ///
1268 ///    num_threads-clause:
1269 ///      'num_threads' '(' expression ')'
1270 ///
1271 ///    safelen-clause:
1272 ///      'safelen' '(' expression ')'
1273 ///
1274 ///    simdlen-clause:
1275 ///      'simdlen' '(' expression ')'
1276 ///
1277 ///    collapse-clause:
1278 ///      'collapse' '(' expression ')'
1279 ///
1280 ///    priority-clause:
1281 ///      'priority' '(' expression ')'
1282 ///
1283 ///    grainsize-clause:
1284 ///      'grainsize' '(' expression ')'
1285 ///
1286 ///    num_tasks-clause:
1287 ///      'num_tasks' '(' expression ')'
1288 ///
1289 ///    hint-clause:
1290 ///      'hint' '(' expression ')'
1291 ///
1292 OMPClause *Parser::ParseOpenMPSingleExprClause(OpenMPClauseKind Kind) {
1293   SourceLocation Loc = ConsumeToken();
1294   SourceLocation LLoc = Tok.getLocation();
1295   SourceLocation RLoc;
1296
1297   ExprResult Val = ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc);
1298
1299   if (Val.isInvalid())
1300     return nullptr;
1301
1302   return Actions.ActOnOpenMPSingleExprClause(Kind, Val.get(), Loc, LLoc, RLoc);
1303 }
1304
1305 /// \brief Parsing of simple OpenMP clauses like 'default' or 'proc_bind'.
1306 ///
1307 ///    default-clause:
1308 ///         'default' '(' 'none' | 'shared' ')
1309 ///
1310 ///    proc_bind-clause:
1311 ///         'proc_bind' '(' 'master' | 'close' | 'spread' ')
1312 ///
1313 OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind) {
1314   SourceLocation Loc = Tok.getLocation();
1315   SourceLocation LOpen = ConsumeToken();
1316   // Parse '('.
1317   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1318   if (T.expectAndConsume(diag::err_expected_lparen_after,
1319                          getOpenMPClauseName(Kind)))
1320     return nullptr;
1321
1322   unsigned Type = getOpenMPSimpleClauseType(
1323       Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1324   SourceLocation TypeLoc = Tok.getLocation();
1325   if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1326       Tok.isNot(tok::annot_pragma_openmp_end))
1327     ConsumeAnyToken();
1328
1329   // Parse ')'.
1330   T.consumeClose();
1331
1332   return Actions.ActOnOpenMPSimpleClause(Kind, Type, TypeLoc, LOpen, Loc,
1333                                          Tok.getLocation());
1334 }
1335
1336 /// \brief Parsing of OpenMP clauses like 'ordered'.
1337 ///
1338 ///    ordered-clause:
1339 ///         'ordered'
1340 ///
1341 ///    nowait-clause:
1342 ///         'nowait'
1343 ///
1344 ///    untied-clause:
1345 ///         'untied'
1346 ///
1347 ///    mergeable-clause:
1348 ///         'mergeable'
1349 ///
1350 ///    read-clause:
1351 ///         'read'
1352 ///
1353 ///    threads-clause:
1354 ///         'threads'
1355 ///
1356 ///    simd-clause:
1357 ///         'simd'
1358 ///
1359 ///    nogroup-clause:
1360 ///         'nogroup'
1361 ///
1362 OMPClause *Parser::ParseOpenMPClause(OpenMPClauseKind Kind) {
1363   SourceLocation Loc = Tok.getLocation();
1364   ConsumeAnyToken();
1365
1366   return Actions.ActOnOpenMPClause(Kind, Loc, Tok.getLocation());
1367 }
1368
1369
1370 /// \brief Parsing of OpenMP clauses with single expressions and some additional
1371 /// argument like 'schedule' or 'dist_schedule'.
1372 ///
1373 ///    schedule-clause:
1374 ///      'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression ]
1375 ///      ')'
1376 ///
1377 ///    if-clause:
1378 ///      'if' '(' [ directive-name-modifier ':' ] expression ')'
1379 ///
1380 ///    defaultmap:
1381 ///      'defaultmap' '(' modifier ':' kind ')'
1382 ///
1383 OMPClause *Parser::ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind) {
1384   SourceLocation Loc = ConsumeToken();
1385   SourceLocation DelimLoc;
1386   // Parse '('.
1387   BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1388   if (T.expectAndConsume(diag::err_expected_lparen_after,
1389                          getOpenMPClauseName(Kind)))
1390     return nullptr;
1391
1392   ExprResult Val;
1393   SmallVector<unsigned, 4> Arg;
1394   SmallVector<SourceLocation, 4> KLoc;
1395   if (Kind == OMPC_schedule) {
1396     enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
1397     Arg.resize(NumberOfElements);
1398     KLoc.resize(NumberOfElements);
1399     Arg[Modifier1] = OMPC_SCHEDULE_MODIFIER_unknown;
1400     Arg[Modifier2] = OMPC_SCHEDULE_MODIFIER_unknown;
1401     Arg[ScheduleKind] = OMPC_SCHEDULE_unknown;
1402     auto KindModifier = getOpenMPSimpleClauseType(
1403         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1404     if (KindModifier > OMPC_SCHEDULE_unknown) {
1405       // Parse 'modifier'
1406       Arg[Modifier1] = KindModifier;
1407       KLoc[Modifier1] = Tok.getLocation();
1408       if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1409           Tok.isNot(tok::annot_pragma_openmp_end))
1410         ConsumeAnyToken();
1411       if (Tok.is(tok::comma)) {
1412         // Parse ',' 'modifier'
1413         ConsumeAnyToken();
1414         KindModifier = getOpenMPSimpleClauseType(
1415             Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1416         Arg[Modifier2] = KindModifier > OMPC_SCHEDULE_unknown
1417                              ? KindModifier
1418                              : (unsigned)OMPC_SCHEDULE_unknown;
1419         KLoc[Modifier2] = Tok.getLocation();
1420         if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1421             Tok.isNot(tok::annot_pragma_openmp_end))
1422           ConsumeAnyToken();
1423       }
1424       // Parse ':'
1425       if (Tok.is(tok::colon))
1426         ConsumeAnyToken();
1427       else
1428         Diag(Tok, diag::warn_pragma_expected_colon) << "schedule modifier";
1429       KindModifier = getOpenMPSimpleClauseType(
1430           Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok));
1431     }
1432     Arg[ScheduleKind] = KindModifier;
1433     KLoc[ScheduleKind] = Tok.getLocation();
1434     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1435         Tok.isNot(tok::annot_pragma_openmp_end))
1436       ConsumeAnyToken();
1437     if ((Arg[ScheduleKind] == OMPC_SCHEDULE_static ||
1438          Arg[ScheduleKind] == OMPC_SCHEDULE_dynamic ||
1439          Arg[ScheduleKind] == OMPC_SCHEDULE_guided) &&
1440         Tok.is(tok::comma))
1441       DelimLoc = ConsumeAnyToken();
1442   } else if (Kind == OMPC_dist_schedule) {
1443     Arg.push_back(getOpenMPSimpleClauseType(
1444         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
1445     KLoc.push_back(Tok.getLocation());
1446     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1447         Tok.isNot(tok::annot_pragma_openmp_end))
1448       ConsumeAnyToken();
1449     if (Arg.back() == OMPC_DIST_SCHEDULE_static && Tok.is(tok::comma))
1450       DelimLoc = ConsumeAnyToken();
1451   } else if (Kind == OMPC_defaultmap) {
1452     // Get a defaultmap modifier
1453     Arg.push_back(getOpenMPSimpleClauseType(
1454         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
1455     KLoc.push_back(Tok.getLocation());
1456     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1457         Tok.isNot(tok::annot_pragma_openmp_end))
1458       ConsumeAnyToken();
1459     // Parse ':'
1460     if (Tok.is(tok::colon))
1461       ConsumeAnyToken();
1462     else if (Arg.back() != OMPC_DEFAULTMAP_MODIFIER_unknown)
1463       Diag(Tok, diag::warn_pragma_expected_colon) << "defaultmap modifier";
1464     // Get a defaultmap kind
1465     Arg.push_back(getOpenMPSimpleClauseType(
1466         Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)));
1467     KLoc.push_back(Tok.getLocation());
1468     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1469         Tok.isNot(tok::annot_pragma_openmp_end))
1470       ConsumeAnyToken();
1471   } else {
1472     assert(Kind == OMPC_if);
1473     KLoc.push_back(Tok.getLocation());
1474     TentativeParsingAction TPA(*this);
1475     Arg.push_back(ParseOpenMPDirectiveKind(*this));
1476     if (Arg.back() != OMPD_unknown) {
1477       ConsumeToken();
1478       if (Tok.is(tok::colon) && getLangOpts().OpenMP > 40) {
1479         TPA.Commit();
1480         DelimLoc = ConsumeToken();
1481       } else {
1482         TPA.Revert();
1483         Arg.back() = OMPD_unknown;
1484       }
1485     } else
1486       TPA.Revert();
1487   }
1488
1489   bool NeedAnExpression = (Kind == OMPC_schedule && DelimLoc.isValid()) ||
1490                           (Kind == OMPC_dist_schedule && DelimLoc.isValid()) ||
1491                           Kind == OMPC_if;
1492   if (NeedAnExpression) {
1493     SourceLocation ELoc = Tok.getLocation();
1494     ExprResult LHS(ParseCastExpression(false, false, NotTypeCast));
1495     Val = ParseRHSOfBinaryExpression(LHS, prec::Conditional);
1496     Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc);
1497   }
1498
1499   // Parse ')'.
1500   T.consumeClose();
1501
1502   if (NeedAnExpression && Val.isInvalid())
1503     return nullptr;
1504
1505   return Actions.ActOnOpenMPSingleExprWithArgClause(
1506       Kind, Arg, Val.get(), Loc, T.getOpenLocation(), KLoc, DelimLoc,
1507       T.getCloseLocation());
1508 }
1509
1510 static bool ParseReductionId(Parser &P, CXXScopeSpec &ReductionIdScopeSpec,
1511                              UnqualifiedId &ReductionId) {
1512   SourceLocation TemplateKWLoc;
1513   if (ReductionIdScopeSpec.isEmpty()) {
1514     auto OOK = OO_None;
1515     switch (P.getCurToken().getKind()) {
1516     case tok::plus:
1517       OOK = OO_Plus;
1518       break;
1519     case tok::minus:
1520       OOK = OO_Minus;
1521       break;
1522     case tok::star:
1523       OOK = OO_Star;
1524       break;
1525     case tok::amp:
1526       OOK = OO_Amp;
1527       break;
1528     case tok::pipe:
1529       OOK = OO_Pipe;
1530       break;
1531     case tok::caret:
1532       OOK = OO_Caret;
1533       break;
1534     case tok::ampamp:
1535       OOK = OO_AmpAmp;
1536       break;
1537     case tok::pipepipe:
1538       OOK = OO_PipePipe;
1539       break;
1540     default:
1541       break;
1542     }
1543     if (OOK != OO_None) {
1544       SourceLocation OpLoc = P.ConsumeToken();
1545       SourceLocation SymbolLocations[] = {OpLoc, OpLoc, SourceLocation()};
1546       ReductionId.setOperatorFunctionId(OpLoc, OOK, SymbolLocations);
1547       return false;
1548     }
1549   }
1550   return P.ParseUnqualifiedId(ReductionIdScopeSpec, /*EnteringContext*/ false,
1551                               /*AllowDestructorName*/ false,
1552                               /*AllowConstructorName*/ false, nullptr,
1553                               TemplateKWLoc, ReductionId);
1554 }
1555
1556 /// Parses clauses with list.
1557 bool Parser::ParseOpenMPVarList(OpenMPDirectiveKind DKind,
1558                                 OpenMPClauseKind Kind,
1559                                 SmallVectorImpl<Expr *> &Vars,
1560                                 OpenMPVarListDataTy &Data) {
1561   UnqualifiedId UnqualifiedReductionId;
1562   bool InvalidReductionId = false;
1563   bool MapTypeModifierSpecified = false;
1564
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(Kind)))
1569     return true;
1570
1571   bool NeedRParenForLinear = false;
1572   BalancedDelimiterTracker LinearT(*this, tok::l_paren,
1573                                   tok::annot_pragma_openmp_end);
1574   // Handle reduction-identifier for reduction clause.
1575   if (Kind == OMPC_reduction) {
1576     ColonProtectionRAIIObject ColonRAII(*this);
1577     if (getLangOpts().CPlusPlus)
1578       ParseOptionalCXXScopeSpecifier(Data.ReductionIdScopeSpec,
1579                                      /*ObjectType=*/nullptr,
1580                                      /*EnteringContext=*/false);
1581     InvalidReductionId = ParseReductionId(*this, Data.ReductionIdScopeSpec,
1582                                           UnqualifiedReductionId);
1583     if (InvalidReductionId) {
1584       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
1585                 StopBeforeMatch);
1586     }
1587     if (Tok.is(tok::colon))
1588       Data.ColonLoc = ConsumeToken();
1589     else
1590       Diag(Tok, diag::warn_pragma_expected_colon) << "reduction identifier";
1591     if (!InvalidReductionId)
1592       Data.ReductionId =
1593           Actions.GetNameFromUnqualifiedId(UnqualifiedReductionId);
1594   } else if (Kind == OMPC_depend) {
1595   // Handle dependency type for depend clause.
1596     ColonProtectionRAIIObject ColonRAII(*this);
1597     Data.DepKind =
1598         static_cast<OpenMPDependClauseKind>(getOpenMPSimpleClauseType(
1599             Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : ""));
1600     Data.DepLinMapLoc = Tok.getLocation();
1601
1602     if (Data.DepKind == OMPC_DEPEND_unknown) {
1603       SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
1604                 StopBeforeMatch);
1605     } else {
1606       ConsumeToken();
1607       // Special processing for depend(source) clause.
1608       if (DKind == OMPD_ordered && Data.DepKind == OMPC_DEPEND_source) {
1609         // Parse ')'.
1610         T.consumeClose();
1611         return false;
1612       }
1613     }
1614     if (Tok.is(tok::colon))
1615       Data.ColonLoc = ConsumeToken();
1616     else {
1617       Diag(Tok, DKind == OMPD_ordered ? diag::warn_pragma_expected_colon_r_paren
1618                                       : diag::warn_pragma_expected_colon)
1619           << "dependency type";
1620     }
1621   } else if (Kind == OMPC_linear) {
1622     // Try to parse modifier if any.
1623     if (Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::l_paren)) {
1624       Data.LinKind = static_cast<OpenMPLinearClauseKind>(
1625           getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok)));
1626       Data.DepLinMapLoc = ConsumeToken();
1627       LinearT.consumeOpen();
1628       NeedRParenForLinear = true;
1629     }
1630   } else if (Kind == OMPC_map) {
1631     // Handle map type for map clause.
1632     ColonProtectionRAIIObject ColonRAII(*this);
1633
1634     /// The map clause modifier token can be either a identifier or the C++
1635     /// delete keyword.
1636     auto &&IsMapClauseModifierToken = [](const Token &Tok) -> bool {
1637       return Tok.isOneOf(tok::identifier, tok::kw_delete);
1638     };
1639
1640     // The first identifier may be a list item, a map-type or a
1641     // map-type-modifier. The map modifier can also be delete which has the same
1642     // spelling of the C++ delete keyword.
1643     Data.MapType =
1644         IsMapClauseModifierToken(Tok)
1645             ? static_cast<OpenMPMapClauseKind>(
1646                   getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok)))
1647             : OMPC_MAP_unknown;
1648     Data.DepLinMapLoc = Tok.getLocation();
1649     bool ColonExpected = false;
1650
1651     if (IsMapClauseModifierToken(Tok)) {
1652       if (PP.LookAhead(0).is(tok::colon)) {
1653         if (Data.MapType == OMPC_MAP_unknown)
1654           Diag(Tok, diag::err_omp_unknown_map_type);
1655         else if (Data.MapType == OMPC_MAP_always)
1656           Diag(Tok, diag::err_omp_map_type_missing);
1657         ConsumeToken();
1658       } else if (PP.LookAhead(0).is(tok::comma)) {
1659         if (IsMapClauseModifierToken(PP.LookAhead(1)) &&
1660             PP.LookAhead(2).is(tok::colon)) {
1661           Data.MapTypeModifier = Data.MapType;
1662           if (Data.MapTypeModifier != OMPC_MAP_always) {
1663             Diag(Tok, diag::err_omp_unknown_map_type_modifier);
1664             Data.MapTypeModifier = OMPC_MAP_unknown;
1665           } else
1666             MapTypeModifierSpecified = true;
1667
1668           ConsumeToken();
1669           ConsumeToken();
1670
1671           Data.MapType =
1672               IsMapClauseModifierToken(Tok)
1673                   ? static_cast<OpenMPMapClauseKind>(
1674                         getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok)))
1675                   : OMPC_MAP_unknown;
1676           if (Data.MapType == OMPC_MAP_unknown ||
1677               Data.MapType == OMPC_MAP_always)
1678             Diag(Tok, diag::err_omp_unknown_map_type);
1679           ConsumeToken();
1680         } else {
1681           Data.MapType = OMPC_MAP_tofrom;
1682           Data.IsMapTypeImplicit = true;
1683         }
1684       } else {
1685         Data.MapType = OMPC_MAP_tofrom;
1686         Data.IsMapTypeImplicit = true;
1687       }
1688     } else {
1689       Data.MapType = OMPC_MAP_tofrom;
1690       Data.IsMapTypeImplicit = true;
1691     }
1692
1693     if (Tok.is(tok::colon))
1694       Data.ColonLoc = ConsumeToken();
1695     else if (ColonExpected)
1696       Diag(Tok, diag::warn_pragma_expected_colon) << "map type";
1697   }
1698
1699   bool IsComma =
1700       (Kind != OMPC_reduction && Kind != OMPC_depend && Kind != OMPC_map) ||
1701       (Kind == OMPC_reduction && !InvalidReductionId) ||
1702       (Kind == OMPC_map && Data.MapType != OMPC_MAP_unknown &&
1703        (!MapTypeModifierSpecified ||
1704         Data.MapTypeModifier == OMPC_MAP_always)) ||
1705       (Kind == OMPC_depend && Data.DepKind != OMPC_DEPEND_unknown);
1706   const bool MayHaveTail = (Kind == OMPC_linear || Kind == OMPC_aligned);
1707   while (IsComma || (Tok.isNot(tok::r_paren) && Tok.isNot(tok::colon) &&
1708                      Tok.isNot(tok::annot_pragma_openmp_end))) {
1709     ColonProtectionRAIIObject ColonRAII(*this, MayHaveTail);
1710     // Parse variable
1711     ExprResult VarExpr =
1712         Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
1713     if (VarExpr.isUsable())
1714       Vars.push_back(VarExpr.get());
1715     else {
1716       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1717                 StopBeforeMatch);
1718     }
1719     // Skip ',' if any
1720     IsComma = Tok.is(tok::comma);
1721     if (IsComma)
1722       ConsumeToken();
1723     else if (Tok.isNot(tok::r_paren) &&
1724              Tok.isNot(tok::annot_pragma_openmp_end) &&
1725              (!MayHaveTail || Tok.isNot(tok::colon)))
1726       Diag(Tok, diag::err_omp_expected_punc)
1727           << ((Kind == OMPC_flush) ? getOpenMPDirectiveName(OMPD_flush)
1728                                    : getOpenMPClauseName(Kind))
1729           << (Kind == OMPC_flush);
1730   }
1731
1732   // Parse ')' for linear clause with modifier.
1733   if (NeedRParenForLinear)
1734     LinearT.consumeClose();
1735
1736   // Parse ':' linear-step (or ':' alignment).
1737   const bool MustHaveTail = MayHaveTail && Tok.is(tok::colon);
1738   if (MustHaveTail) {
1739     Data.ColonLoc = Tok.getLocation();
1740     SourceLocation ELoc = ConsumeToken();
1741     ExprResult Tail = ParseAssignmentExpression();
1742     Tail = Actions.ActOnFinishFullExpr(Tail.get(), ELoc);
1743     if (Tail.isUsable())
1744       Data.TailExpr = Tail.get();
1745     else
1746       SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1747                 StopBeforeMatch);
1748   }
1749
1750   // Parse ')'.
1751   T.consumeClose();
1752   if ((Kind == OMPC_depend && Data.DepKind != OMPC_DEPEND_unknown &&
1753        Vars.empty()) ||
1754       (Kind != OMPC_depend && Kind != OMPC_map && Vars.empty()) ||
1755       (MustHaveTail && !Data.TailExpr) || InvalidReductionId)
1756     return true;
1757   return false;
1758 }
1759
1760 /// \brief Parsing of OpenMP clause 'private', 'firstprivate', 'lastprivate',
1761 /// 'shared', 'copyin', 'copyprivate', 'flush' or 'reduction'.
1762 ///
1763 ///    private-clause:
1764 ///       'private' '(' list ')'
1765 ///    firstprivate-clause:
1766 ///       'firstprivate' '(' list ')'
1767 ///    lastprivate-clause:
1768 ///       'lastprivate' '(' list ')'
1769 ///    shared-clause:
1770 ///       'shared' '(' list ')'
1771 ///    linear-clause:
1772 ///       'linear' '(' linear-list [ ':' linear-step ] ')'
1773 ///    aligned-clause:
1774 ///       'aligned' '(' list [ ':' alignment ] ')'
1775 ///    reduction-clause:
1776 ///       'reduction' '(' reduction-identifier ':' list ')'
1777 ///    copyprivate-clause:
1778 ///       'copyprivate' '(' list ')'
1779 ///    flush-clause:
1780 ///       'flush' '(' list ')'
1781 ///    depend-clause:
1782 ///       'depend' '(' in | out | inout : list | source ')'
1783 ///    map-clause:
1784 ///       'map' '(' [ [ always , ]
1785 ///          to | from | tofrom | alloc | release | delete ':' ] list ')';
1786 ///    to-clause:
1787 ///       'to' '(' list ')'
1788 ///    from-clause:
1789 ///       'from' '(' list ')'
1790 ///    use_device_ptr-clause:
1791 ///       'use_device_ptr' '(' list ')'
1792 ///    is_device_ptr-clause:
1793 ///       'is_device_ptr' '(' list ')'
1794 ///
1795 /// For 'linear' clause linear-list may have the following forms:
1796 ///  list
1797 ///  modifier(list)
1798 /// where modifier is 'val' (C) or 'ref', 'val' or 'uval'(C++).
1799 OMPClause *Parser::ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
1800                                             OpenMPClauseKind Kind) {
1801   SourceLocation Loc = Tok.getLocation();
1802   SourceLocation LOpen = ConsumeToken();
1803   SmallVector<Expr *, 4> Vars;
1804   OpenMPVarListDataTy Data;
1805
1806   if (ParseOpenMPVarList(DKind, Kind, Vars, Data))
1807     return nullptr;
1808
1809   return Actions.ActOnOpenMPVarListClause(
1810       Kind, Vars, Data.TailExpr, Loc, LOpen, Data.ColonLoc, Tok.getLocation(),
1811       Data.ReductionIdScopeSpec, Data.ReductionId, Data.DepKind, Data.LinKind,
1812       Data.MapTypeModifier, Data.MapType, Data.IsMapTypeImplicit,
1813       Data.DepLinMapLoc);
1814 }
1815