ParseOpenMP.cpp 161 KB

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