123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372 |
- //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
- //
- // The LLVM Compiler Infrastructure
- //
- // This file is distributed under the University of Illinois Open Source
- // License. See LICENSE.TXT for details.
- //
- //===----------------------------------------------------------------------===//
- /// \file
- /// \brief This file implements semantic analysis for OpenMP directives and
- /// clauses.
- ///
- //===----------------------------------------------------------------------===//
- #include "TreeTransform.h"
- #include "clang/AST/ASTContext.h"
- #include "clang/AST/ASTMutationListener.h"
- #include "clang/AST/Decl.h"
- #include "clang/AST/DeclCXX.h"
- #include "clang/AST/DeclOpenMP.h"
- #include "clang/AST/StmtCXX.h"
- #include "clang/AST/StmtOpenMP.h"
- #include "clang/AST/StmtVisitor.h"
- #include "clang/Basic/OpenMPKinds.h"
- #include "clang/Basic/TargetInfo.h"
- #include "clang/Lex/Preprocessor.h"
- #include "clang/Sema/Initialization.h"
- #include "clang/Sema/Lookup.h"
- #include "clang/Sema/Scope.h"
- #include "clang/Sema/ScopeInfo.h"
- #include "clang/Sema/SemaInternal.h"
- using namespace clang;
- //===----------------------------------------------------------------------===//
- // Stack of data-sharing attributes for variables
- //===----------------------------------------------------------------------===//
- namespace {
- /// \brief Default data sharing attributes, which can be applied to directive.
- enum DefaultDataSharingAttributes {
- DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
- DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
- DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
- };
- template <class T> struct MatchesAny {
- explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
- bool operator()(T Kind) {
- for (auto KindEl : Arr)
- if (KindEl == Kind)
- return true;
- return false;
- }
- private:
- ArrayRef<T> Arr;
- };
- struct MatchesAlways {
- MatchesAlways() {}
- template <class T> bool operator()(T) { return true; }
- };
- typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
- typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
- /// \brief Stack for tracking declarations used in OpenMP directives and
- /// clauses and their data-sharing attributes.
- class DSAStackTy {
- public:
- struct DSAVarData {
- OpenMPDirectiveKind DKind;
- OpenMPClauseKind CKind;
- Expr *RefExpr;
- SourceLocation ImplicitDSALoc;
- DSAVarData()
- : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
- ImplicitDSALoc() {}
- };
- private:
- typedef SmallVector<Expr *, 4> MapInfo;
- struct DSAInfo {
- OpenMPClauseKind Attributes;
- Expr *RefExpr;
- };
- typedef llvm::SmallDenseMap<ValueDecl *, DSAInfo, 64> DeclSAMapTy;
- typedef llvm::SmallDenseMap<ValueDecl *, Expr *, 64> AlignedMapTy;
- typedef llvm::DenseMap<ValueDecl *, unsigned> LoopControlVariablesMapTy;
- typedef llvm::SmallDenseMap<ValueDecl *, MapInfo, 64> MappedDeclsTy;
- typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
- CriticalsWithHintsTy;
- struct SharingMapTy {
- DeclSAMapTy SharingMap;
- AlignedMapTy AlignedMap;
- MappedDeclsTy MappedDecls;
- LoopControlVariablesMapTy LCVMap;
- DefaultDataSharingAttributes DefaultAttr;
- SourceLocation DefaultAttrLoc;
- OpenMPDirectiveKind Directive;
- DeclarationNameInfo DirectiveName;
- Scope *CurScope;
- SourceLocation ConstructLoc;
- /// \brief first argument (Expr *) contains optional argument of the
- /// 'ordered' clause, the second one is true if the regions has 'ordered'
- /// clause, false otherwise.
- llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
- bool NowaitRegion;
- bool CancelRegion;
- unsigned AssociatedLoops;
- SourceLocation InnerTeamsRegionLoc;
- SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
- Scope *CurScope, SourceLocation Loc)
- : SharingMap(), AlignedMap(), LCVMap(), DefaultAttr(DSA_unspecified),
- Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
- ConstructLoc(Loc), OrderedRegion(), NowaitRegion(false),
- CancelRegion(false), AssociatedLoops(1), InnerTeamsRegionLoc() {}
- SharingMapTy()
- : SharingMap(), AlignedMap(), LCVMap(), DefaultAttr(DSA_unspecified),
- Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
- ConstructLoc(), OrderedRegion(), NowaitRegion(false),
- CancelRegion(false), AssociatedLoops(1), InnerTeamsRegionLoc() {}
- };
- typedef SmallVector<SharingMapTy, 64> StackTy;
- /// \brief Stack of used declaration and their data-sharing attributes.
- StackTy Stack;
- /// \brief true, if check for DSA must be from parent directive, false, if
- /// from current directive.
- OpenMPClauseKind ClauseKindMode;
- Sema &SemaRef;
- bool ForceCapturing;
- CriticalsWithHintsTy Criticals;
- typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
- DSAVarData getDSA(StackTy::reverse_iterator Iter, ValueDecl *D);
- /// \brief Checks if the variable is a local for OpenMP region.
- bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
- public:
- explicit DSAStackTy(Sema &S)
- : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S),
- ForceCapturing(false) {}
- bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
- void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
- bool isForceVarCapturing() const { return ForceCapturing; }
- void setForceVarCapturing(bool V) { ForceCapturing = V; }
- void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
- Scope *CurScope, SourceLocation Loc) {
- Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
- Stack.back().DefaultAttrLoc = Loc;
- }
- void pop() {
- assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
- Stack.pop_back();
- }
- void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
- Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
- }
- const std::pair<OMPCriticalDirective *, llvm::APSInt>
- getCriticalWithHint(const DeclarationNameInfo &Name) const {
- auto I = Criticals.find(Name.getAsString());
- if (I != Criticals.end())
- return I->second;
- return std::make_pair(nullptr, llvm::APSInt());
- }
- /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
- /// add it and return NULL; otherwise return previous occurrence's expression
- /// for diagnostics.
- Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
- /// \brief Register specified variable as loop control variable.
- void addLoopControlVariable(ValueDecl *D);
- /// \brief Check if the specified variable is a loop control variable for
- /// current region.
- /// \return The index of the loop control variable in the list of associated
- /// for-loops (from outer to inner).
- unsigned isLoopControlVariable(ValueDecl *D);
- /// \brief Check if the specified variable is a loop control variable for
- /// parent region.
- /// \return The index of the loop control variable in the list of associated
- /// for-loops (from outer to inner).
- unsigned isParentLoopControlVariable(ValueDecl *D);
- /// \brief Get the loop control variable for the I-th loop (or nullptr) in
- /// parent directive.
- ValueDecl *getParentLoopControlVariable(unsigned I);
- /// \brief Adds explicit data sharing attribute to the specified declaration.
- void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A);
- /// \brief Returns data sharing attributes from top of the stack for the
- /// specified declaration.
- DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
- /// \brief Returns data-sharing attributes for the specified declaration.
- DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
- /// \brief Checks if the specified variables has data-sharing attributes which
- /// match specified \a CPred predicate in any directive which matches \a DPred
- /// predicate.
- template <class ClausesPredicate, class DirectivesPredicate>
- DSAVarData hasDSA(ValueDecl *D, ClausesPredicate CPred,
- DirectivesPredicate DPred, bool FromParent);
- /// \brief Checks if the specified variables has data-sharing attributes which
- /// match specified \a CPred predicate in any innermost directive which
- /// matches \a DPred predicate.
- template <class ClausesPredicate, class DirectivesPredicate>
- DSAVarData hasInnermostDSA(ValueDecl *D, ClausesPredicate CPred,
- DirectivesPredicate DPred, bool FromParent);
- /// \brief Checks if the specified variables has explicit data-sharing
- /// attributes which match specified \a CPred predicate at the specified
- /// OpenMP region.
- bool hasExplicitDSA(ValueDecl *D,
- const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
- unsigned Level);
- /// \brief Returns true if the directive at level \Level matches in the
- /// specified \a DPred predicate.
- bool hasExplicitDirective(
- const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
- unsigned Level);
- /// \brief Finds a directive which matches specified \a DPred predicate.
- template <class NamedDirectivesPredicate>
- bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
- /// \brief Returns currently analyzed directive.
- OpenMPDirectiveKind getCurrentDirective() const {
- return Stack.back().Directive;
- }
- /// \brief Returns parent directive.
- OpenMPDirectiveKind getParentDirective() const {
- if (Stack.size() > 2)
- return Stack[Stack.size() - 2].Directive;
- return OMPD_unknown;
- }
- /// \brief Return the directive associated with the provided scope.
- OpenMPDirectiveKind getDirectiveForScope(const Scope *S) const;
- /// \brief Set default data sharing attribute to none.
- void setDefaultDSANone(SourceLocation Loc) {
- Stack.back().DefaultAttr = DSA_none;
- Stack.back().DefaultAttrLoc = Loc;
- }
- /// \brief Set default data sharing attribute to shared.
- void setDefaultDSAShared(SourceLocation Loc) {
- Stack.back().DefaultAttr = DSA_shared;
- Stack.back().DefaultAttrLoc = Loc;
- }
- DefaultDataSharingAttributes getDefaultDSA() const {
- return Stack.back().DefaultAttr;
- }
- SourceLocation getDefaultDSALocation() const {
- return Stack.back().DefaultAttrLoc;
- }
- /// \brief Checks if the specified variable is a threadprivate.
- bool isThreadPrivate(VarDecl *D) {
- DSAVarData DVar = getTopDSA(D, false);
- return isOpenMPThreadPrivate(DVar.CKind);
- }
- /// \brief Marks current region as ordered (it has an 'ordered' clause).
- void setOrderedRegion(bool IsOrdered, Expr *Param) {
- Stack.back().OrderedRegion.setInt(IsOrdered);
- Stack.back().OrderedRegion.setPointer(Param);
- }
- /// \brief Returns true, if parent region is ordered (has associated
- /// 'ordered' clause), false - otherwise.
- bool isParentOrderedRegion() const {
- if (Stack.size() > 2)
- return Stack[Stack.size() - 2].OrderedRegion.getInt();
- return false;
- }
- /// \brief Returns optional parameter for the ordered region.
- Expr *getParentOrderedRegionParam() const {
- if (Stack.size() > 2)
- return Stack[Stack.size() - 2].OrderedRegion.getPointer();
- return nullptr;
- }
- /// \brief Marks current region as nowait (it has a 'nowait' clause).
- void setNowaitRegion(bool IsNowait = true) {
- Stack.back().NowaitRegion = IsNowait;
- }
- /// \brief Returns true, if parent region is nowait (has associated
- /// 'nowait' clause), false - otherwise.
- bool isParentNowaitRegion() const {
- if (Stack.size() > 2)
- return Stack[Stack.size() - 2].NowaitRegion;
- return false;
- }
- /// \brief Marks parent region as cancel region.
- void setParentCancelRegion(bool Cancel = true) {
- if (Stack.size() > 2)
- Stack[Stack.size() - 2].CancelRegion =
- Stack[Stack.size() - 2].CancelRegion || Cancel;
- }
- /// \brief Return true if current region has inner cancel construct.
- bool isCancelRegion() const {
- return Stack.back().CancelRegion;
- }
- /// \brief Set collapse value for the region.
- void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
- /// \brief Return collapse value for region.
- unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
- /// \brief Marks current target region as one with closely nested teams
- /// region.
- void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
- if (Stack.size() > 2)
- Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
- }
- /// \brief Returns true, if current region has closely nested teams region.
- bool hasInnerTeamsRegion() const {
- return getInnerTeamsRegionLoc().isValid();
- }
- /// \brief Returns location of the nested teams region (if any).
- SourceLocation getInnerTeamsRegionLoc() const {
- if (Stack.size() > 1)
- return Stack.back().InnerTeamsRegionLoc;
- return SourceLocation();
- }
- Scope *getCurScope() const { return Stack.back().CurScope; }
- Scope *getCurScope() { return Stack.back().CurScope; }
- SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
- // Do the check specified in MapInfoCheck and return true if any issue is
- // found.
- template <class MapInfoCheck>
- bool checkMapInfoForVar(ValueDecl *VD, bool CurrentRegionOnly,
- MapInfoCheck Check) {
- auto SI = Stack.rbegin();
- auto SE = Stack.rend();
- if (SI == SE)
- return false;
- if (CurrentRegionOnly) {
- SE = std::next(SI);
- } else {
- ++SI;
- }
- for (; SI != SE; ++SI) {
- auto MI = SI->MappedDecls.find(VD);
- if (MI != SI->MappedDecls.end()) {
- for (Expr *E : MI->second) {
- if (Check(E))
- return true;
- }
- }
- }
- return false;
- }
- void addExprToVarMapInfo(ValueDecl *VD, Expr *E) {
- if (Stack.size() > 1) {
- Stack.back().MappedDecls[VD].push_back(E);
- }
- }
- };
- bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
- return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
- isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown ||
- isOpenMPTaskLoopDirective(DKind);
- }
- } // namespace
- static ValueDecl *getCanonicalDecl(ValueDecl *D) {
- auto *VD = dyn_cast<VarDecl>(D);
- auto *FD = dyn_cast<FieldDecl>(D);
- if (VD != nullptr) {
- VD = VD->getCanonicalDecl();
- D = VD;
- } else {
- assert(FD);
- FD = FD->getCanonicalDecl();
- D = FD;
- }
- return D;
- }
- DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
- ValueDecl *D) {
- D = getCanonicalDecl(D);
- auto *VD = dyn_cast<VarDecl>(D);
- auto *FD = dyn_cast<FieldDecl>(D);
- DSAVarData DVar;
- if (Iter == std::prev(Stack.rend())) {
- // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
- // in a region but not in construct]
- // File-scope or namespace-scope variables referenced in called routines
- // in the region are shared unless they appear in a threadprivate
- // directive.
- if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
- DVar.CKind = OMPC_shared;
- // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
- // in a region but not in construct]
- // Variables with static storage duration that are declared in called
- // routines in the region are shared.
- if (VD && VD->hasGlobalStorage())
- DVar.CKind = OMPC_shared;
- // Non-static data members are shared by default.
- if (FD)
- DVar.CKind = OMPC_shared;
- return DVar;
- }
- DVar.DKind = Iter->Directive;
- // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
- // in a Construct, C/C++, predetermined, p.1]
- // Variables with automatic storage duration that are declared in a scope
- // inside the construct are private.
- if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
- (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
- DVar.CKind = OMPC_private;
- return DVar;
- }
- // Explicitly specified attributes and local variables with predetermined
- // attributes.
- if (Iter->SharingMap.count(D)) {
- DVar.RefExpr = Iter->SharingMap[D].RefExpr;
- DVar.CKind = Iter->SharingMap[D].Attributes;
- DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
- return DVar;
- }
- // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
- // in a Construct, C/C++, implicitly determined, p.1]
- // In a parallel or task construct, the data-sharing attributes of these
- // variables are determined by the default clause, if present.
- switch (Iter->DefaultAttr) {
- case DSA_shared:
- DVar.CKind = OMPC_shared;
- DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
- return DVar;
- case DSA_none:
- return DVar;
- case DSA_unspecified:
- // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
- // in a Construct, implicitly determined, p.2]
- // In a parallel construct, if no default clause is present, these
- // variables are shared.
- DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
- if (isOpenMPParallelDirective(DVar.DKind) ||
- isOpenMPTeamsDirective(DVar.DKind)) {
- DVar.CKind = OMPC_shared;
- return DVar;
- }
- // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
- // in a Construct, implicitly determined, p.4]
- // In a task construct, if no default clause is present, a variable that in
- // the enclosing context is determined to be shared by all implicit tasks
- // bound to the current team is shared.
- if (DVar.DKind == OMPD_task) {
- DSAVarData DVarTemp;
- for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
- I != EE; ++I) {
- // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
- // Referenced
- // in a Construct, implicitly determined, p.6]
- // In a task construct, if no default clause is present, a variable
- // whose data-sharing attribute is not determined by the rules above is
- // firstprivate.
- DVarTemp = getDSA(I, D);
- if (DVarTemp.CKind != OMPC_shared) {
- DVar.RefExpr = nullptr;
- DVar.DKind = OMPD_task;
- DVar.CKind = OMPC_firstprivate;
- return DVar;
- }
- if (isParallelOrTaskRegion(I->Directive))
- break;
- }
- DVar.DKind = OMPD_task;
- DVar.CKind =
- (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
- return DVar;
- }
- }
- // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
- // in a Construct, implicitly determined, p.3]
- // For constructs other than task, if no default clause is present, these
- // variables inherit their data-sharing attributes from the enclosing
- // context.
- return getDSA(std::next(Iter), D);
- }
- Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
- assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
- D = getCanonicalDecl(D);
- auto It = Stack.back().AlignedMap.find(D);
- if (It == Stack.back().AlignedMap.end()) {
- assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
- Stack.back().AlignedMap[D] = NewDE;
- return nullptr;
- } else {
- assert(It->second && "Unexpected nullptr expr in the aligned map");
- return It->second;
- }
- return nullptr;
- }
- void DSAStackTy::addLoopControlVariable(ValueDecl *D) {
- assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
- D = getCanonicalDecl(D);
- Stack.back().LCVMap.insert(std::make_pair(D, Stack.back().LCVMap.size() + 1));
- }
- unsigned DSAStackTy::isLoopControlVariable(ValueDecl *D) {
- assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
- D = getCanonicalDecl(D);
- return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D] : 0;
- }
- unsigned DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
- assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
- D = getCanonicalDecl(D);
- return Stack[Stack.size() - 2].LCVMap.count(D) > 0
- ? Stack[Stack.size() - 2].LCVMap[D]
- : 0;
- }
- ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
- assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
- if (Stack[Stack.size() - 2].LCVMap.size() < I)
- return nullptr;
- for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
- if (Pair.second == I)
- return Pair.first;
- }
- return nullptr;
- }
- void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A) {
- D = getCanonicalDecl(D);
- if (A == OMPC_threadprivate) {
- Stack[0].SharingMap[D].Attributes = A;
- Stack[0].SharingMap[D].RefExpr = E;
- } else {
- assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
- Stack.back().SharingMap[D].Attributes = A;
- Stack.back().SharingMap[D].RefExpr = E;
- }
- }
- bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
- D = D->getCanonicalDecl();
- if (Stack.size() > 2) {
- reverse_iterator I = Iter, E = std::prev(Stack.rend());
- Scope *TopScope = nullptr;
- while (I != E && !isParallelOrTaskRegion(I->Directive)) {
- ++I;
- }
- if (I == E)
- return false;
- TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
- Scope *CurScope = getCurScope();
- while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
- CurScope = CurScope->getParent();
- }
- return CurScope != TopScope;
- }
- return false;
- }
- /// \brief Build a variable declaration for OpenMP loop iteration variable.
- static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
- StringRef Name, const AttrVec *Attrs = nullptr) {
- DeclContext *DC = SemaRef.CurContext;
- IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
- TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
- VarDecl *Decl =
- VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
- if (Attrs) {
- for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
- I != E; ++I)
- Decl->addAttr(*I);
- }
- Decl->setImplicit();
- return Decl;
- }
- static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
- SourceLocation Loc,
- bool RefersToCapture = false) {
- D->setReferenced();
- D->markUsed(S.Context);
- return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
- SourceLocation(), D, RefersToCapture, Loc, Ty,
- VK_LValue);
- }
- DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
- D = getCanonicalDecl(D);
- DSAVarData DVar;
- // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
- // in a Construct, C/C++, predetermined, p.1]
- // Variables appearing in threadprivate directives are threadprivate.
- auto *VD = dyn_cast<VarDecl>(D);
- if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
- !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
- SemaRef.getLangOpts().OpenMPUseTLS &&
- SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
- (VD && VD->getStorageClass() == SC_Register &&
- VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
- addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
- D->getLocation()),
- OMPC_threadprivate);
- }
- if (Stack[0].SharingMap.count(D)) {
- DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
- DVar.CKind = OMPC_threadprivate;
- return DVar;
- }
- // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
- // in a Construct, C/C++, predetermined, p.4]
- // Static data members are shared.
- // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
- // in a Construct, C/C++, predetermined, p.7]
- // Variables with static storage duration that are declared in a scope
- // inside the construct are shared.
- if (VD && VD->isStaticDataMember()) {
- DSAVarData DVarTemp =
- hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
- if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
- return DVar;
- DVar.CKind = OMPC_shared;
- return DVar;
- }
- QualType Type = D->getType().getNonReferenceType().getCanonicalType();
- bool IsConstant = Type.isConstant(SemaRef.getASTContext());
- Type = SemaRef.getASTContext().getBaseElementType(Type);
- // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
- // in a Construct, C/C++, predetermined, p.6]
- // Variables with const qualified type having no mutable member are
- // shared.
- CXXRecordDecl *RD =
- SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
- if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
- if (auto *CTD = CTSD->getSpecializedTemplate())
- RD = CTD->getTemplatedDecl();
- if (IsConstant &&
- !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
- // Variables with const-qualified type having no mutable member may be
- // listed in a firstprivate clause, even if they are static data members.
- DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
- MatchesAlways(), FromParent);
- if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
- return DVar;
- DVar.CKind = OMPC_shared;
- return DVar;
- }
- // Explicitly specified attributes and local variables with predetermined
- // attributes.
- auto StartI = std::next(Stack.rbegin());
- auto EndI = std::prev(Stack.rend());
- if (FromParent && StartI != EndI) {
- StartI = std::next(StartI);
- }
- auto I = std::prev(StartI);
- if (I->SharingMap.count(D)) {
- DVar.RefExpr = I->SharingMap[D].RefExpr;
- DVar.CKind = I->SharingMap[D].Attributes;
- DVar.ImplicitDSALoc = I->DefaultAttrLoc;
- }
- return DVar;
- }
- DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
- bool FromParent) {
- D = getCanonicalDecl(D);
- auto StartI = Stack.rbegin();
- auto EndI = std::prev(Stack.rend());
- if (FromParent && StartI != EndI) {
- StartI = std::next(StartI);
- }
- return getDSA(StartI, D);
- }
- template <class ClausesPredicate, class DirectivesPredicate>
- DSAStackTy::DSAVarData DSAStackTy::hasDSA(ValueDecl *D, ClausesPredicate CPred,
- DirectivesPredicate DPred,
- bool FromParent) {
- D = getCanonicalDecl(D);
- auto StartI = std::next(Stack.rbegin());
- auto EndI = std::prev(Stack.rend());
- if (FromParent && StartI != EndI) {
- StartI = std::next(StartI);
- }
- for (auto I = StartI, EE = EndI; I != EE; ++I) {
- if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
- continue;
- DSAVarData DVar = getDSA(I, D);
- if (CPred(DVar.CKind))
- return DVar;
- }
- return DSAVarData();
- }
- template <class ClausesPredicate, class DirectivesPredicate>
- DSAStackTy::DSAVarData
- DSAStackTy::hasInnermostDSA(ValueDecl *D, ClausesPredicate CPred,
- DirectivesPredicate DPred, bool FromParent) {
- D = getCanonicalDecl(D);
- auto StartI = std::next(Stack.rbegin());
- auto EndI = std::prev(Stack.rend());
- if (FromParent && StartI != EndI) {
- StartI = std::next(StartI);
- }
- for (auto I = StartI, EE = EndI; I != EE; ++I) {
- if (!DPred(I->Directive))
- break;
- DSAVarData DVar = getDSA(I, D);
- if (CPred(DVar.CKind))
- return DVar;
- return DSAVarData();
- }
- return DSAVarData();
- }
- bool DSAStackTy::hasExplicitDSA(
- ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
- unsigned Level) {
- if (CPred(ClauseKindMode))
- return true;
- if (isClauseParsingMode())
- ++Level;
- D = getCanonicalDecl(D);
- auto StartI = Stack.rbegin();
- auto EndI = std::prev(Stack.rend());
- if (std::distance(StartI, EndI) <= (int)Level)
- return false;
- std::advance(StartI, Level);
- return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
- CPred(StartI->SharingMap[D].Attributes);
- }
- bool DSAStackTy::hasExplicitDirective(
- const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
- unsigned Level) {
- if (isClauseParsingMode())
- ++Level;
- auto StartI = Stack.rbegin();
- auto EndI = std::prev(Stack.rend());
- if (std::distance(StartI, EndI) <= (int)Level)
- return false;
- std::advance(StartI, Level);
- return DPred(StartI->Directive);
- }
- template <class NamedDirectivesPredicate>
- bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
- auto StartI = std::next(Stack.rbegin());
- auto EndI = std::prev(Stack.rend());
- if (FromParent && StartI != EndI) {
- StartI = std::next(StartI);
- }
- for (auto I = StartI, EE = EndI; I != EE; ++I) {
- if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
- return true;
- }
- return false;
- }
- OpenMPDirectiveKind DSAStackTy::getDirectiveForScope(const Scope *S) const {
- for (auto I = Stack.rbegin(), EE = Stack.rend(); I != EE; ++I)
- if (I->CurScope == S)
- return I->Directive;
- return OMPD_unknown;
- }
- void Sema::InitDataSharingAttributesStack() {
- VarDataSharingAttributesStack = new DSAStackTy(*this);
- }
- #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
- bool Sema::IsOpenMPCapturedByRef(ValueDecl *D,
- const CapturedRegionScopeInfo *RSI) {
- assert(LangOpts.OpenMP && "OpenMP is not allowed");
- auto &Ctx = getASTContext();
- bool IsByRef = true;
- // Find the directive that is associated with the provided scope.
- auto DKind = DSAStack->getDirectiveForScope(RSI->TheScope);
- auto Ty = D->getType();
- if (isOpenMPTargetExecutionDirective(DKind)) {
- // This table summarizes how a given variable should be passed to the device
- // given its type and the clauses where it appears. This table is based on
- // the description in OpenMP 4.5 [2.10.4, target Construct] and
- // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
- //
- // =========================================================================
- // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
- // | |(tofrom:scalar)| | pvt | | | |
- // =========================================================================
- // | scl | | | | - | | bycopy|
- // | scl | | - | x | - | - | bycopy|
- // | scl | | x | - | - | - | null |
- // | scl | x | | | - | | byref |
- // | scl | x | - | x | - | - | bycopy|
- // | scl | x | x | - | - | - | null |
- // | scl | | - | - | - | x | byref |
- // | scl | x | - | - | - | x | byref |
- //
- // | agg | n.a. | | | - | | byref |
- // | agg | n.a. | - | x | - | - | byref |
- // | agg | n.a. | x | - | - | - | null |
- // | agg | n.a. | - | - | - | x | byref |
- // | agg | n.a. | - | - | - | x[] | byref |
- //
- // | ptr | n.a. | | | - | | bycopy|
- // | ptr | n.a. | - | x | - | - | bycopy|
- // | ptr | n.a. | x | - | - | - | null |
- // | ptr | n.a. | - | - | - | x | byref |
- // | ptr | n.a. | - | - | - | x[] | bycopy|
- // | ptr | n.a. | - | - | x | | bycopy|
- // | ptr | n.a. | - | - | x | x | bycopy|
- // | ptr | n.a. | - | - | x | x[] | bycopy|
- // =========================================================================
- // Legend:
- // scl - scalar
- // ptr - pointer
- // agg - aggregate
- // x - applies
- // - - invalid in this combination
- // [] - mapped with an array section
- // byref - should be mapped by reference
- // byval - should be mapped by value
- // null - initialize a local variable to null on the device
- //
- // Observations:
- // - All scalar declarations that show up in a map clause have to be passed
- // by reference, because they may have been mapped in the enclosing data
- // environment.
- // - If the scalar value does not fit the size of uintptr, it has to be
- // passed by reference, regardless the result in the table above.
- // - For pointers mapped by value that have either an implicit map or an
- // array section, the runtime library may pass the NULL value to the
- // device instead of the value passed to it by the compiler.
- // FIXME: Right now, only implicit maps are implemented. Properly mapping
- // values requires having the map, private, and firstprivate clauses SEMA
- // and parsing in place, which we don't yet.
- if (Ty->isReferenceType())
- Ty = Ty->castAs<ReferenceType>()->getPointeeType();
- IsByRef = !Ty->isScalarType();
- }
- // When passing data by value, we need to make sure it fits the uintptr size
- // and alignment, because the runtime library only deals with uintptr types.
- // If it does not fit the uintptr size, we need to pass the data by reference
- // instead.
- if (!IsByRef &&
- (Ctx.getTypeSizeInChars(Ty) >
- Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
- Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType())))
- IsByRef = true;
- return IsByRef;
- }
- bool Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
- assert(LangOpts.OpenMP && "OpenMP is not allowed");
- D = getCanonicalDecl(D);
- // If we are attempting to capture a global variable in a directive with
- // 'target' we return true so that this global is also mapped to the device.
- //
- // FIXME: If the declaration is enclosed in a 'declare target' directive,
- // then it should not be captured. Therefore, an extra check has to be
- // inserted here once support for 'declare target' is added.
- //
- auto *VD = dyn_cast<VarDecl>(D);
- if (VD && !VD->hasLocalStorage()) {
- if (DSAStack->getCurrentDirective() == OMPD_target &&
- !DSAStack->isClauseParsingMode()) {
- return true;
- }
- if (DSAStack->getCurScope() &&
- DSAStack->hasDirective(
- [](OpenMPDirectiveKind K, const DeclarationNameInfo &DNI,
- SourceLocation Loc) -> bool {
- return isOpenMPTargetExecutionDirective(K);
- },
- false)) {
- return true;
- }
- }
- if (DSAStack->getCurrentDirective() != OMPD_unknown &&
- (!DSAStack->isClauseParsingMode() ||
- DSAStack->getParentDirective() != OMPD_unknown)) {
- if (DSAStack->isLoopControlVariable(D) ||
- (VD && VD->hasLocalStorage() &&
- isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
- (VD && DSAStack->isForceVarCapturing()))
- return true;
- auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
- if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
- return true;
- DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate, MatchesAlways(),
- DSAStack->isClauseParsingMode());
- return DVarPrivate.CKind != OMPC_unknown;
- }
- return false;
- }
- bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
- assert(LangOpts.OpenMP && "OpenMP is not allowed");
- return DSAStack->hasExplicitDSA(
- D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
- }
- bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
- assert(LangOpts.OpenMP && "OpenMP is not allowed");
- // Return true if the current level is no longer enclosed in a target region.
- auto *VD = dyn_cast<VarDecl>(D);
- return VD && !VD->hasLocalStorage() &&
- DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
- Level);
- }
- void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
- void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
- const DeclarationNameInfo &DirName,
- Scope *CurScope, SourceLocation Loc) {
- DSAStack->push(DKind, DirName, CurScope, Loc);
- PushExpressionEvaluationContext(PotentiallyEvaluated);
- }
- void Sema::StartOpenMPClause(OpenMPClauseKind K) {
- DSAStack->setClauseParsingMode(K);
- }
- void Sema::EndOpenMPClause() {
- DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
- }
- void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
- // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
- // A variable of class type (or array thereof) that appears in a lastprivate
- // clause requires an accessible, unambiguous default constructor for the
- // class type, unless the list item is also specified in a firstprivate
- // clause.
- if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
- for (auto *C : D->clauses()) {
- if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
- SmallVector<Expr *, 8> PrivateCopies;
- for (auto *DE : Clause->varlists()) {
- if (DE->isValueDependent() || DE->isTypeDependent()) {
- PrivateCopies.push_back(nullptr);
- continue;
- }
- DE = DE->IgnoreParens();
- VarDecl *VD = nullptr;
- FieldDecl *FD = nullptr;
- ValueDecl *D;
- if (auto *DRE = dyn_cast<DeclRefExpr>(DE)) {
- VD = cast<VarDecl>(DRE->getDecl());
- D = VD;
- } else {
- assert(isa<MemberExpr>(DE));
- FD = cast<FieldDecl>(cast<MemberExpr>(DE)->getMemberDecl());
- D = FD;
- }
- QualType Type = D->getType().getNonReferenceType();
- auto DVar = DSAStack->getTopDSA(D, false);
- if (DVar.CKind == OMPC_lastprivate) {
- // Generate helper private variable and initialize it with the
- // default value. The address of the original variable is replaced
- // by the address of the new private variable in CodeGen. This new
- // variable is not added to IdResolver, so the code in the OpenMP
- // region uses original variable for proper diagnostics.
- auto *VDPrivate = buildVarDecl(
- *this, DE->getExprLoc(), Type.getUnqualifiedType(),
- D->getName(), D->hasAttrs() ? &D->getAttrs() : nullptr);
- ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
- if (VDPrivate->isInvalidDecl())
- continue;
- PrivateCopies.push_back(buildDeclRefExpr(
- *this, VDPrivate, DE->getType(), DE->getExprLoc()));
- } else {
- // The variable is also a firstprivate, so initialization sequence
- // for private copy is generated already.
- PrivateCopies.push_back(nullptr);
- }
- }
- // Set initializers to private copies if no errors were found.
- if (PrivateCopies.size() == Clause->varlist_size())
- Clause->setPrivateCopies(PrivateCopies);
- }
- }
- }
- DSAStack->pop();
- DiscardCleanupsInEvaluationContext();
- PopExpressionEvaluationContext();
- }
- static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
- Expr *NumIterations, Sema &SemaRef,
- Scope *S);
- namespace {
- class VarDeclFilterCCC : public CorrectionCandidateCallback {
- private:
- Sema &SemaRef;
- public:
- explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
- bool ValidateCandidate(const TypoCorrection &Candidate) override {
- NamedDecl *ND = Candidate.getCorrectionDecl();
- if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
- return VD->hasGlobalStorage() &&
- SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
- SemaRef.getCurScope());
- }
- return false;
- }
- };
- } // namespace
- ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
- CXXScopeSpec &ScopeSpec,
- const DeclarationNameInfo &Id) {
- LookupResult Lookup(*this, Id, LookupOrdinaryName);
- LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
- if (Lookup.isAmbiguous())
- return ExprError();
- VarDecl *VD;
- if (!Lookup.isSingleResult()) {
- if (TypoCorrection Corrected = CorrectTypo(
- Id, LookupOrdinaryName, CurScope, nullptr,
- llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
- diagnoseTypo(Corrected,
- PDiag(Lookup.empty()
- ? diag::err_undeclared_var_use_suggest
- : diag::err_omp_expected_var_arg_suggest)
- << Id.getName());
- VD = Corrected.getCorrectionDeclAs<VarDecl>();
- } else {
- Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
- : diag::err_omp_expected_var_arg)
- << Id.getName();
- return ExprError();
- }
- } else {
- if (!(VD = Lookup.getAsSingle<VarDecl>())) {
- Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
- Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
- return ExprError();
- }
- }
- Lookup.suppressDiagnostics();
- // OpenMP [2.9.2, Syntax, C/C++]
- // Variables must be file-scope, namespace-scope, or static block-scope.
- if (!VD->hasGlobalStorage()) {
- Diag(Id.getLoc(), diag::err_omp_global_var_arg)
- << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
- bool IsDecl =
- VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
- Diag(VD->getLocation(),
- IsDecl ? diag::note_previous_decl : diag::note_defined_here)
- << VD;
- return ExprError();
- }
- VarDecl *CanonicalVD = VD->getCanonicalDecl();
- NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
- // OpenMP [2.9.2, Restrictions, C/C++, p.2]
- // A threadprivate directive for file-scope variables must appear outside
- // any definition or declaration.
- if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
- !getCurLexicalContext()->isTranslationUnit()) {
- Diag(Id.getLoc(), diag::err_omp_var_scope)
- << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
- bool IsDecl =
- VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
- Diag(VD->getLocation(),
- IsDecl ? diag::note_previous_decl : diag::note_defined_here)
- << VD;
- return ExprError();
- }
- // OpenMP [2.9.2, Restrictions, C/C++, p.3]
- // A threadprivate directive for static class member variables must appear
- // in the class definition, in the same scope in which the member
- // variables are declared.
- if (CanonicalVD->isStaticDataMember() &&
- !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
- Diag(Id.getLoc(), diag::err_omp_var_scope)
- << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
- bool IsDecl =
- VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
- Diag(VD->getLocation(),
- IsDecl ? diag::note_previous_decl : diag::note_defined_here)
- << VD;
- return ExprError();
- }
- // OpenMP [2.9.2, Restrictions, C/C++, p.4]
- // A threadprivate directive for namespace-scope variables must appear
- // outside any definition or declaration other than the namespace
- // definition itself.
- if (CanonicalVD->getDeclContext()->isNamespace() &&
- (!getCurLexicalContext()->isFileContext() ||
- !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
- Diag(Id.getLoc(), diag::err_omp_var_scope)
- << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
- bool IsDecl =
- VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
- Diag(VD->getLocation(),
- IsDecl ? diag::note_previous_decl : diag::note_defined_here)
- << VD;
- return ExprError();
- }
- // OpenMP [2.9.2, Restrictions, C/C++, p.6]
- // A threadprivate directive for static block-scope variables must appear
- // in the scope of the variable and not in a nested scope.
- if (CanonicalVD->isStaticLocal() && CurScope &&
- !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
- Diag(Id.getLoc(), diag::err_omp_var_scope)
- << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
- bool IsDecl =
- VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
- Diag(VD->getLocation(),
- IsDecl ? diag::note_previous_decl : diag::note_defined_here)
- << VD;
- return ExprError();
- }
- // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
- // A threadprivate directive must lexically precede all references to any
- // of the variables in its list.
- if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
- Diag(Id.getLoc(), diag::err_omp_var_used)
- << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
- return ExprError();
- }
- QualType ExprType = VD->getType().getNonReferenceType();
- ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
- return DE;
- }
- Sema::DeclGroupPtrTy
- Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
- ArrayRef<Expr *> VarList) {
- if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
- CurContext->addDecl(D);
- return DeclGroupPtrTy::make(DeclGroupRef(D));
- }
- return nullptr;
- }
- namespace {
- class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
- Sema &SemaRef;
- public:
- bool VisitDeclRefExpr(const DeclRefExpr *E) {
- if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
- if (VD->hasLocalStorage()) {
- SemaRef.Diag(E->getLocStart(),
- diag::err_omp_local_var_in_threadprivate_init)
- << E->getSourceRange();
- SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
- << VD << VD->getSourceRange();
- return true;
- }
- }
- return false;
- }
- bool VisitStmt(const Stmt *S) {
- for (auto Child : S->children()) {
- if (Child && Visit(Child))
- return true;
- }
- return false;
- }
- explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
- };
- } // namespace
- OMPThreadPrivateDecl *
- Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
- SmallVector<Expr *, 8> Vars;
- for (auto &RefExpr : VarList) {
- DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
- VarDecl *VD = cast<VarDecl>(DE->getDecl());
- SourceLocation ILoc = DE->getExprLoc();
- QualType QType = VD->getType();
- if (QType->isDependentType() || QType->isInstantiationDependentType()) {
- // It will be analyzed later.
- Vars.push_back(DE);
- continue;
- }
- // OpenMP [2.9.2, Restrictions, C/C++, p.10]
- // A threadprivate variable must not have an incomplete type.
- if (RequireCompleteType(ILoc, VD->getType(),
- diag::err_omp_threadprivate_incomplete_type)) {
- continue;
- }
- // OpenMP [2.9.2, Restrictions, C/C++, p.10]
- // A threadprivate variable must not have a reference type.
- if (VD->getType()->isReferenceType()) {
- Diag(ILoc, diag::err_omp_ref_type_arg)
- << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
- bool IsDecl =
- VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
- Diag(VD->getLocation(),
- IsDecl ? diag::note_previous_decl : diag::note_defined_here)
- << VD;
- continue;
- }
- // Check if this is a TLS variable. If TLS is not being supported, produce
- // the corresponding diagnostic.
- if ((VD->getTLSKind() != VarDecl::TLS_None &&
- !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
- getLangOpts().OpenMPUseTLS &&
- getASTContext().getTargetInfo().isTLSSupported())) ||
- (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
- !VD->isLocalVarDecl())) {
- Diag(ILoc, diag::err_omp_var_thread_local)
- << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
- bool IsDecl =
- VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
- Diag(VD->getLocation(),
- IsDecl ? diag::note_previous_decl : diag::note_defined_here)
- << VD;
- continue;
- }
- // Check if initial value of threadprivate variable reference variable with
- // local storage (it is not supported by runtime).
- if (auto Init = VD->getAnyInitializer()) {
- LocalVarRefChecker Checker(*this);
- if (Checker.Visit(Init))
- continue;
- }
- Vars.push_back(RefExpr);
- DSAStack->addDSA(VD, DE, OMPC_threadprivate);
- VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
- Context, SourceRange(Loc, Loc)));
- if (auto *ML = Context.getASTMutationListener())
- ML->DeclarationMarkedOpenMPThreadPrivate(VD);
- }
- OMPThreadPrivateDecl *D = nullptr;
- if (!Vars.empty()) {
- D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
- Vars);
- D->setAccess(AS_public);
- }
- return D;
- }
- static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
- const ValueDecl *D, DSAStackTy::DSAVarData DVar,
- bool IsLoopIterVar = false) {
- if (DVar.RefExpr) {
- SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
- << getOpenMPClauseName(DVar.CKind);
- return;
- }
- enum {
- PDSA_StaticMemberShared,
- PDSA_StaticLocalVarShared,
- PDSA_LoopIterVarPrivate,
- PDSA_LoopIterVarLinear,
- PDSA_LoopIterVarLastprivate,
- PDSA_ConstVarShared,
- PDSA_GlobalVarShared,
- PDSA_TaskVarFirstprivate,
- PDSA_LocalVarPrivate,
- PDSA_Implicit
- } Reason = PDSA_Implicit;
- bool ReportHint = false;
- auto ReportLoc = D->getLocation();
- auto *VD = dyn_cast<VarDecl>(D);
- if (IsLoopIterVar) {
- if (DVar.CKind == OMPC_private)
- Reason = PDSA_LoopIterVarPrivate;
- else if (DVar.CKind == OMPC_lastprivate)
- Reason = PDSA_LoopIterVarLastprivate;
- else
- Reason = PDSA_LoopIterVarLinear;
- } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
- Reason = PDSA_TaskVarFirstprivate;
- ReportLoc = DVar.ImplicitDSALoc;
- } else if (VD && VD->isStaticLocal())
- Reason = PDSA_StaticLocalVarShared;
- else if (VD && VD->isStaticDataMember())
- Reason = PDSA_StaticMemberShared;
- else if (VD && VD->isFileVarDecl())
- Reason = PDSA_GlobalVarShared;
- else if (D->getType().isConstant(SemaRef.getASTContext()))
- Reason = PDSA_ConstVarShared;
- else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
- ReportHint = true;
- Reason = PDSA_LocalVarPrivate;
- }
- if (Reason != PDSA_Implicit) {
- SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
- << Reason << ReportHint
- << getOpenMPDirectiveName(Stack->getCurrentDirective());
- } else if (DVar.ImplicitDSALoc.isValid()) {
- SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
- << getOpenMPClauseName(DVar.CKind);
- }
- }
- namespace {
- class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
- DSAStackTy *Stack;
- Sema &SemaRef;
- bool ErrorFound;
- CapturedStmt *CS;
- llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
- llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
- public:
- void VisitDeclRefExpr(DeclRefExpr *E) {
- if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
- // Skip internally declared variables.
- if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
- return;
- auto DVar = Stack->getTopDSA(VD, false);
- // Check if the variable has explicit DSA set and stop analysis if it so.
- if (DVar.RefExpr) return;
- auto ELoc = E->getExprLoc();
- auto DKind = Stack->getCurrentDirective();
- // The default(none) clause requires that each variable that is referenced
- // in the construct, and does not have a predetermined data-sharing
- // attribute, must have its data-sharing attribute explicitly determined
- // by being listed in a data-sharing attribute clause.
- if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
- isParallelOrTaskRegion(DKind) &&
- VarsWithInheritedDSA.count(VD) == 0) {
- VarsWithInheritedDSA[VD] = E;
- return;
- }
- // OpenMP [2.9.3.6, Restrictions, p.2]
- // A list item that appears in a reduction clause of the innermost
- // enclosing worksharing or parallel construct may not be accessed in an
- // explicit task.
- DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
- [](OpenMPDirectiveKind K) -> bool {
- return isOpenMPParallelDirective(K) ||
- isOpenMPWorksharingDirective(K) ||
- isOpenMPTeamsDirective(K);
- },
- false);
- if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
- ErrorFound = true;
- SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
- ReportOriginalDSA(SemaRef, Stack, VD, DVar);
- return;
- }
- // Define implicit data-sharing attributes for task.
- DVar = Stack->getImplicitDSA(VD, false);
- if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
- ImplicitFirstprivate.push_back(E);
- }
- }
- void VisitMemberExpr(MemberExpr *E) {
- if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
- if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
- auto DVar = Stack->getTopDSA(FD, false);
- // Check if the variable has explicit DSA set and stop analysis if it
- // so.
- if (DVar.RefExpr)
- return;
- auto ELoc = E->getExprLoc();
- auto DKind = Stack->getCurrentDirective();
- // OpenMP [2.9.3.6, Restrictions, p.2]
- // A list item that appears in a reduction clause of the innermost
- // enclosing worksharing or parallel construct may not be accessed in
- // an
- // explicit task.
- DVar =
- Stack->hasInnermostDSA(FD, MatchesAnyClause(OMPC_reduction),
- [](OpenMPDirectiveKind K) -> bool {
- return isOpenMPParallelDirective(K) ||
- isOpenMPWorksharingDirective(K) ||
- isOpenMPTeamsDirective(K);
- },
- false);
- if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
- ErrorFound = true;
- SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
- ReportOriginalDSA(SemaRef, Stack, FD, DVar);
- return;
- }
- // Define implicit data-sharing attributes for task.
- DVar = Stack->getImplicitDSA(FD, false);
- if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
- ImplicitFirstprivate.push_back(E);
- }
- }
- }
- void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
- for (auto *C : S->clauses()) {
- // Skip analysis of arguments of implicitly defined firstprivate clause
- // for task directives.
- if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
- for (auto *CC : C->children()) {
- if (CC)
- Visit(CC);
- }
- }
- }
- void VisitStmt(Stmt *S) {
- for (auto *C : S->children()) {
- if (C && !isa<OMPExecutableDirective>(C))
- Visit(C);
- }
- }
- bool isErrorFound() { return ErrorFound; }
- ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
- llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
- return VarsWithInheritedDSA;
- }
- DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
- : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
- };
- } // namespace
- void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
- switch (DKind) {
- case OMPD_parallel: {
- QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
- QualType KmpInt32PtrTy =
- Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(".global_tid.", KmpInt32PtrTy),
- std::make_pair(".bound_tid.", KmpInt32PtrTy),
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_simd: {
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_for: {
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_for_simd: {
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_sections: {
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_section: {
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_single: {
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_master: {
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_critical: {
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_parallel_for: {
- QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
- QualType KmpInt32PtrTy =
- Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(".global_tid.", KmpInt32PtrTy),
- std::make_pair(".bound_tid.", KmpInt32PtrTy),
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_parallel_for_simd: {
- QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
- QualType KmpInt32PtrTy =
- Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(".global_tid.", KmpInt32PtrTy),
- std::make_pair(".bound_tid.", KmpInt32PtrTy),
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_parallel_sections: {
- QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
- QualType KmpInt32PtrTy =
- Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(".global_tid.", KmpInt32PtrTy),
- std::make_pair(".bound_tid.", KmpInt32PtrTy),
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_task: {
- QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
- QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
- FunctionProtoType::ExtProtoInfo EPI;
- EPI.Variadic = true;
- QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(".global_tid.", KmpInt32Ty),
- std::make_pair(".part_id.", KmpInt32Ty),
- std::make_pair(".privates.",
- Context.VoidPtrTy.withConst().withRestrict()),
- std::make_pair(
- ".copy_fn.",
- Context.getPointerType(CopyFnType).withConst().withRestrict()),
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- // Mark this captured region as inlined, because we don't use outlined
- // function directly.
- getCurCapturedRegion()->TheCapturedDecl->addAttr(
- AlwaysInlineAttr::CreateImplicit(
- Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
- break;
- }
- case OMPD_ordered: {
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_atomic: {
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_target_data:
- case OMPD_target:
- case OMPD_target_parallel: {
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_teams: {
- QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
- QualType KmpInt32PtrTy =
- Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(".global_tid.", KmpInt32PtrTy),
- std::make_pair(".bound_tid.", KmpInt32PtrTy),
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_taskgroup: {
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_taskloop: {
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_taskloop_simd: {
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_distribute: {
- Sema::CapturedParamNameType Params[] = {
- std::make_pair(StringRef(), QualType()) // __context with shared vars
- };
- ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
- Params);
- break;
- }
- case OMPD_threadprivate:
- case OMPD_taskyield:
- case OMPD_barrier:
- case OMPD_taskwait:
- case OMPD_cancellation_point:
- case OMPD_cancel:
- case OMPD_flush:
- case OMPD_target_enter_data:
- case OMPD_target_exit_data:
- llvm_unreachable("OpenMP Directive is not allowed");
- case OMPD_unknown:
- llvm_unreachable("Unknown OpenMP directive");
- }
- }
- StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
- ArrayRef<OMPClause *> Clauses) {
- if (!S.isUsable()) {
- ActOnCapturedRegionError();
- return StmtError();
- }
- OMPOrderedClause *OC = nullptr;
- OMPScheduleClause *SC = nullptr;
- SmallVector<OMPLinearClause *, 4> LCs;
- // This is required for proper codegen.
- for (auto *Clause : Clauses) {
- if (isOpenMPPrivate(Clause->getClauseKind()) ||
- Clause->getClauseKind() == OMPC_copyprivate ||
- (getLangOpts().OpenMPUseTLS &&
- getASTContext().getTargetInfo().isTLSSupported() &&
- Clause->getClauseKind() == OMPC_copyin)) {
- DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
- // Mark all variables in private list clauses as used in inner region.
- for (auto *VarRef : Clause->children()) {
- if (auto *E = cast_or_null<Expr>(VarRef)) {
- MarkDeclarationsReferencedInExpr(E);
- }
- }
- DSAStack->setForceVarCapturing(/*V=*/false);
- } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
- Clause->getClauseKind() == OMPC_schedule) {
- // Mark all variables in private list clauses as used in inner region.
- // Required for proper codegen of combined directives.
- // TODO: add processing for other clauses.
- if (auto *E = cast_or_null<Expr>(
- cast<OMPScheduleClause>(Clause)->getHelperChunkSize()))
- MarkDeclarationsReferencedInExpr(E);
- }
- if (Clause->getClauseKind() == OMPC_schedule)
- SC = cast<OMPScheduleClause>(Clause);
- else if (Clause->getClauseKind() == OMPC_ordered)
- OC = cast<OMPOrderedClause>(Clause);
- else if (Clause->getClauseKind() == OMPC_linear)
- LCs.push_back(cast<OMPLinearClause>(Clause));
- }
- bool ErrorFound = false;
- // OpenMP, 2.7.1 Loop Construct, Restrictions
- // The nonmonotonic modifier cannot be specified if an ordered clause is
- // specified.
- if (SC &&
- (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
- SC->getSecondScheduleModifier() ==
- OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
- OC) {
- Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
- ? SC->getFirstScheduleModifierLoc()
- : SC->getSecondScheduleModifierLoc(),
- diag::err_omp_schedule_nonmonotonic_ordered)
- << SourceRange(OC->getLocStart(), OC->getLocEnd());
- ErrorFound = true;
- }
- if (!LCs.empty() && OC && OC->getNumForLoops()) {
- for (auto *C : LCs) {
- Diag(C->getLocStart(), diag::err_omp_linear_ordered)
- << SourceRange(OC->getLocStart(), OC->getLocEnd());
- }
- ErrorFound = true;
- }
- if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
- isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
- OC->getNumForLoops()) {
- Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
- << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
- ErrorFound = true;
- }
- if (ErrorFound) {
- ActOnCapturedRegionError();
- return StmtError();
- }
- return ActOnCapturedRegionEnd(S.get());
- }
- static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
- OpenMPDirectiveKind CurrentRegion,
- const DeclarationNameInfo &CurrentName,
- OpenMPDirectiveKind CancelRegion,
- SourceLocation StartLoc) {
- // Allowed nesting of constructs
- // +------------------+-----------------+------------------------------------+
- // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
- // +------------------+-----------------+------------------------------------+
- // | parallel | parallel | * |
- // | parallel | for | * |
- // | parallel | for simd | * |
- // | parallel | master | * |
- // | parallel | critical | * |
- // | parallel | simd | * |
- // | parallel | sections | * |
- // | parallel | section | + |
- // | parallel | single | * |
- // | parallel | parallel for | * |
- // | parallel |parallel for simd| * |
- // | parallel |parallel sections| * |
- // | parallel | task | * |
- // | parallel | taskyield | * |
- // | parallel | barrier | * |
- // | parallel | taskwait | * |
- // | parallel | taskgroup | * |
- // | parallel | flush | * |
- // | parallel | ordered | + |
- // | parallel | atomic | * |
- // | parallel | target | * |
- // | parallel | target parallel | * |
- // | parallel | target enter | * |
- // | | data | |
- // | parallel | target exit | * |
- // | | data | |
- // | parallel | teams | + |
- // | parallel | cancellation | |
- // | | point | ! |
- // | parallel | cancel | ! |
- // | parallel | taskloop | * |
- // | parallel | taskloop simd | * |
- // | parallel | distribute | |
- // +------------------+-----------------+------------------------------------+
- // | for | parallel | * |
- // | for | for | + |
- // | for | for simd | + |
- // | for | master | + |
- // | for | critical | * |
- // | for | simd | * |
- // | for | sections | + |
- // | for | section | + |
- // | for | single | + |
- // | for | parallel for | * |
- // | for |parallel for simd| * |
- // | for |parallel sections| * |
- // | for | task | * |
- // | for | taskyield | * |
- // | for | barrier | + |
- // | for | taskwait | * |
- // | for | taskgroup | * |
- // | for | flush | * |
- // | for | ordered | * (if construct is ordered) |
- // | for | atomic | * |
- // | for | target | * |
- // | for | target parallel | * |
- // | for | target enter | * |
- // | | data | |
- // | for | target exit | * |
- // | | data | |
- // | for | teams | + |
- // | for | cancellation | |
- // | | point | ! |
- // | for | cancel | ! |
- // | for | taskloop | * |
- // | for | taskloop simd | * |
- // | for | distribute | |
- // +------------------+-----------------+------------------------------------+
- // | master | parallel | * |
- // | master | for | + |
- // | master | for simd | + |
- // | master | master | * |
- // | master | critical | * |
- // | master | simd | * |
- // | master | sections | + |
- // | master | section | + |
- // | master | single | + |
- // | master | parallel for | * |
- // | master |parallel for simd| * |
- // | master |parallel sections| * |
- // | master | task | * |
- // | master | taskyield | * |
- // | master | barrier | + |
- // | master | taskwait | * |
- // | master | taskgroup | * |
- // | master | flush | * |
- // | master | ordered | + |
- // | master | atomic | * |
- // | master | target | * |
- // | master | target parallel | * |
- // | master | target enter | * |
- // | | data | |
- // | master | target exit | * |
- // | | data | |
- // | master | teams | + |
- // | master | cancellation | |
- // | | point | |
- // | master | cancel | |
- // | master | taskloop | * |
- // | master | taskloop simd | * |
- // | master | distribute | |
- // +------------------+-----------------+------------------------------------+
- // | critical | parallel | * |
- // | critical | for | + |
- // | critical | for simd | + |
- // | critical | master | * |
- // | critical | critical | * (should have different names) |
- // | critical | simd | * |
- // | critical | sections | + |
- // | critical | section | + |
- // | critical | single | + |
- // | critical | parallel for | * |
- // | critical |parallel for simd| * |
- // | critical |parallel sections| * |
- // | critical | task | * |
- // | critical | taskyield | * |
- // | critical | barrier | + |
- // | critical | taskwait | * |
- // | critical | taskgroup | * |
- // | critical | ordered | + |
- // | critical | atomic | * |
- // | critical | target | * |
- // | critical | target parallel | * |
- // | critical | target enter | * |
- // | | data | |
- // | critical | target exit | * |
- // | | data | |
- // | critical | teams | + |
- // | critical | cancellation | |
- // | | point | |
- // | critical | cancel | |
- // | critical | taskloop | * |
- // | critical | taskloop simd | * |
- // | critical | distribute | |
- // +------------------+-----------------+------------------------------------+
- // | simd | parallel | |
- // | simd | for | |
- // | simd | for simd | |
- // | simd | master | |
- // | simd | critical | |
- // | simd | simd | * |
- // | simd | sections | |
- // | simd | section | |
- // | simd | single | |
- // | simd | parallel for | |
- // | simd |parallel for simd| |
- // | simd |parallel sections| |
- // | simd | task | |
- // | simd | taskyield | |
- // | simd | barrier | |
- // | simd | taskwait | |
- // | simd | taskgroup | |
- // | simd | flush | |
- // | simd | ordered | + (with simd clause) |
- // | simd | atomic | |
- // | simd | target | |
- // | simd | target parallel | |
- // | simd | target enter | |
- // | | data | |
- // | simd | target exit | |
- // | | data | |
- // | simd | teams | |
- // | simd | cancellation | |
- // | | point | |
- // | simd | cancel | |
- // | simd | taskloop | |
- // | simd | taskloop simd | |
- // | simd | distribute | |
- // +------------------+-----------------+------------------------------------+
- // | for simd | parallel | |
- // | for simd | for | |
- // | for simd | for simd | |
- // | for simd | master | |
- // | for simd | critical | |
- // | for simd | simd | * |
- // | for simd | sections | |
- // | for simd | section | |
- // | for simd | single | |
- // | for simd | parallel for | |
- // | for simd |parallel for simd| |
- // | for simd |parallel sections| |
- // | for simd | task | |
- // | for simd | taskyield | |
- // | for simd | barrier | |
- // | for simd | taskwait | |
- // | for simd | taskgroup | |
- // | for simd | flush | |
- // | for simd | ordered | + (with simd clause) |
- // | for simd | atomic | |
- // | for simd | target | |
- // | for simd | target parallel | |
- // | for simd | target enter | |
- // | | data | |
- // | for simd | target exit | |
- // | | data | |
- // | for simd | teams | |
- // | for simd | cancellation | |
- // | | point | |
- // | for simd | cancel | |
- // | for simd | taskloop | |
- // | for simd | taskloop simd | |
- // | for simd | distribute | |
- // +------------------+-----------------+------------------------------------+
- // | parallel for simd| parallel | |
- // | parallel for simd| for | |
- // | parallel for simd| for simd | |
- // | parallel for simd| master | |
- // | parallel for simd| critical | |
- // | parallel for simd| simd | * |
- // | parallel for simd| sections | |
- // | parallel for simd| section | |
- // | parallel for simd| single | |
- // | parallel for simd| parallel for | |
- // | parallel for simd|parallel for simd| |
- // | parallel for simd|parallel sections| |
- // | parallel for simd| task | |
- // | parallel for simd| taskyield | |
- // | parallel for simd| barrier | |
- // | parallel for simd| taskwait | |
- // | parallel for simd| taskgroup | |
- // | parallel for simd| flush | |
- // | parallel for simd| ordered | + (with simd clause) |
- // | parallel for simd| atomic | |
- // | parallel for simd| target | |
- // | parallel for simd| target parallel | |
- // | parallel for simd| target enter | |
- // | | data | |
- // | parallel for simd| target exit | |
- // | | data | |
- // | parallel for simd| teams | |
- // | parallel for simd| cancellation | |
- // | | point | |
- // | parallel for simd| cancel | |
- // | parallel for simd| taskloop | |
- // | parallel for simd| taskloop simd | |
- // | parallel for simd| distribute | |
- // +------------------+-----------------+------------------------------------+
- // | sections | parallel | * |
- // | sections | for | + |
- // | sections | for simd | + |
- // | sections | master | + |
- // | sections | critical | * |
- // | sections | simd | * |
- // | sections | sections | + |
- // | sections | section | * |
- // | sections | single | + |
- // | sections | parallel for | * |
- // | sections |parallel for simd| * |
- // | sections |parallel sections| * |
- // | sections | task | * |
- // | sections | taskyield | * |
- // | sections | barrier | + |
- // | sections | taskwait | * |
- // | sections | taskgroup | * |
- // | sections | flush | * |
- // | sections | ordered | + |
- // | sections | atomic | * |
- // | sections | target | * |
- // | sections | target parallel | * |
- // | sections | target enter | * |
- // | | data | |
- // | sections | target exit | * |
- // | | data | |
- // | sections | teams | + |
- // | sections | cancellation | |
- // | | point | ! |
- // | sections | cancel | ! |
- // | sections | taskloop | * |
- // | sections | taskloop simd | * |
- // | sections | distribute | |
- // +------------------+-----------------+------------------------------------+
- // | section | parallel | * |
- // | section | for | + |
- // | section | for simd | + |
- // | section | master | + |
- // | section | critical | * |
- // | section | simd | * |
- // | section | sections | + |
- // | section | section | + |
- // | section | single | + |
- // | section | parallel for | * |
- // | section |parallel for simd| * |
- // | section |parallel sections| * |
- // | section | task | * |
- // | section | taskyield | * |
- // | section | barrier | + |
- // | section | taskwait | * |
- // | section | taskgroup | * |
- // | section | flush | * |
- // | section | ordered | + |
- // | section | atomic | * |
- // | section | target | * |
- // | section | target parallel | * |
- // | section | target enter | * |
- // | | data | |
- // | section | target exit | * |
- // | | data | |
- // | section | teams | + |
- // | section | cancellation | |
- // | | point | ! |
- // | section | cancel | ! |
- // | section | taskloop | * |
- // | section | taskloop simd | * |
- // | section | distribute | |
- // +------------------+-----------------+------------------------------------+
- // | single | parallel | * |
- // | single | for | + |
- // | single | for simd | + |
- // | single | master | + |
- // | single | critical | * |
- // | single | simd | * |
- // | single | sections | + |
- // | single | section | + |
- // | single | single | + |
- // | single | parallel for | * |
- // | single |parallel for simd| * |
- // | single |parallel sections| * |
- // | single | task | * |
- // | single | taskyield | * |
- // | single | barrier | + |
- // | single | taskwait | * |
- // | single | taskgroup | * |
- // | single | flush | * |
- // | single | ordered | + |
- // | single | atomic | * |
- // | single | target | * |
- // | single | target parallel | * |
- // | single | target enter | * |
- // | | data | |
- // | single | target exit | * |
- // | | data | |
- // | single | teams | + |
- // | single | cancellation | |
- // | | point | |
- // | single | cancel | |
- // | single | taskloop | * |
- // | single | taskloop simd | * |
- // | single | distribute | |
- // +------------------+-----------------+------------------------------------+
- // | parallel for | parallel | * |
- // | parallel for | for | + |
- // | parallel for | for simd | + |
- // | parallel for | master | + |
- // | parallel for | critical | * |
- // | parallel for | simd | * |
- // | parallel for | sections | + |
- // | parallel for | section | + |
- // | parallel for | single | + |
- // | parallel for | parallel for | * |
- // | parallel for |parallel for simd| * |
- // | parallel for |parallel sections| * |
- // | parallel for | task | * |
- // | parallel for | taskyield | * |
- // | parallel for | barrier | + |
- // | parallel for | taskwait | * |
- // | parallel for | taskgroup | * |
- // | parallel for | flush | * |
- // | parallel for | ordered | * (if construct is ordered) |
- // | parallel for | atomic | * |
- // | parallel for | target | * |
- // | parallel for | target parallel | * |
- // | parallel for | target enter | * |
- // | | data | |
- // | parallel for | target exit | * |
- // | | data | |
- // | parallel for | teams | + |
- // | parallel for | cancellation | |
- // | | point | ! |
- // | parallel for | cancel | ! |
- // | parallel for | taskloop | * |
- // | parallel for | taskloop simd | * |
- // | parallel for | distribute | |
- // +------------------+-----------------+------------------------------------+
- // | parallel sections| parallel | * |
- // | parallel sections| for | + |
- // | parallel sections| for simd | + |
- // | parallel sections| master | + |
- // | parallel sections| critical | + |
- // | parallel sections| simd | * |
- // | parallel sections| sections | + |
- // | parallel sections| section | * |
- // | parallel sections| single | + |
- // | parallel sections| parallel for | * |
- // | parallel sections|parallel for simd| * |
- // | parallel sections|parallel sections| * |
- // | parallel sections| task | * |
- // | parallel sections| taskyield | * |
- // | parallel sections| barrier | + |
- // | parallel sections| taskwait | * |
- // | parallel sections| taskgroup | * |
- // | parallel sections| flush | * |
- // | parallel sections| ordered | + |
- // | parallel sections| atomic | * |
- // | parallel sections| target | * |
- // | parallel sections| target parallel | * |
- // | parallel sections| target enter | * |
- // | | data | |
- // | parallel sections| target exit | * |
- // | | data | |
- // | parallel sections| teams | + |
- // | parallel sections| cancellation | |
- // | | point | ! |
- // | parallel sections| cancel | ! |
- // | parallel sections| taskloop | * |
- // | parallel sections| taskloop simd | * |
- // | parallel sections| distribute | |
- // +------------------+-----------------+------------------------------------+
- // | task | parallel | * |
- // | task | for | + |
- // | task | for simd | + |
- // | task | master | + |
- // | task | critical | * |
- // | task | simd | * |
- // | task | sections | + |
- // | task | section | + |
- // | task | single | + |
- // | task | parallel for | * |
- // | task |parallel for simd| * |
- // | task |parallel sections| * |
- // | task | task | * |
- // | task | taskyield | * |
- // | task | barrier | + |
- // | task | taskwait | * |
- // | task | taskgroup | * |
- // | task | flush | * |
- // | task | ordered | + |
- // | task | atomic | * |
- // | task | target | * |
- // | task | target parallel | * |
- // | task | target enter | * |
- // | | data | |
- // | task | target exit | * |
- // | | data | |
- // | task | teams | + |
- // | task | cancellation | |
- // | | point | ! |
- // | task | cancel | ! |
- // | task | taskloop | * |
- // | task | taskloop simd | * |
- // | task | distribute | |
- // +------------------+-----------------+------------------------------------+
- // | ordered | parallel | * |
- // | ordered | for | + |
- // | ordered | for simd | + |
- // | ordered | master | * |
- // | ordered | critical | * |
- // | ordered | simd | * |
- // | ordered | sections | + |
- // | ordered | section | + |
- // | ordered | single | + |
- // | ordered | parallel for | * |
- // | ordered |parallel for simd| * |
- // | ordered |parallel sections| * |
- // | ordered | task | * |
- // | ordered | taskyield | * |
- // | ordered | barrier | + |
- // | ordered | taskwait | * |
- // | ordered | taskgroup | * |
- // | ordered | flush | * |
- // | ordered | ordered | + |
- // | ordered | atomic | * |
- // | ordered | target | * |
- // | ordered | target parallel | * |
- // | ordered | target enter | * |
- // | | data | |
- // | ordered | target exit | * |
- // | | data | |
- // | ordered | teams | + |
- // | ordered | cancellation | |
- // | | point | |
- // | ordered | cancel | |
- // | ordered | taskloop | * |
- // | ordered | taskloop simd | * |
- // | ordered | distribute | |
- // +------------------+-----------------+------------------------------------+
- // | atomic | parallel | |
- // | atomic | for | |
- // | atomic | for simd | |
- // | atomic | master | |
- // | atomic | critical | |
- // | atomic | simd | |
- // | atomic | sections | |
- // | atomic | section | |
- // | atomic | single | |
- // | atomic | parallel for | |
- // | atomic |parallel for simd| |
- // | atomic |parallel sections| |
- // | atomic | task | |
- // | atomic | taskyield | |
- // | atomic | barrier | |
- // | atomic | taskwait | |
- // | atomic | taskgroup | |
- // | atomic | flush | |
- // | atomic | ordered | |
- // | atomic | atomic | |
- // | atomic | target | |
- // | atomic | target parallel | |
- // | atomic | target enter | |
- // | | data | |
- // | atomic | target exit | |
- // | | data | |
- // | atomic | teams | |
- // | atomic | cancellation | |
- // | | point | |
- // | atomic | cancel | |
- // | atomic | taskloop | |
- // | atomic | taskloop simd | |
- // | atomic | distribute | |
- // +------------------+-----------------+------------------------------------+
- // | target | parallel | * |
- // | target | for | * |
- // | target | for simd | * |
- // | target | master | * |
- // | target | critical | * |
- // | target | simd | * |
- // | target | sections | * |
- // | target | section | * |
- // | target | single | * |
- // | target | parallel for | * |
- // | target |parallel for simd| * |
- // | target |parallel sections| * |
- // | target | task | * |
- // | target | taskyield | * |
- // | target | barrier | * |
- // | target | taskwait | * |
- // | target | taskgroup | * |
- // | target | flush | * |
- // | target | ordered | * |
- // | target | atomic | * |
- // | target | target | |
- // | target | target parallel | |
- // | target | target enter | |
- // | | data | |
- // | target | target exit | |
- // | | data | |
- // | target | teams | * |
- // | target | cancellation | |
- // | | point | |
- // | target | cancel | |
- // | target | taskloop | * |
- // | target | taskloop simd | * |
- // | target | distribute | |
- // +------------------+-----------------+------------------------------------+
- // | target parallel | parallel | * |
- // | target parallel | for | * |
- // | target parallel | for simd | * |
- // | target parallel | master | * |
- // | target parallel | critical | * |
- // | target parallel | simd | * |
- // | target parallel | sections | * |
- // | target parallel | section | * |
- // | target parallel | single | * |
- // | target parallel | parallel for | * |
- // | target parallel |parallel for simd| * |
- // | target parallel |parallel sections| * |
- // | target parallel | task | * |
- // | target parallel | taskyield | * |
- // | target parallel | barrier | * |
- // | target parallel | taskwait | * |
- // | target parallel | taskgroup | * |
- // | target parallel | flush | * |
- // | target parallel | ordered | * |
- // | target parallel | atomic | * |
- // | target parallel | target | |
- // | target parallel | target parallel | |
- // | target parallel | target enter | |
- // | | data | |
- // | target parallel | target exit | |
- // | | data | |
- // | target parallel | teams | |
- // | target parallel | cancellation | |
- // | | point | ! |
- // | target parallel | cancel | ! |
- // | target parallel | taskloop | * |
- // | target parallel | taskloop simd | * |
- // | target parallel | distribute | |
- // +------------------+-----------------+------------------------------------+
- // | teams | parallel | * |
- // | teams | for | + |
- // | teams | for simd | + |
- // | teams | master | + |
- // | teams | critical | + |
- // | teams | simd | + |
- // | teams | sections | + |
- // | teams | section | + |
- // | teams | single | + |
- // | teams | parallel for | * |
- // | teams |parallel for simd| * |
- // | teams |parallel sections| * |
- // | teams | task | + |
- // | teams | taskyield | + |
- // | teams | barrier | + |
- // | teams | taskwait | + |
- // | teams | taskgroup | + |
- // | teams | flush | + |
- // | teams | ordered | + |
- // | teams | atomic | + |
- // | teams | target | + |
- // | teams | target parallel | + |
- // | teams | target enter | + |
- // | | data | |
- // | teams | target exit | + |
- // | | data | |
- // | teams | teams | + |
- // | teams | cancellation | |
- // | | point | |
- // | teams | cancel | |
- // | teams | taskloop | + |
- // | teams | taskloop simd | + |
- // | teams | distribute | ! |
- // +------------------+-----------------+------------------------------------+
- // | taskloop | parallel | * |
- // | taskloop | for | + |
- // | taskloop | for simd | + |
- // | taskloop | master | + |
- // | taskloop | critical | * |
- // | taskloop | simd | * |
- // | taskloop | sections | + |
- // | taskloop | section | + |
- // | taskloop | single | + |
- // | taskloop | parallel for | * |
- // | taskloop |parallel for simd| * |
- // | taskloop |parallel sections| * |
- // | taskloop | task | * |
- // | taskloop | taskyield | * |
- // | taskloop | barrier | + |
- // | taskloop | taskwait | * |
- // | taskloop | taskgroup | * |
- // | taskloop | flush | * |
- // | taskloop | ordered | + |
- // | taskloop | atomic | * |
- // | taskloop | target | * |
- // | taskloop | target parallel | * |
- // | taskloop | target enter | * |
- // | | data | |
- // | taskloop | target exit | * |
- // | | data | |
- // | taskloop | teams | + |
- // | taskloop | cancellation | |
- // | | point | |
- // | taskloop | cancel | |
- // | taskloop | taskloop | * |
- // | taskloop | distribute | |
- // +------------------+-----------------+------------------------------------+
- // | taskloop simd | parallel | |
- // | taskloop simd | for | |
- // | taskloop simd | for simd | |
- // | taskloop simd | master | |
- // | taskloop simd | critical | |
- // | taskloop simd | simd | * |
- // | taskloop simd | sections | |
- // | taskloop simd | section | |
- // | taskloop simd | single | |
- // | taskloop simd | parallel for | |
- // | taskloop simd |parallel for simd| |
- // | taskloop simd |parallel sections| |
- // | taskloop simd | task | |
- // | taskloop simd | taskyield | |
- // | taskloop simd | barrier | |
- // | taskloop simd | taskwait | |
- // | taskloop simd | taskgroup | |
- // | taskloop simd | flush | |
- // | taskloop simd | ordered | + (with simd clause) |
- // | taskloop simd | atomic | |
- // | taskloop simd | target | |
- // | taskloop simd | target parallel | |
- // | taskloop simd | target enter | |
- // | | data | |
- // | taskloop simd | target exit | |
- // | | data | |
- // | taskloop simd | teams | |
- // | taskloop simd | cancellation | |
- // | | point | |
- // | taskloop simd | cancel | |
- // | taskloop simd | taskloop | |
- // | taskloop simd | taskloop simd | |
- // | taskloop simd | distribute | |
- // +------------------+-----------------+------------------------------------+
- // | distribute | parallel | * |
- // | distribute | for | * |
- // | distribute | for simd | * |
- // | distribute | master | * |
- // | distribute | critical | * |
- // | distribute | simd | * |
- // | distribute | sections | * |
- // | distribute | section | * |
- // | distribute | single | * |
- // | distribute | parallel for | * |
- // | distribute |parallel for simd| * |
- // | distribute |parallel sections| * |
- // | distribute | task | * |
- // | distribute | taskyield | * |
- // | distribute | barrier | * |
- // | distribute | taskwait | * |
- // | distribute | taskgroup | * |
- // | distribute | flush | * |
- // | distribute | ordered | + |
- // | distribute | atomic | * |
- // | distribute | target | |
- // | distribute | target parallel | |
- // | distribute | target enter | |
- // | | data | |
- // | distribute | target exit | |
- // | | data | |
- // | distribute | teams | |
- // | distribute | cancellation | + |
- // | | point | |
- // | distribute | cancel | + |
- // | distribute | taskloop | * |
- // | distribute | taskloop simd | * |
- // | distribute | distribute | |
- // +------------------+-----------------+------------------------------------+
- if (Stack->getCurScope()) {
- auto ParentRegion = Stack->getParentDirective();
- auto OffendingRegion = ParentRegion;
- bool NestingProhibited = false;
- bool CloseNesting = true;
- enum {
- NoRecommend,
- ShouldBeInParallelRegion,
- ShouldBeInOrderedRegion,
- ShouldBeInTargetRegion,
- ShouldBeInTeamsRegion
- } Recommend = NoRecommend;
- if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered &&
- CurrentRegion != OMPD_simd) {
- // OpenMP [2.16, Nesting of Regions]
- // OpenMP constructs may not be nested inside a simd region.
- // OpenMP [2.8.1,simd Construct, Restrictions]
- // An ordered construct with the simd clause is the only OpenMP construct
- // that can appear in the simd region.
- SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
- return true;
- }
- if (ParentRegion == OMPD_atomic) {
- // OpenMP [2.16, Nesting of Regions]
- // OpenMP constructs may not be nested inside an atomic region.
- SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
- return true;
- }
- if (CurrentRegion == OMPD_section) {
- // OpenMP [2.7.2, sections Construct, Restrictions]
- // Orphaned section directives are prohibited. That is, the section
- // directives must appear within the sections construct and must not be
- // encountered elsewhere in the sections region.
- if (ParentRegion != OMPD_sections &&
- ParentRegion != OMPD_parallel_sections) {
- SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
- << (ParentRegion != OMPD_unknown)
- << getOpenMPDirectiveName(ParentRegion);
- return true;
- }
- return false;
- }
- // Allow some constructs to be orphaned (they could be used in functions,
- // called from OpenMP regions with the required preconditions).
- if (ParentRegion == OMPD_unknown)
- return false;
- if (CurrentRegion == OMPD_cancellation_point ||
- CurrentRegion == OMPD_cancel) {
- // OpenMP [2.16, Nesting of Regions]
- // A cancellation point construct for which construct-type-clause is
- // taskgroup must be nested inside a task construct. A cancellation
- // point construct for which construct-type-clause is not taskgroup must
- // be closely nested inside an OpenMP construct that matches the type
- // specified in construct-type-clause.
- // A cancel construct for which construct-type-clause is taskgroup must be
- // nested inside a task construct. A cancel construct for which
- // construct-type-clause is not taskgroup must be closely nested inside an
- // OpenMP construct that matches the type specified in
- // construct-type-clause.
- NestingProhibited =
- !((CancelRegion == OMPD_parallel &&
- (ParentRegion == OMPD_parallel ||
- ParentRegion == OMPD_target_parallel)) ||
- (CancelRegion == OMPD_for &&
- (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for)) ||
- (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
- (CancelRegion == OMPD_sections &&
- (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
- ParentRegion == OMPD_parallel_sections)));
- } else if (CurrentRegion == OMPD_master) {
- // OpenMP [2.16, Nesting of Regions]
- // A master region may not be closely nested inside a worksharing,
- // atomic, or explicit task region.
- NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
- ParentRegion == OMPD_task ||
- isOpenMPTaskLoopDirective(ParentRegion);
- } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
- // OpenMP [2.16, Nesting of Regions]
- // A critical region may not be nested (closely or otherwise) inside a
- // critical region with the same name. Note that this restriction is not
- // sufficient to prevent deadlock.
- SourceLocation PreviousCriticalLoc;
- bool DeadLock =
- Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
- OpenMPDirectiveKind K,
- const DeclarationNameInfo &DNI,
- SourceLocation Loc)
- ->bool {
- if (K == OMPD_critical &&
- DNI.getName() == CurrentName.getName()) {
- PreviousCriticalLoc = Loc;
- return true;
- } else
- return false;
- },
- false /* skip top directive */);
- if (DeadLock) {
- SemaRef.Diag(StartLoc,
- diag::err_omp_prohibited_region_critical_same_name)
- << CurrentName.getName();
- if (PreviousCriticalLoc.isValid())
- SemaRef.Diag(PreviousCriticalLoc,
- diag::note_omp_previous_critical_region);
- return true;
- }
- } else if (CurrentRegion == OMPD_barrier) {
- // OpenMP [2.16, Nesting of Regions]
- // A barrier region may not be closely nested inside a worksharing,
- // explicit task, critical, ordered, atomic, or master region.
- NestingProhibited =
- isOpenMPWorksharingDirective(ParentRegion) ||
- ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
- ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered ||
- isOpenMPTaskLoopDirective(ParentRegion);
- } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
- !isOpenMPParallelDirective(CurrentRegion)) {
- // OpenMP [2.16, Nesting of Regions]
- // A worksharing region may not be closely nested inside a worksharing,
- // explicit task, critical, ordered, atomic, or master region.
- NestingProhibited =
- isOpenMPWorksharingDirective(ParentRegion) ||
- ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
- ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered ||
- isOpenMPTaskLoopDirective(ParentRegion);
- Recommend = ShouldBeInParallelRegion;
- } else if (CurrentRegion == OMPD_ordered) {
- // OpenMP [2.16, Nesting of Regions]
- // An ordered region may not be closely nested inside a critical,
- // atomic, or explicit task region.
- // An ordered region must be closely nested inside a loop region (or
- // parallel loop region) with an ordered clause.
- // OpenMP [2.8.1,simd Construct, Restrictions]
- // An ordered construct with the simd clause is the only OpenMP construct
- // that can appear in the simd region.
- NestingProhibited = ParentRegion == OMPD_critical ||
- ParentRegion == OMPD_task ||
- isOpenMPTaskLoopDirective(ParentRegion) ||
- !(isOpenMPSimdDirective(ParentRegion) ||
- Stack->isParentOrderedRegion());
- Recommend = ShouldBeInOrderedRegion;
- } else if (isOpenMPTeamsDirective(CurrentRegion)) {
- // OpenMP [2.16, Nesting of Regions]
- // If specified, a teams construct must be contained within a target
- // construct.
- NestingProhibited = ParentRegion != OMPD_target;
- Recommend = ShouldBeInTargetRegion;
- Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
- }
- if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
- // OpenMP [2.16, Nesting of Regions]
- // distribute, parallel, parallel sections, parallel workshare, and the
- // parallel loop and parallel loop SIMD constructs are the only OpenMP
- // constructs that can be closely nested in the teams region.
- NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
- !isOpenMPDistributeDirective(CurrentRegion);
- Recommend = ShouldBeInParallelRegion;
- }
- if (!NestingProhibited && isOpenMPDistributeDirective(CurrentRegion)) {
- // OpenMP 4.5 [2.17 Nesting of Regions]
- // The region associated with the distribute construct must be strictly
- // nested inside a teams region
- NestingProhibited = !isOpenMPTeamsDirective(ParentRegion);
- Recommend = ShouldBeInTeamsRegion;
- }
- if (!NestingProhibited &&
- (isOpenMPTargetExecutionDirective(CurrentRegion) ||
- isOpenMPTargetDataManagementDirective(CurrentRegion))) {
- // OpenMP 4.5 [2.17 Nesting of Regions]
- // If a target, target update, target data, target enter data, or
- // target exit data construct is encountered during execution of a
- // target region, the behavior is unspecified.
- NestingProhibited = Stack->hasDirective(
- [&OffendingRegion](OpenMPDirectiveKind K,
- const DeclarationNameInfo &DNI,
- SourceLocation Loc) -> bool {
- if (isOpenMPTargetExecutionDirective(K)) {
- OffendingRegion = K;
- return true;
- } else
- return false;
- },
- false /* don't skip top directive */);
- CloseNesting = false;
- }
- if (NestingProhibited) {
- SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
- << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
- << Recommend << getOpenMPDirectiveName(CurrentRegion);
- return true;
- }
- }
- return false;
- }
- static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
- ArrayRef<OMPClause *> Clauses,
- ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
- bool ErrorFound = false;
- unsigned NamedModifiersNumber = 0;
- SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
- OMPD_unknown + 1);
- SmallVector<SourceLocation, 4> NameModifierLoc;
- for (const auto *C : Clauses) {
- if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
- // At most one if clause without a directive-name-modifier can appear on
- // the directive.
- OpenMPDirectiveKind CurNM = IC->getNameModifier();
- if (FoundNameModifiers[CurNM]) {
- S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
- << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
- << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
- ErrorFound = true;
- } else if (CurNM != OMPD_unknown) {
- NameModifierLoc.push_back(IC->getNameModifierLoc());
- ++NamedModifiersNumber;
- }
- FoundNameModifiers[CurNM] = IC;
- if (CurNM == OMPD_unknown)
- continue;
- // Check if the specified name modifier is allowed for the current
- // directive.
- // At most one if clause with the particular directive-name-modifier can
- // appear on the directive.
- bool MatchFound = false;
- for (auto NM : AllowedNameModifiers) {
- if (CurNM == NM) {
- MatchFound = true;
- break;
- }
- }
- if (!MatchFound) {
- S.Diag(IC->getNameModifierLoc(),
- diag::err_omp_wrong_if_directive_name_modifier)
- << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
- ErrorFound = true;
- }
- }
- }
- // If any if clause on the directive includes a directive-name-modifier then
- // all if clauses on the directive must include a directive-name-modifier.
- if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
- if (NamedModifiersNumber == AllowedNameModifiers.size()) {
- S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
- diag::err_omp_no_more_if_clause);
- } else {
- std::string Values;
- std::string Sep(", ");
- unsigned AllowedCnt = 0;
- unsigned TotalAllowedNum =
- AllowedNameModifiers.size() - NamedModifiersNumber;
- for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
- ++Cnt) {
- OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
- if (!FoundNameModifiers[NM]) {
- Values += "'";
- Values += getOpenMPDirectiveName(NM);
- Values += "'";
- if (AllowedCnt + 2 == TotalAllowedNum)
- Values += " or ";
- else if (AllowedCnt + 1 != TotalAllowedNum)
- Values += Sep;
- ++AllowedCnt;
- }
- }
- S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
- diag::err_omp_unnamed_if_clause)
- << (TotalAllowedNum > 1) << Values;
- }
- for (auto Loc : NameModifierLoc) {
- S.Diag(Loc, diag::note_omp_previous_named_if_clause);
- }
- ErrorFound = true;
- }
- return ErrorFound;
- }
- StmtResult Sema::ActOnOpenMPExecutableDirective(
- OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
- OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
- Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
- StmtResult Res = StmtError();
- if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
- StartLoc))
- return StmtError();
- llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
- llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
- bool ErrorFound = false;
- ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
- if (AStmt) {
- assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
- // Check default data sharing attributes for referenced variables.
- DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
- DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
- if (DSAChecker.isErrorFound())
- return StmtError();
- // Generate list of implicitly defined firstprivate variables.
- VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
- if (!DSAChecker.getImplicitFirstprivate().empty()) {
- if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
- DSAChecker.getImplicitFirstprivate(), SourceLocation(),
- SourceLocation(), SourceLocation())) {
- ClausesWithImplicit.push_back(Implicit);
- ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
- DSAChecker.getImplicitFirstprivate().size();
- } else
- ErrorFound = true;
- }
- }
- llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
- switch (Kind) {
- case OMPD_parallel:
- Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
- EndLoc);
- AllowedNameModifiers.push_back(OMPD_parallel);
- break;
- case OMPD_simd:
- Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
- VarsWithInheritedDSA);
- break;
- case OMPD_for:
- Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
- VarsWithInheritedDSA);
- break;
- case OMPD_for_simd:
- Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
- EndLoc, VarsWithInheritedDSA);
- break;
- case OMPD_sections:
- Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
- EndLoc);
- break;
- case OMPD_section:
- assert(ClausesWithImplicit.empty() &&
- "No clauses are allowed for 'omp section' directive");
- Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
- break;
- case OMPD_single:
- Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
- EndLoc);
- break;
- case OMPD_master:
- assert(ClausesWithImplicit.empty() &&
- "No clauses are allowed for 'omp master' directive");
- Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
- break;
- case OMPD_critical:
- Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
- StartLoc, EndLoc);
- break;
- case OMPD_parallel_for:
- Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
- EndLoc, VarsWithInheritedDSA);
- AllowedNameModifiers.push_back(OMPD_parallel);
- break;
- case OMPD_parallel_for_simd:
- Res = ActOnOpenMPParallelForSimdDirective(
- ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
- AllowedNameModifiers.push_back(OMPD_parallel);
- break;
- case OMPD_parallel_sections:
- Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
- StartLoc, EndLoc);
- AllowedNameModifiers.push_back(OMPD_parallel);
- break;
- case OMPD_task:
- Res =
- ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
- AllowedNameModifiers.push_back(OMPD_task);
- break;
- case OMPD_taskyield:
- assert(ClausesWithImplicit.empty() &&
- "No clauses are allowed for 'omp taskyield' directive");
- assert(AStmt == nullptr &&
- "No associated statement allowed for 'omp taskyield' directive");
- Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
- break;
- case OMPD_barrier:
- assert(ClausesWithImplicit.empty() &&
- "No clauses are allowed for 'omp barrier' directive");
- assert(AStmt == nullptr &&
- "No associated statement allowed for 'omp barrier' directive");
- Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
- break;
- case OMPD_taskwait:
- assert(ClausesWithImplicit.empty() &&
- "No clauses are allowed for 'omp taskwait' directive");
- assert(AStmt == nullptr &&
- "No associated statement allowed for 'omp taskwait' directive");
- Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
- break;
- case OMPD_taskgroup:
- assert(ClausesWithImplicit.empty() &&
- "No clauses are allowed for 'omp taskgroup' directive");
- Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
- break;
- case OMPD_flush:
- assert(AStmt == nullptr &&
- "No associated statement allowed for 'omp flush' directive");
- Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
- break;
- case OMPD_ordered:
- Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
- EndLoc);
- break;
- case OMPD_atomic:
- Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
- EndLoc);
- break;
- case OMPD_teams:
- Res =
- ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
- break;
- case OMPD_target:
- Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
- EndLoc);
- AllowedNameModifiers.push_back(OMPD_target);
- break;
- case OMPD_target_parallel:
- Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
- StartLoc, EndLoc);
- AllowedNameModifiers.push_back(OMPD_target);
- AllowedNameModifiers.push_back(OMPD_parallel);
- break;
- case OMPD_cancellation_point:
- assert(ClausesWithImplicit.empty() &&
- "No clauses are allowed for 'omp cancellation point' directive");
- assert(AStmt == nullptr && "No associated statement allowed for 'omp "
- "cancellation point' directive");
- Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
- break;
- case OMPD_cancel:
- assert(AStmt == nullptr &&
- "No associated statement allowed for 'omp cancel' directive");
- Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
- CancelRegion);
- AllowedNameModifiers.push_back(OMPD_cancel);
- break;
- case OMPD_target_data:
- Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
- EndLoc);
- AllowedNameModifiers.push_back(OMPD_target_data);
- break;
- case OMPD_target_enter_data:
- Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
- EndLoc);
- AllowedNameModifiers.push_back(OMPD_target_enter_data);
- break;
- case OMPD_target_exit_data:
- Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
- EndLoc);
- AllowedNameModifiers.push_back(OMPD_target_exit_data);
- break;
- case OMPD_taskloop:
- Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
- EndLoc, VarsWithInheritedDSA);
- AllowedNameModifiers.push_back(OMPD_taskloop);
- break;
- case OMPD_taskloop_simd:
- Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
- EndLoc, VarsWithInheritedDSA);
- AllowedNameModifiers.push_back(OMPD_taskloop);
- break;
- case OMPD_distribute:
- Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
- EndLoc, VarsWithInheritedDSA);
- break;
- case OMPD_threadprivate:
- llvm_unreachable("OpenMP Directive is not allowed");
- case OMPD_unknown:
- llvm_unreachable("Unknown OpenMP directive");
- }
- for (auto P : VarsWithInheritedDSA) {
- Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
- << P.first << P.second->getSourceRange();
- }
- ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
- if (!AllowedNameModifiers.empty())
- ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
- ErrorFound;
- if (ErrorFound)
- return StmtError();
- return Res;
- }
- StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
- Stmt *AStmt,
- SourceLocation StartLoc,
- SourceLocation EndLoc) {
- if (!AStmt)
- return StmtError();
- CapturedStmt *CS = cast<CapturedStmt>(AStmt);
- // 1.2.2 OpenMP Language Terminology
- // Structured block - An executable statement with a single entry at the
- // top and a single exit at the bottom.
- // The point of exit cannot be a branch out of the structured block.
- // longjmp() and throw() must not violate the entry/exit criteria.
- CS->getCapturedDecl()->setNothrow();
- getCurFunction()->setHasBranchProtectedScope();
- return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
- DSAStack->isCancelRegion());
- }
- namespace {
- /// \brief Helper class for checking canonical form of the OpenMP loops and
- /// extracting iteration space of each loop in the loop nest, that will be used
- /// for IR generation.
- class OpenMPIterationSpaceChecker {
- /// \brief Reference to Sema.
- Sema &SemaRef;
- /// \brief A location for diagnostics (when there is no some better location).
- SourceLocation DefaultLoc;
- /// \brief A location for diagnostics (when increment is not compatible).
- SourceLocation ConditionLoc;
- /// \brief A source location for referring to loop init later.
- SourceRange InitSrcRange;
- /// \brief A source location for referring to condition later.
- SourceRange ConditionSrcRange;
- /// \brief A source location for referring to increment later.
- SourceRange IncrementSrcRange;
- /// \brief Loop variable.
- VarDecl *Var;
- /// \brief Reference to loop variable.
- DeclRefExpr *VarRef;
- /// \brief Lower bound (initializer for the var).
- Expr *LB;
- /// \brief Upper bound.
- Expr *UB;
- /// \brief Loop step (increment).
- Expr *Step;
- /// \brief This flag is true when condition is one of:
- /// Var < UB
- /// Var <= UB
- /// UB > Var
- /// UB >= Var
- bool TestIsLessOp;
- /// \brief This flag is true when condition is strict ( < or > ).
- bool TestIsStrictOp;
- /// \brief This flag is true when step is subtracted on each iteration.
- bool SubtractStep;
- public:
- OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
- : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
- InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
- IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
- LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
- TestIsStrictOp(false), SubtractStep(false) {}
- /// \brief Check init-expr for canonical loop form and save loop counter
- /// variable - #Var and its initialization value - #LB.
- bool CheckInit(Stmt *S, bool EmitDiags = true);
- /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
- /// for less/greater and for strict/non-strict comparison.
- bool CheckCond(Expr *S);
- /// \brief Check incr-expr for canonical loop form and return true if it
- /// does not conform, otherwise save loop step (#Step).
- bool CheckInc(Expr *S);
- /// \brief Return the loop counter variable.
- VarDecl *GetLoopVar() const { return Var; }
- /// \brief Return the reference expression to loop counter variable.
- DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
- /// \brief Source range of the loop init.
- SourceRange GetInitSrcRange() const { return InitSrcRange; }
- /// \brief Source range of the loop condition.
- SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
- /// \brief Source range of the loop increment.
- SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
- /// \brief True if the step should be subtracted.
- bool ShouldSubtractStep() const { return SubtractStep; }
- /// \brief Build the expression to calculate the number of iterations.
- Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
- /// \brief Build the precondition expression for the loops.
- Expr *BuildPreCond(Scope *S, Expr *Cond) const;
- /// \brief Build reference expression to the counter be used for codegen.
- Expr *BuildCounterVar() const;
- /// \brief Build reference expression to the private counter be used for
- /// codegen.
- Expr *BuildPrivateCounterVar() const;
- /// \brief Build initization of the counter be used for codegen.
- Expr *BuildCounterInit() const;
- /// \brief Build step of the counter be used for codegen.
- Expr *BuildCounterStep() const;
- /// \brief Return true if any expression is dependent.
- bool Dependent() const;
- private:
- /// \brief Check the right-hand side of an assignment in the increment
- /// expression.
- bool CheckIncRHS(Expr *RHS);
- /// \brief Helper to set loop counter variable and its initializer.
- bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
- /// \brief Helper to set upper bound.
- bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
- SourceLocation SL);
- /// \brief Helper to set loop increment.
- bool SetStep(Expr *NewStep, bool Subtract);
- };
- bool OpenMPIterationSpaceChecker::Dependent() const {
- if (!Var) {
- assert(!LB && !UB && !Step);
- return false;
- }
- return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
- (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
- }
- template <typename T>
- static T *getExprAsWritten(T *E) {
- if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
- E = ExprTemp->getSubExpr();
- if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
- E = MTE->GetTemporaryExpr();
- while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
- E = Binder->getSubExpr();
- if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
- E = ICE->getSubExprAsWritten();
- return E->IgnoreParens();
- }
- bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
- DeclRefExpr *NewVarRefExpr,
- Expr *NewLB) {
- // State consistency checking to ensure correct usage.
- assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
- UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
- if (!NewVar || !NewLB)
- return true;
- Var = NewVar;
- VarRef = NewVarRefExpr;
- if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
- if (const CXXConstructorDecl *Ctor = CE->getConstructor())
- if ((Ctor->isCopyOrMoveConstructor() ||
- Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
- CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
- NewLB = CE->getArg(0)->IgnoreParenImpCasts();
- LB = NewLB;
- return false;
- }
- bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
- SourceRange SR, SourceLocation SL) {
- // State consistency checking to ensure correct usage.
- assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
- !TestIsLessOp && !TestIsStrictOp);
- if (!NewUB)
- return true;
- UB = NewUB;
- TestIsLessOp = LessOp;
- TestIsStrictOp = StrictOp;
- ConditionSrcRange = SR;
- ConditionLoc = SL;
- return false;
- }
- bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
- // State consistency checking to ensure correct usage.
- assert(Var != nullptr && LB != nullptr && Step == nullptr);
- if (!NewStep)
- return true;
- if (!NewStep->isValueDependent()) {
- // Check that the step is integer expression.
- SourceLocation StepLoc = NewStep->getLocStart();
- ExprResult Val =
- SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
- if (Val.isInvalid())
- return true;
- NewStep = Val.get();
- // OpenMP [2.6, Canonical Loop Form, Restrictions]
- // If test-expr is of form var relational-op b and relational-op is < or
- // <= then incr-expr must cause var to increase on each iteration of the
- // loop. If test-expr is of form var relational-op b and relational-op is
- // > or >= then incr-expr must cause var to decrease on each iteration of
- // the loop.
- // If test-expr is of form b relational-op var and relational-op is < or
- // <= then incr-expr must cause var to decrease on each iteration of the
- // loop. If test-expr is of form b relational-op var and relational-op is
- // > or >= then incr-expr must cause var to increase on each iteration of
- // the loop.
- llvm::APSInt Result;
- bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
- bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
- bool IsConstNeg =
- IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
- bool IsConstPos =
- IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
- bool IsConstZero = IsConstant && !Result.getBoolValue();
- if (UB && (IsConstZero ||
- (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
- : (IsConstPos || (IsUnsigned && !Subtract))))) {
- SemaRef.Diag(NewStep->getExprLoc(),
- diag::err_omp_loop_incr_not_compatible)
- << Var << TestIsLessOp << NewStep->getSourceRange();
- SemaRef.Diag(ConditionLoc,
- diag::note_omp_loop_cond_requres_compatible_incr)
- << TestIsLessOp << ConditionSrcRange;
- return true;
- }
- if (TestIsLessOp == Subtract) {
- NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
- NewStep).get();
- Subtract = !Subtract;
- }
- }
- Step = NewStep;
- SubtractStep = Subtract;
- return false;
- }
- bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
- // Check init-expr for canonical loop form and save loop counter
- // variable - #Var and its initialization value - #LB.
- // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
- // var = lb
- // integer-type var = lb
- // random-access-iterator-type var = lb
- // pointer-type var = lb
- //
- if (!S) {
- if (EmitDiags) {
- SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
- }
- return true;
- }
- InitSrcRange = S->getSourceRange();
- if (Expr *E = dyn_cast<Expr>(S))
- S = E->IgnoreParens();
- if (auto BO = dyn_cast<BinaryOperator>(S)) {
- if (BO->getOpcode() == BO_Assign)
- if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
- return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
- BO->getRHS());
- } else if (auto DS = dyn_cast<DeclStmt>(S)) {
- if (DS->isSingleDecl()) {
- if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
- if (Var->hasInit() && !Var->getType()->isReferenceType()) {
- // Accept non-canonical init form here but emit ext. warning.
- if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
- SemaRef.Diag(S->getLocStart(),
- diag::ext_omp_loop_not_canonical_init)
- << S->getSourceRange();
- return SetVarAndLB(Var, nullptr, Var->getInit());
- }
- }
- }
- } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
- if (CE->getOperator() == OO_Equal)
- if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
- return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
- CE->getArg(1));
- if (EmitDiags) {
- SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
- << S->getSourceRange();
- }
- return true;
- }
- /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
- /// variable (which may be the loop variable) if possible.
- static const VarDecl *GetInitVarDecl(const Expr *E) {
- if (!E)
- return nullptr;
- E = getExprAsWritten(E);
- if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
- if (const CXXConstructorDecl *Ctor = CE->getConstructor())
- if ((Ctor->isCopyOrMoveConstructor() ||
- Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
- CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
- E = CE->getArg(0)->IgnoreParenImpCasts();
- auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
- if (!DRE)
- return nullptr;
- return dyn_cast<VarDecl>(DRE->getDecl());
- }
- bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
- // Check test-expr for canonical form, save upper-bound UB, flags for
- // less/greater and for strict/non-strict comparison.
- // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
- // var relational-op b
- // b relational-op var
- //
- if (!S) {
- SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
- return true;
- }
- S = getExprAsWritten(S);
- SourceLocation CondLoc = S->getLocStart();
- if (auto BO = dyn_cast<BinaryOperator>(S)) {
- if (BO->isRelationalOp()) {
- if (GetInitVarDecl(BO->getLHS()) == Var)
- return SetUB(BO->getRHS(),
- (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
- (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
- BO->getSourceRange(), BO->getOperatorLoc());
- if (GetInitVarDecl(BO->getRHS()) == Var)
- return SetUB(BO->getLHS(),
- (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
- (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
- BO->getSourceRange(), BO->getOperatorLoc());
- }
- } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
- if (CE->getNumArgs() == 2) {
- auto Op = CE->getOperator();
- switch (Op) {
- case OO_Greater:
- case OO_GreaterEqual:
- case OO_Less:
- case OO_LessEqual:
- if (GetInitVarDecl(CE->getArg(0)) == Var)
- return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
- Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
- CE->getOperatorLoc());
- if (GetInitVarDecl(CE->getArg(1)) == Var)
- return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
- Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
- CE->getOperatorLoc());
- break;
- default:
- break;
- }
- }
- }
- SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
- << S->getSourceRange() << Var;
- return true;
- }
- bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
- // RHS of canonical loop form increment can be:
- // var + incr
- // incr + var
- // var - incr
- //
- RHS = RHS->IgnoreParenImpCasts();
- if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
- if (BO->isAdditiveOp()) {
- bool IsAdd = BO->getOpcode() == BO_Add;
- if (GetInitVarDecl(BO->getLHS()) == Var)
- return SetStep(BO->getRHS(), !IsAdd);
- if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
- return SetStep(BO->getLHS(), false);
- }
- } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
- bool IsAdd = CE->getOperator() == OO_Plus;
- if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
- if (GetInitVarDecl(CE->getArg(0)) == Var)
- return SetStep(CE->getArg(1), !IsAdd);
- if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
- return SetStep(CE->getArg(0), false);
- }
- }
- SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
- << RHS->getSourceRange() << Var;
- return true;
- }
- bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
- // Check incr-expr for canonical loop form and return true if it
- // does not conform.
- // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
- // ++var
- // var++
- // --var
- // var--
- // var += incr
- // var -= incr
- // var = var + incr
- // var = incr + var
- // var = var - incr
- //
- if (!S) {
- SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
- return true;
- }
- IncrementSrcRange = S->getSourceRange();
- S = S->IgnoreParens();
- if (auto UO = dyn_cast<UnaryOperator>(S)) {
- if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
- return SetStep(
- SemaRef.ActOnIntegerConstant(UO->getLocStart(),
- (UO->isDecrementOp() ? -1 : 1)).get(),
- false);
- } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
- switch (BO->getOpcode()) {
- case BO_AddAssign:
- case BO_SubAssign:
- if (GetInitVarDecl(BO->getLHS()) == Var)
- return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
- break;
- case BO_Assign:
- if (GetInitVarDecl(BO->getLHS()) == Var)
- return CheckIncRHS(BO->getRHS());
- break;
- default:
- break;
- }
- } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
- switch (CE->getOperator()) {
- case OO_PlusPlus:
- case OO_MinusMinus:
- if (GetInitVarDecl(CE->getArg(0)) == Var)
- return SetStep(
- SemaRef.ActOnIntegerConstant(
- CE->getLocStart(),
- ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
- false);
- break;
- case OO_PlusEqual:
- case OO_MinusEqual:
- if (GetInitVarDecl(CE->getArg(0)) == Var)
- return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
- break;
- case OO_Equal:
- if (GetInitVarDecl(CE->getArg(0)) == Var)
- return CheckIncRHS(CE->getArg(1));
- break;
- default:
- break;
- }
- }
- SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
- << S->getSourceRange() << Var;
- return true;
- }
- namespace {
- // Transform variables declared in GNU statement expressions to new ones to
- // avoid crash on codegen.
- class TransformToNewDefs : public TreeTransform<TransformToNewDefs> {
- typedef TreeTransform<TransformToNewDefs> BaseTransform;
- public:
- TransformToNewDefs(Sema &SemaRef) : BaseTransform(SemaRef) {}
- Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
- if (auto *VD = cast<VarDecl>(D))
- if (!isa<ParmVarDecl>(D) && !isa<VarTemplateSpecializationDecl>(D) &&
- !isa<ImplicitParamDecl>(D)) {
- auto *NewVD = VarDecl::Create(
- SemaRef.Context, VD->getDeclContext(), VD->getLocStart(),
- VD->getLocation(), VD->getIdentifier(), VD->getType(),
- VD->getTypeSourceInfo(), VD->getStorageClass());
- NewVD->setTSCSpec(VD->getTSCSpec());
- NewVD->setInit(VD->getInit());
- NewVD->setInitStyle(VD->getInitStyle());
- NewVD->setExceptionVariable(VD->isExceptionVariable());
- NewVD->setNRVOVariable(VD->isNRVOVariable());
- NewVD->setCXXForRangeDecl(VD->isInExternCXXContext());
- NewVD->setConstexpr(VD->isConstexpr());
- NewVD->setInitCapture(VD->isInitCapture());
- NewVD->setPreviousDeclInSameBlockScope(
- VD->isPreviousDeclInSameBlockScope());
- VD->getDeclContext()->addHiddenDecl(NewVD);
- if (VD->hasAttrs())
- NewVD->setAttrs(VD->getAttrs());
- transformedLocalDecl(VD, NewVD);
- return NewVD;
- }
- return BaseTransform::TransformDefinition(Loc, D);
- }
- ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
- if (auto *NewD = TransformDecl(E->getExprLoc(), E->getDecl()))
- if (E->getDecl() != NewD) {
- NewD->setReferenced();
- NewD->markUsed(SemaRef.Context);
- return DeclRefExpr::Create(
- SemaRef.Context, E->getQualifierLoc(), E->getTemplateKeywordLoc(),
- cast<ValueDecl>(NewD), E->refersToEnclosingVariableOrCapture(),
- E->getNameInfo(), E->getType(), E->getValueKind());
- }
- return BaseTransform::TransformDeclRefExpr(E);
- }
- };
- }
- /// \brief Build the expression to calculate the number of iterations.
- Expr *
- OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
- const bool LimitedType) const {
- TransformToNewDefs Transform(SemaRef);
- ExprResult Diff;
- auto VarType = Var->getType().getNonReferenceType();
- if (VarType->isIntegerType() || VarType->isPointerType() ||
- SemaRef.getLangOpts().CPlusPlus) {
- // Upper - Lower
- auto *UBExpr = TestIsLessOp ? UB : LB;
- auto *LBExpr = TestIsLessOp ? LB : UB;
- Expr *Upper = Transform.TransformExpr(UBExpr).get();
- Expr *Lower = Transform.TransformExpr(LBExpr).get();
- if (!Upper || !Lower)
- return nullptr;
- Upper = SemaRef.PerformImplicitConversion(Upper, UBExpr->getType(),
- Sema::AA_Converting,
- /*AllowExplicit=*/true)
- .get();
- Lower = SemaRef.PerformImplicitConversion(Lower, LBExpr->getType(),
- Sema::AA_Converting,
- /*AllowExplicit=*/true)
- .get();
- if (!Upper || !Lower)
- return nullptr;
- Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
- if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
- // BuildBinOp already emitted error, this one is to point user to upper
- // and lower bound, and to tell what is passed to 'operator-'.
- SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
- << Upper->getSourceRange() << Lower->getSourceRange();
- return nullptr;
- }
- }
- if (!Diff.isUsable())
- return nullptr;
- // Upper - Lower [- 1]
- if (TestIsStrictOp)
- Diff = SemaRef.BuildBinOp(
- S, DefaultLoc, BO_Sub, Diff.get(),
- SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
- if (!Diff.isUsable())
- return nullptr;
- // Upper - Lower [- 1] + Step
- auto NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
- if (NewStep.isInvalid())
- return nullptr;
- NewStep = SemaRef.PerformImplicitConversion(
- NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
- /*AllowExplicit=*/true);
- if (NewStep.isInvalid())
- return nullptr;
- Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
- if (!Diff.isUsable())
- return nullptr;
- // Parentheses (for dumping/debugging purposes only).
- Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
- if (!Diff.isUsable())
- return nullptr;
- // (Upper - Lower [- 1] + Step) / Step
- NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
- if (NewStep.isInvalid())
- return nullptr;
- NewStep = SemaRef.PerformImplicitConversion(
- NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
- /*AllowExplicit=*/true);
- if (NewStep.isInvalid())
- return nullptr;
- Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
- if (!Diff.isUsable())
- return nullptr;
- // OpenMP runtime requires 32-bit or 64-bit loop variables.
- QualType Type = Diff.get()->getType();
- auto &C = SemaRef.Context;
- bool UseVarType = VarType->hasIntegerRepresentation() &&
- C.getTypeSize(Type) > C.getTypeSize(VarType);
- if (!Type->isIntegerType() || UseVarType) {
- unsigned NewSize =
- UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
- bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
- : Type->hasSignedIntegerRepresentation();
- Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
- Diff = SemaRef.PerformImplicitConversion(
- Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
- if (!Diff.isUsable())
- return nullptr;
- }
- if (LimitedType) {
- unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
- if (NewSize != C.getTypeSize(Type)) {
- if (NewSize < C.getTypeSize(Type)) {
- assert(NewSize == 64 && "incorrect loop var size");
- SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
- << InitSrcRange << ConditionSrcRange;
- }
- QualType NewType = C.getIntTypeForBitwidth(
- NewSize, Type->hasSignedIntegerRepresentation() ||
- C.getTypeSize(Type) < NewSize);
- Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
- Sema::AA_Converting, true);
- if (!Diff.isUsable())
- return nullptr;
- }
- }
- return Diff.get();
- }
- Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
- // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
- bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
- SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
- TransformToNewDefs Transform(SemaRef);
- auto NewLB = Transform.TransformExpr(LB);
- auto NewUB = Transform.TransformExpr(UB);
- if (NewLB.isInvalid() || NewUB.isInvalid())
- return Cond;
- NewLB = SemaRef.PerformImplicitConversion(NewLB.get(), LB->getType(),
- Sema::AA_Converting,
- /*AllowExplicit=*/true);
- NewUB = SemaRef.PerformImplicitConversion(NewUB.get(), UB->getType(),
- Sema::AA_Converting,
- /*AllowExplicit=*/true);
- if (NewLB.isInvalid() || NewUB.isInvalid())
- return Cond;
- auto CondExpr = SemaRef.BuildBinOp(
- S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
- : (TestIsStrictOp ? BO_GT : BO_GE),
- NewLB.get(), NewUB.get());
- if (CondExpr.isUsable()) {
- CondExpr = SemaRef.PerformImplicitConversion(
- CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
- /*AllowExplicit=*/true);
- }
- SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
- // Otherwise use original loop conditon and evaluate it in runtime.
- return CondExpr.isUsable() ? CondExpr.get() : Cond;
- }
- /// \brief Build reference expression to the counter be used for codegen.
- Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
- return buildDeclRefExpr(SemaRef, Var, Var->getType().getNonReferenceType(),
- DefaultLoc);
- }
- Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
- if (Var && !Var->isInvalidDecl()) {
- auto Type = Var->getType().getNonReferenceType();
- auto *PrivateVar =
- buildVarDecl(SemaRef, DefaultLoc, Type, Var->getName(),
- Var->hasAttrs() ? &Var->getAttrs() : nullptr);
- if (PrivateVar->isInvalidDecl())
- return nullptr;
- return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
- }
- return nullptr;
- }
- /// \brief Build initization of the counter be used for codegen.
- Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
- /// \brief Build step of the counter be used for codegen.
- Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
- /// \brief Iteration space of a single for loop.
- struct LoopIterationSpace {
- /// \brief Condition of the loop.
- Expr *PreCond;
- /// \brief This expression calculates the number of iterations in the loop.
- /// It is always possible to calculate it before starting the loop.
- Expr *NumIterations;
- /// \brief The loop counter variable.
- Expr *CounterVar;
- /// \brief Private loop counter variable.
- Expr *PrivateCounterVar;
- /// \brief This is initializer for the initial value of #CounterVar.
- Expr *CounterInit;
- /// \brief This is step for the #CounterVar used to generate its update:
- /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
- Expr *CounterStep;
- /// \brief Should step be subtracted?
- bool Subtract;
- /// \brief Source range of the loop init.
- SourceRange InitSrcRange;
- /// \brief Source range of the loop condition.
- SourceRange CondSrcRange;
- /// \brief Source range of the loop increment.
- SourceRange IncSrcRange;
- };
- } // namespace
- void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
- assert(getLangOpts().OpenMP && "OpenMP is not active.");
- assert(Init && "Expected loop in canonical form.");
- unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
- if (AssociatedLoops > 0 &&
- isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
- OpenMPIterationSpaceChecker ISC(*this, ForLoc);
- if (!ISC.CheckInit(Init, /*EmitDiags=*/false))
- DSAStack->addLoopControlVariable(ISC.GetLoopVar());
- DSAStack->setAssociatedLoops(AssociatedLoops - 1);
- }
- }
- /// \brief Called on a for stmt to check and extract its iteration space
- /// for further processing (such as collapsing).
- static bool CheckOpenMPIterationSpace(
- OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
- unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
- Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
- llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
- LoopIterationSpace &ResultIterSpace) {
- // OpenMP [2.6, Canonical Loop Form]
- // for (init-expr; test-expr; incr-expr) structured-block
- auto For = dyn_cast_or_null<ForStmt>(S);
- if (!For) {
- SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
- << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
- << getOpenMPDirectiveName(DKind) << NestedLoopCount
- << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
- if (NestedLoopCount > 1) {
- if (CollapseLoopCountExpr && OrderedLoopCountExpr)
- SemaRef.Diag(DSA.getConstructLoc(),
- diag::note_omp_collapse_ordered_expr)
- << 2 << CollapseLoopCountExpr->getSourceRange()
- << OrderedLoopCountExpr->getSourceRange();
- else if (CollapseLoopCountExpr)
- SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
- diag::note_omp_collapse_ordered_expr)
- << 0 << CollapseLoopCountExpr->getSourceRange();
- else
- SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
- diag::note_omp_collapse_ordered_expr)
- << 1 << OrderedLoopCountExpr->getSourceRange();
- }
- return true;
- }
- assert(For->getBody());
- OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
- // Check init.
- auto Init = For->getInit();
- if (ISC.CheckInit(Init)) {
- return true;
- }
- bool HasErrors = false;
- // Check loop variable's type.
- auto Var = ISC.GetLoopVar();
- // OpenMP [2.6, Canonical Loop Form]
- // Var is one of the following:
- // A variable of signed or unsigned integer type.
- // For C++, a variable of a random access iterator type.
- // For C, a variable of a pointer type.
- auto VarType = Var->getType().getNonReferenceType();
- if (!VarType->isDependentType() && !VarType->isIntegerType() &&
- !VarType->isPointerType() &&
- !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
- SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
- << SemaRef.getLangOpts().CPlusPlus;
- HasErrors = true;
- }
- // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
- // Construct
- // The loop iteration variable(s) in the associated for-loop(s) of a for or
- // parallel for construct is (are) private.
- // The loop iteration variable in the associated for-loop of a simd construct
- // with just one associated for-loop is linear with a constant-linear-step
- // that is the increment of the associated for-loop.
- // Exclude loop var from the list of variables with implicitly defined data
- // sharing attributes.
- VarsWithImplicitDSA.erase(Var);
- // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
- // a Construct, C/C++].
- // The loop iteration variable in the associated for-loop of a simd construct
- // with just one associated for-loop may be listed in a linear clause with a
- // constant-linear-step that is the increment of the associated for-loop.
- // The loop iteration variable(s) in the associated for-loop(s) of a for or
- // parallel for construct may be listed in a private or lastprivate clause.
- DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
- auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
- // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
- // declared in the loop and it is predetermined as a private.
- auto PredeterminedCKind =
- isOpenMPSimdDirective(DKind)
- ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
- : OMPC_private;
- if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
- DVar.CKind != PredeterminedCKind) ||
- ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
- isOpenMPDistributeDirective(DKind)) &&
- !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
- DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
- (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
- SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
- << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
- << getOpenMPClauseName(PredeterminedCKind);
- if (DVar.RefExpr == nullptr)
- DVar.CKind = PredeterminedCKind;
- ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
- HasErrors = true;
- } else if (LoopVarRefExpr != nullptr) {
- // Make the loop iteration variable private (for worksharing constructs),
- // linear (for simd directives with the only one associated loop) or
- // lastprivate (for simd directives with several collapsed or ordered
- // loops).
- if (DVar.CKind == OMPC_unknown)
- DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
- /*FromParent=*/false);
- DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
- }
- assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
- // Check test-expr.
- HasErrors |= ISC.CheckCond(For->getCond());
- // Check incr-expr.
- HasErrors |= ISC.CheckInc(For->getInc());
- if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
- return HasErrors;
- // Build the loop's iteration space representation.
- ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
- ResultIterSpace.NumIterations = ISC.BuildNumIterations(
- DSA.getCurScope(), (isOpenMPWorksharingDirective(DKind) ||
- isOpenMPTaskLoopDirective(DKind) ||
- isOpenMPDistributeDirective(DKind)));
- ResultIterSpace.CounterVar = ISC.BuildCounterVar();
- ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
- ResultIterSpace.CounterInit = ISC.BuildCounterInit();
- ResultIterSpace.CounterStep = ISC.BuildCounterStep();
- ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
- ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
- ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
- ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
- HasErrors |= (ResultIterSpace.PreCond == nullptr ||
- ResultIterSpace.NumIterations == nullptr ||
- ResultIterSpace.CounterVar == nullptr ||
- ResultIterSpace.PrivateCounterVar == nullptr ||
- ResultIterSpace.CounterInit == nullptr ||
- ResultIterSpace.CounterStep == nullptr);
- return HasErrors;
- }
- /// \brief Build 'VarRef = Start.
- static ExprResult BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc,
- ExprResult VarRef, ExprResult Start) {
- TransformToNewDefs Transform(SemaRef);
- // Build 'VarRef = Start.
- auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
- if (NewStart.isInvalid())
- return ExprError();
- NewStart = SemaRef.PerformImplicitConversion(
- NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
- Sema::AA_Converting,
- /*AllowExplicit=*/true);
- if (NewStart.isInvalid())
- return ExprError();
- NewStart = SemaRef.PerformImplicitConversion(
- NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
- /*AllowExplicit=*/true);
- if (!NewStart.isUsable())
- return ExprError();
- auto Init =
- SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
- return Init;
- }
- /// \brief Build 'VarRef = Start + Iter * Step'.
- static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
- SourceLocation Loc, ExprResult VarRef,
- ExprResult Start, ExprResult Iter,
- ExprResult Step, bool Subtract) {
- // Add parentheses (for debugging purposes only).
- Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
- if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
- !Step.isUsable())
- return ExprError();
- TransformToNewDefs Transform(SemaRef);
- auto NewStep = Transform.TransformExpr(Step.get()->IgnoreImplicit());
- if (NewStep.isInvalid())
- return ExprError();
- NewStep = SemaRef.PerformImplicitConversion(
- NewStep.get(), Step.get()->IgnoreImplicit()->getType(),
- Sema::AA_Converting,
- /*AllowExplicit=*/true);
- if (NewStep.isInvalid())
- return ExprError();
- ExprResult Update =
- SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
- if (!Update.isUsable())
- return ExprError();
- // Build 'VarRef = Start + Iter * Step'.
- auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
- if (NewStart.isInvalid())
- return ExprError();
- NewStart = SemaRef.PerformImplicitConversion(
- NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
- Sema::AA_Converting,
- /*AllowExplicit=*/true);
- if (NewStart.isInvalid())
- return ExprError();
- Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
- NewStart.get(), Update.get());
- if (!Update.isUsable())
- return ExprError();
- Update = SemaRef.PerformImplicitConversion(
- Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
- if (!Update.isUsable())
- return ExprError();
- Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
- return Update;
- }
- /// \brief Convert integer expression \a E to make it have at least \a Bits
- /// bits.
- static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
- Sema &SemaRef) {
- if (E == nullptr)
- return ExprError();
- auto &C = SemaRef.Context;
- QualType OldType = E->getType();
- unsigned HasBits = C.getTypeSize(OldType);
- if (HasBits >= Bits)
- return ExprResult(E);
- // OK to convert to signed, because new type has more bits than old.
- QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
- return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
- true);
- }
- /// \brief Check if the given expression \a E is a constant integer that fits
- /// into \a Bits bits.
- static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
- if (E == nullptr)
- return false;
- llvm::APSInt Result;
- if (E->isIntegerConstantExpr(Result, SemaRef.Context))
- return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
- return false;
- }
- /// \brief Called on a for stmt to check itself and nested loops (if any).
- /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
- /// number of collapsed loops otherwise.
- static unsigned
- CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
- Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
- DSAStackTy &DSA,
- llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
- OMPLoopDirective::HelperExprs &Built) {
- unsigned NestedLoopCount = 1;
- if (CollapseLoopCountExpr) {
- // Found 'collapse' clause - calculate collapse number.
- llvm::APSInt Result;
- if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
- NestedLoopCount = Result.getLimitedValue();
- }
- if (OrderedLoopCountExpr) {
- // Found 'ordered' clause - calculate collapse number.
- llvm::APSInt Result;
- if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
- if (Result.getLimitedValue() < NestedLoopCount) {
- SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
- diag::err_omp_wrong_ordered_loop_count)
- << OrderedLoopCountExpr->getSourceRange();
- SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
- diag::note_collapse_loop_count)
- << CollapseLoopCountExpr->getSourceRange();
- }
- NestedLoopCount = Result.getLimitedValue();
- }
- }
- // This is helper routine for loop directives (e.g., 'for', 'simd',
- // 'for simd', etc.).
- SmallVector<LoopIterationSpace, 4> IterSpaces;
- IterSpaces.resize(NestedLoopCount);
- Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
- for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
- if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
- NestedLoopCount, CollapseLoopCountExpr,
- OrderedLoopCountExpr, VarsWithImplicitDSA,
- IterSpaces[Cnt]))
- return 0;
- // Move on to the next nested for loop, or to the loop body.
- // OpenMP [2.8.1, simd construct, Restrictions]
- // All loops associated with the construct must be perfectly nested; that
- // is, there must be no intervening code nor any OpenMP directive between
- // any two loops.
- CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
- }
- Built.clear(/* size */ NestedLoopCount);
- if (SemaRef.CurContext->isDependentContext())
- return NestedLoopCount;
- // An example of what is generated for the following code:
- //
- // #pragma omp simd collapse(2) ordered(2)
- // for (i = 0; i < NI; ++i)
- // for (k = 0; k < NK; ++k)
- // for (j = J0; j < NJ; j+=2) {
- // <loop body>
- // }
- //
- // We generate the code below.
- // Note: the loop body may be outlined in CodeGen.
- // Note: some counters may be C++ classes, operator- is used to find number of
- // iterations and operator+= to calculate counter value.
- // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
- // or i64 is currently supported).
- //
- // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
- // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
- // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
- // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
- // // similar updates for vars in clauses (e.g. 'linear')
- // <loop body (using local i and j)>
- // }
- // i = NI; // assign final values of counters
- // j = NJ;
- //
- // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
- // the iteration counts of the collapsed for loops.
- // Precondition tests if there is at least one iteration (all conditions are
- // true).
- auto PreCond = ExprResult(IterSpaces[0].PreCond);
- auto N0 = IterSpaces[0].NumIterations;
- ExprResult LastIteration32 = WidenIterationCount(
- 32 /* Bits */, SemaRef.PerformImplicitConversion(
- N0->IgnoreImpCasts(), N0->getType(),
- Sema::AA_Converting, /*AllowExplicit=*/true)
- .get(),
- SemaRef);
- ExprResult LastIteration64 = WidenIterationCount(
- 64 /* Bits */, SemaRef.PerformImplicitConversion(
- N0->IgnoreImpCasts(), N0->getType(),
- Sema::AA_Converting, /*AllowExplicit=*/true)
- .get(),
- SemaRef);
- if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
- return NestedLoopCount;
- auto &C = SemaRef.Context;
- bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
- Scope *CurScope = DSA.getCurScope();
- for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
- if (PreCond.isUsable()) {
- PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
- PreCond.get(), IterSpaces[Cnt].PreCond);
- }
- auto N = IterSpaces[Cnt].NumIterations;
- AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
- if (LastIteration32.isUsable())
- LastIteration32 = SemaRef.BuildBinOp(
- CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
- SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
- Sema::AA_Converting,
- /*AllowExplicit=*/true)
- .get());
- if (LastIteration64.isUsable())
- LastIteration64 = SemaRef.BuildBinOp(
- CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
- SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
- Sema::AA_Converting,
- /*AllowExplicit=*/true)
- .get());
- }
- // Choose either the 32-bit or 64-bit version.
- ExprResult LastIteration = LastIteration64;
- if (LastIteration32.isUsable() &&
- C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
- (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
- FitsInto(
- 32 /* Bits */,
- LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
- LastIteration64.get(), SemaRef)))
- LastIteration = LastIteration32;
- if (!LastIteration.isUsable())
- return 0;
- // Save the number of iterations.
- ExprResult NumIterations = LastIteration;
- {
- LastIteration = SemaRef.BuildBinOp(
- CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
- SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
- if (!LastIteration.isUsable())
- return 0;
- }
- // Calculate the last iteration number beforehand instead of doing this on
- // each iteration. Do not do this if the number of iterations may be kfold-ed.
- llvm::APSInt Result;
- bool IsConstant =
- LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
- ExprResult CalcLastIteration;
- if (!IsConstant) {
- SourceLocation SaveLoc;
- VarDecl *SaveVar =
- buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
- ".omp.last.iteration");
- ExprResult SaveRef = buildDeclRefExpr(
- SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
- CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
- SaveRef.get(), LastIteration.get());
- LastIteration = SaveRef;
- // Prepare SaveRef + 1.
- NumIterations = SemaRef.BuildBinOp(
- CurScope, SaveLoc, BO_Add, SaveRef.get(),
- SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
- if (!NumIterations.isUsable())
- return 0;
- }
- SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
- QualType VType = LastIteration.get()->getType();
- // Build variables passed into runtime, nesessary for worksharing directives.
- ExprResult LB, UB, IL, ST, EUB;
- if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
- isOpenMPDistributeDirective(DKind)) {
- // Lower bound variable, initialized with zero.
- VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
- LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
- SemaRef.AddInitializerToDecl(
- LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
- /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
- // Upper bound variable, initialized with last iteration number.
- VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
- UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
- SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
- /*DirectInit*/ false,
- /*TypeMayContainAuto*/ false);
- // A 32-bit variable-flag where runtime returns 1 for the last iteration.
- // This will be used to implement clause 'lastprivate'.
- QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
- VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
- IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
- SemaRef.AddInitializerToDecl(
- ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
- /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
- // Stride variable returned by runtime (we initialize it to 1 by default).
- VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
- ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
- SemaRef.AddInitializerToDecl(
- STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
- /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
- // Build expression: UB = min(UB, LastIteration)
- // It is nesessary for CodeGen of directives with static scheduling.
- ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
- UB.get(), LastIteration.get());
- ExprResult CondOp = SemaRef.ActOnConditionalOp(
- InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
- EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
- CondOp.get());
- EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
- }
- // Build the iteration variable and its initialization before loop.
- ExprResult IV;
- ExprResult Init;
- {
- VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
- IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
- Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
- isOpenMPTaskLoopDirective(DKind) ||
- isOpenMPDistributeDirective(DKind))
- ? LB.get()
- : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
- Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
- Init = SemaRef.ActOnFinishFullExpr(Init.get());
- }
- // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
- SourceLocation CondLoc;
- ExprResult Cond =
- (isOpenMPWorksharingDirective(DKind) ||
- isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
- ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
- : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
- NumIterations.get());
- // Loop increment (IV = IV + 1)
- SourceLocation IncLoc;
- ExprResult Inc =
- SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
- SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
- if (!Inc.isUsable())
- return 0;
- Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
- Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
- if (!Inc.isUsable())
- return 0;
- // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
- // Used for directives with static scheduling.
- ExprResult NextLB, NextUB;
- if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
- isOpenMPDistributeDirective(DKind)) {
- // LB + ST
- NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
- if (!NextLB.isUsable())
- return 0;
- // LB = LB + ST
- NextLB =
- SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
- NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
- if (!NextLB.isUsable())
- return 0;
- // UB + ST
- NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
- if (!NextUB.isUsable())
- return 0;
- // UB = UB + ST
- NextUB =
- SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
- NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
- if (!NextUB.isUsable())
- return 0;
- }
- // Build updates and final values of the loop counters.
- bool HasErrors = false;
- Built.Counters.resize(NestedLoopCount);
- Built.Inits.resize(NestedLoopCount);
- Built.Updates.resize(NestedLoopCount);
- Built.Finals.resize(NestedLoopCount);
- {
- ExprResult Div;
- // Go from inner nested loop to outer.
- for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
- LoopIterationSpace &IS = IterSpaces[Cnt];
- SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
- // Build: Iter = (IV / Div) % IS.NumIters
- // where Div is product of previous iterations' IS.NumIters.
- ExprResult Iter;
- if (Div.isUsable()) {
- Iter =
- SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
- } else {
- Iter = IV;
- assert((Cnt == (int)NestedLoopCount - 1) &&
- "unusable div expected on first iteration only");
- }
- if (Cnt != 0 && Iter.isUsable())
- Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
- IS.NumIterations);
- if (!Iter.isUsable()) {
- HasErrors = true;
- break;
- }
- // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
- auto *CounterVar = buildDeclRefExpr(
- SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
- IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
- /*RefersToCapture=*/true);
- ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
- IS.CounterInit);
- if (!Init.isUsable()) {
- HasErrors = true;
- break;
- }
- ExprResult Update =
- BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
- IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
- if (!Update.isUsable()) {
- HasErrors = true;
- break;
- }
- // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
- ExprResult Final = BuildCounterUpdate(
- SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
- IS.NumIterations, IS.CounterStep, IS.Subtract);
- if (!Final.isUsable()) {
- HasErrors = true;
- break;
- }
- // Build Div for the next iteration: Div <- Div * IS.NumIters
- if (Cnt != 0) {
- if (Div.isUnset())
- Div = IS.NumIterations;
- else
- Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
- IS.NumIterations);
- // Add parentheses (for debugging purposes only).
- if (Div.isUsable())
- Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
- if (!Div.isUsable()) {
- HasErrors = true;
- break;
- }
- }
- if (!Update.isUsable() || !Final.isUsable()) {
- HasErrors = true;
- break;
- }
- // Save results
- Built.Counters[Cnt] = IS.CounterVar;
- Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
- Built.Inits[Cnt] = Init.get();
- Built.Updates[Cnt] = Update.get();
- Built.Finals[Cnt] = Final.get();
- }
- }
- if (HasErrors)
- return 0;
- // Save results
- Built.IterationVarRef = IV.get();
- Built.LastIteration = LastIteration.get();
- Built.NumIterations = NumIterations.get();
- Built.CalcLastIteration =
- SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
- Built.PreCond = PreCond.get();
- Built.Cond = Cond.get();
- Built.Init = Init.get();
- Built.Inc = Inc.get();
- Built.LB = LB.get();
- Built.UB = UB.get();
- Built.IL = IL.get();
- Built.ST = ST.get();
- Built.EUB = EUB.get();
- Built.NLB = NextLB.get();
- Built.NUB = NextUB.get();
- return NestedLoopCount;
- }
- static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
- auto CollapseClauses =
- OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
- if (CollapseClauses.begin() != CollapseClauses.end())
- return (*CollapseClauses.begin())->getNumForLoops();
- return nullptr;
- }
- static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
- auto OrderedClauses =
- OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
- if (OrderedClauses.begin() != OrderedClauses.end())
- return (*OrderedClauses.begin())->getNumForLoops();
- return nullptr;
- }
- static bool checkSimdlenSafelenValues(Sema &S, const Expr *Simdlen,
- const Expr *Safelen) {
- llvm::APSInt SimdlenRes, SafelenRes;
- if (Simdlen->isValueDependent() || Simdlen->isTypeDependent() ||
- Simdlen->isInstantiationDependent() ||
- Simdlen->containsUnexpandedParameterPack())
- return false;
- if (Safelen->isValueDependent() || Safelen->isTypeDependent() ||
- Safelen->isInstantiationDependent() ||
- Safelen->containsUnexpandedParameterPack())
- return false;
- Simdlen->EvaluateAsInt(SimdlenRes, S.Context);
- Safelen->EvaluateAsInt(SafelenRes, S.Context);
- // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
- // If both simdlen and safelen clauses are specified, the value of the simdlen
- // parameter must be less than or equal to the value of the safelen parameter.
- if (SimdlenRes > SafelenRes) {
- S.Diag(Simdlen->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values)
- << Simdlen->getSourceRange() << Safelen->getSourceRange();
- return true;
- }
- return false;
- }
- StmtResult Sema::ActOnOpenMPSimdDirective(
- ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
- SourceLocation EndLoc,
- llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
- if (!AStmt)
- return StmtError();
- assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
- OMPLoopDirective::HelperExprs B;
- // In presence of clause 'collapse' or 'ordered' with number of loops, it will
- // define the nested loops number.
- unsigned NestedLoopCount = CheckOpenMPLoop(
- OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
- AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
- if (NestedLoopCount == 0)
- return StmtError();
- assert((CurContext->isDependentContext() || B.builtAll()) &&
- "omp simd loop exprs were not built");
- if (!CurContext->isDependentContext()) {
- // Finalize the clauses that need pre-built expressions for CodeGen.
- for (auto C : Clauses) {
- if (auto LC = dyn_cast<OMPLinearClause>(C))
- if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
- B.NumIterations, *this, CurScope))
- return StmtError();
- }
- }
- // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
- // If both simdlen and safelen clauses are specified, the value of the simdlen
- // parameter must be less than or equal to the value of the safelen parameter.
- OMPSafelenClause *Safelen = nullptr;
- OMPSimdlenClause *Simdlen = nullptr;
- for (auto *Clause : Clauses) {
- if (Clause->getClauseKind() == OMPC_safelen)
- Safelen = cast<OMPSafelenClause>(Clause);
- else if (Clause->getClauseKind() == OMPC_simdlen)
- Simdlen = cast<OMPSimdlenClause>(Clause);
- if (Safelen && Simdlen)
- break;
- }
- if (Simdlen && Safelen &&
- checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
- Safelen->getSafelen()))
- return StmtError();
- getCurFunction()->setHasBranchProtectedScope();
- return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
- Clauses, AStmt, B);
- }
- StmtResult Sema::ActOnOpenMPForDirective(
- ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
- SourceLocation EndLoc,
- llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
- if (!AStmt)
- return StmtError();
- assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
- OMPLoopDirective::HelperExprs B;
- // In presence of clause 'collapse' or 'ordered' with number of loops, it will
- // define the nested loops number.
- unsigned NestedLoopCount = CheckOpenMPLoop(
- OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
- AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
- if (NestedLoopCount == 0)
- return StmtError();
- assert((CurContext->isDependentContext() || B.builtAll()) &&
- "omp for loop exprs were not built");
- if (!CurContext->isDependentContext()) {
- // Finalize the clauses that need pre-built expressions for CodeGen.
- for (auto C : Clauses) {
- if (auto LC = dyn_cast<OMPLinearClause>(C))
- if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
- B.NumIterations, *this, CurScope))
- return StmtError();
- }
- }
- getCurFunction()->setHasBranchProtectedScope();
- return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
- Clauses, AStmt, B, DSAStack->isCancelRegion());
- }
- StmtResult Sema::ActOnOpenMPForSimdDirective(
- ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
- SourceLocation EndLoc,
- llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
- if (!AStmt)
- return StmtError();
- assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
- OMPLoopDirective::HelperExprs B;
- // In presence of clause 'collapse' or 'ordered' with number of loops, it will
- // define the nested loops number.
- unsigned NestedLoopCount =
- CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
- getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
- VarsWithImplicitDSA, B);
- if (NestedLoopCount == 0)
- return StmtError();
- assert((CurContext->isDependentContext() || B.builtAll()) &&
- "omp for simd loop exprs were not built");
- if (!CurContext->isDependentContext()) {
- // Finalize the clauses that need pre-built expressions for CodeGen.
- for (auto C : Clauses) {
- if (auto LC = dyn_cast<OMPLinearClause>(C))
- if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
- B.NumIterations, *this, CurScope))
- return StmtError();
- }
- }
- // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
- // If both simdlen and safelen clauses are specified, the value of the simdlen
- // parameter must be less than or equal to the value of the safelen parameter.
- OMPSafelenClause *Safelen = nullptr;
- OMPSimdlenClause *Simdlen = nullptr;
- for (auto *Clause : Clauses) {
- if (Clause->getClauseKind() == OMPC_safelen)
- Safelen = cast<OMPSafelenClause>(Clause);
- else if (Clause->getClauseKind() == OMPC_simdlen)
- Simdlen = cast<OMPSimdlenClause>(Clause);
- if (Safelen && Simdlen)
- break;
- }
- if (Simdlen && Safelen &&
- checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
- Safelen->getSafelen()))
- return StmtError();
- getCurFunction()->setHasBranchProtectedScope();
- return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
- Clauses, AStmt, B);
- }
- StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
- Stmt *AStmt,
- SourceLocation StartLoc,
- SourceLocation EndLoc) {
- if (!AStmt)
- return StmtError();
- assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
- auto BaseStmt = AStmt;
- while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
- BaseStmt = CS->getCapturedStmt();
- if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
- auto S = C->children();
- if (S.begin() == S.end())
- return StmtError();
- // All associated statements must be '#pragma omp section' except for
- // the first one.
- for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
- if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
- if (SectionStmt)
- Diag(SectionStmt->getLocStart(),
- diag::err_omp_sections_substmt_not_section);
- return StmtError();
- }
- cast<OMPSectionDirective>(SectionStmt)
- ->setHasCancel(DSAStack->isCancelRegion());
- }
- } else {
- Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
- return StmtError();
- }
- getCurFunction()->setHasBranchProtectedScope();
- return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
- DSAStack->isCancelRegion());
- }
- StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
- SourceLocation StartLoc,
- SourceLocation EndLoc) {
- if (!AStmt)
- return StmtError();
- assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
- getCurFunction()->setHasBranchProtectedScope();
- DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
- return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
- DSAStack->isCancelRegion());
- }
- StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
- Stmt *AStmt,
- SourceLocation StartLoc,
- SourceLocation EndLoc) {
- if (!AStmt)
- return StmtError();
- assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
- getCurFunction()->setHasBranchProtectedScope();
- // OpenMP [2.7.3, single Construct, Restrictions]
- // The copyprivate clause must not be used with the nowait clause.
- OMPClause *Nowait = nullptr;
- OMPClause *Copyprivate = nullptr;
- for (auto *Clause : Clauses) {
- if (Clause->getClauseKind() == OMPC_nowait)
- Nowait = Clause;
- else if (Clause->getClauseKind() == OMPC_copyprivate)
- Copyprivate = Clause;
- if (Copyprivate && Nowait) {
- Diag(Copyprivate->getLocStart(),
- diag::err_omp_single_copyprivate_with_nowait);
- Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
- return StmtError();
- }
- }
- return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
- }
- StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
- SourceLocation StartLoc,
- SourceLocation EndLoc) {
- if (!AStmt)
- return StmtError();
- assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
- getCurFunction()->setHasBranchProtectedScope();
- return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
- }
- StmtResult Sema::ActOnOpenMPCriticalDirective(
- const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
- Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
- if (!AStmt)
- return StmtError();
- assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
- bool ErrorFound = false;
- llvm::APSInt Hint;
- SourceLocation HintLoc;
- bool DependentHint = false;
- for (auto *C : Clauses) {
- if (C->getClauseKind() == OMPC_hint) {
- if (!DirName.getName()) {
- Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
- ErrorFound = true;
- }
- Expr *E = cast<OMPHintClause>(C)->getHint();
- if (E->isTypeDependent() || E->isValueDependent() ||
- E->isInstantiationDependent())
- DependentHint = true;
- else {
- Hint = E->EvaluateKnownConstInt(Context);
- HintLoc = C->getLocStart();
- }
- }
- }
- if (ErrorFound)
- return StmtError();
- auto Pair = DSAStack->getCriticalWithHint(DirName);
- if (Pair.first && DirName.getName() && !DependentHint) {
- if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
- Diag(StartLoc, diag::err_omp_critical_with_hint);
- if (HintLoc.isValid()) {
- Diag(HintLoc, diag::note_omp_critical_hint_here)
- << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
- } else
- Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
- if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
- Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
- << 1
- << C->getHint()->EvaluateKnownConstInt(Context).toString(
- /*Radix=*/10, /*Signed=*/false);
- } else
- Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
- }
- }
- getCurFunction()->setHasBranchProtectedScope();
- auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
- Clauses, AStmt);
- if (!Pair.first && DirName.getName() && !DependentHint)
- DSAStack->addCriticalWithHint(Dir, Hint);
- return Dir;
- }
- StmtResult Sema::ActOnOpenMPParallelForDirective(
- ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
- SourceLocation EndLoc,
- llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
- if (!AStmt)
- return StmtError();
- CapturedStmt *CS = cast<CapturedStmt>(AStmt);
- // 1.2.2 OpenMP Language Terminology
- // Structured block - An executable statement with a single entry at the
- // top and a single exit at the bottom.
- // The point of exit cannot be a branch out of the structured block.
- // longjmp() and throw() must not violate the entry/exit criteria.
- CS->getCapturedDecl()->setNothrow();
- OMPLoopDirective::HelperExprs B;
- // In presence of clause 'collapse' or 'ordered' with number of loops, it will
- // define the nested loops number.
- unsigned NestedLoopCount =
- CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
- getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
- VarsWithImplicitDSA, B);
- if (NestedLoopCount == 0)
- return StmtError();
- assert((CurContext->isDependentContext() || B.builtAll()) &&
- "omp parallel for loop exprs were not built");
- if (!CurContext->isDependentContext()) {
- // Finalize the clauses that need pre-built expressions for CodeGen.
- for (auto C : Clauses) {
- if (auto LC = dyn_cast<OMPLinearClause>(C))
- if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
- B.NumIterations, *this, CurScope))
- return StmtError();
- }
- }
- getCurFunction()->setHasBranchProtectedScope();
- return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
- NestedLoopCount, Clauses, AStmt, B,
- DSAStack->isCancelRegion());
- }
- StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
- ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
- SourceLocation EndLoc,
- llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
- if (!AStmt)
- return StmtError();
- CapturedStmt *CS = cast<CapturedStmt>(AStmt);
- // 1.2.2 OpenMP Language Terminology
- // Structured block - An executable statement with a single entry at the
- // top and a single exit at the bottom.
- // The point of exit cannot be a branch out of the structured block.
- // longjmp() and throw() must not violate the entry/exit criteria.
- CS->getCapturedDecl()->setNothrow();
- OMPLoopDirective::HelperExprs B;
- // In presence of clause 'collapse' or 'ordered' with number of loops, it will
- // define the nested loops number.
- unsigned NestedLoopCount =
- CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
- getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
- VarsWithImplicitDSA, B);
- if (NestedLoopCount == 0)
- return StmtError();
- if (!CurContext->isDependentContext()) {
- // Finalize the clauses that need pre-built expressions for CodeGen.
- for (auto C : Clauses) {
- if (auto LC = dyn_cast<OMPLinearClause>(C))
- if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
- B.NumIterations, *this, CurScope))
- return StmtError();
- }
- }
- // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
- // If both simdlen and safelen clauses are specified, the value of the simdlen
- // parameter must be less than or equal to the value of the safelen parameter.
- OMPSafelenClause *Safelen = nullptr;
- OMPSimdlenClause *Simdlen = nullptr;
- for (auto *Clause : Clauses) {
- if (Clause->getClauseKind() == OMPC_safelen)
- Safelen = cast<OMPSafelenClause>(Clause);
- else if (Clause->getClauseKind() == OMPC_simdlen)
- Simdlen = cast<OMPSimdlenClause>(Clause);
- if (Safelen && Simdlen)
- break;
- }
- if (Simdlen && Safelen &&
- checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
- Safelen->getSafelen()))
- return StmtError();
- getCurFunction()->setHasBranchProtectedScope();
- return OMPParallelForSimdDirective::Create(
- Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
- }
- StmtResult
- Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
- Stmt *AStmt, SourceLocation StartLoc,
- SourceLocation EndLoc) {
- if (!AStmt)
- return StmtError();
- assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
- auto BaseStmt = AStmt;
- while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
- BaseStmt = CS->getCapturedStmt();
- if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
- auto S = C->children();
- if (S.begin() == S.end())
- return StmtError();
- // All associated statements must be '#pragma omp section' except for
- // the first one.
- for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
- if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
- if (SectionStmt)
- Diag(SectionStmt->getLocStart(),
- diag::err_omp_parallel_sections_substmt_not_section);
- return StmtError();
- }
- cast<OMPSectionDirective>(SectionStmt)
- ->setHasCancel(DSAStack->isCancelRegion());
- }
- } else {
- Diag(AStmt->getLocStart(),
- diag::err_omp_parallel_sections_not_compound_stmt);
- return StmtError();
- }
- getCurFunction()->setHasBranchProtectedScope();
- return OMPParallelSectionsDirective::Create(
- Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
- }
- StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
- Stmt *AStmt, SourceLocation StartLoc,
- SourceLocation EndLoc) {
- if (!AStmt)
- return StmtError();
- CapturedStmt *CS = cast<CapturedStmt>(AStmt);
- // 1.2.2 OpenMP Language Terminology
- // Structured block - An executable statement with a single entry at the
- // top and a single exit at the bottom.
- // The point of exit cannot be a branch out of the structured block.
- // longjmp() and throw() must not violate the entry/exit criteria.
- CS->getCapturedDecl()->setNothrow();
- getCurFunction()->setHasBranchProtectedScope();
- return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
- DSAStack->isCancelRegion());
- }
- StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
- SourceLocation EndLoc) {
- return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
- }
- StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
- SourceLocation EndLoc) {
- return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
- }
- StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
- SourceLocation EndLoc) {
- return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
- }
- StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
- SourceLocation StartLoc,
- SourceLocation EndLoc) {
- if (!AStmt)
- return StmtError();
- assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
- getCurFunction()->setHasBranchProtectedScope();
- return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
- }
- StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
- SourceLocation StartLoc,
- SourceLocation EndLoc) {
- assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
- return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
- }
- StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
- Stmt *AStmt,
- SourceLocation StartLoc,
- SourceLocation EndLoc) {
- OMPClause *DependFound = nullptr;
- OMPClause *DependSourceClause = nullptr;
- OMPClause *DependSinkClause = nullptr;
- bool ErrorFound = false;
- OMPThreadsClause *TC = nullptr;
- OMPSIMDClause *SC = nullptr;
- for (auto *C : Clauses) {
- if (auto *DC = dyn_cast<OMPDependClause>(C)) {
- DependFound = C;
- if (DC->getDependencyKind() == OMPC_DEPEND_source) {
- if (DependSourceClause) {
- Diag(C->getLocStart(), diag::err_omp_more_one_clause)
- << getOpenMPDirectiveName(OMPD_ordered)
- << getOpenMPClauseName(OMPC_depend) << 2;
- ErrorFound = true;
- } else
- DependSourceClause = C;
- if (DependSinkClause) {
- Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
- << 0;
- ErrorFound = true;
- }
- } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
- if (DependSourceClause) {
- Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
- << 1;
- ErrorFound = true;
- }
- DependSinkClause = C;
- }
- } else if (C->getClauseKind() == OMPC_threads)
- TC = cast<OMPThreadsClause>(C);
- else if (C->getClauseKind() == OMPC_simd)
- SC = cast<OMPSIMDClause>(C);
- }
- if (!ErrorFound && !SC &&
- isOpenMPSimdDirective(DSAStack->getParentDirective())) {
- // OpenMP [2.8.1,simd Construct, Restrictions]
- // An ordered construct with the simd clause is the only OpenMP construct
- // that can appear in the simd region.
- Diag(StartLoc, diag::err_omp_prohibited_region_simd);
- ErrorFound = true;
- } else if (DependFound && (TC || SC)) {
- Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
- << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
- ErrorFound = true;
- } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
- Diag(DependFound->getLocStart(),
- diag::err_omp_ordered_directive_without_param);
- ErrorFound = true;
- } else if (TC || Clauses.empty()) {
- if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
- SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
- Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
- << (TC != nullptr);
- Diag(Param->getLocStart(), diag::note_omp_ordered_param);
- ErrorFound = true;
- }
- }
- if ((!AStmt && !DependFound) || ErrorFound)
- return StmtError();
- if (AStmt) {
- assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
- getCurFunction()->setHasBranchProtectedScope();
- }
- return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
- }
- namespace {
- /// \brief Helper class for checking expression in 'omp atomic [update]'
- /// construct.
- class OpenMPAtomicUpdateChecker {
- /// \brief Error results for atomic update expressions.
- enum ExprAnalysisErrorCode {
- /// \brief A statement is not an expression statement.
- NotAnExpression,
- /// \brief Expression is not builtin binary or unary operation.
- NotABinaryOrUnaryExpression,
- /// \brief Unary operation is not post-/pre- increment/decrement operation.
- NotAnUnaryIncDecExpression,
- /// \brief An expression is not of scalar type.
- NotAScalarType,
- /// \brief A binary operation is not an assignment operation.
- NotAnAssignmentOp,
- /// \brief RHS part of the binary operation is not a binary expression.
- NotABinaryExpression,
- /// \brief RHS part is not additive/multiplicative/shift/biwise binary
- /// expression.
- NotABinaryOperator,
- /// \brief RHS binary operation does not have reference to the updated LHS
- /// part.
- NotAnUpdateExpression,
- /// \brief No errors is found.
- NoError
- };
- /// \brief Reference to Sema.
- Sema &SemaRef;
- /// \brief A location for note diagnostics (when error is found).
- SourceLocation NoteLoc;
- /// \brief 'x' lvalue part of the source atomic expression.
- Expr *X;
- /// \brief 'expr' rvalue part of the source atomic expression.
- Expr *E;
- /// \brief Helper expression of the form
- /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
- /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
- Expr *UpdateExpr;
- /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
- /// important for non-associative operations.
- bool IsXLHSInRHSPart;
- BinaryOperatorKind Op;
- SourceLocation OpLoc;
- /// \brief true if the source expression is a postfix unary operation, false
- /// if it is a prefix unary operation.
- bool IsPostfixUpdate;
- public:
- OpenMPAtomicUpdateChecker(Sema &SemaRef)
- : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
- IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
- /// \brief Check specified statement that it is suitable for 'atomic update'
- /// constructs and extract 'x', 'expr' and Operation from the original
- /// expression. If DiagId and NoteId == 0, then only check is performed
- /// without error notification.
- /// \param DiagId Diagnostic which should be emitted if error is found.
- /// \param NoteId Diagnostic note for the main error message.
- /// \return true if statement is not an update expression, false otherwise.
- bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
- /// \brief Return the 'x' lvalue part of the source atomic expression.
- Expr *getX() const { return X; }
- /// \brief Return the 'expr' rvalue part of the source atomic expression.
- Expr *getExpr() const { return E; }
- /// \brief Return the update expression used in calculation of the updated
- /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
- /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
- Expr *getUpdateExpr() const { return UpdateExpr; }
- /// \brief Return true if 'x' is LHS in RHS part of full update expression,
- /// false otherwise.
- bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
- /// \brief true if the source expression is a postfix unary operation, false
- /// if it is a prefix unary operation.
- bool isPostfixUpdate() const { return IsPostfixUpdate; }
- private:
- bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
- unsigned NoteId = 0);
- };
- } // namespace
- bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
- BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
- ExprAnalysisErrorCode ErrorFound = NoError;
- SourceLocation ErrorLoc, NoteLoc;
- SourceRange ErrorRange, NoteRange;
- // Allowed constructs are:
- // x = x binop expr;
- // x = expr binop x;
- if (AtomicBinOp->getOpcode() == BO_Assign) {
- X = AtomicBinOp->getLHS();
- if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
- AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
- if (AtomicInnerBinOp->isMultiplicativeOp() ||
- AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
- AtomicInnerBinOp->isBitwiseOp()) {
- Op = AtomicInnerBinOp->getOpcode();
- OpLoc = AtomicInnerBinOp->getOperatorLoc();
- auto *LHS = AtomicInnerBinOp->getLHS();
- auto *RHS = AtomicInnerBinOp->getRHS();
- llvm::FoldingSetNodeID XId, LHSId, RHSId;
- X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
- /*Canonical=*/true);
- LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
- /*Canonical=*/true);
- RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
- /*Canonical=*/true);
- if (XId == LHSId) {
- E = RHS;
- IsXLHSInRHSPart = true;
- } else if (XId == RHSId) {
- E = LHS;
- IsXLHSInRHSPart = false;
- } else {
- ErrorLoc = AtomicInnerBinOp->getExprLoc();
- ErrorRange = AtomicInnerBinOp->getSourceRange();
- NoteLoc = X->getExprLoc();
- NoteRange = X->getSourceRange();
- ErrorFound = NotAnUpdateExpression;
- }
- } else {
- ErrorLoc = AtomicInnerBinOp->getExprLoc();
- ErrorRange = AtomicInnerBinOp->getSourceRange();
- NoteLoc = AtomicInnerBinOp->getOperatorLoc();
- NoteRange = SourceRange(NoteLoc, NoteLoc);
- ErrorFound = NotABinaryOperator;
- }
- } else {
- NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
- NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
- ErrorFound = NotABinaryExpression;
- }
- } else {
- ErrorLoc = AtomicBinOp->getExprLoc();
- ErrorRange = AtomicBinOp->getSourceRange();
- NoteLoc = AtomicBinOp->getOperatorLoc();
- NoteRange = SourceRange(NoteLoc, NoteLoc);
- ErrorFound = NotAnAssignmentOp;
- }
- if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
- SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
- SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
- return true;
- } else if (SemaRef.CurContext->isDependentContext())
- E = X = UpdateExpr = nullptr;
- return ErrorFound != NoError;
- }
- bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
- unsigned NoteId) {
- ExprAnalysisErrorCode ErrorFound = NoError;
- SourceLocation ErrorLoc, NoteLoc;
- SourceRange ErrorRange, NoteRange;
- // Allowed constructs are:
- // x++;
- // x--;
- // ++x;
- // --x;
- // x binop= expr;
- // x = x binop expr;
- // x = expr binop x;
- if (auto *AtomicBody = dyn_cast<Expr>(S)) {
- AtomicBody = AtomicBody->IgnoreParenImpCasts();
- if (AtomicBody->getType()->isScalarType() ||
- AtomicBody->isInstantiationDependent()) {
- if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
- AtomicBody->IgnoreParenImpCasts())) {
- // Check for Compound Assignment Operation
- Op = BinaryOperator::getOpForCompoundAssignment(
- AtomicCompAssignOp->getOpcode());
- OpLoc = AtomicCompAssignOp->getOperatorLoc();
- E = AtomicCompAssignOp->getRHS();
- X = AtomicCompAssignOp->getLHS();
- IsXLHSInRHSPart = true;
- } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
- AtomicBody->IgnoreParenImpCasts())) {
- // Check for Binary Operation
- if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
- return true;
- } else if (auto *AtomicUnaryOp =
- dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
- // Check for Unary Operation
- if (AtomicUnaryOp->isIncrementDecrementOp()) {
- IsPostfixUpdate = AtomicUnaryOp->isPostfix();
- Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
- OpLoc = AtomicUnaryOp->getOperatorLoc();
- X = AtomicUnaryOp->getSubExpr();
- E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
- IsXLHSInRHSPart = true;
- } else {
- ErrorFound = NotAnUnaryIncDecExpression;
- ErrorLoc = AtomicUnaryOp->getExprLoc();
- ErrorRange = AtomicUnaryOp->getSourceRange();
- NoteLoc = AtomicUnaryOp->getOperatorLoc();
- NoteRange = SourceRange(NoteLoc, NoteLoc);
- }
- } else if (!AtomicBody->isInstantiationDependent()) {
- ErrorFound = NotABinaryOrUnaryExpression;
- NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
- NoteRange = ErrorRange = AtomicBody->getSourceRange();
- }
- } else {
- ErrorFound = NotAScalarType;
- NoteLoc = ErrorLoc = AtomicBody->getLocStart();
- NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
- }
- } else {
- ErrorFound = NotAnExpression;
- NoteLoc = ErrorLoc = S->getLocStart();
- NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
- }
- if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
- SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
- SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
- return true;
- } else if (SemaRef.CurContext->isDependentContext())
- E = X = UpdateExpr = nullptr;
- if (ErrorFound == NoError && E && X) {
- // Build an update expression of form 'OpaqueValueExpr(x) binop
- // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
- // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
- auto *OVEX = new (SemaRef.getASTContext())
- OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
- auto *OVEExpr = new (SemaRef.getASTContext())
- OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
- auto Update =
- SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
- IsXLHSInRHSPart ? OVEExpr : OVEX);
- if (Update.isInvalid())
- return true;
- Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
- Sema::AA_Casting);
- if (Update.isInvalid())
- return true;
- UpdateExpr = Update.get();
- }
- return ErrorFound != NoError;
- }
- StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
- Stmt *AStmt,
- SourceLocation StartLoc,
- SourceLocation EndLoc) {
- if (!AStmt)
- return StmtError();
- auto CS = cast<CapturedStmt>(AStmt);
- // 1.2.2 OpenMP Language Terminology
- // Structured block - An executable statement with a single entry at the
- // top and a single exit at the bottom.
- // The point of exit cannot be a branch out of the structured block.
- // longjmp() and throw() must not violate the entry/exit criteria.
- OpenMPClauseKind AtomicKind = OMPC_unknown;
- SourceLocation AtomicKindLoc;
- for (auto *C : Clauses) {
- if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
- C->getClauseKind() == OMPC_update ||
- C->getClauseKind() == OMPC_capture) {
- if (AtomicKind != OMPC_unknown) {
- Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
- << SourceRange(C->getLocStart(), C->getLocEnd());
- Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
- << getOpenMPClauseName(AtomicKind);
- } else {
- AtomicKind = C->getClauseKind();
- AtomicKindLoc = C->getLocStart();
- }
- }
- }
- auto Body = CS->getCapturedStmt();
- if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
- Body = EWC->getSubExpr();
- Expr *X = nullptr;
- Expr *V = nullptr;
- Expr *E = nullptr;
- Expr *UE = nullptr;
- bool IsXLHSInRHSPart = false;
- bool IsPostfixUpdate = false;
- // OpenMP [2.12.6, atomic Construct]
- // In the next expressions:
- // * x and v (as applicable) are both l-value expressions with scalar type.
- // * During the execution of an atomic region, multiple syntactic
- // occurrences of x must designate the same storage location.
- // * Neither of v and expr (as applicable) may access the storage location
- // designated by x.
- // * Neither of x and expr (as applicable) may access the storage location
- // designated by v.
- // * expr is an expression with scalar type.
- // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
- // * binop, binop=, ++, and -- are not overloaded operators.
- // * The expression x binop expr must be numerically equivalent to x binop
- // (expr). This requirement is satisfied if the operators in expr have
- // precedence greater than binop, or by using parentheses around expr or
- // subexpressions of expr.
- // * The expression expr binop x must be numerically equivalent to (expr)
- // binop x. This requirement is satisfied if the operators in expr have
- // precedence equal to or greater than binop, or by using parentheses around
- // expr or subexpressions of expr.
- // * For forms that allow multiple occurrences of x, the number of times
- // that x is evaluated is unspecified.
- if (AtomicKind == OMPC_read) {
- enum {
- NotAnExpression,
- NotAnAssignmentOp,
- NotAScalarType,
- NotAnLValue,
- NoError
- } ErrorFound = NoError;
- SourceLocation ErrorLoc, NoteLoc;
- SourceRange ErrorRange, NoteRange;
- // If clause is read:
- // v = x;
- if (auto AtomicBody = dyn_cast<Expr>(Body)) {
- auto AtomicBinOp =
- dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
- if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
- X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
- V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
- if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
- (V->isInstantiationDependent() || V->getType()->isScalarType())) {
- if (!X->isLValue() || !V->isLValue()) {
- auto NotLValueExpr = X->isLValue() ? V : X;
- ErrorFound = NotAnLValue;
- ErrorLoc = AtomicBinOp->getExprLoc();
- ErrorRange = AtomicBinOp->getSourceRange();
- NoteLoc = NotLValueExpr->getExprLoc();
- NoteRange = NotLValueExpr->getSourceRange();
- }
- } else if (!X->isInstantiationDependent() ||
- !V->isInstantiationDependent()) {
- auto NotScalarExpr =
- (X->isInstantiationDependent() || X->getType()->isScalarType())
- ? V
- : X;
- ErrorFound = NotAScalarType;
- ErrorLoc = AtomicBinOp->getExprLoc();
- ErrorRange = AtomicBinOp->getSourceRange();
- NoteLoc = NotScalarExpr->getExprLoc();
- NoteRange = NotScalarExpr->getSourceRange();
- }
- } else if (!AtomicBody->isInstantiationDependent()) {
- ErrorFound = NotAnAssignmentOp;
- ErrorLoc = AtomicBody->getExprLoc();
- ErrorRange = AtomicBody->getSourceRange();
- NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
- : AtomicBody->getExprLoc();
- NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
- : AtomicBody->getSourceRange();
- }
- } else {
- ErrorFound = NotAnExpression;
- NoteLoc = ErrorLoc = Body->getLocStart();
- NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
- }
- if (ErrorFound != NoError) {
- Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
- << ErrorRange;
- Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
- << NoteRange;
- return StmtError();
- } else if (CurContext->isDependentContext())
- V = X = nullptr;
- } else if (AtomicKind == OMPC_write) {
- enum {
- NotAnExpression,
- NotAnAssignmentOp,
- NotAScalarType,
- NotAnLValue,
- NoError
- } ErrorFound = NoError;
- SourceLocation ErrorLoc, NoteLoc;
- SourceRange ErrorRange, NoteRange;
- // If clause is write:
- // x = expr;
- if (auto AtomicBody = dyn_cast<Expr>(Body)) {
- auto AtomicBinOp =
- dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
- if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
- X = AtomicBinOp->getLHS();
- E = AtomicBinOp->getRHS();
- if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
- (E->isInstantiationDependent() || E->getType()->isScalarType())) {
- if (!X->isLValue()) {
- ErrorFound = NotAnLValue;
- ErrorLoc = AtomicBinOp->getExprLoc();
- ErrorRange = AtomicBinOp->getSourceRange();
- NoteLoc = X->getExprLoc();
- NoteRange = X->getSourceRange();
- }
- } else if (!X->isInstantiationDependent() ||
- !E->isInstantiationDependent()) {
- auto NotScalarExpr =
- (X->isInstantiationDependent() || X->getType()->isScalarType())
- ? E
- : X;
- ErrorFound = NotAScalarType;
- ErrorLoc = AtomicBinOp->getExprLoc();
- ErrorRange = AtomicBinOp->getSourceRange();
- NoteLoc = NotScalarExpr->getExprLoc();
- NoteRange = NotScalarExpr->getSourceRange();
- }
- } else if (!AtomicBody->isInstantiationDependent()) {
- ErrorFound = NotAnAssignmentOp;
- ErrorLoc = AtomicBody->getExprLoc();
- ErrorRange = AtomicBody->getSourceRange();
- NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
- : AtomicBody->getExprLoc();
- NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
- : AtomicBody->getSourceRange();
- }
- } else {
- ErrorFound = NotAnExpression;
- NoteLoc = ErrorLoc = Body->getLocStart();
- NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
- }
- if (ErrorFound != NoError) {
- Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
- << ErrorRange;
- Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
- << NoteRange;
- return StmtError();
- } else if (CurContext->isDependentContext())
- E = X = nullptr;
- } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
- // If clause is update:
- // x++;
- // x--;
- // ++x;
- // --x;
- // x binop= expr;
- // x = x binop expr;
- // x = expr binop x;
- OpenMPAtomicUpdateChecker Checker(*this);
- if (Checker.checkStatement(
- Body, (AtomicKind == OMPC_update)
- ? diag::err_omp_atomic_update_not_expression_statement
- : diag::err_omp_atomic_not_expression_statement,
- diag::note_omp_atomic_update))
- return StmtError();
- if (!CurContext->isDependentContext()) {
- E = Checker.getExpr();
- X = Checker.getX();
- UE = Checker.getUpdateExpr();
- IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
- }
- } else if (AtomicKind == OMPC_capture) {
- enum {
- NotAnAssignmentOp,
- NotACompoundStatement,
- NotTwoSubstatements,
- NotASpecificExpression,
- NoError
- } ErrorFound = NoError;
- SourceLocation ErrorLoc, NoteLoc;
- SourceRange ErrorRange, NoteRange;
- if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
- // If clause is a capture:
- // v = x++;
- // v = x--;
- // v = ++x;
- // v = --x;
- // v = x binop= expr;
- // v = x = x binop expr;
- // v = x = expr binop x;
- auto *AtomicBinOp =
- dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
- if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
- V = AtomicBinOp->getLHS();
- Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
- OpenMPAtomicUpdateChecker Checker(*this);
- if (Checker.checkStatement(
- Body, diag::err_omp_atomic_capture_not_expression_statement,
- diag::note_omp_atomic_update))
- return StmtError();
- E = Checker.getExpr();
- X = Checker.getX();
- UE = Checker.getUpdateExpr();
- IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
- IsPostfixUpdate = Checker.isPostfixUpdate();
- } else if (!AtomicBody->isInstantiationDependent()) {
- ErrorLoc = AtomicBody->getExprLoc();
- ErrorRange = AtomicBody->getSourceRange();
- NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
- : AtomicBody->getExprLoc();
- NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
- : AtomicBody->getSourceRange();
- ErrorFound = NotAnAssignmentOp;
- }
- if (ErrorFound != NoError) {
- Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
- << ErrorRange;
- Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
- return StmtError();
- } else if (CurContext->isDependentContext()) {
- UE = V = E = X = nullptr;
- }
- } else {
- // If clause is a capture:
- // { v = x; x = expr; }
- // { v = x; x++; }
- // { v = x; x--; }
- // { v = x; ++x; }
- // { v = x; --x; }
- // { v = x; x binop= expr; }
- // { v = x; x = x binop expr; }
- // { v = x; x = expr binop x; }
- // { x++; v = x; }
- // { x--; v = x; }
- // { ++x; v = x; }
- // { --x; v = x; }
- // { x binop= expr; v = x; }
- // { x = x binop expr; v = x; }
- // { x = expr binop x; v = x; }
- if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
- // Check that this is { expr1; expr2; }
- if (CS->size() == 2) {
- auto *First = CS->body_front();
- auto *Second = CS->body_back();
- if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
- First = EWC->getSubExpr()->IgnoreParenImpCasts();
- if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
- Second = EWC->getSubExpr()->IgnoreParenImpCasts();
- // Need to find what subexpression is 'v' and what is 'x'.
- OpenMPAtomicUpdateChecker Checker(*this);
- bool IsUpdateExprFound = !Checker.checkStatement(Second);
- BinaryOperator *BinOp = nullptr;
- if (IsUpdateExprFound) {
- BinOp = dyn_cast<BinaryOperator>(First);
- IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
- }
- if (IsUpdateExprFound && !CurContext->isDependentContext()) {
- // { v = x; x++; }
- // { v = x; x--; }
- // { v = x; ++x; }
- // { v = x; --x; }
- // { v = x; x binop= expr; }
- // { v = x; x = x binop expr; }
- // { v = x; x = expr binop x; }
- // Check that the first expression has form v = x.
- auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
- llvm::FoldingSetNodeID XId, PossibleXId;
- Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
- PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
- IsUpdateExprFound = XId == PossibleXId;
- if (IsUpdateExprFound) {
- V = BinOp->getLHS();
- X = Checker.getX();
- E = Checker.getExpr();
- UE = Checker.getUpdateExpr();
- IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
- IsPostfixUpdate = true;
- }
- }
- if (!IsUpdateExprFound) {
- IsUpdateExprFound = !Checker.checkStatement(First);
- BinOp = nullptr;
- if (IsUpdateExprFound) {
- BinOp = dyn_cast<BinaryOperator>(Second);
- IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
- }
- if (IsUpdateExprFound && !CurContext->isDependentContext()) {
- // { x++; v = x; }
- // { x--; v = x; }
- // { ++x; v = x; }
- // { --x; v = x; }
- // { x binop= expr; v = x; }
- // { x = x binop expr; v = x; }
- // { x = expr binop x; v = x; }
- // Check that the second expression has form v = x.
- auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
- llvm::FoldingSetNodeID XId, PossibleXId;
- Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
- PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
- IsUpdateExprFound = XId == PossibleXId;
- if (IsUpdateExprFound) {
- V = BinOp->getLHS();
- X = Checker.getX();
- E = Checker.getExpr();
- UE = Checker.getUpdateExpr();
- IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
- IsPostfixUpdate = false;
- }
- }
- }
- if (!IsUpdateExprFound) {
- // { v = x; x = expr; }
- auto *FirstExpr = dyn_cast<Expr>(First);
- auto *SecondExpr = dyn_cast<Expr>(Second);
- if (!FirstExpr || !SecondExpr ||
- !(FirstExpr->isInstantiationDependent() ||
- SecondExpr->isInstantiationDependent())) {
- auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
- if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
- ErrorFound = NotAnAssignmentOp;
- NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
- : First->getLocStart();
- NoteRange = ErrorRange = FirstBinOp
- ? FirstBinOp->getSourceRange()
- : SourceRange(ErrorLoc, ErrorLoc);
- } else {
- auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
- if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
- ErrorFound = NotAnAssignmentOp;
- NoteLoc = ErrorLoc = SecondBinOp
- ? SecondBinOp->getOperatorLoc()
- : Second->getLocStart();
- NoteRange = ErrorRange =
- SecondBinOp ? SecondBinOp->getSourceRange()
- : SourceRange(ErrorLoc, ErrorLoc);
- } else {
- auto *PossibleXRHSInFirst =
- FirstBinOp->getRHS()->IgnoreParenImpCasts();
- auto *PossibleXLHSInSecond =
- SecondBinOp->getLHS()->IgnoreParenImpCasts();
- llvm::FoldingSetNodeID X1Id, X2Id;
- PossibleXRHSInFirst->Profile(X1Id, Context,
- /*Canonical=*/true);
- PossibleXLHSInSecond->Profile(X2Id, Context,
- /*Canonical=*/true);
- IsUpdateExprFound = X1Id == X2Id;
- if (IsUpdateExprFound) {
- V = FirstBinOp->getLHS();
- X = SecondBinOp->getLHS();
- E = SecondBinOp->getRHS();
- UE = nullptr;
- IsXLHSInRHSPart = false;
- IsPostfixUpdate = true;
- } else {
- ErrorFound = NotASpecificExpression;
- ErrorLoc = FirstBinOp->getExprLoc();
- ErrorRange = FirstBinOp->getSourceRange();
- NoteLoc = SecondBinOp->getLHS()->getExprLoc();
- NoteRange = SecondBinOp->getRHS()->getSourceRange();
- }
- }
- }
- }
- }
- } else {
- NoteLoc = ErrorLoc = Body->getLocStart();
- NoteRange = ErrorRange =
- SourceRange(Body->getLocStart(), Body->getLocStart());
- ErrorFound = NotTwoSubstatements;
- }
- } else {
- NoteLoc = ErrorLoc = Body->getLocStart();
- NoteRange = ErrorRange =
- SourceRange(Body->getLocStart(), Body->getLocStart());
- ErrorFound = NotACompoundStatement;
- }
- if (ErrorFound != NoError) {
- Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
- << ErrorRange;
- Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
- return StmtError();
- } else if (CurContext->isDependentContext()) {
- UE = V = E = X = nullptr;
- }
- }
- }
- getCurFunction()->setHasBranchProtectedScope();
- return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
- X, V, E, UE, IsXLHSInRHSPart,
- IsPostfixUpdate);
- }
- StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
- Stmt *AStmt,
- SourceLocation StartLoc,
- SourceLocation EndLoc) {
- if (!AStmt)
- return StmtError();
- CapturedStmt *CS = cast<CapturedStmt>(AStmt);
- // 1.2.2 OpenMP Language Terminology
- // Structured block - An executable statement with a single entry at the
- // top and a single exit at the bottom.
- // The point of exit cannot be a branch out of the structured block.
- // longjmp() and throw() must not violate the entry/exit criteria.
- CS->getCapturedDecl()->setNothrow();
- // OpenMP [2.16, Nesting of Regions]
- // If specified, a teams construct must be contained within a target
- // construct. That target construct must contain no statements or directives
- // outside of the teams construct.
- if (DSAStack->hasInnerTeamsRegion()) {
- auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
- bool OMPTeamsFound = true;
- if (auto *CS = dyn_cast<CompoundStmt>(S)) {
- auto I = CS->body_begin();
- while (I != CS->body_end()) {
- auto OED = dyn_cast<OMPExecutableDirective>(*I);
- if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
- OMPTeamsFound = false;
- break;
- }
- ++I;
- }
- assert(I != CS->body_end() && "Not found statement");
- S = *I;
- }
- if (!OMPTeamsFound) {
- Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
- Diag(DSAStack->getInnerTeamsRegionLoc(),
- diag::note_omp_nested_teams_construct_here);
- Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
- << isa<OMPExecutableDirective>(S);
- return StmtError();
- }
- }
- getCurFunction()->setHasBranchProtectedScope();
- return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
- }
- StmtResult
- Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
- Stmt *AStmt, SourceLocation StartLoc,
- SourceLocation EndLoc) {
- if (!AStmt)
- return StmtError();
- CapturedStmt *CS = cast<CapturedStmt>(AStmt);
- // 1.2.2 OpenMP Language Terminology
- // Structured block - An executable statement with a single entry at the
- // top and a single exit at the bottom.
- // The point of exit cannot be a branch out of the structured block.
- // longjmp() and throw() must not violate the entry/exit criteria.
- CS->getCapturedDecl()->setNothrow();
- getCurFunction()->setHasBranchProtectedScope();
- return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
- AStmt);
- }
- /// \brief Check for existence of a map clause in the list of clauses.
- static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
- for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
- I != E; ++I) {
- if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
- return true;
- }
- }
- return false;
- }
- StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
- Stmt *AStmt,
- SourceLocation StartLoc,
- SourceLocation EndLoc) {
- if (!AStmt)
- return StmtError();
- assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
- // OpenMP [2.10.1, Restrictions, p. 97]
- // At least one map clause must appear on the directive.
- if (!HasMapClause(Clauses)) {
- Diag(StartLoc, diag::err_omp_no_map_for_directive) <<
- getOpenMPDirectiveName(OMPD_target_data);
- return StmtError();
- }
- getCurFunction()->setHasBranchProtectedScope();
- return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
- AStmt);
- }
- StmtResult
- Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
- SourceLocation StartLoc,
- SourceLocation EndLoc) {
- // OpenMP [2.10.2, Restrictions, p. 99]
- // At least one map clause must appear on the directive.
- if (!HasMapClause(Clauses)) {
- Diag(StartLoc, diag::err_omp_no_map_for_directive)
- << getOpenMPDirectiveName(OMPD_target_enter_data);
- return StmtError();
- }
- return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
- Clauses);
- }
- StmtResult
- Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
- SourceLocation StartLoc,
- SourceLocation EndLoc) {
- // OpenMP [2.10.3, Restrictions, p. 102]
- // At least one map clause must appear on the directive.
- if (!HasMapClause(Clauses)) {
- Diag(StartLoc, diag::err_omp_no_map_for_directive)
- << getOpenMPDirectiveName(OMPD_target_exit_data);
- return StmtError();
- }
- return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
- }
- StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
- Stmt *AStmt, SourceLocation StartLoc,
- SourceLocation EndLoc) {
- if (!AStmt)
- return StmtError();
- CapturedStmt *CS = cast<CapturedStmt>(AStmt);
- // 1.2.2 OpenMP Language Terminology
- // Structured block - An executable statement with a single entry at the
- // top and a single exit at the bottom.
- // The point of exit cannot be a branch out of the structured block.
- // longjmp() and throw() must not violate the entry/exit criteria.
- CS->getCapturedDecl()->setNothrow();
- getCurFunction()->setHasBranchProtectedScope();
- return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
- }
- StmtResult
- Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
- SourceLocation EndLoc,
- OpenMPDirectiveKind CancelRegion) {
- if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
- CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
- Diag(StartLoc, diag::err_omp_wrong_cancel_region)
- << getOpenMPDirectiveName(CancelRegion);
- return StmtError();
- }
- if (DSAStack->isParentNowaitRegion()) {
- Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
- return StmtError();
- }
- if (DSAStack->isParentOrderedRegion()) {
- Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
- return StmtError();
- }
- return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
- CancelRegion);
- }
- StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
- SourceLocation StartLoc,
- SourceLocation EndLoc,
- OpenMPDirectiveKind CancelRegion) {
- if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
- CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
- Diag(StartLoc, diag::err_omp_wrong_cancel_region)
- << getOpenMPDirectiveName(CancelRegion);
- return StmtError();
- }
- if (DSAStack->isParentNowaitRegion()) {
- Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
- return StmtError();
- }
- if (DSAStack->isParentOrderedRegion()) {
- Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
- return StmtError();
- }
- DSAStack->setParentCancelRegion(/*Cancel=*/true);
- return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
- CancelRegion);
- }
- static bool checkGrainsizeNumTasksClauses(Sema &S,
- ArrayRef<OMPClause *> Clauses) {
- OMPClause *PrevClause = nullptr;
- bool ErrorFound = false;
- for (auto *C : Clauses) {
- if (C->getClauseKind() == OMPC_grainsize ||
- C->getClauseKind() == OMPC_num_tasks) {
- if (!PrevClause)
- PrevClause = C;
- else if (PrevClause->getClauseKind() != C->getClauseKind()) {
- S.Diag(C->getLocStart(),
- diag::err_omp_grainsize_num_tasks_mutually_exclusive)
- << getOpenMPClauseName(C->getClauseKind())
- << getOpenMPClauseName(PrevClause->getClauseKind());
- S.Diag(PrevClause->getLocStart(),
- diag::note_omp_previous_grainsize_num_tasks)
- << getOpenMPClauseName(PrevClause->getClauseKind());
- ErrorFound = true;
- }
- }
- }
- return ErrorFound;
- }
- StmtResult Sema::ActOnOpenMPTaskLoopDirective(
- ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
- SourceLocation EndLoc,
- llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
- if (!AStmt)
- return StmtError();
- assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
- OMPLoopDirective::HelperExprs B;
- // In presence of clause 'collapse' or 'ordered' with number of loops, it will
- // define the nested loops number.
- unsigned NestedLoopCount =
- CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
- /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
- VarsWithImplicitDSA, B);
- if (NestedLoopCount == 0)
- return StmtError();
- assert((CurContext->isDependentContext() || B.builtAll()) &&
- "omp for loop exprs were not built");
- // OpenMP, [2.9.2 taskloop Construct, Restrictions]
- // The grainsize clause and num_tasks clause are mutually exclusive and may
- // not appear on the same taskloop directive.
- if (checkGrainsizeNumTasksClauses(*this, Clauses))
- return StmtError();
- getCurFunction()->setHasBranchProtectedScope();
- return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
- NestedLoopCount, Clauses, AStmt, B);
- }
- StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
- ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
- SourceLocation EndLoc,
- llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
- if (!AStmt)
- return StmtError();
- assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
- OMPLoopDirective::HelperExprs B;
- // In presence of clause 'collapse' or 'ordered' with number of loops, it will
- // define the nested loops number.
- unsigned NestedLoopCount =
- CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
- /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
- VarsWithImplicitDSA, B);
- if (NestedLoopCount == 0)
- return StmtError();
- assert((CurContext->isDependentContext() || B.builtAll()) &&
- "omp for loop exprs were not built");
- // OpenMP, [2.9.2 taskloop Construct, Restrictions]
- // The grainsize clause and num_tasks clause are mutually exclusive and may
- // not appear on the same taskloop directive.
- if (checkGrainsizeNumTasksClauses(*this, Clauses))
- return StmtError();
- getCurFunction()->setHasBranchProtectedScope();
- return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
- NestedLoopCount, Clauses, AStmt, B);
- }
- StmtResult Sema::ActOnOpenMPDistributeDirective(
- ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
- SourceLocation EndLoc,
- llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
- if (!AStmt)
- return StmtError();
- assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
- OMPLoopDirective::HelperExprs B;
- // In presence of clause 'collapse' with number of loops, it will
- // define the nested loops number.
- unsigned NestedLoopCount =
- CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
- nullptr /*ordered not a clause on distribute*/, AStmt,
- *this, *DSAStack, VarsWithImplicitDSA, B);
- if (NestedLoopCount == 0)
- return StmtError();
- assert((CurContext->isDependentContext() || B.builtAll()) &&
- "omp for loop exprs were not built");
- getCurFunction()->setHasBranchProtectedScope();
- return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
- NestedLoopCount, Clauses, AStmt, B);
- }
- OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- OMPClause *Res = nullptr;
- switch (Kind) {
- case OMPC_final:
- Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_num_threads:
- Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_safelen:
- Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_simdlen:
- Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_collapse:
- Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_ordered:
- Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
- break;
- case OMPC_device:
- Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_num_teams:
- Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_thread_limit:
- Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_priority:
- Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_grainsize:
- Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_num_tasks:
- Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_hint:
- Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_if:
- case OMPC_default:
- case OMPC_proc_bind:
- case OMPC_schedule:
- case OMPC_private:
- case OMPC_firstprivate:
- case OMPC_lastprivate:
- case OMPC_shared:
- case OMPC_reduction:
- case OMPC_linear:
- case OMPC_aligned:
- case OMPC_copyin:
- case OMPC_copyprivate:
- case OMPC_nowait:
- case OMPC_untied:
- case OMPC_mergeable:
- case OMPC_threadprivate:
- case OMPC_flush:
- case OMPC_read:
- case OMPC_write:
- case OMPC_update:
- case OMPC_capture:
- case OMPC_seq_cst:
- case OMPC_depend:
- case OMPC_threads:
- case OMPC_simd:
- case OMPC_map:
- case OMPC_nogroup:
- case OMPC_dist_schedule:
- case OMPC_defaultmap:
- case OMPC_unknown:
- llvm_unreachable("Clause is not allowed.");
- }
- return Res;
- }
- OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
- Expr *Condition, SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation NameModifierLoc,
- SourceLocation ColonLoc,
- SourceLocation EndLoc) {
- Expr *ValExpr = Condition;
- if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
- !Condition->isInstantiationDependent() &&
- !Condition->containsUnexpandedParameterPack()) {
- ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
- Condition->getExprLoc(), Condition);
- if (Val.isInvalid())
- return nullptr;
- ValExpr = Val.get();
- }
- return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
- NameModifierLoc, ColonLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- Expr *ValExpr = Condition;
- if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
- !Condition->isInstantiationDependent() &&
- !Condition->containsUnexpandedParameterPack()) {
- ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
- Condition->getExprLoc(), Condition);
- if (Val.isInvalid())
- return nullptr;
- ValExpr = Val.get();
- }
- return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
- }
- ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
- Expr *Op) {
- if (!Op)
- return ExprError();
- class IntConvertDiagnoser : public ICEConvertDiagnoser {
- public:
- IntConvertDiagnoser()
- : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
- SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
- QualType T) override {
- return S.Diag(Loc, diag::err_omp_not_integral) << T;
- }
- SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
- QualType T) override {
- return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
- }
- SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
- QualType T,
- QualType ConvTy) override {
- return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
- }
- SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
- QualType ConvTy) override {
- return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
- << ConvTy->isEnumeralType() << ConvTy;
- }
- SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
- QualType T) override {
- return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
- }
- SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
- QualType ConvTy) override {
- return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
- << ConvTy->isEnumeralType() << ConvTy;
- }
- SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
- QualType) override {
- llvm_unreachable("conversion functions are permitted");
- }
- } ConvertDiagnoser;
- return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
- }
- static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
- OpenMPClauseKind CKind,
- bool StrictlyPositive) {
- if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
- !ValExpr->isInstantiationDependent()) {
- SourceLocation Loc = ValExpr->getExprLoc();
- ExprResult Value =
- SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
- if (Value.isInvalid())
- return false;
- ValExpr = Value.get();
- // The expression must evaluate to a non-negative integer value.
- llvm::APSInt Result;
- if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
- Result.isSigned() &&
- !((!StrictlyPositive && Result.isNonNegative()) ||
- (StrictlyPositive && Result.isStrictlyPositive()))) {
- SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
- << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
- << ValExpr->getSourceRange();
- return false;
- }
- }
- return true;
- }
- OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- Expr *ValExpr = NumThreads;
- // OpenMP [2.5, Restrictions]
- // The num_threads expression must evaluate to a positive integer value.
- if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
- /*StrictlyPositive=*/true))
- return nullptr;
- return new (Context)
- OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
- }
- ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
- OpenMPClauseKind CKind,
- bool StrictlyPositive) {
- if (!E)
- return ExprError();
- if (E->isValueDependent() || E->isTypeDependent() ||
- E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
- return E;
- llvm::APSInt Result;
- ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
- if (ICE.isInvalid())
- return ExprError();
- if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
- (!StrictlyPositive && !Result.isNonNegative())) {
- Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
- << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
- << E->getSourceRange();
- return ExprError();
- }
- if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
- Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
- << E->getSourceRange();
- return ExprError();
- }
- if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
- DSAStack->setAssociatedLoops(Result.getExtValue());
- else if (CKind == OMPC_ordered)
- DSAStack->setAssociatedLoops(Result.getExtValue());
- return ICE;
- }
- OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- // OpenMP [2.8.1, simd construct, Description]
- // The parameter of the safelen clause must be a constant
- // positive integer expression.
- ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
- if (Safelen.isInvalid())
- return nullptr;
- return new (Context)
- OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- // OpenMP [2.8.1, simd construct, Description]
- // The parameter of the simdlen clause must be a constant
- // positive integer expression.
- ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
- if (Simdlen.isInvalid())
- return nullptr;
- return new (Context)
- OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- // OpenMP [2.7.1, loop construct, Description]
- // OpenMP [2.8.1, simd construct, Description]
- // OpenMP [2.9.6, distribute construct, Description]
- // The parameter of the collapse clause must be a constant
- // positive integer expression.
- ExprResult NumForLoopsResult =
- VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
- if (NumForLoopsResult.isInvalid())
- return nullptr;
- return new (Context)
- OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
- SourceLocation EndLoc,
- SourceLocation LParenLoc,
- Expr *NumForLoops) {
- // OpenMP [2.7.1, loop construct, Description]
- // OpenMP [2.8.1, simd construct, Description]
- // OpenMP [2.9.6, distribute construct, Description]
- // The parameter of the ordered clause must be a constant
- // positive integer expression if any.
- if (NumForLoops && LParenLoc.isValid()) {
- ExprResult NumForLoopsResult =
- VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
- if (NumForLoopsResult.isInvalid())
- return nullptr;
- NumForLoops = NumForLoopsResult.get();
- } else
- NumForLoops = nullptr;
- DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
- return new (Context)
- OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPSimpleClause(
- OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
- SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
- OMPClause *Res = nullptr;
- switch (Kind) {
- case OMPC_default:
- Res =
- ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
- ArgumentLoc, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_proc_bind:
- Res = ActOnOpenMPProcBindClause(
- static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
- LParenLoc, EndLoc);
- break;
- case OMPC_if:
- case OMPC_final:
- case OMPC_num_threads:
- case OMPC_safelen:
- case OMPC_simdlen:
- case OMPC_collapse:
- case OMPC_schedule:
- case OMPC_private:
- case OMPC_firstprivate:
- case OMPC_lastprivate:
- case OMPC_shared:
- case OMPC_reduction:
- case OMPC_linear:
- case OMPC_aligned:
- case OMPC_copyin:
- case OMPC_copyprivate:
- case OMPC_ordered:
- case OMPC_nowait:
- case OMPC_untied:
- case OMPC_mergeable:
- case OMPC_threadprivate:
- case OMPC_flush:
- case OMPC_read:
- case OMPC_write:
- case OMPC_update:
- case OMPC_capture:
- case OMPC_seq_cst:
- case OMPC_depend:
- case OMPC_device:
- case OMPC_threads:
- case OMPC_simd:
- case OMPC_map:
- case OMPC_num_teams:
- case OMPC_thread_limit:
- case OMPC_priority:
- case OMPC_grainsize:
- case OMPC_nogroup:
- case OMPC_num_tasks:
- case OMPC_hint:
- case OMPC_dist_schedule:
- case OMPC_defaultmap:
- case OMPC_unknown:
- llvm_unreachable("Clause is not allowed.");
- }
- return Res;
- }
- static std::string
- getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
- ArrayRef<unsigned> Exclude = llvm::None) {
- std::string Values;
- unsigned Bound = Last >= 2 ? Last - 2 : 0;
- unsigned Skipped = Exclude.size();
- auto S = Exclude.begin(), E = Exclude.end();
- for (unsigned i = First; i < Last; ++i) {
- if (std::find(S, E, i) != E) {
- --Skipped;
- continue;
- }
- Values += "'";
- Values += getOpenMPSimpleClauseTypeName(K, i);
- Values += "'";
- if (i == Bound - Skipped)
- Values += " or ";
- else if (i != Bound + 1 - Skipped)
- Values += ", ";
- }
- return Values;
- }
- OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
- SourceLocation KindKwLoc,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- if (Kind == OMPC_DEFAULT_unknown) {
- static_assert(OMPC_DEFAULT_unknown > 0,
- "OMPC_DEFAULT_unknown not greater than 0");
- Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
- << getListOfPossibleValues(OMPC_default, /*First=*/0,
- /*Last=*/OMPC_DEFAULT_unknown)
- << getOpenMPClauseName(OMPC_default);
- return nullptr;
- }
- switch (Kind) {
- case OMPC_DEFAULT_none:
- DSAStack->setDefaultDSANone(KindKwLoc);
- break;
- case OMPC_DEFAULT_shared:
- DSAStack->setDefaultDSAShared(KindKwLoc);
- break;
- case OMPC_DEFAULT_unknown:
- llvm_unreachable("Clause kind is not allowed.");
- break;
- }
- return new (Context)
- OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
- SourceLocation KindKwLoc,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- if (Kind == OMPC_PROC_BIND_unknown) {
- Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
- << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
- /*Last=*/OMPC_PROC_BIND_unknown)
- << getOpenMPClauseName(OMPC_proc_bind);
- return nullptr;
- }
- return new (Context)
- OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
- OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
- SourceLocation StartLoc, SourceLocation LParenLoc,
- ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
- SourceLocation EndLoc) {
- OMPClause *Res = nullptr;
- switch (Kind) {
- case OMPC_schedule:
- enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
- assert(Argument.size() == NumberOfElements &&
- ArgumentLoc.size() == NumberOfElements);
- Res = ActOnOpenMPScheduleClause(
- static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
- static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
- static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
- StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
- ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
- break;
- case OMPC_if:
- assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
- Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
- Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
- DelimLoc, EndLoc);
- break;
- case OMPC_dist_schedule:
- Res = ActOnOpenMPDistScheduleClause(
- static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
- StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
- break;
- case OMPC_defaultmap:
- enum { Modifier, DefaultmapKind };
- Res = ActOnOpenMPDefaultmapClause(
- static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
- static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
- StartLoc, LParenLoc, ArgumentLoc[Modifier],
- ArgumentLoc[DefaultmapKind], EndLoc);
- break;
- case OMPC_final:
- case OMPC_num_threads:
- case OMPC_safelen:
- case OMPC_simdlen:
- case OMPC_collapse:
- case OMPC_default:
- case OMPC_proc_bind:
- case OMPC_private:
- case OMPC_firstprivate:
- case OMPC_lastprivate:
- case OMPC_shared:
- case OMPC_reduction:
- case OMPC_linear:
- case OMPC_aligned:
- case OMPC_copyin:
- case OMPC_copyprivate:
- case OMPC_ordered:
- case OMPC_nowait:
- case OMPC_untied:
- case OMPC_mergeable:
- case OMPC_threadprivate:
- case OMPC_flush:
- case OMPC_read:
- case OMPC_write:
- case OMPC_update:
- case OMPC_capture:
- case OMPC_seq_cst:
- case OMPC_depend:
- case OMPC_device:
- case OMPC_threads:
- case OMPC_simd:
- case OMPC_map:
- case OMPC_num_teams:
- case OMPC_thread_limit:
- case OMPC_priority:
- case OMPC_grainsize:
- case OMPC_nogroup:
- case OMPC_num_tasks:
- case OMPC_hint:
- case OMPC_unknown:
- llvm_unreachable("Clause is not allowed.");
- }
- return Res;
- }
- static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
- OpenMPScheduleClauseModifier M2,
- SourceLocation M1Loc, SourceLocation M2Loc) {
- if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
- SmallVector<unsigned, 2> Excluded;
- if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
- Excluded.push_back(M2);
- if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
- Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
- if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
- Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
- S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
- << getListOfPossibleValues(OMPC_schedule,
- /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
- /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
- Excluded)
- << getOpenMPClauseName(OMPC_schedule);
- return true;
- }
- return false;
- }
- OMPClause *Sema::ActOnOpenMPScheduleClause(
- OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
- OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
- SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
- SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
- if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
- checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
- return nullptr;
- // OpenMP, 2.7.1, Loop Construct, Restrictions
- // Either the monotonic modifier or the nonmonotonic modifier can be specified
- // but not both.
- if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
- (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
- M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
- (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
- M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
- Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
- << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
- << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
- return nullptr;
- }
- if (Kind == OMPC_SCHEDULE_unknown) {
- std::string Values;
- if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
- unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
- Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
- /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
- Exclude);
- } else {
- Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
- /*Last=*/OMPC_SCHEDULE_unknown);
- }
- Diag(KindLoc, diag::err_omp_unexpected_clause_value)
- << Values << getOpenMPClauseName(OMPC_schedule);
- return nullptr;
- }
- // OpenMP, 2.7.1, Loop Construct, Restrictions
- // The nonmonotonic modifier can only be specified with schedule(dynamic) or
- // schedule(guided).
- if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
- M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
- Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
- Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
- diag::err_omp_schedule_nonmonotonic_static);
- return nullptr;
- }
- Expr *ValExpr = ChunkSize;
- Expr *HelperValExpr = nullptr;
- if (ChunkSize) {
- if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
- !ChunkSize->isInstantiationDependent() &&
- !ChunkSize->containsUnexpandedParameterPack()) {
- SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
- ExprResult Val =
- PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
- if (Val.isInvalid())
- return nullptr;
- ValExpr = Val.get();
- // OpenMP [2.7.1, Restrictions]
- // chunk_size must be a loop invariant integer expression with a positive
- // value.
- llvm::APSInt Result;
- if (ValExpr->isIntegerConstantExpr(Result, Context)) {
- if (Result.isSigned() && !Result.isStrictlyPositive()) {
- Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
- << "schedule" << 1 << ChunkSize->getSourceRange();
- return nullptr;
- }
- } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
- auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
- ChunkSize->getType(), ".chunk.");
- auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
- ChunkSize->getExprLoc(),
- /*RefersToCapture=*/true);
- HelperValExpr = ImpVarRef;
- }
- }
- }
- return new (Context)
- OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
- ValExpr, HelperValExpr, M1, M1Loc, M2, M2Loc);
- }
- OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
- SourceLocation StartLoc,
- SourceLocation EndLoc) {
- OMPClause *Res = nullptr;
- switch (Kind) {
- case OMPC_ordered:
- Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
- break;
- case OMPC_nowait:
- Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
- break;
- case OMPC_untied:
- Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
- break;
- case OMPC_mergeable:
- Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
- break;
- case OMPC_read:
- Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
- break;
- case OMPC_write:
- Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
- break;
- case OMPC_update:
- Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
- break;
- case OMPC_capture:
- Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
- break;
- case OMPC_seq_cst:
- Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
- break;
- case OMPC_threads:
- Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
- break;
- case OMPC_simd:
- Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
- break;
- case OMPC_nogroup:
- Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
- break;
- case OMPC_if:
- case OMPC_final:
- case OMPC_num_threads:
- case OMPC_safelen:
- case OMPC_simdlen:
- case OMPC_collapse:
- case OMPC_schedule:
- case OMPC_private:
- case OMPC_firstprivate:
- case OMPC_lastprivate:
- case OMPC_shared:
- case OMPC_reduction:
- case OMPC_linear:
- case OMPC_aligned:
- case OMPC_copyin:
- case OMPC_copyprivate:
- case OMPC_default:
- case OMPC_proc_bind:
- case OMPC_threadprivate:
- case OMPC_flush:
- case OMPC_depend:
- case OMPC_device:
- case OMPC_map:
- case OMPC_num_teams:
- case OMPC_thread_limit:
- case OMPC_priority:
- case OMPC_grainsize:
- case OMPC_num_tasks:
- case OMPC_hint:
- case OMPC_dist_schedule:
- case OMPC_defaultmap:
- case OMPC_unknown:
- llvm_unreachable("Clause is not allowed.");
- }
- return Res;
- }
- OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
- SourceLocation EndLoc) {
- DSAStack->setNowaitRegion();
- return new (Context) OMPNowaitClause(StartLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
- SourceLocation EndLoc) {
- return new (Context) OMPUntiedClause(StartLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
- SourceLocation EndLoc) {
- return new (Context) OMPMergeableClause(StartLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
- SourceLocation EndLoc) {
- return new (Context) OMPReadClause(StartLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
- SourceLocation EndLoc) {
- return new (Context) OMPWriteClause(StartLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
- SourceLocation EndLoc) {
- return new (Context) OMPUpdateClause(StartLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
- SourceLocation EndLoc) {
- return new (Context) OMPCaptureClause(StartLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
- SourceLocation EndLoc) {
- return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
- SourceLocation EndLoc) {
- return new (Context) OMPThreadsClause(StartLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
- SourceLocation EndLoc) {
- return new (Context) OMPSIMDClause(StartLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
- SourceLocation EndLoc) {
- return new (Context) OMPNogroupClause(StartLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPVarListClause(
- OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
- SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
- SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
- const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
- OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
- OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
- SourceLocation DepLinMapLoc) {
- OMPClause *Res = nullptr;
- switch (Kind) {
- case OMPC_private:
- Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_firstprivate:
- Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_lastprivate:
- Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_shared:
- Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_reduction:
- Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
- EndLoc, ReductionIdScopeSpec, ReductionId);
- break;
- case OMPC_linear:
- Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
- LinKind, DepLinMapLoc, ColonLoc, EndLoc);
- break;
- case OMPC_aligned:
- Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
- ColonLoc, EndLoc);
- break;
- case OMPC_copyin:
- Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_copyprivate:
- Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_flush:
- Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_depend:
- Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
- StartLoc, LParenLoc, EndLoc);
- break;
- case OMPC_map:
- Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
- DepLinMapLoc, ColonLoc, VarList, StartLoc,
- LParenLoc, EndLoc);
- break;
- case OMPC_if:
- case OMPC_final:
- case OMPC_num_threads:
- case OMPC_safelen:
- case OMPC_simdlen:
- case OMPC_collapse:
- case OMPC_default:
- case OMPC_proc_bind:
- case OMPC_schedule:
- case OMPC_ordered:
- case OMPC_nowait:
- case OMPC_untied:
- case OMPC_mergeable:
- case OMPC_threadprivate:
- case OMPC_read:
- case OMPC_write:
- case OMPC_update:
- case OMPC_capture:
- case OMPC_seq_cst:
- case OMPC_device:
- case OMPC_threads:
- case OMPC_simd:
- case OMPC_num_teams:
- case OMPC_thread_limit:
- case OMPC_priority:
- case OMPC_grainsize:
- case OMPC_nogroup:
- case OMPC_num_tasks:
- case OMPC_hint:
- case OMPC_dist_schedule:
- case OMPC_defaultmap:
- case OMPC_unknown:
- llvm_unreachable("Clause is not allowed.");
- }
- return Res;
- }
- OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- SmallVector<Expr *, 8> Vars;
- SmallVector<Expr *, 8> PrivateCopies;
- for (auto &RefExpr : VarList) {
- assert(RefExpr && "NULL expr in OpenMP private clause.");
- if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
- RefExpr->containsUnexpandedParameterPack()) {
- // It will be analyzed later.
- Vars.push_back(RefExpr);
- PrivateCopies.push_back(nullptr);
- continue;
- }
- SourceLocation ELoc = RefExpr->getExprLoc();
- // OpenMP [3.1, C/C++]
- // A list item is a variable name.
- // OpenMP [2.9.3.3, Restrictions, p.1]
- // A variable that is part of another variable (as an array or
- // structure element) cannot appear in a private clause.
- auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr->IgnoreParens());
- auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr->IgnoreParens());
- if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
- (getCurrentThisType().isNull() || !ME ||
- !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
- !isa<FieldDecl>(ME->getMemberDecl()))) {
- Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
- << (getCurrentThisType().isNull() ? 0 : 1)
- << RefExpr->getSourceRange();
- continue;
- }
- ValueDecl *D = DE ? DE->getDecl() : ME->getMemberDecl();
- QualType Type = D->getType();
- auto *VD = dyn_cast<VarDecl>(D);
- // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
- // A variable that appears in a private clause must not have an incomplete
- // type or a reference type.
- if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
- continue;
- Type = Type.getNonReferenceType();
- // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
- // in a Construct]
- // Variables with the predetermined data-sharing attributes may not be
- // listed in data-sharing attributes clauses, except for the cases
- // listed below. For these exceptions only, listing a predetermined
- // variable in a data-sharing attribute clause is allowed and overrides
- // the variable's predetermined data-sharing attributes.
- DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
- if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
- Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
- << getOpenMPClauseName(OMPC_private);
- ReportOriginalDSA(*this, DSAStack, D, DVar);
- continue;
- }
- // Variably modified types are not supported for tasks.
- if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
- DSAStack->getCurrentDirective() == OMPD_task) {
- Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
- << getOpenMPClauseName(OMPC_private) << Type
- << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
- bool IsDecl =
- !VD ||
- VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
- Diag(D->getLocation(),
- IsDecl ? diag::note_previous_decl : diag::note_defined_here)
- << D;
- continue;
- }
- // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
- // A variable of class type (or array thereof) that appears in a private
- // clause requires an accessible, unambiguous default constructor for the
- // class type.
- // Generate helper private variable and initialize it with the default
- // value. The address of the original variable is replaced by the address of
- // the new private variable in CodeGen. This new variable is not added to
- // IdResolver, so the code in the OpenMP region uses original variable for
- // proper diagnostics.
- Type = Type.getUnqualifiedType();
- auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
- D->hasAttrs() ? &D->getAttrs() : nullptr);
- ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
- if (VDPrivate->isInvalidDecl())
- continue;
- auto VDPrivateRefExpr = buildDeclRefExpr(
- *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
- DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private);
- Vars.push_back(RefExpr->IgnoreParens());
- PrivateCopies.push_back(VDPrivateRefExpr);
- }
- if (Vars.empty())
- return nullptr;
- return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
- PrivateCopies);
- }
- namespace {
- class DiagsUninitializedSeveretyRAII {
- private:
- DiagnosticsEngine &Diags;
- SourceLocation SavedLoc;
- bool IsIgnored;
- public:
- DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
- bool IsIgnored)
- : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
- if (!IsIgnored) {
- Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
- /*Map*/ diag::Severity::Ignored, Loc);
- }
- }
- ~DiagsUninitializedSeveretyRAII() {
- if (!IsIgnored)
- Diags.popMappings(SavedLoc);
- }
- };
- }
- OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- SmallVector<Expr *, 8> Vars;
- SmallVector<Expr *, 8> PrivateCopies;
- SmallVector<Expr *, 8> Inits;
- bool IsImplicitClause =
- StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
- auto ImplicitClauseLoc = DSAStack->getConstructLoc();
- for (auto &RefExpr : VarList) {
- assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
- if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
- // It will be analyzed later.
- Vars.push_back(RefExpr);
- PrivateCopies.push_back(nullptr);
- Inits.push_back(nullptr);
- continue;
- }
- SourceLocation ELoc =
- IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
- // OpenMP [2.1, C/C++]
- // A list item is a variable name.
- // OpenMP [2.9.3.3, Restrictions, p.1]
- // A variable that is part of another variable (as an array or
- // structure element) cannot appear in a private clause.
- DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
- if (!DE || !isa<VarDecl>(DE->getDecl())) {
- Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
- << 0 << RefExpr->getSourceRange();
- continue;
- }
- Decl *D = DE->getDecl();
- VarDecl *VD = cast<VarDecl>(D);
- QualType Type = VD->getType();
- if (Type->isDependentType() || Type->isInstantiationDependentType()) {
- // It will be analyzed later.
- Vars.push_back(DE);
- PrivateCopies.push_back(nullptr);
- Inits.push_back(nullptr);
- continue;
- }
- // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
- // A variable that appears in a private clause must not have an incomplete
- // type or a reference type.
- if (RequireCompleteType(ELoc, Type,
- diag::err_omp_firstprivate_incomplete_type)) {
- continue;
- }
- Type = Type.getNonReferenceType();
- // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
- // A variable of class type (or array thereof) that appears in a private
- // clause requires an accessible, unambiguous copy constructor for the
- // class type.
- auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
- // If an implicit firstprivate variable found it was checked already.
- if (!IsImplicitClause) {
- DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
- bool IsConstant = ElemType.isConstant(Context);
- // OpenMP [2.4.13, Data-sharing Attribute Clauses]
- // A list item that specifies a given variable may not appear in more
- // than one clause on the same directive, except that a variable may be
- // specified in both firstprivate and lastprivate clauses.
- if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
- DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
- Diag(ELoc, diag::err_omp_wrong_dsa)
- << getOpenMPClauseName(DVar.CKind)
- << getOpenMPClauseName(OMPC_firstprivate);
- ReportOriginalDSA(*this, DSAStack, VD, DVar);
- continue;
- }
- // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
- // in a Construct]
- // Variables with the predetermined data-sharing attributes may not be
- // listed in data-sharing attributes clauses, except for the cases
- // listed below. For these exceptions only, listing a predetermined
- // variable in a data-sharing attribute clause is allowed and overrides
- // the variable's predetermined data-sharing attributes.
- // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
- // in a Construct, C/C++, p.2]
- // Variables with const-qualified type having no mutable member may be
- // listed in a firstprivate clause, even if they are static data members.
- if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
- DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
- Diag(ELoc, diag::err_omp_wrong_dsa)
- << getOpenMPClauseName(DVar.CKind)
- << getOpenMPClauseName(OMPC_firstprivate);
- ReportOriginalDSA(*this, DSAStack, VD, DVar);
- continue;
- }
- OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
- // OpenMP [2.9.3.4, Restrictions, p.2]
- // A list item that is private within a parallel region must not appear
- // in a firstprivate clause on a worksharing construct if any of the
- // worksharing regions arising from the worksharing construct ever bind
- // to any of the parallel regions arising from the parallel construct.
- if (isOpenMPWorksharingDirective(CurrDir) &&
- !isOpenMPParallelDirective(CurrDir)) {
- DVar = DSAStack->getImplicitDSA(VD, true);
- if (DVar.CKind != OMPC_shared &&
- (isOpenMPParallelDirective(DVar.DKind) ||
- DVar.DKind == OMPD_unknown)) {
- Diag(ELoc, diag::err_omp_required_access)
- << getOpenMPClauseName(OMPC_firstprivate)
- << getOpenMPClauseName(OMPC_shared);
- ReportOriginalDSA(*this, DSAStack, VD, DVar);
- continue;
- }
- }
- // OpenMP [2.9.3.4, Restrictions, p.3]
- // A list item that appears in a reduction clause of a parallel construct
- // must not appear in a firstprivate clause on a worksharing or task
- // construct if any of the worksharing or task regions arising from the
- // worksharing or task construct ever bind to any of the parallel regions
- // arising from the parallel construct.
- // OpenMP [2.9.3.4, Restrictions, p.4]
- // A list item that appears in a reduction clause in worksharing
- // construct must not appear in a firstprivate clause in a task construct
- // encountered during execution of any of the worksharing regions arising
- // from the worksharing construct.
- if (CurrDir == OMPD_task) {
- DVar =
- DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
- [](OpenMPDirectiveKind K) -> bool {
- return isOpenMPParallelDirective(K) ||
- isOpenMPWorksharingDirective(K);
- },
- false);
- if (DVar.CKind == OMPC_reduction &&
- (isOpenMPParallelDirective(DVar.DKind) ||
- isOpenMPWorksharingDirective(DVar.DKind))) {
- Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
- << getOpenMPDirectiveName(DVar.DKind);
- ReportOriginalDSA(*this, DSAStack, VD, DVar);
- continue;
- }
- }
- // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
- // A list item that is private within a teams region must not appear in a
- // firstprivate clause on a distribute construct if any of the distribute
- // regions arising from the distribute construct ever bind to any of the
- // teams regions arising from the teams construct.
- // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
- // A list item that appears in a reduction clause of a teams construct
- // must not appear in a firstprivate clause on a distribute construct if
- // any of the distribute regions arising from the distribute construct
- // ever bind to any of the teams regions arising from the teams construct.
- // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
- // A list item may appear in a firstprivate or lastprivate clause but not
- // both.
- if (CurrDir == OMPD_distribute) {
- DVar = DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_private),
- [](OpenMPDirectiveKind K) -> bool {
- return isOpenMPTeamsDirective(K);
- },
- false);
- if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
- Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
- ReportOriginalDSA(*this, DSAStack, VD, DVar);
- continue;
- }
- DVar = DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
- [](OpenMPDirectiveKind K) -> bool {
- return isOpenMPTeamsDirective(K);
- },
- false);
- if (DVar.CKind == OMPC_reduction &&
- isOpenMPTeamsDirective(DVar.DKind)) {
- Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
- ReportOriginalDSA(*this, DSAStack, VD, DVar);
- continue;
- }
- DVar = DSAStack->getTopDSA(VD, false);
- if (DVar.CKind == OMPC_lastprivate) {
- Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
- ReportOriginalDSA(*this, DSAStack, VD, DVar);
- continue;
- }
- }
- }
- // Variably modified types are not supported for tasks.
- if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
- DSAStack->getCurrentDirective() == OMPD_task) {
- Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
- << getOpenMPClauseName(OMPC_firstprivate) << Type
- << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
- bool IsDecl =
- VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
- Diag(VD->getLocation(),
- IsDecl ? diag::note_previous_decl : diag::note_defined_here)
- << VD;
- continue;
- }
- Type = Type.getUnqualifiedType();
- auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName(),
- VD->hasAttrs() ? &VD->getAttrs() : nullptr);
- // Generate helper private variable and initialize it with the value of the
- // original variable. The address of the original variable is replaced by
- // the address of the new private variable in the CodeGen. This new variable
- // is not added to IdResolver, so the code in the OpenMP region uses
- // original variable for proper diagnostics and variable capturing.
- Expr *VDInitRefExpr = nullptr;
- // For arrays generate initializer for single element and replace it by the
- // original array element in CodeGen.
- if (Type->isArrayType()) {
- auto VDInit =
- buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
- VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
- auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
- ElemType = ElemType.getUnqualifiedType();
- auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
- ".firstprivate.temp");
- InitializedEntity Entity =
- InitializedEntity::InitializeVariable(VDInitTemp);
- InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
- InitializationSequence InitSeq(*this, Entity, Kind, Init);
- ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
- if (Result.isInvalid())
- VDPrivate->setInvalidDecl();
- else
- VDPrivate->setInit(Result.getAs<Expr>());
- // Remove temp variable declaration.
- Context.Deallocate(VDInitTemp);
- } else {
- auto *VDInit =
- buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
- VDInitRefExpr =
- buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
- AddInitializerToDecl(VDPrivate,
- DefaultLvalueConversion(VDInitRefExpr).get(),
- /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
- }
- if (VDPrivate->isInvalidDecl()) {
- if (IsImplicitClause) {
- Diag(DE->getExprLoc(),
- diag::note_omp_task_predetermined_firstprivate_here);
- }
- continue;
- }
- CurContext->addDecl(VDPrivate);
- auto VDPrivateRefExpr = buildDeclRefExpr(
- *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
- DSAStack->addDSA(VD, DE, OMPC_firstprivate);
- Vars.push_back(DE);
- PrivateCopies.push_back(VDPrivateRefExpr);
- Inits.push_back(VDInitRefExpr);
- }
- if (Vars.empty())
- return nullptr;
- return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
- Vars, PrivateCopies, Inits);
- }
- OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- SmallVector<Expr *, 8> Vars;
- SmallVector<Expr *, 8> SrcExprs;
- SmallVector<Expr *, 8> DstExprs;
- SmallVector<Expr *, 8> AssignmentOps;
- for (auto &RefExpr : VarList) {
- assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
- if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
- // It will be analyzed later.
- Vars.push_back(RefExpr);
- SrcExprs.push_back(nullptr);
- DstExprs.push_back(nullptr);
- AssignmentOps.push_back(nullptr);
- continue;
- }
- SourceLocation ELoc = RefExpr->getExprLoc();
- // OpenMP [2.1, C/C++]
- // A list item is a variable name.
- // OpenMP [2.14.3.5, Restrictions, p.1]
- // A variable that is part of another variable (as an array or structure
- // element) cannot appear in a lastprivate clause.
- DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
- if (!DE || !isa<VarDecl>(DE->getDecl())) {
- Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
- << 0 << RefExpr->getSourceRange();
- continue;
- }
- Decl *D = DE->getDecl();
- VarDecl *VD = cast<VarDecl>(D);
- QualType Type = VD->getType();
- if (Type->isDependentType() || Type->isInstantiationDependentType()) {
- // It will be analyzed later.
- Vars.push_back(DE);
- SrcExprs.push_back(nullptr);
- DstExprs.push_back(nullptr);
- AssignmentOps.push_back(nullptr);
- continue;
- }
- // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
- // A variable that appears in a lastprivate clause must not have an
- // incomplete type or a reference type.
- if (RequireCompleteType(ELoc, Type,
- diag::err_omp_lastprivate_incomplete_type)) {
- continue;
- }
- Type = Type.getNonReferenceType();
- // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
- // in a Construct]
- // Variables with the predetermined data-sharing attributes may not be
- // listed in data-sharing attributes clauses, except for the cases
- // listed below.
- DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
- if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
- DVar.CKind != OMPC_firstprivate &&
- (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
- Diag(ELoc, diag::err_omp_wrong_dsa)
- << getOpenMPClauseName(DVar.CKind)
- << getOpenMPClauseName(OMPC_lastprivate);
- ReportOriginalDSA(*this, DSAStack, VD, DVar);
- continue;
- }
- OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
- // OpenMP [2.14.3.5, Restrictions, p.2]
- // A list item that is private within a parallel region, or that appears in
- // the reduction clause of a parallel construct, must not appear in a
- // lastprivate clause on a worksharing construct if any of the corresponding
- // worksharing regions ever binds to any of the corresponding parallel
- // regions.
- DSAStackTy::DSAVarData TopDVar = DVar;
- if (isOpenMPWorksharingDirective(CurrDir) &&
- !isOpenMPParallelDirective(CurrDir)) {
- DVar = DSAStack->getImplicitDSA(VD, true);
- if (DVar.CKind != OMPC_shared) {
- Diag(ELoc, diag::err_omp_required_access)
- << getOpenMPClauseName(OMPC_lastprivate)
- << getOpenMPClauseName(OMPC_shared);
- ReportOriginalDSA(*this, DSAStack, VD, DVar);
- continue;
- }
- }
- // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
- // A variable of class type (or array thereof) that appears in a
- // lastprivate clause requires an accessible, unambiguous default
- // constructor for the class type, unless the list item is also specified
- // in a firstprivate clause.
- // A variable of class type (or array thereof) that appears in a
- // lastprivate clause requires an accessible, unambiguous copy assignment
- // operator for the class type.
- Type = Context.getBaseElementType(Type).getNonReferenceType();
- auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
- Type.getUnqualifiedType(), ".lastprivate.src",
- VD->hasAttrs() ? &VD->getAttrs() : nullptr);
- auto *PseudoSrcExpr = buildDeclRefExpr(
- *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
- auto *DstVD =
- buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst",
- VD->hasAttrs() ? &VD->getAttrs() : nullptr);
- auto *PseudoDstExpr =
- buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
- // For arrays generate assignment operation for single element and replace
- // it by the original array element in CodeGen.
- auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
- PseudoDstExpr, PseudoSrcExpr);
- if (AssignmentOp.isInvalid())
- continue;
- AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
- /*DiscardedValue=*/true);
- if (AssignmentOp.isInvalid())
- continue;
- // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
- // A list item may appear in a firstprivate or lastprivate clause but not
- // both.
- if (CurrDir == OMPD_distribute) {
- DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
- if (DVar.CKind == OMPC_firstprivate) {
- Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
- ReportOriginalDSA(*this, DSAStack, VD, DVar);
- continue;
- }
- }
- if (TopDVar.CKind != OMPC_firstprivate)
- DSAStack->addDSA(VD, DE, OMPC_lastprivate);
- Vars.push_back(DE);
- SrcExprs.push_back(PseudoSrcExpr);
- DstExprs.push_back(PseudoDstExpr);
- AssignmentOps.push_back(AssignmentOp.get());
- }
- if (Vars.empty())
- return nullptr;
- return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
- Vars, SrcExprs, DstExprs, AssignmentOps);
- }
- OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- SmallVector<Expr *, 8> Vars;
- for (auto &RefExpr : VarList) {
- assert(RefExpr && "NULL expr in OpenMP shared clause.");
- if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
- // It will be analyzed later.
- Vars.push_back(RefExpr);
- continue;
- }
- SourceLocation ELoc = RefExpr->getExprLoc();
- // OpenMP [2.1, C/C++]
- // A list item is a variable name.
- // OpenMP [2.14.3.2, Restrictions, p.1]
- // A variable that is part of another variable (as an array or structure
- // element) cannot appear in a shared unless it is a static data member
- // of a C++ class.
- DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
- if (!DE || !isa<VarDecl>(DE->getDecl())) {
- Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
- << 0 << RefExpr->getSourceRange();
- continue;
- }
- Decl *D = DE->getDecl();
- VarDecl *VD = cast<VarDecl>(D);
- QualType Type = VD->getType();
- if (Type->isDependentType() || Type->isInstantiationDependentType()) {
- // It will be analyzed later.
- Vars.push_back(DE);
- continue;
- }
- // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
- // in a Construct]
- // Variables with the predetermined data-sharing attributes may not be
- // listed in data-sharing attributes clauses, except for the cases
- // listed below. For these exceptions only, listing a predetermined
- // variable in a data-sharing attribute clause is allowed and overrides
- // the variable's predetermined data-sharing attributes.
- DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
- if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
- DVar.RefExpr) {
- Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
- << getOpenMPClauseName(OMPC_shared);
- ReportOriginalDSA(*this, DSAStack, VD, DVar);
- continue;
- }
- DSAStack->addDSA(VD, DE, OMPC_shared);
- Vars.push_back(DE);
- }
- if (Vars.empty())
- return nullptr;
- return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
- }
- namespace {
- class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
- DSAStackTy *Stack;
- public:
- bool VisitDeclRefExpr(DeclRefExpr *E) {
- if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
- DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
- if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
- return false;
- if (DVar.CKind != OMPC_unknown)
- return true;
- DSAStackTy::DSAVarData DVarPrivate =
- Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
- if (DVarPrivate.CKind != OMPC_unknown)
- return true;
- return false;
- }
- return false;
- }
- bool VisitStmt(Stmt *S) {
- for (auto Child : S->children()) {
- if (Child && Visit(Child))
- return true;
- }
- return false;
- }
- explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
- };
- } // namespace
- OMPClause *Sema::ActOnOpenMPReductionClause(
- ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
- SourceLocation ColonLoc, SourceLocation EndLoc,
- CXXScopeSpec &ReductionIdScopeSpec,
- const DeclarationNameInfo &ReductionId) {
- // TODO: Allow scope specification search when 'declare reduction' is
- // supported.
- assert(ReductionIdScopeSpec.isEmpty() &&
- "No support for scoped reduction identifiers yet.");
- auto DN = ReductionId.getName();
- auto OOK = DN.getCXXOverloadedOperator();
- BinaryOperatorKind BOK = BO_Comma;
- // OpenMP [2.14.3.6, reduction clause]
- // C
- // reduction-identifier is either an identifier or one of the following
- // operators: +, -, *, &, |, ^, && and ||
- // C++
- // reduction-identifier is either an id-expression or one of the following
- // operators: +, -, *, &, |, ^, && and ||
- // FIXME: Only 'min' and 'max' identifiers are supported for now.
- switch (OOK) {
- case OO_Plus:
- case OO_Minus:
- BOK = BO_Add;
- break;
- case OO_Star:
- BOK = BO_Mul;
- break;
- case OO_Amp:
- BOK = BO_And;
- break;
- case OO_Pipe:
- BOK = BO_Or;
- break;
- case OO_Caret:
- BOK = BO_Xor;
- break;
- case OO_AmpAmp:
- BOK = BO_LAnd;
- break;
- case OO_PipePipe:
- BOK = BO_LOr;
- break;
- case OO_New:
- case OO_Delete:
- case OO_Array_New:
- case OO_Array_Delete:
- case OO_Slash:
- case OO_Percent:
- case OO_Tilde:
- case OO_Exclaim:
- case OO_Equal:
- case OO_Less:
- case OO_Greater:
- case OO_LessEqual:
- case OO_GreaterEqual:
- case OO_PlusEqual:
- case OO_MinusEqual:
- case OO_StarEqual:
- case OO_SlashEqual:
- case OO_PercentEqual:
- case OO_CaretEqual:
- case OO_AmpEqual:
- case OO_PipeEqual:
- case OO_LessLess:
- case OO_GreaterGreater:
- case OO_LessLessEqual:
- case OO_GreaterGreaterEqual:
- case OO_EqualEqual:
- case OO_ExclaimEqual:
- case OO_PlusPlus:
- case OO_MinusMinus:
- case OO_Comma:
- case OO_ArrowStar:
- case OO_Arrow:
- case OO_Call:
- case OO_Subscript:
- case OO_Conditional:
- case OO_Coawait:
- case NUM_OVERLOADED_OPERATORS:
- llvm_unreachable("Unexpected reduction identifier");
- case OO_None:
- if (auto II = DN.getAsIdentifierInfo()) {
- if (II->isStr("max"))
- BOK = BO_GT;
- else if (II->isStr("min"))
- BOK = BO_LT;
- }
- break;
- }
- SourceRange ReductionIdRange;
- if (ReductionIdScopeSpec.isValid()) {
- ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
- }
- ReductionIdRange.setEnd(ReductionId.getEndLoc());
- if (BOK == BO_Comma) {
- // Not allowed reduction identifier is found.
- Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
- << ReductionIdRange;
- return nullptr;
- }
- SmallVector<Expr *, 8> Vars;
- SmallVector<Expr *, 8> Privates;
- SmallVector<Expr *, 8> LHSs;
- SmallVector<Expr *, 8> RHSs;
- SmallVector<Expr *, 8> ReductionOps;
- for (auto RefExpr : VarList) {
- assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
- if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
- // It will be analyzed later.
- Vars.push_back(RefExpr);
- Privates.push_back(nullptr);
- LHSs.push_back(nullptr);
- RHSs.push_back(nullptr);
- ReductionOps.push_back(nullptr);
- continue;
- }
- if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
- RefExpr->isInstantiationDependent() ||
- RefExpr->containsUnexpandedParameterPack()) {
- // It will be analyzed later.
- Vars.push_back(RefExpr);
- Privates.push_back(nullptr);
- LHSs.push_back(nullptr);
- RHSs.push_back(nullptr);
- ReductionOps.push_back(nullptr);
- continue;
- }
- auto ELoc = RefExpr->getExprLoc();
- auto ERange = RefExpr->getSourceRange();
- // OpenMP [2.1, C/C++]
- // A list item is a variable or array section, subject to the restrictions
- // specified in Section 2.4 on page 42 and in each of the sections
- // describing clauses and directives for which a list appears.
- // OpenMP [2.14.3.3, Restrictions, p.1]
- // A variable that is part of another variable (as an array or
- // structure element) cannot appear in a private clause.
- auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
- auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr);
- auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr);
- if (!ASE && !OASE && (!DE || !isa<VarDecl>(DE->getDecl()))) {
- Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
- << 0 << ERange;
- continue;
- }
- QualType Type;
- VarDecl *VD = nullptr;
- if (DE) {
- auto D = DE->getDecl();
- VD = cast<VarDecl>(D);
- Type = Context.getBaseElementType(VD->getType());
- } else if (ASE) {
- Type = ASE->getType();
- auto *Base = ASE->getBase()->IgnoreParenImpCasts();
- while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
- Base = TempASE->getBase()->IgnoreParenImpCasts();
- DE = dyn_cast<DeclRefExpr>(Base);
- if (DE)
- VD = dyn_cast<VarDecl>(DE->getDecl());
- if (!VD) {
- Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
- << 0 << Base->getSourceRange();
- continue;
- }
- } else if (OASE) {
- auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
- if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
- Type = ATy->getElementType();
- else
- Type = BaseType->getPointeeType();
- auto *Base = OASE->getBase()->IgnoreParenImpCasts();
- while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
- Base = TempOASE->getBase()->IgnoreParenImpCasts();
- while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
- Base = TempASE->getBase()->IgnoreParenImpCasts();
- DE = dyn_cast<DeclRefExpr>(Base);
- if (DE)
- VD = dyn_cast<VarDecl>(DE->getDecl());
- if (!VD) {
- Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
- << 1 << Base->getSourceRange();
- continue;
- }
- }
- // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
- // A variable that appears in a private clause must not have an incomplete
- // type or a reference type.
- if (RequireCompleteType(ELoc, Type,
- diag::err_omp_reduction_incomplete_type))
- continue;
- // OpenMP [2.14.3.6, reduction clause, Restrictions]
- // A list item that appears in a reduction clause must not be
- // const-qualified.
- if (Type.getNonReferenceType().isConstant(Context)) {
- Diag(ELoc, diag::err_omp_const_reduction_list_item)
- << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
- if (!ASE && !OASE) {
- bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
- VarDecl::DeclarationOnly;
- Diag(VD->getLocation(),
- IsDecl ? diag::note_previous_decl : diag::note_defined_here)
- << VD;
- }
- continue;
- }
- // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
- // If a list-item is a reference type then it must bind to the same object
- // for all threads of the team.
- if (!ASE && !OASE) {
- VarDecl *VDDef = VD->getDefinition();
- if (Type->isReferenceType() && VDDef) {
- DSARefChecker Check(DSAStack);
- if (Check.Visit(VDDef->getInit())) {
- Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
- Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
- continue;
- }
- }
- }
- // OpenMP [2.14.3.6, reduction clause, Restrictions]
- // The type of a list item that appears in a reduction clause must be valid
- // for the reduction-identifier. For a max or min reduction in C, the type
- // of the list item must be an allowed arithmetic data type: char, int,
- // float, double, or _Bool, possibly modified with long, short, signed, or
- // unsigned. For a max or min reduction in C++, the type of the list item
- // must be an allowed arithmetic data type: char, wchar_t, int, float,
- // double, or bool, possibly modified with long, short, signed, or unsigned.
- if ((BOK == BO_GT || BOK == BO_LT) &&
- !(Type->isScalarType() ||
- (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
- Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
- << getLangOpts().CPlusPlus;
- if (!ASE && !OASE) {
- bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
- VarDecl::DeclarationOnly;
- Diag(VD->getLocation(),
- IsDecl ? diag::note_previous_decl : diag::note_defined_here)
- << VD;
- }
- continue;
- }
- if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
- !getLangOpts().CPlusPlus && Type->isFloatingType()) {
- Diag(ELoc, diag::err_omp_clause_floating_type_arg);
- if (!ASE && !OASE) {
- bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
- VarDecl::DeclarationOnly;
- Diag(VD->getLocation(),
- IsDecl ? diag::note_previous_decl : diag::note_defined_here)
- << VD;
- }
- continue;
- }
- // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
- // in a Construct]
- // Variables with the predetermined data-sharing attributes may not be
- // listed in data-sharing attributes clauses, except for the cases
- // listed below. For these exceptions only, listing a predetermined
- // variable in a data-sharing attribute clause is allowed and overrides
- // the variable's predetermined data-sharing attributes.
- // OpenMP [2.14.3.6, Restrictions, p.3]
- // Any number of reduction clauses can be specified on the directive,
- // but a list item can appear only once in the reduction clauses for that
- // directive.
- DSAStackTy::DSAVarData DVar;
- DVar = DSAStack->getTopDSA(VD, false);
- if (DVar.CKind == OMPC_reduction) {
- Diag(ELoc, diag::err_omp_once_referenced)
- << getOpenMPClauseName(OMPC_reduction);
- if (DVar.RefExpr) {
- Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
- }
- } else if (DVar.CKind != OMPC_unknown) {
- Diag(ELoc, diag::err_omp_wrong_dsa)
- << getOpenMPClauseName(DVar.CKind)
- << getOpenMPClauseName(OMPC_reduction);
- ReportOriginalDSA(*this, DSAStack, VD, DVar);
- continue;
- }
- // OpenMP [2.14.3.6, Restrictions, p.1]
- // A list item that appears in a reduction clause of a worksharing
- // construct must be shared in the parallel regions to which any of the
- // worksharing regions arising from the worksharing construct bind.
- OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
- if (isOpenMPWorksharingDirective(CurrDir) &&
- !isOpenMPParallelDirective(CurrDir)) {
- DVar = DSAStack->getImplicitDSA(VD, true);
- if (DVar.CKind != OMPC_shared) {
- Diag(ELoc, diag::err_omp_required_access)
- << getOpenMPClauseName(OMPC_reduction)
- << getOpenMPClauseName(OMPC_shared);
- ReportOriginalDSA(*this, DSAStack, VD, DVar);
- continue;
- }
- }
- Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
- auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
- VD->hasAttrs() ? &VD->getAttrs() : nullptr);
- auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName(),
- VD->hasAttrs() ? &VD->getAttrs() : nullptr);
- auto PrivateTy = Type;
- if (OASE ||
- (DE && VD->getType().getNonReferenceType()->isVariablyModifiedType())) {
- // For arays/array sections only:
- // Create pseudo array type for private copy. The size for this array will
- // be generated during codegen.
- // For array subscripts or single variables Private Ty is the same as Type
- // (type of the variable or single array element).
- PrivateTy = Context.getVariableArrayType(
- Type, new (Context) OpaqueValueExpr(SourceLocation(),
- Context.getSizeType(), VK_RValue),
- ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
- } else if (DE &&
- Context.getAsArrayType(VD->getType().getNonReferenceType()))
- PrivateTy = VD->getType().getNonReferenceType();
- // Private copy.
- auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, VD->getName(),
- VD->hasAttrs() ? &VD->getAttrs() : nullptr);
- // Add initializer for private variable.
- Expr *Init = nullptr;
- switch (BOK) {
- case BO_Add:
- case BO_Xor:
- case BO_Or:
- case BO_LOr:
- // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
- if (Type->isScalarType() || Type->isAnyComplexType()) {
- Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
- }
- break;
- case BO_Mul:
- case BO_LAnd:
- if (Type->isScalarType() || Type->isAnyComplexType()) {
- // '*' and '&&' reduction ops - initializer is '1'.
- Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
- }
- break;
- case BO_And: {
- // '&' reduction op - initializer is '~0'.
- QualType OrigType = Type;
- if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
- Type = ComplexTy->getElementType();
- }
- if (Type->isRealFloatingType()) {
- llvm::APFloat InitValue =
- llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
- /*isIEEE=*/true);
- Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
- Type, ELoc);
- } else if (Type->isScalarType()) {
- auto Size = Context.getTypeSize(Type);
- QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
- llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
- Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
- }
- if (Init && OrigType->isAnyComplexType()) {
- // Init = 0xFFFF + 0xFFFFi;
- auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
- Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
- }
- Type = OrigType;
- break;
- }
- case BO_LT:
- case BO_GT: {
- // 'min' reduction op - initializer is 'Largest representable number in
- // the reduction list item type'.
- // 'max' reduction op - initializer is 'Least representable number in
- // the reduction list item type'.
- if (Type->isIntegerType() || Type->isPointerType()) {
- bool IsSigned = Type->hasSignedIntegerRepresentation();
- auto Size = Context.getTypeSize(Type);
- QualType IntTy =
- Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
- llvm::APInt InitValue =
- (BOK != BO_LT)
- ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
- : llvm::APInt::getMinValue(Size)
- : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
- : llvm::APInt::getMaxValue(Size);
- Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
- if (Type->isPointerType()) {
- // Cast to pointer type.
- auto CastExpr = BuildCStyleCastExpr(
- SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
- SourceLocation(), Init);
- if (CastExpr.isInvalid())
- continue;
- Init = CastExpr.get();
- }
- } else if (Type->isRealFloatingType()) {
- llvm::APFloat InitValue = llvm::APFloat::getLargest(
- Context.getFloatTypeSemantics(Type), BOK != BO_LT);
- Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
- Type, ELoc);
- }
- break;
- }
- case BO_PtrMemD:
- case BO_PtrMemI:
- case BO_MulAssign:
- case BO_Div:
- case BO_Rem:
- case BO_Sub:
- case BO_Shl:
- case BO_Shr:
- case BO_LE:
- case BO_GE:
- case BO_EQ:
- case BO_NE:
- case BO_AndAssign:
- case BO_XorAssign:
- case BO_OrAssign:
- case BO_Assign:
- case BO_AddAssign:
- case BO_SubAssign:
- case BO_DivAssign:
- case BO_RemAssign:
- case BO_ShlAssign:
- case BO_ShrAssign:
- case BO_Comma:
- llvm_unreachable("Unexpected reduction operation");
- }
- if (Init) {
- AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
- /*TypeMayContainAuto=*/false);
- } else
- ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
- if (!RHSVD->hasInit()) {
- Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
- << ReductionIdRange;
- if (VD) {
- bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
- VarDecl::DeclarationOnly;
- Diag(VD->getLocation(),
- IsDecl ? diag::note_previous_decl : diag::note_defined_here)
- << VD;
- }
- continue;
- }
- // Store initializer for single element in private copy. Will be used during
- // codegen.
- PrivateVD->setInit(RHSVD->getInit());
- PrivateVD->setInitStyle(RHSVD->getInitStyle());
- auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
- auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
- auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
- ExprResult ReductionOp =
- BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
- LHSDRE, RHSDRE);
- if (ReductionOp.isUsable()) {
- if (BOK != BO_LT && BOK != BO_GT) {
- ReductionOp =
- BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
- BO_Assign, LHSDRE, ReductionOp.get());
- } else {
- auto *ConditionalOp = new (Context) ConditionalOperator(
- ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
- RHSDRE, Type, VK_LValue, OK_Ordinary);
- ReductionOp =
- BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
- BO_Assign, LHSDRE, ConditionalOp);
- }
- ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
- }
- if (ReductionOp.isInvalid())
- continue;
- DSAStack->addDSA(VD, DE, OMPC_reduction);
- Vars.push_back(RefExpr);
- Privates.push_back(PrivateDRE);
- LHSs.push_back(LHSDRE);
- RHSs.push_back(RHSDRE);
- ReductionOps.push_back(ReductionOp.get());
- }
- if (Vars.empty())
- return nullptr;
- return OMPReductionClause::Create(
- Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
- ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
- LHSs, RHSs, ReductionOps);
- }
- OMPClause *Sema::ActOnOpenMPLinearClause(
- ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
- SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
- SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
- SmallVector<Expr *, 8> Vars;
- SmallVector<Expr *, 8> Privates;
- SmallVector<Expr *, 8> Inits;
- if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
- LinKind == OMPC_LINEAR_unknown) {
- Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
- LinKind = OMPC_LINEAR_val;
- }
- for (auto &RefExpr : VarList) {
- assert(RefExpr && "NULL expr in OpenMP linear clause.");
- if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
- // It will be analyzed later.
- Vars.push_back(RefExpr);
- Privates.push_back(nullptr);
- Inits.push_back(nullptr);
- continue;
- }
- // OpenMP [2.14.3.7, linear clause]
- // A list item that appears in a linear clause is subject to the private
- // clause semantics described in Section 2.14.3.3 on page 159 except as
- // noted. In addition, the value of the new list item on each iteration
- // of the associated loop(s) corresponds to the value of the original
- // list item before entering the construct plus the logical number of
- // the iteration times linear-step.
- SourceLocation ELoc = RefExpr->getExprLoc();
- // OpenMP [2.1, C/C++]
- // A list item is a variable name.
- // OpenMP [2.14.3.3, Restrictions, p.1]
- // A variable that is part of another variable (as an array or
- // structure element) cannot appear in a private clause.
- DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
- if (!DE || !isa<VarDecl>(DE->getDecl())) {
- Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
- << 0 << RefExpr->getSourceRange();
- continue;
- }
- VarDecl *VD = cast<VarDecl>(DE->getDecl());
- // OpenMP [2.14.3.7, linear clause]
- // A list-item cannot appear in more than one linear clause.
- // A list-item that appears in a linear clause cannot appear in any
- // other data-sharing attribute clause.
- DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
- if (DVar.RefExpr) {
- Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
- << getOpenMPClauseName(OMPC_linear);
- ReportOriginalDSA(*this, DSAStack, VD, DVar);
- continue;
- }
- QualType QType = VD->getType();
- if (QType->isDependentType() || QType->isInstantiationDependentType()) {
- // It will be analyzed later.
- Vars.push_back(DE);
- Privates.push_back(nullptr);
- Inits.push_back(nullptr);
- continue;
- }
- // A variable must not have an incomplete type or a reference type.
- if (RequireCompleteType(ELoc, QType,
- diag::err_omp_linear_incomplete_type)) {
- continue;
- }
- if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
- !QType->isReferenceType()) {
- Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
- << QType << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
- continue;
- }
- QType = QType.getNonReferenceType();
- // A list item must not be const-qualified.
- if (QType.isConstant(Context)) {
- Diag(ELoc, diag::err_omp_const_variable)
- << getOpenMPClauseName(OMPC_linear);
- bool IsDecl =
- VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
- Diag(VD->getLocation(),
- IsDecl ? diag::note_previous_decl : diag::note_defined_here)
- << VD;
- continue;
- }
- // A list item must be of integral or pointer type.
- QType = QType.getUnqualifiedType().getCanonicalType();
- const Type *Ty = QType.getTypePtrOrNull();
- if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
- !Ty->isPointerType())) {
- Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
- bool IsDecl =
- VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
- Diag(VD->getLocation(),
- IsDecl ? diag::note_previous_decl : diag::note_defined_here)
- << VD;
- continue;
- }
- // Build private copy of original var.
- auto *Private = buildVarDecl(*this, ELoc, QType, VD->getName(),
- VD->hasAttrs() ? &VD->getAttrs() : nullptr);
- auto *PrivateRef = buildDeclRefExpr(
- *this, Private, DE->getType().getUnqualifiedType(), DE->getExprLoc());
- // Build var to save initial value.
- VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
- Expr *InitExpr;
- if (LinKind == OMPC_LINEAR_uval)
- InitExpr = VD->getInit();
- else
- InitExpr = DE;
- AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
- /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
- auto InitRef = buildDeclRefExpr(
- *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
- DSAStack->addDSA(VD, DE, OMPC_linear);
- Vars.push_back(DE);
- Privates.push_back(PrivateRef);
- Inits.push_back(InitRef);
- }
- if (Vars.empty())
- return nullptr;
- Expr *StepExpr = Step;
- Expr *CalcStepExpr = nullptr;
- if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
- !Step->isInstantiationDependent() &&
- !Step->containsUnexpandedParameterPack()) {
- SourceLocation StepLoc = Step->getLocStart();
- ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
- if (Val.isInvalid())
- return nullptr;
- StepExpr = Val.get();
- // Build var to save the step value.
- VarDecl *SaveVar =
- buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
- ExprResult SaveRef =
- buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
- ExprResult CalcStep =
- BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
- CalcStep = ActOnFinishFullExpr(CalcStep.get());
- // Warn about zero linear step (it would be probably better specified as
- // making corresponding variables 'const').
- llvm::APSInt Result;
- bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
- if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
- Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
- << (Vars.size() > 1);
- if (!IsConstant && CalcStep.isUsable()) {
- // Calculate the step beforehand instead of doing this on each iteration.
- // (This is not used if the number of iterations may be kfold-ed).
- CalcStepExpr = CalcStep.get();
- }
- }
- return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
- ColonLoc, EndLoc, Vars, Privates, Inits,
- StepExpr, CalcStepExpr);
- }
- static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
- Expr *NumIterations, Sema &SemaRef,
- Scope *S) {
- // Walk the vars and build update/final expressions for the CodeGen.
- SmallVector<Expr *, 8> Updates;
- SmallVector<Expr *, 8> Finals;
- Expr *Step = Clause.getStep();
- Expr *CalcStep = Clause.getCalcStep();
- // OpenMP [2.14.3.7, linear clause]
- // If linear-step is not specified it is assumed to be 1.
- if (Step == nullptr)
- Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
- else if (CalcStep)
- Step = cast<BinaryOperator>(CalcStep)->getLHS();
- bool HasErrors = false;
- auto CurInit = Clause.inits().begin();
- auto CurPrivate = Clause.privates().begin();
- auto LinKind = Clause.getModifier();
- for (auto &RefExpr : Clause.varlists()) {
- Expr *InitExpr = *CurInit;
- // Build privatized reference to the current linear var.
- auto DE = cast<DeclRefExpr>(RefExpr);
- Expr *CapturedRef;
- if (LinKind == OMPC_LINEAR_uval)
- CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
- else
- CapturedRef =
- buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
- DE->getType().getUnqualifiedType(), DE->getExprLoc(),
- /*RefersToCapture=*/true);
- // Build update: Var = InitExpr + IV * Step
- ExprResult Update =
- BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
- InitExpr, IV, Step, /* Subtract */ false);
- Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
- /*DiscardedValue=*/true);
- // Build final: Var = InitExpr + NumIterations * Step
- ExprResult Final =
- BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
- InitExpr, NumIterations, Step, /* Subtract */ false);
- Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
- /*DiscardedValue=*/true);
- if (!Update.isUsable() || !Final.isUsable()) {
- Updates.push_back(nullptr);
- Finals.push_back(nullptr);
- HasErrors = true;
- } else {
- Updates.push_back(Update.get());
- Finals.push_back(Final.get());
- }
- ++CurInit, ++CurPrivate;
- }
- Clause.setUpdates(Updates);
- Clause.setFinals(Finals);
- return HasErrors;
- }
- OMPClause *Sema::ActOnOpenMPAlignedClause(
- ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
- SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
- SmallVector<Expr *, 8> Vars;
- for (auto &RefExpr : VarList) {
- assert(RefExpr && "NULL expr in OpenMP aligned clause.");
- if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
- // It will be analyzed later.
- Vars.push_back(RefExpr);
- continue;
- }
- SourceLocation ELoc = RefExpr->getExprLoc();
- // OpenMP [2.1, C/C++]
- // A list item is a variable name.
- DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
- if (!DE || !isa<VarDecl>(DE->getDecl())) {
- Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
- << 0 << RefExpr->getSourceRange();
- continue;
- }
- VarDecl *VD = cast<VarDecl>(DE->getDecl());
- // OpenMP [2.8.1, simd construct, Restrictions]
- // The type of list items appearing in the aligned clause must be
- // array, pointer, reference to array, or reference to pointer.
- QualType QType = VD->getType();
- QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
- const Type *Ty = QType.getTypePtrOrNull();
- if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
- !Ty->isPointerType())) {
- Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
- << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
- bool IsDecl =
- VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
- Diag(VD->getLocation(),
- IsDecl ? diag::note_previous_decl : diag::note_defined_here)
- << VD;
- continue;
- }
- // OpenMP [2.8.1, simd construct, Restrictions]
- // A list-item cannot appear in more than one aligned clause.
- if (Expr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
- Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
- Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
- << getOpenMPClauseName(OMPC_aligned);
- continue;
- }
- Vars.push_back(DE);
- }
- // OpenMP [2.8.1, simd construct, Description]
- // The parameter of the aligned clause, alignment, must be a constant
- // positive integer expression.
- // If no optional parameter is specified, implementation-defined default
- // alignments for SIMD instructions on the target platforms are assumed.
- if (Alignment != nullptr) {
- ExprResult AlignResult =
- VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
- if (AlignResult.isInvalid())
- return nullptr;
- Alignment = AlignResult.get();
- }
- if (Vars.empty())
- return nullptr;
- return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
- EndLoc, Vars, Alignment);
- }
- OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- SmallVector<Expr *, 8> Vars;
- SmallVector<Expr *, 8> SrcExprs;
- SmallVector<Expr *, 8> DstExprs;
- SmallVector<Expr *, 8> AssignmentOps;
- for (auto &RefExpr : VarList) {
- assert(RefExpr && "NULL expr in OpenMP copyin clause.");
- if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
- // It will be analyzed later.
- Vars.push_back(RefExpr);
- SrcExprs.push_back(nullptr);
- DstExprs.push_back(nullptr);
- AssignmentOps.push_back(nullptr);
- continue;
- }
- SourceLocation ELoc = RefExpr->getExprLoc();
- // OpenMP [2.1, C/C++]
- // A list item is a variable name.
- // OpenMP [2.14.4.1, Restrictions, p.1]
- // A list item that appears in a copyin clause must be threadprivate.
- DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
- if (!DE || !isa<VarDecl>(DE->getDecl())) {
- Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
- << 0 << RefExpr->getSourceRange();
- continue;
- }
- Decl *D = DE->getDecl();
- VarDecl *VD = cast<VarDecl>(D);
- QualType Type = VD->getType();
- if (Type->isDependentType() || Type->isInstantiationDependentType()) {
- // It will be analyzed later.
- Vars.push_back(DE);
- SrcExprs.push_back(nullptr);
- DstExprs.push_back(nullptr);
- AssignmentOps.push_back(nullptr);
- continue;
- }
- // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
- // A list item that appears in a copyin clause must be threadprivate.
- if (!DSAStack->isThreadPrivate(VD)) {
- Diag(ELoc, diag::err_omp_required_access)
- << getOpenMPClauseName(OMPC_copyin)
- << getOpenMPDirectiveName(OMPD_threadprivate);
- continue;
- }
- // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
- // A variable of class type (or array thereof) that appears in a
- // copyin clause requires an accessible, unambiguous copy assignment
- // operator for the class type.
- auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
- auto *SrcVD =
- buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
- ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
- auto *PseudoSrcExpr = buildDeclRefExpr(
- *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
- auto *DstVD =
- buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
- VD->hasAttrs() ? &VD->getAttrs() : nullptr);
- auto *PseudoDstExpr =
- buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
- // For arrays generate assignment operation for single element and replace
- // it by the original array element in CodeGen.
- auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
- PseudoDstExpr, PseudoSrcExpr);
- if (AssignmentOp.isInvalid())
- continue;
- AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
- /*DiscardedValue=*/true);
- if (AssignmentOp.isInvalid())
- continue;
- DSAStack->addDSA(VD, DE, OMPC_copyin);
- Vars.push_back(DE);
- SrcExprs.push_back(PseudoSrcExpr);
- DstExprs.push_back(PseudoDstExpr);
- AssignmentOps.push_back(AssignmentOp.get());
- }
- if (Vars.empty())
- return nullptr;
- return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
- SrcExprs, DstExprs, AssignmentOps);
- }
- OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- SmallVector<Expr *, 8> Vars;
- SmallVector<Expr *, 8> SrcExprs;
- SmallVector<Expr *, 8> DstExprs;
- SmallVector<Expr *, 8> AssignmentOps;
- for (auto &RefExpr : VarList) {
- assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
- if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
- // It will be analyzed later.
- Vars.push_back(RefExpr);
- SrcExprs.push_back(nullptr);
- DstExprs.push_back(nullptr);
- AssignmentOps.push_back(nullptr);
- continue;
- }
- SourceLocation ELoc = RefExpr->getExprLoc();
- // OpenMP [2.1, C/C++]
- // A list item is a variable name.
- // OpenMP [2.14.4.1, Restrictions, p.1]
- // A list item that appears in a copyin clause must be threadprivate.
- DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
- if (!DE || !isa<VarDecl>(DE->getDecl())) {
- Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
- << 0 << RefExpr->getSourceRange();
- continue;
- }
- Decl *D = DE->getDecl();
- VarDecl *VD = cast<VarDecl>(D);
- QualType Type = VD->getType();
- if (Type->isDependentType() || Type->isInstantiationDependentType()) {
- // It will be analyzed later.
- Vars.push_back(DE);
- SrcExprs.push_back(nullptr);
- DstExprs.push_back(nullptr);
- AssignmentOps.push_back(nullptr);
- continue;
- }
- // OpenMP [2.14.4.2, Restrictions, p.2]
- // A list item that appears in a copyprivate clause may not appear in a
- // private or firstprivate clause on the single construct.
- if (!DSAStack->isThreadPrivate(VD)) {
- auto DVar = DSAStack->getTopDSA(VD, false);
- if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
- DVar.RefExpr) {
- Diag(ELoc, diag::err_omp_wrong_dsa)
- << getOpenMPClauseName(DVar.CKind)
- << getOpenMPClauseName(OMPC_copyprivate);
- ReportOriginalDSA(*this, DSAStack, VD, DVar);
- continue;
- }
- // OpenMP [2.11.4.2, Restrictions, p.1]
- // All list items that appear in a copyprivate clause must be either
- // threadprivate or private in the enclosing context.
- if (DVar.CKind == OMPC_unknown) {
- DVar = DSAStack->getImplicitDSA(VD, false);
- if (DVar.CKind == OMPC_shared) {
- Diag(ELoc, diag::err_omp_required_access)
- << getOpenMPClauseName(OMPC_copyprivate)
- << "threadprivate or private in the enclosing context";
- ReportOriginalDSA(*this, DSAStack, VD, DVar);
- continue;
- }
- }
- }
- // Variably modified types are not supported.
- if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
- Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
- << getOpenMPClauseName(OMPC_copyprivate) << Type
- << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
- bool IsDecl =
- VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
- Diag(VD->getLocation(),
- IsDecl ? diag::note_previous_decl : diag::note_defined_here)
- << VD;
- continue;
- }
- // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
- // A variable of class type (or array thereof) that appears in a
- // copyin clause requires an accessible, unambiguous copy assignment
- // operator for the class type.
- Type = Context.getBaseElementType(Type.getNonReferenceType())
- .getUnqualifiedType();
- auto *SrcVD =
- buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src",
- VD->hasAttrs() ? &VD->getAttrs() : nullptr);
- auto *PseudoSrcExpr =
- buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
- auto *DstVD =
- buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst",
- VD->hasAttrs() ? &VD->getAttrs() : nullptr);
- auto *PseudoDstExpr =
- buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
- auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
- PseudoDstExpr, PseudoSrcExpr);
- if (AssignmentOp.isInvalid())
- continue;
- AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
- /*DiscardedValue=*/true);
- if (AssignmentOp.isInvalid())
- continue;
- // No need to mark vars as copyprivate, they are already threadprivate or
- // implicitly private.
- Vars.push_back(DE);
- SrcExprs.push_back(PseudoSrcExpr);
- DstExprs.push_back(PseudoDstExpr);
- AssignmentOps.push_back(AssignmentOp.get());
- }
- if (Vars.empty())
- return nullptr;
- return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
- Vars, SrcExprs, DstExprs, AssignmentOps);
- }
- OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- if (VarList.empty())
- return nullptr;
- return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
- }
- OMPClause *
- Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
- SourceLocation DepLoc, SourceLocation ColonLoc,
- ArrayRef<Expr *> VarList, SourceLocation StartLoc,
- SourceLocation LParenLoc, SourceLocation EndLoc) {
- if (DSAStack->getCurrentDirective() == OMPD_ordered &&
- DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
- Diag(DepLoc, diag::err_omp_unexpected_clause_value)
- << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
- return nullptr;
- }
- if (DSAStack->getCurrentDirective() != OMPD_ordered &&
- (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
- DepKind == OMPC_DEPEND_sink)) {
- unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
- Diag(DepLoc, diag::err_omp_unexpected_clause_value)
- << getListOfPossibleValues(OMPC_depend, /*First=*/0,
- /*Last=*/OMPC_DEPEND_unknown, Except)
- << getOpenMPClauseName(OMPC_depend);
- return nullptr;
- }
- SmallVector<Expr *, 8> Vars;
- llvm::APSInt DepCounter(/*BitWidth=*/32);
- llvm::APSInt TotalDepCount(/*BitWidth=*/32);
- if (DepKind == OMPC_DEPEND_sink) {
- if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
- TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
- TotalDepCount.setIsUnsigned(/*Val=*/true);
- }
- }
- if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
- DSAStack->getParentOrderedRegionParam()) {
- for (auto &RefExpr : VarList) {
- assert(RefExpr && "NULL expr in OpenMP shared clause.");
- if (isa<DependentScopeDeclRefExpr>(RefExpr) ||
- (DepKind == OMPC_DEPEND_sink && CurContext->isDependentContext())) {
- // It will be analyzed later.
- Vars.push_back(RefExpr);
- continue;
- }
- SourceLocation ELoc = RefExpr->getExprLoc();
- auto *SimpleExpr = RefExpr->IgnoreParenCasts();
- if (DepKind == OMPC_DEPEND_sink) {
- if (DepCounter >= TotalDepCount) {
- Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
- continue;
- }
- ++DepCounter;
- // OpenMP [2.13.9, Summary]
- // depend(dependence-type : vec), where dependence-type is:
- // 'sink' and where vec is the iteration vector, which has the form:
- // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
- // where n is the value specified by the ordered clause in the loop
- // directive, xi denotes the loop iteration variable of the i-th nested
- // loop associated with the loop directive, and di is a constant
- // non-negative integer.
- SimpleExpr = SimpleExpr->IgnoreImplicit();
- auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
- if (!DE) {
- OverloadedOperatorKind OOK = OO_None;
- SourceLocation OOLoc;
- Expr *LHS, *RHS;
- if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
- OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
- OOLoc = BO->getOperatorLoc();
- LHS = BO->getLHS()->IgnoreParenImpCasts();
- RHS = BO->getRHS()->IgnoreParenImpCasts();
- } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
- OOK = OCE->getOperator();
- OOLoc = OCE->getOperatorLoc();
- LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
- RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
- } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
- OOK = MCE->getMethodDecl()
- ->getNameInfo()
- .getName()
- .getCXXOverloadedOperator();
- OOLoc = MCE->getCallee()->getExprLoc();
- LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
- RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
- } else {
- Diag(ELoc, diag::err_omp_depend_sink_wrong_expr);
- continue;
- }
- DE = dyn_cast<DeclRefExpr>(LHS);
- if (!DE) {
- Diag(LHS->getExprLoc(),
- diag::err_omp_depend_sink_expected_loop_iteration)
- << DSAStack->getParentLoopControlVariable(
- DepCounter.getZExtValue());
- continue;
- }
- if (OOK != OO_Plus && OOK != OO_Minus) {
- Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
- continue;
- }
- ExprResult Res = VerifyPositiveIntegerConstantInClause(
- RHS, OMPC_depend, /*StrictlyPositive=*/false);
- if (Res.isInvalid())
- continue;
- }
- auto *VD = dyn_cast<VarDecl>(DE->getDecl());
- if (!CurContext->isDependentContext() &&
- DSAStack->getParentOrderedRegionParam() &&
- (!VD || DepCounter != DSAStack->isParentLoopControlVariable(VD))) {
- Diag(DE->getExprLoc(),
- diag::err_omp_depend_sink_expected_loop_iteration)
- << DSAStack->getParentLoopControlVariable(
- DepCounter.getZExtValue());
- continue;
- }
- } else {
- // OpenMP [2.11.1.1, Restrictions, p.3]
- // A variable that is part of another variable (such as a field of a
- // structure) but is not an array element or an array section cannot
- // appear in a depend clause.
- auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
- auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
- auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
- if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
- (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
- (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
- !ASE->getBase()->getType()->isArrayType())) {
- Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
- << 0 << RefExpr->getSourceRange();
- continue;
- }
- }
- Vars.push_back(RefExpr->IgnoreParenImpCasts());
- }
- if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
- TotalDepCount > VarList.size() &&
- DSAStack->getParentOrderedRegionParam()) {
- Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
- << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
- }
- if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
- Vars.empty())
- return nullptr;
- }
- return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
- DepLoc, ColonLoc, Vars);
- }
- OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- Expr *ValExpr = Device;
- // OpenMP [2.9.1, Restrictions]
- // The device expression must evaluate to a non-negative integer value.
- if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
- /*StrictlyPositive=*/false))
- return nullptr;
- return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
- }
- static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
- DSAStackTy *Stack, CXXRecordDecl *RD) {
- if (!RD || RD->isInvalidDecl())
- return true;
- if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
- if (auto *CTD = CTSD->getSpecializedTemplate())
- RD = CTD->getTemplatedDecl();
- auto QTy = SemaRef.Context.getRecordType(RD);
- if (RD->isDynamicClass()) {
- SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
- SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
- return false;
- }
- auto *DC = RD;
- bool IsCorrect = true;
- for (auto *I : DC->decls()) {
- if (I) {
- if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
- if (MD->isStatic()) {
- SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
- SemaRef.Diag(MD->getLocation(),
- diag::note_omp_static_member_in_target);
- IsCorrect = false;
- }
- } else if (auto *VD = dyn_cast<VarDecl>(I)) {
- if (VD->isStaticDataMember()) {
- SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
- SemaRef.Diag(VD->getLocation(),
- diag::note_omp_static_member_in_target);
- IsCorrect = false;
- }
- }
- }
- }
- for (auto &I : RD->bases()) {
- if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
- I.getType()->getAsCXXRecordDecl()))
- IsCorrect = false;
- }
- return IsCorrect;
- }
- static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
- DSAStackTy *Stack, QualType QTy) {
- NamedDecl *ND;
- if (QTy->isIncompleteType(&ND)) {
- SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
- return false;
- } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
- if (!RD->isInvalidDecl() &&
- !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
- return false;
- }
- return true;
- }
- // Return the expression of the base of the map clause or null if it cannot
- // be determined and do all the necessary checks to see if the expression is
- // valid as a standalone map clause expression.
- static Expr *CheckMapClauseExpressionBase(Sema &SemaRef, Expr *E) {
- SourceLocation ELoc = E->getExprLoc();
- SourceRange ERange = E->getSourceRange();
- // The base of elements of list in a map clause have to be either:
- // - a reference to variable or field.
- // - a member expression.
- // - an array expression.
- //
- // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
- // reference to 'r'.
- //
- // If we have:
- //
- // struct SS {
- // Bla S;
- // foo() {
- // #pragma omp target map (S.Arr[:12]);
- // }
- // }
- //
- // We want to retrieve the member expression 'this->S';
- Expr *RelevantExpr = nullptr;
- // Flags to help capture some memory
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
- // If a list item is an array section, it must specify contiguous storage.
- //
- // For this restriction it is sufficient that we make sure only references
- // to variables or fields and array expressions, and that no array sections
- // exist except in the rightmost expression. E.g. these would be invalid:
- //
- // r.ArrS[3:5].Arr[6:7]
- //
- // r.ArrS[3:5].x
- //
- // but these would be valid:
- // r.ArrS[3].Arr[6:7]
- //
- // r.ArrS[3].x
- bool IsRightMostExpression = true;
- while (!RelevantExpr) {
- auto AllowArraySection = IsRightMostExpression;
- IsRightMostExpression = false;
- E = E->IgnoreParenImpCasts();
- if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
- if (!isa<VarDecl>(CurE->getDecl()))
- break;
- RelevantExpr = CurE;
- continue;
- }
- if (auto *CurE = dyn_cast<MemberExpr>(E)) {
- auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
- if (isa<CXXThisExpr>(BaseE))
- // We found a base expression: this->Val.
- RelevantExpr = CurE;
- else
- E = BaseE;
- if (!isa<FieldDecl>(CurE->getMemberDecl())) {
- SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
- << CurE->getSourceRange();
- break;
- }
- auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
- // A bit-field cannot appear in a map clause.
- //
- if (FD->isBitField()) {
- SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_map_clause)
- << CurE->getSourceRange();
- break;
- }
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
- // If the type of a list item is a reference to a type T then the type
- // will be considered to be T for all purposes of this clause.
- QualType CurType = BaseE->getType();
- if (CurType->isReferenceType())
- CurType = CurType->getPointeeType();
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
- // A list item cannot be a variable that is a member of a structure with
- // a union type.
- //
- if (auto *RT = CurType->getAs<RecordType>())
- if (RT->isUnionType()) {
- SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
- << CurE->getSourceRange();
- break;
- }
- continue;
- }
- if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
- E = CurE->getBase()->IgnoreParenImpCasts();
- if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
- SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
- << 0 << CurE->getSourceRange();
- break;
- }
- continue;
- }
- if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
- // If a list item is an element of a structure, only the rightmost symbol
- // of the variable reference can be an array section.
- //
- if (!AllowArraySection) {
- SemaRef.Diag(ELoc, diag::err_omp_array_section_in_rightmost_expression)
- << CurE->getSourceRange();
- break;
- }
- E = CurE->getBase()->IgnoreParenImpCasts();
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
- // If the type of a list item is a reference to a type T then the type
- // will be considered to be T for all purposes of this clause.
- QualType CurType = E->getType();
- if (CurType->isReferenceType())
- CurType = CurType->getPointeeType();
- if (!CurType->isAnyPointerType() && !CurType->isArrayType()) {
- SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
- << 0 << CurE->getSourceRange();
- break;
- }
- continue;
- }
- // If nothing else worked, this is not a valid map clause expression.
- SemaRef.Diag(ELoc,
- diag::err_omp_expected_named_var_member_or_array_expression)
- << ERange;
- break;
- }
- return RelevantExpr;
- }
- // Return true if expression E associated with value VD has conflicts with other
- // map information.
- static bool CheckMapConflicts(Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD,
- Expr *E, bool CurrentRegionOnly) {
- assert(VD && E);
- // Types used to organize the components of a valid map clause.
- typedef std::pair<Expr *, ValueDecl *> MapExpressionComponent;
- typedef SmallVector<MapExpressionComponent, 4> MapExpressionComponents;
- // Helper to extract the components in the map clause expression E and store
- // them into MEC. This assumes that E is a valid map clause expression, i.e.
- // it has already passed the single clause checks.
- auto ExtractMapExpressionComponents = [](Expr *TE,
- MapExpressionComponents &MEC) {
- while (true) {
- TE = TE->IgnoreParenImpCasts();
- if (auto *CurE = dyn_cast<DeclRefExpr>(TE)) {
- MEC.push_back(
- MapExpressionComponent(CurE, cast<VarDecl>(CurE->getDecl())));
- break;
- }
- if (auto *CurE = dyn_cast<MemberExpr>(TE)) {
- auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
- MEC.push_back(MapExpressionComponent(
- CurE, cast<FieldDecl>(CurE->getMemberDecl())));
- if (isa<CXXThisExpr>(BaseE))
- break;
- TE = BaseE;
- continue;
- }
- if (auto *CurE = dyn_cast<ArraySubscriptExpr>(TE)) {
- MEC.push_back(MapExpressionComponent(CurE, nullptr));
- TE = CurE->getBase()->IgnoreParenImpCasts();
- continue;
- }
- if (auto *CurE = dyn_cast<OMPArraySectionExpr>(TE)) {
- MEC.push_back(MapExpressionComponent(CurE, nullptr));
- TE = CurE->getBase()->IgnoreParenImpCasts();
- continue;
- }
- llvm_unreachable(
- "Expecting only valid map clause expressions at this point!");
- }
- };
- SourceLocation ELoc = E->getExprLoc();
- SourceRange ERange = E->getSourceRange();
- // In order to easily check the conflicts we need to match each component of
- // the expression under test with the components of the expressions that are
- // already in the stack.
- MapExpressionComponents CurComponents;
- ExtractMapExpressionComponents(E, CurComponents);
- assert(!CurComponents.empty() && "Map clause expression with no components!");
- assert(CurComponents.back().second == VD &&
- "Map clause expression with unexpected base!");
- // Variables to help detecting enclosing problems in data environment nests.
- bool IsEnclosedByDataEnvironmentExpr = false;
- Expr *EnclosingExpr = nullptr;
- bool FoundError =
- DSAS->checkMapInfoForVar(VD, CurrentRegionOnly, [&](Expr *RE) -> bool {
- MapExpressionComponents StackComponents;
- ExtractMapExpressionComponents(RE, StackComponents);
- assert(!StackComponents.empty() &&
- "Map clause expression with no components!");
- assert(StackComponents.back().second == VD &&
- "Map clause expression with unexpected base!");
- // Expressions must start from the same base. Here we detect at which
- // point both expressions diverge from each other and see if we can
- // detect if the memory referred to both expressions is contiguous and
- // do not overlap.
- auto CI = CurComponents.rbegin();
- auto CE = CurComponents.rend();
- auto SI = StackComponents.rbegin();
- auto SE = StackComponents.rend();
- for (; CI != CE && SI != SE; ++CI, ++SI) {
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
- // At most one list item can be an array item derived from a given
- // variable in map clauses of the same construct.
- if (CurrentRegionOnly && (isa<ArraySubscriptExpr>(CI->first) ||
- isa<OMPArraySectionExpr>(CI->first)) &&
- (isa<ArraySubscriptExpr>(SI->first) ||
- isa<OMPArraySectionExpr>(SI->first))) {
- SemaRef.Diag(CI->first->getExprLoc(),
- diag::err_omp_multiple_array_items_in_map_clause)
- << CI->first->getSourceRange();
- ;
- SemaRef.Diag(SI->first->getExprLoc(), diag::note_used_here)
- << SI->first->getSourceRange();
- return true;
- }
- // Do both expressions have the same kind?
- if (CI->first->getStmtClass() != SI->first->getStmtClass())
- break;
- // Are we dealing with different variables/fields?
- if (CI->second != SI->second)
- break;
- }
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
- // List items of map clauses in the same construct must not share
- // original storage.
- //
- // If the expressions are exactly the same or one is a subset of the
- // other, it means they are sharing storage.
- if (CI == CE && SI == SE) {
- if (CurrentRegionOnly) {
- SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
- SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
- << RE->getSourceRange();
- return true;
- } else {
- // If we find the same expression in the enclosing data environment,
- // that is legal.
- IsEnclosedByDataEnvironmentExpr = true;
- return false;
- }
- }
- QualType DerivedType = std::prev(CI)->first->getType();
- SourceLocation DerivedLoc = std::prev(CI)->first->getExprLoc();
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
- // If the type of a list item is a reference to a type T then the type
- // will be considered to be T for all purposes of this clause.
- if (DerivedType->isReferenceType())
- DerivedType = DerivedType->getPointeeType();
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
- // A variable for which the type is pointer and an array section
- // derived from that variable must not appear as list items of map
- // clauses of the same construct.
- //
- // Also, cover one of the cases in:
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
- // If any part of the original storage of a list item has corresponding
- // storage in the device data environment, all of the original storage
- // must have corresponding storage in the device data environment.
- //
- if (DerivedType->isAnyPointerType()) {
- if (CI == CE || SI == SE) {
- SemaRef.Diag(
- DerivedLoc,
- diag::err_omp_pointer_mapped_along_with_derived_section)
- << DerivedLoc;
- } else {
- assert(CI != CE && SI != SE);
- SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
- << DerivedLoc;
- }
- SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
- << RE->getSourceRange();
- return true;
- }
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
- // List items of map clauses in the same construct must not share
- // original storage.
- //
- // An expression is a subset of the other.
- if (CurrentRegionOnly && (CI == CE || SI == SE)) {
- SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
- SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
- << RE->getSourceRange();
- return true;
- }
- // The current expression uses the same base as other expression in the
- // data environment but does not contain it completelly.
- if (!CurrentRegionOnly && SI != SE)
- EnclosingExpr = RE;
- // The current expression is a subset of the expression in the data
- // environment.
- IsEnclosedByDataEnvironmentExpr |=
- (!CurrentRegionOnly && CI != CE && SI == SE);
- return false;
- });
- if (CurrentRegionOnly)
- return FoundError;
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
- // If any part of the original storage of a list item has corresponding
- // storage in the device data environment, all of the original storage must
- // have corresponding storage in the device data environment.
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
- // If a list item is an element of a structure, and a different element of
- // the structure has a corresponding list item in the device data environment
- // prior to a task encountering the construct associated with the map clause,
- // then the list item must also have a correspnding list item in the device
- // data environment prior to the task encountering the construct.
- //
- if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
- SemaRef.Diag(ELoc,
- diag::err_omp_original_storage_is_shared_and_does_not_contain)
- << ERange;
- SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
- << EnclosingExpr->getSourceRange();
- return true;
- }
- return FoundError;
- }
- OMPClause *
- Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
- OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
- SourceLocation MapLoc, SourceLocation ColonLoc,
- ArrayRef<Expr *> VarList, SourceLocation StartLoc,
- SourceLocation LParenLoc, SourceLocation EndLoc) {
- SmallVector<Expr *, 4> Vars;
- for (auto &RE : VarList) {
- assert(RE && "Null expr in omp map");
- if (isa<DependentScopeDeclRefExpr>(RE)) {
- // It will be analyzed later.
- Vars.push_back(RE);
- continue;
- }
- SourceLocation ELoc = RE->getExprLoc();
- auto *VE = RE->IgnoreParenLValueCasts();
- if (VE->isValueDependent() || VE->isTypeDependent() ||
- VE->isInstantiationDependent() ||
- VE->containsUnexpandedParameterPack()) {
- // We can only analyze this information once the missing information is
- // resolved.
- Vars.push_back(RE);
- continue;
- }
- auto *SimpleExpr = RE->IgnoreParenCasts();
- if (!RE->IgnoreParenImpCasts()->isLValue()) {
- Diag(ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
- << RE->getSourceRange();
- continue;
- }
- // Obtain the array or member expression bases if required.
- auto *BE = CheckMapClauseExpressionBase(*this, SimpleExpr);
- if (!BE)
- continue;
- // If the base is a reference to a variable, we rely on that variable for
- // the following checks. If it is a 'this' expression we rely on the field.
- ValueDecl *D = nullptr;
- if (auto *DRE = dyn_cast<DeclRefExpr>(BE)) {
- D = DRE->getDecl();
- } else {
- auto *ME = cast<MemberExpr>(BE);
- assert(isa<CXXThisExpr>(ME->getBase()) && "Unexpected expression!");
- D = ME->getMemberDecl();
- }
- assert(D && "Null decl on map clause.");
- auto *VD = dyn_cast<VarDecl>(D);
- auto *FD = dyn_cast<FieldDecl>(D);
- assert((VD || FD) && "Only variables or fields are expected here!");
- (void)FD;
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
- // threadprivate variables cannot appear in a map clause.
- if (VD && DSAStack->isThreadPrivate(VD)) {
- auto DVar = DSAStack->getTopDSA(VD, false);
- Diag(ELoc, diag::err_omp_threadprivate_in_map);
- ReportOriginalDSA(*this, DSAStack, VD, DVar);
- continue;
- }
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
- // A list item cannot appear in both a map clause and a data-sharing
- // attribute clause on the same construct.
- //
- // TODO: Implement this check - it cannot currently be tested because of
- // missing implementation of the other data sharing clauses in target
- // directives.
- // Check conflicts with other map clause expressions. We check the conflicts
- // with the current construct separately from the enclosing data
- // environment, because the restrictions are different.
- if (CheckMapConflicts(*this, DSAStack, D, SimpleExpr,
- /*CurrentRegionOnly=*/true))
- break;
- if (CheckMapConflicts(*this, DSAStack, D, SimpleExpr,
- /*CurrentRegionOnly=*/false))
- break;
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
- // If the type of a list item is a reference to a type T then the type will
- // be considered to be T for all purposes of this clause.
- QualType Type = D->getType();
- if (Type->isReferenceType())
- Type = Type->getPointeeType();
- // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
- // A list item must have a mappable type.
- if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), *this,
- DSAStack, Type))
- continue;
- // target enter data
- // OpenMP [2.10.2, Restrictions, p. 99]
- // A map-type must be specified in all map clauses and must be either
- // to or alloc.
- OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
- if (DKind == OMPD_target_enter_data &&
- !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
- Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
- << (IsMapTypeImplicit ? 1 : 0)
- << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
- << getOpenMPDirectiveName(DKind);
- continue;
- }
- // target exit_data
- // OpenMP [2.10.3, Restrictions, p. 102]
- // A map-type must be specified in all map clauses and must be either
- // from, release, or delete.
- DKind = DSAStack->getCurrentDirective();
- if (DKind == OMPD_target_exit_data &&
- !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
- MapType == OMPC_MAP_delete)) {
- Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
- << (IsMapTypeImplicit ? 1 : 0)
- << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
- << getOpenMPDirectiveName(DKind);
- continue;
- }
- Vars.push_back(RE);
- DSAStack->addExprToVarMapInfo(D, RE);
- }
- // We need to produce a map clause even if we don't have variables so that
- // other diagnostics related with non-existing map clauses are accurate.
- return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
- MapTypeModifier, MapType, IsMapTypeImplicit,
- MapLoc);
- }
- OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- Expr *ValExpr = NumTeams;
- // OpenMP [teams Constrcut, Restrictions]
- // The num_teams expression must evaluate to a positive integer value.
- if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
- /*StrictlyPositive=*/true))
- return nullptr;
- return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- Expr *ValExpr = ThreadLimit;
- // OpenMP [teams Constrcut, Restrictions]
- // The thread_limit expression must evaluate to a positive integer value.
- if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
- /*StrictlyPositive=*/true))
- return nullptr;
- return new (Context) OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc,
- EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- Expr *ValExpr = Priority;
- // OpenMP [2.9.1, task Constrcut]
- // The priority-value is a non-negative numerical scalar expression.
- if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
- /*StrictlyPositive=*/false))
- return nullptr;
- return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- Expr *ValExpr = Grainsize;
- // OpenMP [2.9.2, taskloop Constrcut]
- // The parameter of the grainsize clause must be a positive integer
- // expression.
- if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
- /*StrictlyPositive=*/true))
- return nullptr;
- return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
- SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- Expr *ValExpr = NumTasks;
- // OpenMP [2.9.2, taskloop Constrcut]
- // The parameter of the num_tasks clause must be a positive integer
- // expression.
- if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
- /*StrictlyPositive=*/true))
- return nullptr;
- return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
- SourceLocation LParenLoc,
- SourceLocation EndLoc) {
- // OpenMP [2.13.2, critical construct, Description]
- // ... where hint-expression is an integer constant expression that evaluates
- // to a valid lock hint.
- ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
- if (HintExpr.isInvalid())
- return nullptr;
- return new (Context)
- OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
- }
- OMPClause *Sema::ActOnOpenMPDistScheduleClause(
- OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
- SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
- SourceLocation EndLoc) {
- if (Kind == OMPC_DIST_SCHEDULE_unknown) {
- std::string Values;
- Values += "'";
- Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
- Values += "'";
- Diag(KindLoc, diag::err_omp_unexpected_clause_value)
- << Values << getOpenMPClauseName(OMPC_dist_schedule);
- return nullptr;
- }
- Expr *ValExpr = ChunkSize;
- Expr *HelperValExpr = nullptr;
- if (ChunkSize) {
- if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
- !ChunkSize->isInstantiationDependent() &&
- !ChunkSize->containsUnexpandedParameterPack()) {
- SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
- ExprResult Val =
- PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
- if (Val.isInvalid())
- return nullptr;
- ValExpr = Val.get();
- // OpenMP [2.7.1, Restrictions]
- // chunk_size must be a loop invariant integer expression with a positive
- // value.
- llvm::APSInt Result;
- if (ValExpr->isIntegerConstantExpr(Result, Context)) {
- if (Result.isSigned() && !Result.isStrictlyPositive()) {
- Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
- << "dist_schedule" << ChunkSize->getSourceRange();
- return nullptr;
- }
- } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
- auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
- ChunkSize->getType(), ".chunk.");
- auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
- ChunkSize->getExprLoc(),
- /*RefersToCapture=*/true);
- HelperValExpr = ImpVarRef;
- }
- }
- }
- return new (Context)
- OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
- Kind, ValExpr, HelperValExpr);
- }
- OMPClause *Sema::ActOnOpenMPDefaultmapClause(
- OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
- SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
- SourceLocation KindLoc, SourceLocation EndLoc) {
- // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
- if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
- Kind != OMPC_DEFAULTMAP_scalar) {
- std::string Value;
- SourceLocation Loc;
- Value += "'";
- if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
- Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
- OMPC_DEFAULTMAP_MODIFIER_tofrom);
- Loc = MLoc;
- } else {
- Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
- OMPC_DEFAULTMAP_scalar);
- Loc = KindLoc;
- }
- Value += "'";
- Diag(Loc, diag::err_omp_unexpected_clause_value)
- << Value << getOpenMPClauseName(OMPC_defaultmap);
- return nullptr;
- }
- return new (Context)
- OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
- }
|