ParseOpenMP.cpp 103 KB

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