SemaOpenMP.cpp 591 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886
  1. //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. /// \file
  9. /// This file implements semantic analysis for OpenMP directives and
  10. /// clauses.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "TreeTransform.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/Decl.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/DeclOpenMP.h"
  20. #include "clang/AST/StmtCXX.h"
  21. #include "clang/AST/StmtOpenMP.h"
  22. #include "clang/AST/StmtVisitor.h"
  23. #include "clang/AST/TypeOrdering.h"
  24. #include "clang/Basic/OpenMPKinds.h"
  25. #include "clang/Sema/Initialization.h"
  26. #include "clang/Sema/Lookup.h"
  27. #include "clang/Sema/Scope.h"
  28. #include "clang/Sema/ScopeInfo.h"
  29. #include "clang/Sema/SemaInternal.h"
  30. #include "llvm/ADT/PointerEmbeddedInt.h"
  31. using namespace clang;
  32. //===----------------------------------------------------------------------===//
  33. // Stack of data-sharing attributes for variables
  34. //===----------------------------------------------------------------------===//
  35. static const Expr *checkMapClauseExpressionBase(
  36. Sema &SemaRef, Expr *E,
  37. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  38. OpenMPClauseKind CKind, bool NoDiagnose);
  39. namespace {
  40. /// Default data sharing attributes, which can be applied to directive.
  41. enum DefaultDataSharingAttributes {
  42. DSA_unspecified = 0, /// Data sharing attribute not specified.
  43. DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
  44. DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
  45. };
  46. /// Attributes of the defaultmap clause.
  47. enum DefaultMapAttributes {
  48. DMA_unspecified, /// Default mapping is not specified.
  49. DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
  50. };
  51. /// Stack for tracking declarations used in OpenMP directives and
  52. /// clauses and their data-sharing attributes.
  53. class DSAStackTy {
  54. public:
  55. struct DSAVarData {
  56. OpenMPDirectiveKind DKind = OMPD_unknown;
  57. OpenMPClauseKind CKind = OMPC_unknown;
  58. const Expr *RefExpr = nullptr;
  59. DeclRefExpr *PrivateCopy = nullptr;
  60. SourceLocation ImplicitDSALoc;
  61. DSAVarData() = default;
  62. DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  63. const Expr *RefExpr, DeclRefExpr *PrivateCopy,
  64. SourceLocation ImplicitDSALoc)
  65. : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
  66. PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
  67. };
  68. using OperatorOffsetTy =
  69. llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
  70. using DoacrossDependMapTy =
  71. llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
  72. private:
  73. struct DSAInfo {
  74. OpenMPClauseKind Attributes = OMPC_unknown;
  75. /// Pointer to a reference expression and a flag which shows that the
  76. /// variable is marked as lastprivate(true) or not (false).
  77. llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
  78. DeclRefExpr *PrivateCopy = nullptr;
  79. };
  80. using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
  81. using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
  82. using LCDeclInfo = std::pair<unsigned, VarDecl *>;
  83. using LoopControlVariablesMapTy =
  84. llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
  85. /// Struct that associates a component with the clause kind where they are
  86. /// found.
  87. struct MappedExprComponentTy {
  88. OMPClauseMappableExprCommon::MappableExprComponentLists Components;
  89. OpenMPClauseKind Kind = OMPC_unknown;
  90. };
  91. using MappedExprComponentsTy =
  92. llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
  93. using CriticalsWithHintsTy =
  94. llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
  95. struct ReductionData {
  96. using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
  97. SourceRange ReductionRange;
  98. llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
  99. ReductionData() = default;
  100. void set(BinaryOperatorKind BO, SourceRange RR) {
  101. ReductionRange = RR;
  102. ReductionOp = BO;
  103. }
  104. void set(const Expr *RefExpr, SourceRange RR) {
  105. ReductionRange = RR;
  106. ReductionOp = RefExpr;
  107. }
  108. };
  109. using DeclReductionMapTy =
  110. llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
  111. struct SharingMapTy {
  112. DeclSAMapTy SharingMap;
  113. DeclReductionMapTy ReductionMap;
  114. AlignedMapTy AlignedMap;
  115. MappedExprComponentsTy MappedExprComponents;
  116. LoopControlVariablesMapTy LCVMap;
  117. DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
  118. SourceLocation DefaultAttrLoc;
  119. DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
  120. SourceLocation DefaultMapAttrLoc;
  121. OpenMPDirectiveKind Directive = OMPD_unknown;
  122. DeclarationNameInfo DirectiveName;
  123. Scope *CurScope = nullptr;
  124. SourceLocation ConstructLoc;
  125. /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
  126. /// get the data (loop counters etc.) about enclosing loop-based construct.
  127. /// This data is required during codegen.
  128. DoacrossDependMapTy DoacrossDepends;
  129. /// First argument (Expr *) contains optional argument of the
  130. /// 'ordered' clause, the second one is true if the regions has 'ordered'
  131. /// clause, false otherwise.
  132. llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
  133. unsigned AssociatedLoops = 1;
  134. const Decl *PossiblyLoopCounter = nullptr;
  135. bool NowaitRegion = false;
  136. bool CancelRegion = false;
  137. bool LoopStart = false;
  138. SourceLocation InnerTeamsRegionLoc;
  139. /// Reference to the taskgroup task_reduction reference expression.
  140. Expr *TaskgroupReductionRef = nullptr;
  141. llvm::DenseSet<QualType> MappedClassesQualTypes;
  142. /// List of globals marked as declare target link in this target region
  143. /// (isOpenMPTargetExecutionDirective(Directive) == true).
  144. llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
  145. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  146. Scope *CurScope, SourceLocation Loc)
  147. : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
  148. ConstructLoc(Loc) {}
  149. SharingMapTy() = default;
  150. };
  151. using StackTy = SmallVector<SharingMapTy, 4>;
  152. /// Stack of used declaration and their data-sharing attributes.
  153. DeclSAMapTy Threadprivates;
  154. const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
  155. SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
  156. /// true, if check for DSA must be from parent directive, false, if
  157. /// from current directive.
  158. OpenMPClauseKind ClauseKindMode = OMPC_unknown;
  159. Sema &SemaRef;
  160. bool ForceCapturing = false;
  161. /// true if all the vaiables in the target executable directives must be
  162. /// captured by reference.
  163. bool ForceCaptureByReferenceInTargetExecutable = false;
  164. CriticalsWithHintsTy Criticals;
  165. using iterator = StackTy::const_reverse_iterator;
  166. DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
  167. /// Checks if the variable is a local for OpenMP region.
  168. bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
  169. bool isStackEmpty() const {
  170. return Stack.empty() ||
  171. Stack.back().second != CurrentNonCapturingFunctionScope ||
  172. Stack.back().first.empty();
  173. }
  174. /// Vector of previously declared requires directives
  175. SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
  176. /// omp_allocator_handle_t type.
  177. QualType OMPAllocatorHandleT;
  178. /// Expression for the predefined allocators.
  179. Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
  180. nullptr};
  181. public:
  182. explicit DSAStackTy(Sema &S) : SemaRef(S) {}
  183. /// Sets omp_allocator_handle_t type.
  184. void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
  185. /// Gets omp_allocator_handle_t type.
  186. QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
  187. /// Sets the given default allocator.
  188. void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
  189. Expr *Allocator) {
  190. OMPPredefinedAllocators[AllocatorKind] = Allocator;
  191. }
  192. /// Returns the specified default allocator.
  193. Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
  194. return OMPPredefinedAllocators[AllocatorKind];
  195. }
  196. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  197. OpenMPClauseKind getClauseParsingMode() const {
  198. assert(isClauseParsingMode() && "Must be in clause parsing mode.");
  199. return ClauseKindMode;
  200. }
  201. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  202. bool isForceVarCapturing() const { return ForceCapturing; }
  203. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  204. void setForceCaptureByReferenceInTargetExecutable(bool V) {
  205. ForceCaptureByReferenceInTargetExecutable = V;
  206. }
  207. bool isForceCaptureByReferenceInTargetExecutable() const {
  208. return ForceCaptureByReferenceInTargetExecutable;
  209. }
  210. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  211. Scope *CurScope, SourceLocation Loc) {
  212. if (Stack.empty() ||
  213. Stack.back().second != CurrentNonCapturingFunctionScope)
  214. Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
  215. Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
  216. Stack.back().first.back().DefaultAttrLoc = Loc;
  217. }
  218. void pop() {
  219. assert(!Stack.back().first.empty() &&
  220. "Data-sharing attributes stack is empty!");
  221. Stack.back().first.pop_back();
  222. }
  223. /// Marks that we're started loop parsing.
  224. void loopInit() {
  225. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  226. "Expected loop-based directive.");
  227. Stack.back().first.back().LoopStart = true;
  228. }
  229. /// Start capturing of the variables in the loop context.
  230. void loopStart() {
  231. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  232. "Expected loop-based directive.");
  233. Stack.back().first.back().LoopStart = false;
  234. }
  235. /// true, if variables are captured, false otherwise.
  236. bool isLoopStarted() const {
  237. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  238. "Expected loop-based directive.");
  239. return !Stack.back().first.back().LoopStart;
  240. }
  241. /// Marks (or clears) declaration as possibly loop counter.
  242. void resetPossibleLoopCounter(const Decl *D = nullptr) {
  243. Stack.back().first.back().PossiblyLoopCounter =
  244. D ? D->getCanonicalDecl() : D;
  245. }
  246. /// Gets the possible loop counter decl.
  247. const Decl *getPossiblyLoopCunter() const {
  248. return Stack.back().first.back().PossiblyLoopCounter;
  249. }
  250. /// Start new OpenMP region stack in new non-capturing function.
  251. void pushFunction() {
  252. const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
  253. assert(!isa<CapturingScopeInfo>(CurFnScope));
  254. CurrentNonCapturingFunctionScope = CurFnScope;
  255. }
  256. /// Pop region stack for non-capturing function.
  257. void popFunction(const FunctionScopeInfo *OldFSI) {
  258. if (!Stack.empty() && Stack.back().second == OldFSI) {
  259. assert(Stack.back().first.empty());
  260. Stack.pop_back();
  261. }
  262. CurrentNonCapturingFunctionScope = nullptr;
  263. for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
  264. if (!isa<CapturingScopeInfo>(FSI)) {
  265. CurrentNonCapturingFunctionScope = FSI;
  266. break;
  267. }
  268. }
  269. }
  270. void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
  271. Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
  272. }
  273. const std::pair<const OMPCriticalDirective *, llvm::APSInt>
  274. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  275. auto I = Criticals.find(Name.getAsString());
  276. if (I != Criticals.end())
  277. return I->second;
  278. return std::make_pair(nullptr, llvm::APSInt());
  279. }
  280. /// If 'aligned' declaration for given variable \a D was not seen yet,
  281. /// add it and return NULL; otherwise return previous occurrence's expression
  282. /// for diagnostics.
  283. const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
  284. /// Register specified variable as loop control variable.
  285. void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
  286. /// Check if the specified variable is a loop control variable for
  287. /// current region.
  288. /// \return The index of the loop control variable in the list of associated
  289. /// for-loops (from outer to inner).
  290. const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
  291. /// Check if the specified variable is a loop control variable for
  292. /// parent region.
  293. /// \return The index of the loop control variable in the list of associated
  294. /// for-loops (from outer to inner).
  295. const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
  296. /// Get the loop control variable for the I-th loop (or nullptr) in
  297. /// parent directive.
  298. const ValueDecl *getParentLoopControlVariable(unsigned I) const;
  299. /// Adds explicit data sharing attribute to the specified declaration.
  300. void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  301. DeclRefExpr *PrivateCopy = nullptr);
  302. /// Adds additional information for the reduction items with the reduction id
  303. /// represented as an operator.
  304. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  305. BinaryOperatorKind BOK);
  306. /// Adds additional information for the reduction items with the reduction id
  307. /// represented as reduction identifier.
  308. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  309. const Expr *ReductionRef);
  310. /// Returns the location and reduction operation from the innermost parent
  311. /// region for the given \p D.
  312. const DSAVarData
  313. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  314. BinaryOperatorKind &BOK,
  315. Expr *&TaskgroupDescriptor) const;
  316. /// Returns the location and reduction operation from the innermost parent
  317. /// region for the given \p D.
  318. const DSAVarData
  319. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  320. const Expr *&ReductionRef,
  321. Expr *&TaskgroupDescriptor) const;
  322. /// Return reduction reference expression for the current taskgroup.
  323. Expr *getTaskgroupReductionRef() const {
  324. assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
  325. "taskgroup reference expression requested for non taskgroup "
  326. "directive.");
  327. return Stack.back().first.back().TaskgroupReductionRef;
  328. }
  329. /// Checks if the given \p VD declaration is actually a taskgroup reduction
  330. /// descriptor variable at the \p Level of OpenMP regions.
  331. bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
  332. return Stack.back().first[Level].TaskgroupReductionRef &&
  333. cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
  334. ->getDecl() == VD;
  335. }
  336. /// Returns data sharing attributes from top of the stack for the
  337. /// specified declaration.
  338. const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  339. /// Returns data-sharing attributes for the specified declaration.
  340. const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
  341. /// Checks if the specified variables has data-sharing attributes which
  342. /// match specified \a CPred predicate in any directive which matches \a DPred
  343. /// predicate.
  344. const DSAVarData
  345. hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  346. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  347. bool FromParent) const;
  348. /// Checks if the specified variables has data-sharing attributes which
  349. /// match specified \a CPred predicate in any innermost directive which
  350. /// matches \a DPred predicate.
  351. const DSAVarData
  352. hasInnermostDSA(ValueDecl *D,
  353. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  354. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  355. bool FromParent) const;
  356. /// Checks if the specified variables has explicit data-sharing
  357. /// attributes which match specified \a CPred predicate at the specified
  358. /// OpenMP region.
  359. bool hasExplicitDSA(const ValueDecl *D,
  360. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  361. unsigned Level, bool NotLastprivate = false) const;
  362. /// Returns true if the directive at level \Level matches in the
  363. /// specified \a DPred predicate.
  364. bool hasExplicitDirective(
  365. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  366. unsigned Level) const;
  367. /// Finds a directive which matches specified \a DPred predicate.
  368. bool hasDirective(
  369. const llvm::function_ref<bool(
  370. OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
  371. DPred,
  372. bool FromParent) const;
  373. /// Returns currently analyzed directive.
  374. OpenMPDirectiveKind getCurrentDirective() const {
  375. return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
  376. }
  377. /// Returns directive kind at specified level.
  378. OpenMPDirectiveKind getDirective(unsigned Level) const {
  379. assert(!isStackEmpty() && "No directive at specified level.");
  380. return Stack.back().first[Level].Directive;
  381. }
  382. /// Returns parent directive.
  383. OpenMPDirectiveKind getParentDirective() const {
  384. if (isStackEmpty() || Stack.back().first.size() == 1)
  385. return OMPD_unknown;
  386. return std::next(Stack.back().first.rbegin())->Directive;
  387. }
  388. /// Add requires decl to internal vector
  389. void addRequiresDecl(OMPRequiresDecl *RD) {
  390. RequiresDecls.push_back(RD);
  391. }
  392. /// Checks if the defined 'requires' directive has specified type of clause.
  393. template <typename ClauseType>
  394. bool hasRequiresDeclWithClause() {
  395. return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
  396. return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
  397. return isa<ClauseType>(C);
  398. });
  399. });
  400. }
  401. /// Checks for a duplicate clause amongst previously declared requires
  402. /// directives
  403. bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
  404. bool IsDuplicate = false;
  405. for (OMPClause *CNew : ClauseList) {
  406. for (const OMPRequiresDecl *D : RequiresDecls) {
  407. for (const OMPClause *CPrev : D->clauselists()) {
  408. if (CNew->getClauseKind() == CPrev->getClauseKind()) {
  409. SemaRef.Diag(CNew->getBeginLoc(),
  410. diag::err_omp_requires_clause_redeclaration)
  411. << getOpenMPClauseName(CNew->getClauseKind());
  412. SemaRef.Diag(CPrev->getBeginLoc(),
  413. diag::note_omp_requires_previous_clause)
  414. << getOpenMPClauseName(CPrev->getClauseKind());
  415. IsDuplicate = true;
  416. }
  417. }
  418. }
  419. }
  420. return IsDuplicate;
  421. }
  422. /// Set default data sharing attribute to none.
  423. void setDefaultDSANone(SourceLocation Loc) {
  424. assert(!isStackEmpty());
  425. Stack.back().first.back().DefaultAttr = DSA_none;
  426. Stack.back().first.back().DefaultAttrLoc = Loc;
  427. }
  428. /// Set default data sharing attribute to shared.
  429. void setDefaultDSAShared(SourceLocation Loc) {
  430. assert(!isStackEmpty());
  431. Stack.back().first.back().DefaultAttr = DSA_shared;
  432. Stack.back().first.back().DefaultAttrLoc = Loc;
  433. }
  434. /// Set default data mapping attribute to 'tofrom:scalar'.
  435. void setDefaultDMAToFromScalar(SourceLocation Loc) {
  436. assert(!isStackEmpty());
  437. Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
  438. Stack.back().first.back().DefaultMapAttrLoc = Loc;
  439. }
  440. DefaultDataSharingAttributes getDefaultDSA() const {
  441. return isStackEmpty() ? DSA_unspecified
  442. : Stack.back().first.back().DefaultAttr;
  443. }
  444. SourceLocation getDefaultDSALocation() const {
  445. return isStackEmpty() ? SourceLocation()
  446. : Stack.back().first.back().DefaultAttrLoc;
  447. }
  448. DefaultMapAttributes getDefaultDMA() const {
  449. return isStackEmpty() ? DMA_unspecified
  450. : Stack.back().first.back().DefaultMapAttr;
  451. }
  452. DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
  453. return Stack.back().first[Level].DefaultMapAttr;
  454. }
  455. SourceLocation getDefaultDMALocation() const {
  456. return isStackEmpty() ? SourceLocation()
  457. : Stack.back().first.back().DefaultMapAttrLoc;
  458. }
  459. /// Checks if the specified variable is a threadprivate.
  460. bool isThreadPrivate(VarDecl *D) {
  461. const DSAVarData DVar = getTopDSA(D, false);
  462. return isOpenMPThreadPrivate(DVar.CKind);
  463. }
  464. /// Marks current region as ordered (it has an 'ordered' clause).
  465. void setOrderedRegion(bool IsOrdered, const Expr *Param,
  466. OMPOrderedClause *Clause) {
  467. assert(!isStackEmpty());
  468. if (IsOrdered)
  469. Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
  470. else
  471. Stack.back().first.back().OrderedRegion.reset();
  472. }
  473. /// Returns true, if region is ordered (has associated 'ordered' clause),
  474. /// false - otherwise.
  475. bool isOrderedRegion() const {
  476. if (isStackEmpty())
  477. return false;
  478. return Stack.back().first.rbegin()->OrderedRegion.hasValue();
  479. }
  480. /// Returns optional parameter for the ordered region.
  481. std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
  482. if (isStackEmpty() ||
  483. !Stack.back().first.rbegin()->OrderedRegion.hasValue())
  484. return std::make_pair(nullptr, nullptr);
  485. return Stack.back().first.rbegin()->OrderedRegion.getValue();
  486. }
  487. /// Returns true, if parent region is ordered (has associated
  488. /// 'ordered' clause), false - otherwise.
  489. bool isParentOrderedRegion() const {
  490. if (isStackEmpty() || Stack.back().first.size() == 1)
  491. return false;
  492. return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
  493. }
  494. /// Returns optional parameter for the ordered region.
  495. std::pair<const Expr *, OMPOrderedClause *>
  496. getParentOrderedRegionParam() const {
  497. if (isStackEmpty() || Stack.back().first.size() == 1 ||
  498. !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
  499. return std::make_pair(nullptr, nullptr);
  500. return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
  501. }
  502. /// Marks current region as nowait (it has a 'nowait' clause).
  503. void setNowaitRegion(bool IsNowait = true) {
  504. assert(!isStackEmpty());
  505. Stack.back().first.back().NowaitRegion = IsNowait;
  506. }
  507. /// Returns true, if parent region is nowait (has associated
  508. /// 'nowait' clause), false - otherwise.
  509. bool isParentNowaitRegion() const {
  510. if (isStackEmpty() || Stack.back().first.size() == 1)
  511. return false;
  512. return std::next(Stack.back().first.rbegin())->NowaitRegion;
  513. }
  514. /// Marks parent region as cancel region.
  515. void setParentCancelRegion(bool Cancel = true) {
  516. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  517. auto &StackElemRef = *std::next(Stack.back().first.rbegin());
  518. StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
  519. }
  520. }
  521. /// Return true if current region has inner cancel construct.
  522. bool isCancelRegion() const {
  523. return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
  524. }
  525. /// Set collapse value for the region.
  526. void setAssociatedLoops(unsigned Val) {
  527. assert(!isStackEmpty());
  528. Stack.back().first.back().AssociatedLoops = Val;
  529. }
  530. /// Return collapse value for region.
  531. unsigned getAssociatedLoops() const {
  532. return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
  533. }
  534. /// Marks current target region as one with closely nested teams
  535. /// region.
  536. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  537. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  538. std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
  539. TeamsRegionLoc;
  540. }
  541. }
  542. /// Returns true, if current region has closely nested teams region.
  543. bool hasInnerTeamsRegion() const {
  544. return getInnerTeamsRegionLoc().isValid();
  545. }
  546. /// Returns location of the nested teams region (if any).
  547. SourceLocation getInnerTeamsRegionLoc() const {
  548. return isStackEmpty() ? SourceLocation()
  549. : Stack.back().first.back().InnerTeamsRegionLoc;
  550. }
  551. Scope *getCurScope() const {
  552. return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
  553. }
  554. SourceLocation getConstructLoc() const {
  555. return isStackEmpty() ? SourceLocation()
  556. : Stack.back().first.back().ConstructLoc;
  557. }
  558. /// Do the check specified in \a Check to all component lists and return true
  559. /// if any issue is found.
  560. bool checkMappableExprComponentListsForDecl(
  561. const ValueDecl *VD, bool CurrentRegionOnly,
  562. const llvm::function_ref<
  563. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  564. OpenMPClauseKind)>
  565. Check) const {
  566. if (isStackEmpty())
  567. return false;
  568. auto SI = Stack.back().first.rbegin();
  569. auto SE = Stack.back().first.rend();
  570. if (SI == SE)
  571. return false;
  572. if (CurrentRegionOnly)
  573. SE = std::next(SI);
  574. else
  575. std::advance(SI, 1);
  576. for (; SI != SE; ++SI) {
  577. auto MI = SI->MappedExprComponents.find(VD);
  578. if (MI != SI->MappedExprComponents.end())
  579. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  580. MI->second.Components)
  581. if (Check(L, MI->second.Kind))
  582. return true;
  583. }
  584. return false;
  585. }
  586. /// Do the check specified in \a Check to all component lists at a given level
  587. /// and return true if any issue is found.
  588. bool checkMappableExprComponentListsForDeclAtLevel(
  589. const ValueDecl *VD, unsigned Level,
  590. const llvm::function_ref<
  591. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  592. OpenMPClauseKind)>
  593. Check) const {
  594. if (isStackEmpty())
  595. return false;
  596. auto StartI = Stack.back().first.begin();
  597. auto EndI = Stack.back().first.end();
  598. if (std::distance(StartI, EndI) <= (int)Level)
  599. return false;
  600. std::advance(StartI, Level);
  601. auto MI = StartI->MappedExprComponents.find(VD);
  602. if (MI != StartI->MappedExprComponents.end())
  603. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  604. MI->second.Components)
  605. if (Check(L, MI->second.Kind))
  606. return true;
  607. return false;
  608. }
  609. /// Create a new mappable expression component list associated with a given
  610. /// declaration and initialize it with the provided list of components.
  611. void addMappableExpressionComponents(
  612. const ValueDecl *VD,
  613. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  614. OpenMPClauseKind WhereFoundClauseKind) {
  615. assert(!isStackEmpty() &&
  616. "Not expecting to retrieve components from a empty stack!");
  617. MappedExprComponentTy &MEC =
  618. Stack.back().first.back().MappedExprComponents[VD];
  619. // Create new entry and append the new components there.
  620. MEC.Components.resize(MEC.Components.size() + 1);
  621. MEC.Components.back().append(Components.begin(), Components.end());
  622. MEC.Kind = WhereFoundClauseKind;
  623. }
  624. unsigned getNestingLevel() const {
  625. assert(!isStackEmpty());
  626. return Stack.back().first.size() - 1;
  627. }
  628. void addDoacrossDependClause(OMPDependClause *C,
  629. const OperatorOffsetTy &OpsOffs) {
  630. assert(!isStackEmpty() && Stack.back().first.size() > 1);
  631. SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  632. assert(isOpenMPWorksharingDirective(StackElem.Directive));
  633. StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
  634. }
  635. llvm::iterator_range<DoacrossDependMapTy::const_iterator>
  636. getDoacrossDependClauses() const {
  637. assert(!isStackEmpty());
  638. const SharingMapTy &StackElem = Stack.back().first.back();
  639. if (isOpenMPWorksharingDirective(StackElem.Directive)) {
  640. const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
  641. return llvm::make_range(Ref.begin(), Ref.end());
  642. }
  643. return llvm::make_range(StackElem.DoacrossDepends.end(),
  644. StackElem.DoacrossDepends.end());
  645. }
  646. // Store types of classes which have been explicitly mapped
  647. void addMappedClassesQualTypes(QualType QT) {
  648. SharingMapTy &StackElem = Stack.back().first.back();
  649. StackElem.MappedClassesQualTypes.insert(QT);
  650. }
  651. // Return set of mapped classes types
  652. bool isClassPreviouslyMapped(QualType QT) const {
  653. const SharingMapTy &StackElem = Stack.back().first.back();
  654. return StackElem.MappedClassesQualTypes.count(QT) != 0;
  655. }
  656. /// Adds global declare target to the parent target region.
  657. void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
  658. assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  659. E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
  660. "Expected declare target link global.");
  661. if (isStackEmpty())
  662. return;
  663. auto It = Stack.back().first.rbegin();
  664. while (It != Stack.back().first.rend() &&
  665. !isOpenMPTargetExecutionDirective(It->Directive))
  666. ++It;
  667. if (It != Stack.back().first.rend()) {
  668. assert(isOpenMPTargetExecutionDirective(It->Directive) &&
  669. "Expected target executable directive.");
  670. It->DeclareTargetLinkVarDecls.push_back(E);
  671. }
  672. }
  673. /// Returns the list of globals with declare target link if current directive
  674. /// is target.
  675. ArrayRef<DeclRefExpr *> getLinkGlobals() const {
  676. assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
  677. "Expected target executable directive.");
  678. return Stack.back().first.back().DeclareTargetLinkVarDecls;
  679. }
  680. };
  681. bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  682. return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
  683. }
  684. bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  685. return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || DKind == OMPD_unknown;
  686. }
  687. } // namespace
  688. static const Expr *getExprAsWritten(const Expr *E) {
  689. if (const auto *FE = dyn_cast<FullExpr>(E))
  690. E = FE->getSubExpr();
  691. if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  692. E = MTE->GetTemporaryExpr();
  693. while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  694. E = Binder->getSubExpr();
  695. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  696. E = ICE->getSubExprAsWritten();
  697. return E->IgnoreParens();
  698. }
  699. static Expr *getExprAsWritten(Expr *E) {
  700. return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
  701. }
  702. static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
  703. if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
  704. if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  705. D = ME->getMemberDecl();
  706. const auto *VD = dyn_cast<VarDecl>(D);
  707. const auto *FD = dyn_cast<FieldDecl>(D);
  708. if (VD != nullptr) {
  709. VD = VD->getCanonicalDecl();
  710. D = VD;
  711. } else {
  712. assert(FD);
  713. FD = FD->getCanonicalDecl();
  714. D = FD;
  715. }
  716. return D;
  717. }
  718. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  719. return const_cast<ValueDecl *>(
  720. getCanonicalDecl(const_cast<const ValueDecl *>(D)));
  721. }
  722. DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
  723. ValueDecl *D) const {
  724. D = getCanonicalDecl(D);
  725. auto *VD = dyn_cast<VarDecl>(D);
  726. const auto *FD = dyn_cast<FieldDecl>(D);
  727. DSAVarData DVar;
  728. if (isStackEmpty() || Iter == Stack.back().first.rend()) {
  729. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  730. // in a region but not in construct]
  731. // File-scope or namespace-scope variables referenced in called routines
  732. // in the region are shared unless they appear in a threadprivate
  733. // directive.
  734. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
  735. DVar.CKind = OMPC_shared;
  736. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  737. // in a region but not in construct]
  738. // Variables with static storage duration that are declared in called
  739. // routines in the region are shared.
  740. if (VD && VD->hasGlobalStorage())
  741. DVar.CKind = OMPC_shared;
  742. // Non-static data members are shared by default.
  743. if (FD)
  744. DVar.CKind = OMPC_shared;
  745. return DVar;
  746. }
  747. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  748. // in a Construct, C/C++, predetermined, p.1]
  749. // Variables with automatic storage duration that are declared in a scope
  750. // inside the construct are private.
  751. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  752. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  753. DVar.CKind = OMPC_private;
  754. return DVar;
  755. }
  756. DVar.DKind = Iter->Directive;
  757. // Explicitly specified attributes and local variables with predetermined
  758. // attributes.
  759. if (Iter->SharingMap.count(D)) {
  760. const DSAInfo &Data = Iter->SharingMap.lookup(D);
  761. DVar.RefExpr = Data.RefExpr.getPointer();
  762. DVar.PrivateCopy = Data.PrivateCopy;
  763. DVar.CKind = Data.Attributes;
  764. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  765. return DVar;
  766. }
  767. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  768. // in a Construct, C/C++, implicitly determined, p.1]
  769. // In a parallel or task construct, the data-sharing attributes of these
  770. // variables are determined by the default clause, if present.
  771. switch (Iter->DefaultAttr) {
  772. case DSA_shared:
  773. DVar.CKind = OMPC_shared;
  774. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  775. return DVar;
  776. case DSA_none:
  777. return DVar;
  778. case DSA_unspecified:
  779. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  780. // in a Construct, implicitly determined, p.2]
  781. // In a parallel construct, if no default clause is present, these
  782. // variables are shared.
  783. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  784. if (isOpenMPParallelDirective(DVar.DKind) ||
  785. isOpenMPTeamsDirective(DVar.DKind)) {
  786. DVar.CKind = OMPC_shared;
  787. return DVar;
  788. }
  789. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  790. // in a Construct, implicitly determined, p.4]
  791. // In a task construct, if no default clause is present, a variable that in
  792. // the enclosing context is determined to be shared by all implicit tasks
  793. // bound to the current team is shared.
  794. if (isOpenMPTaskingDirective(DVar.DKind)) {
  795. DSAVarData DVarTemp;
  796. iterator I = Iter, E = Stack.back().first.rend();
  797. do {
  798. ++I;
  799. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  800. // Referenced in a Construct, implicitly determined, p.6]
  801. // In a task construct, if no default clause is present, a variable
  802. // whose data-sharing attribute is not determined by the rules above is
  803. // firstprivate.
  804. DVarTemp = getDSA(I, D);
  805. if (DVarTemp.CKind != OMPC_shared) {
  806. DVar.RefExpr = nullptr;
  807. DVar.CKind = OMPC_firstprivate;
  808. return DVar;
  809. }
  810. } while (I != E && !isImplicitTaskingRegion(I->Directive));
  811. DVar.CKind =
  812. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  813. return DVar;
  814. }
  815. }
  816. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  817. // in a Construct, implicitly determined, p.3]
  818. // For constructs other than task, if no default clause is present, these
  819. // variables inherit their data-sharing attributes from the enclosing
  820. // context.
  821. return getDSA(++Iter, D);
  822. }
  823. const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
  824. const Expr *NewDE) {
  825. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  826. D = getCanonicalDecl(D);
  827. SharingMapTy &StackElem = Stack.back().first.back();
  828. auto It = StackElem.AlignedMap.find(D);
  829. if (It == StackElem.AlignedMap.end()) {
  830. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  831. StackElem.AlignedMap[D] = NewDE;
  832. return nullptr;
  833. }
  834. assert(It->second && "Unexpected nullptr expr in the aligned map");
  835. return It->second;
  836. }
  837. void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
  838. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  839. D = getCanonicalDecl(D);
  840. SharingMapTy &StackElem = Stack.back().first.back();
  841. StackElem.LCVMap.try_emplace(
  842. D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
  843. }
  844. const DSAStackTy::LCDeclInfo
  845. DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
  846. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  847. D = getCanonicalDecl(D);
  848. const SharingMapTy &StackElem = Stack.back().first.back();
  849. auto It = StackElem.LCVMap.find(D);
  850. if (It != StackElem.LCVMap.end())
  851. return It->second;
  852. return {0, nullptr};
  853. }
  854. const DSAStackTy::LCDeclInfo
  855. DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
  856. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  857. "Data-sharing attributes stack is empty");
  858. D = getCanonicalDecl(D);
  859. const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  860. auto It = StackElem.LCVMap.find(D);
  861. if (It != StackElem.LCVMap.end())
  862. return It->second;
  863. return {0, nullptr};
  864. }
  865. const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
  866. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  867. "Data-sharing attributes stack is empty");
  868. const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  869. if (StackElem.LCVMap.size() < I)
  870. return nullptr;
  871. for (const auto &Pair : StackElem.LCVMap)
  872. if (Pair.second.first == I)
  873. return Pair.first;
  874. return nullptr;
  875. }
  876. void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  877. DeclRefExpr *PrivateCopy) {
  878. D = getCanonicalDecl(D);
  879. if (A == OMPC_threadprivate) {
  880. DSAInfo &Data = Threadprivates[D];
  881. Data.Attributes = A;
  882. Data.RefExpr.setPointer(E);
  883. Data.PrivateCopy = nullptr;
  884. } else {
  885. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  886. DSAInfo &Data = Stack.back().first.back().SharingMap[D];
  887. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  888. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  889. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  890. (isLoopControlVariable(D).first && A == OMPC_private));
  891. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  892. Data.RefExpr.setInt(/*IntVal=*/true);
  893. return;
  894. }
  895. const bool IsLastprivate =
  896. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  897. Data.Attributes = A;
  898. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  899. Data.PrivateCopy = PrivateCopy;
  900. if (PrivateCopy) {
  901. DSAInfo &Data =
  902. Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
  903. Data.Attributes = A;
  904. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  905. Data.PrivateCopy = nullptr;
  906. }
  907. }
  908. }
  909. /// Build a variable declaration for OpenMP loop iteration variable.
  910. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  911. StringRef Name, const AttrVec *Attrs = nullptr,
  912. DeclRefExpr *OrigRef = nullptr) {
  913. DeclContext *DC = SemaRef.CurContext;
  914. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  915. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  916. auto *Decl =
  917. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  918. if (Attrs) {
  919. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  920. I != E; ++I)
  921. Decl->addAttr(*I);
  922. }
  923. Decl->setImplicit();
  924. if (OrigRef) {
  925. Decl->addAttr(
  926. OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
  927. }
  928. return Decl;
  929. }
  930. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  931. SourceLocation Loc,
  932. bool RefersToCapture = false) {
  933. D->setReferenced();
  934. D->markUsed(S.Context);
  935. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  936. SourceLocation(), D, RefersToCapture, Loc, Ty,
  937. VK_LValue);
  938. }
  939. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  940. BinaryOperatorKind BOK) {
  941. D = getCanonicalDecl(D);
  942. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  943. assert(
  944. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  945. "Additional reduction info may be specified only for reduction items.");
  946. ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
  947. assert(ReductionData.ReductionRange.isInvalid() &&
  948. Stack.back().first.back().Directive == OMPD_taskgroup &&
  949. "Additional reduction info may be specified only once for reduction "
  950. "items.");
  951. ReductionData.set(BOK, SR);
  952. Expr *&TaskgroupReductionRef =
  953. Stack.back().first.back().TaskgroupReductionRef;
  954. if (!TaskgroupReductionRef) {
  955. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  956. SemaRef.Context.VoidPtrTy, ".task_red.");
  957. TaskgroupReductionRef =
  958. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  959. }
  960. }
  961. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  962. const Expr *ReductionRef) {
  963. D = getCanonicalDecl(D);
  964. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  965. assert(
  966. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  967. "Additional reduction info may be specified only for reduction items.");
  968. ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
  969. assert(ReductionData.ReductionRange.isInvalid() &&
  970. Stack.back().first.back().Directive == OMPD_taskgroup &&
  971. "Additional reduction info may be specified only once for reduction "
  972. "items.");
  973. ReductionData.set(ReductionRef, SR);
  974. Expr *&TaskgroupReductionRef =
  975. Stack.back().first.back().TaskgroupReductionRef;
  976. if (!TaskgroupReductionRef) {
  977. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  978. SemaRef.Context.VoidPtrTy, ".task_red.");
  979. TaskgroupReductionRef =
  980. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  981. }
  982. }
  983. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  984. const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
  985. Expr *&TaskgroupDescriptor) const {
  986. D = getCanonicalDecl(D);
  987. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  988. if (Stack.back().first.empty())
  989. return DSAVarData();
  990. for (iterator I = std::next(Stack.back().first.rbegin(), 1),
  991. E = Stack.back().first.rend();
  992. I != E; std::advance(I, 1)) {
  993. const DSAInfo &Data = I->SharingMap.lookup(D);
  994. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  995. continue;
  996. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  997. if (!ReductionData.ReductionOp ||
  998. ReductionData.ReductionOp.is<const Expr *>())
  999. return DSAVarData();
  1000. SR = ReductionData.ReductionRange;
  1001. BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
  1002. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  1003. "expression for the descriptor is not "
  1004. "set.");
  1005. TaskgroupDescriptor = I->TaskgroupReductionRef;
  1006. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  1007. Data.PrivateCopy, I->DefaultAttrLoc);
  1008. }
  1009. return DSAVarData();
  1010. }
  1011. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  1012. const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
  1013. Expr *&TaskgroupDescriptor) const {
  1014. D = getCanonicalDecl(D);
  1015. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  1016. if (Stack.back().first.empty())
  1017. return DSAVarData();
  1018. for (iterator I = std::next(Stack.back().first.rbegin(), 1),
  1019. E = Stack.back().first.rend();
  1020. I != E; std::advance(I, 1)) {
  1021. const DSAInfo &Data = I->SharingMap.lookup(D);
  1022. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  1023. continue;
  1024. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  1025. if (!ReductionData.ReductionOp ||
  1026. !ReductionData.ReductionOp.is<const Expr *>())
  1027. return DSAVarData();
  1028. SR = ReductionData.ReductionRange;
  1029. ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
  1030. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  1031. "expression for the descriptor is not "
  1032. "set.");
  1033. TaskgroupDescriptor = I->TaskgroupReductionRef;
  1034. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  1035. Data.PrivateCopy, I->DefaultAttrLoc);
  1036. }
  1037. return DSAVarData();
  1038. }
  1039. bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
  1040. D = D->getCanonicalDecl();
  1041. if (!isStackEmpty()) {
  1042. iterator I = Iter, E = Stack.back().first.rend();
  1043. Scope *TopScope = nullptr;
  1044. while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) &&
  1045. !isOpenMPTargetExecutionDirective(I->Directive))
  1046. ++I;
  1047. if (I == E)
  1048. return false;
  1049. TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  1050. Scope *CurScope = getCurScope();
  1051. while (CurScope != TopScope && !CurScope->isDeclScope(D))
  1052. CurScope = CurScope->getParent();
  1053. return CurScope != TopScope;
  1054. }
  1055. return false;
  1056. }
  1057. static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
  1058. bool AcceptIfMutable = true,
  1059. bool *IsClassType = nullptr) {
  1060. ASTContext &Context = SemaRef.getASTContext();
  1061. Type = Type.getNonReferenceType().getCanonicalType();
  1062. bool IsConstant = Type.isConstant(Context);
  1063. Type = Context.getBaseElementType(Type);
  1064. const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
  1065. ? Type->getAsCXXRecordDecl()
  1066. : nullptr;
  1067. if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  1068. if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
  1069. RD = CTD->getTemplatedDecl();
  1070. if (IsClassType)
  1071. *IsClassType = RD;
  1072. return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
  1073. RD->hasDefinition() && RD->hasMutableFields());
  1074. }
  1075. static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
  1076. QualType Type, OpenMPClauseKind CKind,
  1077. SourceLocation ELoc,
  1078. bool AcceptIfMutable = true,
  1079. bool ListItemNotVar = false) {
  1080. ASTContext &Context = SemaRef.getASTContext();
  1081. bool IsClassType;
  1082. if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
  1083. unsigned Diag = ListItemNotVar
  1084. ? diag::err_omp_const_list_item
  1085. : IsClassType ? diag::err_omp_const_not_mutable_variable
  1086. : diag::err_omp_const_variable;
  1087. SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
  1088. if (!ListItemNotVar && D) {
  1089. const VarDecl *VD = dyn_cast<VarDecl>(D);
  1090. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  1091. VarDecl::DeclarationOnly;
  1092. SemaRef.Diag(D->getLocation(),
  1093. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1094. << D;
  1095. }
  1096. return true;
  1097. }
  1098. return false;
  1099. }
  1100. const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
  1101. bool FromParent) {
  1102. D = getCanonicalDecl(D);
  1103. DSAVarData DVar;
  1104. auto *VD = dyn_cast<VarDecl>(D);
  1105. auto TI = Threadprivates.find(D);
  1106. if (TI != Threadprivates.end()) {
  1107. DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
  1108. DVar.CKind = OMPC_threadprivate;
  1109. return DVar;
  1110. }
  1111. if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  1112. DVar.RefExpr = buildDeclRefExpr(
  1113. SemaRef, VD, D->getType().getNonReferenceType(),
  1114. VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
  1115. DVar.CKind = OMPC_threadprivate;
  1116. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1117. return DVar;
  1118. }
  1119. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1120. // in a Construct, C/C++, predetermined, p.1]
  1121. // Variables appearing in threadprivate directives are threadprivate.
  1122. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  1123. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1124. SemaRef.getLangOpts().OpenMPUseTLS &&
  1125. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  1126. (VD && VD->getStorageClass() == SC_Register &&
  1127. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  1128. DVar.RefExpr = buildDeclRefExpr(
  1129. SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
  1130. DVar.CKind = OMPC_threadprivate;
  1131. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1132. return DVar;
  1133. }
  1134. if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
  1135. VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
  1136. !isLoopControlVariable(D).first) {
  1137. iterator IterTarget =
  1138. std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
  1139. [](const SharingMapTy &Data) {
  1140. return isOpenMPTargetExecutionDirective(Data.Directive);
  1141. });
  1142. if (IterTarget != Stack.back().first.rend()) {
  1143. iterator ParentIterTarget = std::next(IterTarget, 1);
  1144. for (iterator Iter = Stack.back().first.rbegin();
  1145. Iter != ParentIterTarget; std::advance(Iter, 1)) {
  1146. if (isOpenMPLocal(VD, Iter)) {
  1147. DVar.RefExpr =
  1148. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1149. D->getLocation());
  1150. DVar.CKind = OMPC_threadprivate;
  1151. return DVar;
  1152. }
  1153. }
  1154. if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
  1155. auto DSAIter = IterTarget->SharingMap.find(D);
  1156. if (DSAIter != IterTarget->SharingMap.end() &&
  1157. isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
  1158. DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
  1159. DVar.CKind = OMPC_threadprivate;
  1160. return DVar;
  1161. }
  1162. iterator End = Stack.back().first.rend();
  1163. if (!SemaRef.isOpenMPCapturedByRef(
  1164. D, std::distance(ParentIterTarget, End))) {
  1165. DVar.RefExpr =
  1166. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1167. IterTarget->ConstructLoc);
  1168. DVar.CKind = OMPC_threadprivate;
  1169. return DVar;
  1170. }
  1171. }
  1172. }
  1173. }
  1174. if (isStackEmpty())
  1175. // Not in OpenMP execution region and top scope was already checked.
  1176. return DVar;
  1177. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1178. // in a Construct, C/C++, predetermined, p.4]
  1179. // Static data members are shared.
  1180. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1181. // in a Construct, C/C++, predetermined, p.7]
  1182. // Variables with static storage duration that are declared in a scope
  1183. // inside the construct are shared.
  1184. auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
  1185. if (VD && VD->isStaticDataMember()) {
  1186. DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
  1187. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  1188. return DVar;
  1189. DVar.CKind = OMPC_shared;
  1190. return DVar;
  1191. }
  1192. // The predetermined shared attribute for const-qualified types having no
  1193. // mutable members was removed after OpenMP 3.1.
  1194. if (SemaRef.LangOpts.OpenMP <= 31) {
  1195. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1196. // in a Construct, C/C++, predetermined, p.6]
  1197. // Variables with const qualified type having no mutable member are
  1198. // shared.
  1199. if (isConstNotMutableType(SemaRef, D->getType())) {
  1200. // Variables with const-qualified type having no mutable member may be
  1201. // listed in a firstprivate clause, even if they are static data members.
  1202. DSAVarData DVarTemp = hasInnermostDSA(
  1203. D,
  1204. [](OpenMPClauseKind C) {
  1205. return C == OMPC_firstprivate || C == OMPC_shared;
  1206. },
  1207. MatchesAlways, FromParent);
  1208. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  1209. return DVarTemp;
  1210. DVar.CKind = OMPC_shared;
  1211. return DVar;
  1212. }
  1213. }
  1214. // Explicitly specified attributes and local variables with predetermined
  1215. // attributes.
  1216. iterator I = Stack.back().first.rbegin();
  1217. iterator EndI = Stack.back().first.rend();
  1218. if (FromParent && I != EndI)
  1219. std::advance(I, 1);
  1220. auto It = I->SharingMap.find(D);
  1221. if (It != I->SharingMap.end()) {
  1222. const DSAInfo &Data = It->getSecond();
  1223. DVar.RefExpr = Data.RefExpr.getPointer();
  1224. DVar.PrivateCopy = Data.PrivateCopy;
  1225. DVar.CKind = Data.Attributes;
  1226. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1227. DVar.DKind = I->Directive;
  1228. }
  1229. return DVar;
  1230. }
  1231. const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  1232. bool FromParent) const {
  1233. if (isStackEmpty()) {
  1234. iterator I;
  1235. return getDSA(I, D);
  1236. }
  1237. D = getCanonicalDecl(D);
  1238. iterator StartI = Stack.back().first.rbegin();
  1239. iterator EndI = Stack.back().first.rend();
  1240. if (FromParent && StartI != EndI)
  1241. std::advance(StartI, 1);
  1242. return getDSA(StartI, D);
  1243. }
  1244. const DSAStackTy::DSAVarData
  1245. DSAStackTy::hasDSA(ValueDecl *D,
  1246. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1247. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1248. bool FromParent) const {
  1249. if (isStackEmpty())
  1250. return {};
  1251. D = getCanonicalDecl(D);
  1252. iterator I = Stack.back().first.rbegin();
  1253. iterator EndI = Stack.back().first.rend();
  1254. if (FromParent && I != EndI)
  1255. std::advance(I, 1);
  1256. for (; I != EndI; std::advance(I, 1)) {
  1257. if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive))
  1258. continue;
  1259. iterator NewI = I;
  1260. DSAVarData DVar = getDSA(NewI, D);
  1261. if (I == NewI && CPred(DVar.CKind))
  1262. return DVar;
  1263. }
  1264. return {};
  1265. }
  1266. const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  1267. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1268. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1269. bool FromParent) const {
  1270. if (isStackEmpty())
  1271. return {};
  1272. D = getCanonicalDecl(D);
  1273. iterator StartI = Stack.back().first.rbegin();
  1274. iterator EndI = Stack.back().first.rend();
  1275. if (FromParent && StartI != EndI)
  1276. std::advance(StartI, 1);
  1277. if (StartI == EndI || !DPred(StartI->Directive))
  1278. return {};
  1279. iterator NewI = StartI;
  1280. DSAVarData DVar = getDSA(NewI, D);
  1281. return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
  1282. }
  1283. bool DSAStackTy::hasExplicitDSA(
  1284. const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1285. unsigned Level, bool NotLastprivate) const {
  1286. if (isStackEmpty())
  1287. return false;
  1288. D = getCanonicalDecl(D);
  1289. auto StartI = Stack.back().first.begin();
  1290. auto EndI = Stack.back().first.end();
  1291. if (std::distance(StartI, EndI) <= (int)Level)
  1292. return false;
  1293. std::advance(StartI, Level);
  1294. auto I = StartI->SharingMap.find(D);
  1295. if ((I != StartI->SharingMap.end()) &&
  1296. I->getSecond().RefExpr.getPointer() &&
  1297. CPred(I->getSecond().Attributes) &&
  1298. (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
  1299. return true;
  1300. // Check predetermined rules for the loop control variables.
  1301. auto LI = StartI->LCVMap.find(D);
  1302. if (LI != StartI->LCVMap.end())
  1303. return CPred(OMPC_private);
  1304. return false;
  1305. }
  1306. bool DSAStackTy::hasExplicitDirective(
  1307. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1308. unsigned Level) const {
  1309. if (isStackEmpty())
  1310. return false;
  1311. auto StartI = Stack.back().first.begin();
  1312. auto EndI = Stack.back().first.end();
  1313. if (std::distance(StartI, EndI) <= (int)Level)
  1314. return false;
  1315. std::advance(StartI, Level);
  1316. return DPred(StartI->Directive);
  1317. }
  1318. bool DSAStackTy::hasDirective(
  1319. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1320. const DeclarationNameInfo &, SourceLocation)>
  1321. DPred,
  1322. bool FromParent) const {
  1323. // We look only in the enclosing region.
  1324. if (isStackEmpty())
  1325. return false;
  1326. auto StartI = std::next(Stack.back().first.rbegin());
  1327. auto EndI = Stack.back().first.rend();
  1328. if (FromParent && StartI != EndI)
  1329. StartI = std::next(StartI);
  1330. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  1331. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1332. return true;
  1333. }
  1334. return false;
  1335. }
  1336. void Sema::InitDataSharingAttributesStack() {
  1337. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1338. }
  1339. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1340. void Sema::pushOpenMPFunctionRegion() {
  1341. DSAStack->pushFunction();
  1342. }
  1343. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1344. DSAStack->popFunction(OldFSI);
  1345. }
  1346. static bool isOpenMPDeviceDelayedContext(Sema &S) {
  1347. assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  1348. "Expected OpenMP device compilation.");
  1349. return !S.isInOpenMPTargetExecutionDirective() &&
  1350. !S.isInOpenMPDeclareTargetContext();
  1351. }
  1352. /// Do we know that we will eventually codegen the given function?
  1353. static bool isKnownEmitted(Sema &S, FunctionDecl *FD) {
  1354. assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  1355. "Expected OpenMP device compilation.");
  1356. // Templates are emitted when they're instantiated.
  1357. if (FD->isDependentContext())
  1358. return false;
  1359. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  1360. FD->getCanonicalDecl()))
  1361. return true;
  1362. // Otherwise, the function is known-emitted if it's in our set of
  1363. // known-emitted functions.
  1364. return S.DeviceKnownEmittedFns.count(FD) > 0;
  1365. }
  1366. Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
  1367. unsigned DiagID) {
  1368. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1369. "Expected OpenMP device compilation.");
  1370. return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) &&
  1371. !isKnownEmitted(*this, getCurFunctionDecl()))
  1372. ? DeviceDiagBuilder::K_Deferred
  1373. : DeviceDiagBuilder::K_Immediate,
  1374. Loc, DiagID, getCurFunctionDecl(), *this);
  1375. }
  1376. void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) {
  1377. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1378. "Expected OpenMP device compilation.");
  1379. assert(Callee && "Callee may not be null.");
  1380. FunctionDecl *Caller = getCurFunctionDecl();
  1381. // If the caller is known-emitted, mark the callee as known-emitted.
  1382. // Otherwise, mark the call in our call graph so we can traverse it later.
  1383. if (!isOpenMPDeviceDelayedContext(*this) ||
  1384. (Caller && isKnownEmitted(*this, Caller)))
  1385. markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted);
  1386. else if (Caller)
  1387. DeviceCallGraph[Caller].insert({Callee, Loc});
  1388. }
  1389. void Sema::checkOpenMPDeviceExpr(const Expr *E) {
  1390. assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1391. "OpenMP device compilation mode is expected.");
  1392. QualType Ty = E->getType();
  1393. if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
  1394. (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
  1395. (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
  1396. !Context.getTargetInfo().hasInt128Type()))
  1397. targetDiag(E->getExprLoc(), diag::err_type_unsupported)
  1398. << Ty << E->getSourceRange();
  1399. }
  1400. bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
  1401. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1402. ASTContext &Ctx = getASTContext();
  1403. bool IsByRef = true;
  1404. // Find the directive that is associated with the provided scope.
  1405. D = cast<ValueDecl>(D->getCanonicalDecl());
  1406. QualType Ty = D->getType();
  1407. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1408. // This table summarizes how a given variable should be passed to the device
  1409. // given its type and the clauses where it appears. This table is based on
  1410. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1411. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1412. //
  1413. // =========================================================================
  1414. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1415. // | |(tofrom:scalar)| | pvt | | | |
  1416. // =========================================================================
  1417. // | scl | | | | - | | bycopy|
  1418. // | scl | | - | x | - | - | bycopy|
  1419. // | scl | | x | - | - | - | null |
  1420. // | scl | x | | | - | | byref |
  1421. // | scl | x | - | x | - | - | bycopy|
  1422. // | scl | x | x | - | - | - | null |
  1423. // | scl | | - | - | - | x | byref |
  1424. // | scl | x | - | - | - | x | byref |
  1425. //
  1426. // | agg | n.a. | | | - | | byref |
  1427. // | agg | n.a. | - | x | - | - | byref |
  1428. // | agg | n.a. | x | - | - | - | null |
  1429. // | agg | n.a. | - | - | - | x | byref |
  1430. // | agg | n.a. | - | - | - | x[] | byref |
  1431. //
  1432. // | ptr | n.a. | | | - | | bycopy|
  1433. // | ptr | n.a. | - | x | - | - | bycopy|
  1434. // | ptr | n.a. | x | - | - | - | null |
  1435. // | ptr | n.a. | - | - | - | x | byref |
  1436. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1437. // | ptr | n.a. | - | - | x | | bycopy|
  1438. // | ptr | n.a. | - | - | x | x | bycopy|
  1439. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1440. // =========================================================================
  1441. // Legend:
  1442. // scl - scalar
  1443. // ptr - pointer
  1444. // agg - aggregate
  1445. // x - applies
  1446. // - - invalid in this combination
  1447. // [] - mapped with an array section
  1448. // byref - should be mapped by reference
  1449. // byval - should be mapped by value
  1450. // null - initialize a local variable to null on the device
  1451. //
  1452. // Observations:
  1453. // - All scalar declarations that show up in a map clause have to be passed
  1454. // by reference, because they may have been mapped in the enclosing data
  1455. // environment.
  1456. // - If the scalar value does not fit the size of uintptr, it has to be
  1457. // passed by reference, regardless the result in the table above.
  1458. // - For pointers mapped by value that have either an implicit map or an
  1459. // array section, the runtime library may pass the NULL value to the
  1460. // device instead of the value passed to it by the compiler.
  1461. if (Ty->isReferenceType())
  1462. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1463. // Locate map clauses and see if the variable being captured is referred to
  1464. // in any of those clauses. Here we only care about variables, not fields,
  1465. // because fields are part of aggregates.
  1466. bool IsVariableUsedInMapClause = false;
  1467. bool IsVariableAssociatedWithSection = false;
  1468. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1469. D, Level,
  1470. [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
  1471. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1472. MapExprComponents,
  1473. OpenMPClauseKind WhereFoundClauseKind) {
  1474. // Only the map clause information influences how a variable is
  1475. // captured. E.g. is_device_ptr does not require changing the default
  1476. // behavior.
  1477. if (WhereFoundClauseKind != OMPC_map)
  1478. return false;
  1479. auto EI = MapExprComponents.rbegin();
  1480. auto EE = MapExprComponents.rend();
  1481. assert(EI != EE && "Invalid map expression!");
  1482. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1483. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1484. ++EI;
  1485. if (EI == EE)
  1486. return false;
  1487. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1488. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1489. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1490. IsVariableAssociatedWithSection = true;
  1491. // There is nothing more we need to know about this variable.
  1492. return true;
  1493. }
  1494. // Keep looking for more map info.
  1495. return false;
  1496. });
  1497. if (IsVariableUsedInMapClause) {
  1498. // If variable is identified in a map clause it is always captured by
  1499. // reference except if it is a pointer that is dereferenced somehow.
  1500. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1501. } else {
  1502. // By default, all the data that has a scalar type is mapped by copy
  1503. // (except for reduction variables).
  1504. IsByRef =
  1505. (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1506. !Ty->isAnyPointerType()) ||
  1507. !Ty->isScalarType() ||
  1508. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
  1509. DSAStack->hasExplicitDSA(
  1510. D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
  1511. }
  1512. }
  1513. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1514. IsByRef =
  1515. ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1516. !Ty->isAnyPointerType()) ||
  1517. !DSAStack->hasExplicitDSA(
  1518. D,
  1519. [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1520. Level, /*NotLastprivate=*/true)) &&
  1521. // If the variable is artificial and must be captured by value - try to
  1522. // capture by value.
  1523. !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
  1524. !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
  1525. }
  1526. // When passing data by copy, we need to make sure it fits the uintptr size
  1527. // and alignment, because the runtime library only deals with uintptr types.
  1528. // If it does not fit the uintptr size, we need to pass the data by reference
  1529. // instead.
  1530. if (!IsByRef &&
  1531. (Ctx.getTypeSizeInChars(Ty) >
  1532. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1533. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1534. IsByRef = true;
  1535. }
  1536. return IsByRef;
  1537. }
  1538. unsigned Sema::getOpenMPNestingLevel() const {
  1539. assert(getLangOpts().OpenMP);
  1540. return DSAStack->getNestingLevel();
  1541. }
  1542. bool Sema::isInOpenMPTargetExecutionDirective() const {
  1543. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1544. !DSAStack->isClauseParsingMode()) ||
  1545. DSAStack->hasDirective(
  1546. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1547. SourceLocation) -> bool {
  1548. return isOpenMPTargetExecutionDirective(K);
  1549. },
  1550. false);
  1551. }
  1552. VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
  1553. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1554. D = getCanonicalDecl(D);
  1555. // If we are attempting to capture a global variable in a directive with
  1556. // 'target' we return true so that this global is also mapped to the device.
  1557. //
  1558. auto *VD = dyn_cast<VarDecl>(D);
  1559. if (VD && !VD->hasLocalStorage()) {
  1560. if (isInOpenMPDeclareTargetContext() &&
  1561. (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
  1562. // Try to mark variable as declare target if it is used in capturing
  1563. // regions.
  1564. if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1565. checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
  1566. return nullptr;
  1567. } else if (isInOpenMPTargetExecutionDirective()) {
  1568. // If the declaration is enclosed in a 'declare target' directive,
  1569. // then it should not be captured.
  1570. //
  1571. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1572. return nullptr;
  1573. return VD;
  1574. }
  1575. }
  1576. // Capture variables captured by reference in lambdas for target-based
  1577. // directives.
  1578. if (VD && !DSAStack->isClauseParsingMode()) {
  1579. if (const auto *RD = VD->getType()
  1580. .getCanonicalType()
  1581. .getNonReferenceType()
  1582. ->getAsCXXRecordDecl()) {
  1583. bool SavedForceCaptureByReferenceInTargetExecutable =
  1584. DSAStack->isForceCaptureByReferenceInTargetExecutable();
  1585. DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
  1586. if (RD->isLambda()) {
  1587. llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
  1588. FieldDecl *ThisCapture;
  1589. RD->getCaptureFields(Captures, ThisCapture);
  1590. for (const LambdaCapture &LC : RD->captures()) {
  1591. if (LC.getCaptureKind() == LCK_ByRef) {
  1592. VarDecl *VD = LC.getCapturedVar();
  1593. DeclContext *VDC = VD->getDeclContext();
  1594. if (!VDC->Encloses(CurContext))
  1595. continue;
  1596. DSAStackTy::DSAVarData DVarPrivate =
  1597. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  1598. // Do not capture already captured variables.
  1599. if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
  1600. DVarPrivate.CKind == OMPC_unknown &&
  1601. !DSAStack->checkMappableExprComponentListsForDecl(
  1602. D, /*CurrentRegionOnly=*/true,
  1603. [](OMPClauseMappableExprCommon::
  1604. MappableExprComponentListRef,
  1605. OpenMPClauseKind) { return true; }))
  1606. MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
  1607. } else if (LC.getCaptureKind() == LCK_This) {
  1608. QualType ThisTy = getCurrentThisType();
  1609. if (!ThisTy.isNull() &&
  1610. Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
  1611. CheckCXXThisCapture(LC.getLocation());
  1612. }
  1613. }
  1614. }
  1615. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  1616. SavedForceCaptureByReferenceInTargetExecutable);
  1617. }
  1618. }
  1619. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1620. (!DSAStack->isClauseParsingMode() ||
  1621. DSAStack->getParentDirective() != OMPD_unknown)) {
  1622. auto &&Info = DSAStack->isLoopControlVariable(D);
  1623. if (Info.first ||
  1624. (VD && VD->hasLocalStorage() &&
  1625. isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
  1626. (VD && DSAStack->isForceVarCapturing()))
  1627. return VD ? VD : Info.second;
  1628. DSAStackTy::DSAVarData DVarPrivate =
  1629. DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1630. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1631. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1632. DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
  1633. [](OpenMPDirectiveKind) { return true; },
  1634. DSAStack->isClauseParsingMode());
  1635. if (DVarPrivate.CKind != OMPC_unknown)
  1636. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1637. }
  1638. return nullptr;
  1639. }
  1640. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  1641. unsigned Level) const {
  1642. SmallVector<OpenMPDirectiveKind, 4> Regions;
  1643. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  1644. FunctionScopesIndex -= Regions.size();
  1645. }
  1646. void Sema::startOpenMPLoop() {
  1647. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  1648. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
  1649. DSAStack->loopInit();
  1650. }
  1651. bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
  1652. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1653. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  1654. if (DSAStack->getAssociatedLoops() > 0 &&
  1655. !DSAStack->isLoopStarted()) {
  1656. DSAStack->resetPossibleLoopCounter(D);
  1657. DSAStack->loopStart();
  1658. return true;
  1659. }
  1660. if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
  1661. DSAStack->isLoopControlVariable(D).first) &&
  1662. !DSAStack->hasExplicitDSA(
  1663. D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
  1664. !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
  1665. return true;
  1666. }
  1667. return DSAStack->hasExplicitDSA(
  1668. D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
  1669. (DSAStack->isClauseParsingMode() &&
  1670. DSAStack->getClauseParsingMode() == OMPC_private) ||
  1671. // Consider taskgroup reduction descriptor variable a private to avoid
  1672. // possible capture in the region.
  1673. (DSAStack->hasExplicitDirective(
  1674. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1675. Level) &&
  1676. DSAStack->isTaskgroupReductionRef(D, Level));
  1677. }
  1678. void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
  1679. unsigned Level) {
  1680. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1681. D = getCanonicalDecl(D);
  1682. OpenMPClauseKind OMPC = OMPC_unknown;
  1683. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1684. const unsigned NewLevel = I - 1;
  1685. if (DSAStack->hasExplicitDSA(D,
  1686. [&OMPC](const OpenMPClauseKind K) {
  1687. if (isOpenMPPrivate(K)) {
  1688. OMPC = K;
  1689. return true;
  1690. }
  1691. return false;
  1692. },
  1693. NewLevel))
  1694. break;
  1695. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1696. D, NewLevel,
  1697. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1698. OpenMPClauseKind) { return true; })) {
  1699. OMPC = OMPC_map;
  1700. break;
  1701. }
  1702. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1703. NewLevel)) {
  1704. OMPC = OMPC_map;
  1705. if (D->getType()->isScalarType() &&
  1706. DSAStack->getDefaultDMAAtLevel(NewLevel) !=
  1707. DefaultMapAttributes::DMA_tofrom_scalar)
  1708. OMPC = OMPC_firstprivate;
  1709. break;
  1710. }
  1711. }
  1712. if (OMPC != OMPC_unknown)
  1713. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1714. }
  1715. bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
  1716. unsigned Level) const {
  1717. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1718. // Return true if the current level is no longer enclosed in a target region.
  1719. const auto *VD = dyn_cast<VarDecl>(D);
  1720. return VD && !VD->hasLocalStorage() &&
  1721. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1722. Level);
  1723. }
  1724. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1725. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1726. const DeclarationNameInfo &DirName,
  1727. Scope *CurScope, SourceLocation Loc) {
  1728. DSAStack->push(DKind, DirName, CurScope, Loc);
  1729. PushExpressionEvaluationContext(
  1730. ExpressionEvaluationContext::PotentiallyEvaluated);
  1731. }
  1732. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1733. DSAStack->setClauseParsingMode(K);
  1734. }
  1735. void Sema::EndOpenMPClause() {
  1736. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1737. }
  1738. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  1739. ArrayRef<OMPClause *> Clauses);
  1740. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1741. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1742. // A variable of class type (or array thereof) that appears in a lastprivate
  1743. // clause requires an accessible, unambiguous default constructor for the
  1744. // class type, unless the list item is also specified in a firstprivate
  1745. // clause.
  1746. if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1747. for (OMPClause *C : D->clauses()) {
  1748. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1749. SmallVector<Expr *, 8> PrivateCopies;
  1750. for (Expr *DE : Clause->varlists()) {
  1751. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1752. PrivateCopies.push_back(nullptr);
  1753. continue;
  1754. }
  1755. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  1756. auto *VD = cast<VarDecl>(DRE->getDecl());
  1757. QualType Type = VD->getType().getNonReferenceType();
  1758. const DSAStackTy::DSAVarData DVar =
  1759. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  1760. if (DVar.CKind == OMPC_lastprivate) {
  1761. // Generate helper private variable and initialize it with the
  1762. // default value. The address of the original variable is replaced
  1763. // by the address of the new private variable in CodeGen. This new
  1764. // variable is not added to IdResolver, so the code in the OpenMP
  1765. // region uses original variable for proper diagnostics.
  1766. VarDecl *VDPrivate = buildVarDecl(
  1767. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  1768. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
  1769. ActOnUninitializedDecl(VDPrivate);
  1770. if (VDPrivate->isInvalidDecl()) {
  1771. PrivateCopies.push_back(nullptr);
  1772. continue;
  1773. }
  1774. PrivateCopies.push_back(buildDeclRefExpr(
  1775. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  1776. } else {
  1777. // The variable is also a firstprivate, so initialization sequence
  1778. // for private copy is generated already.
  1779. PrivateCopies.push_back(nullptr);
  1780. }
  1781. }
  1782. Clause->setPrivateCopies(PrivateCopies);
  1783. }
  1784. }
  1785. // Check allocate clauses.
  1786. if (!CurContext->isDependentContext())
  1787. checkAllocateClauses(*this, DSAStack, D->clauses());
  1788. }
  1789. DSAStack->pop();
  1790. DiscardCleanupsInEvaluationContext();
  1791. PopExpressionEvaluationContext();
  1792. }
  1793. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  1794. Expr *NumIterations, Sema &SemaRef,
  1795. Scope *S, DSAStackTy *Stack);
  1796. namespace {
  1797. class VarDeclFilterCCC final : public CorrectionCandidateCallback {
  1798. private:
  1799. Sema &SemaRef;
  1800. public:
  1801. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1802. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1803. NamedDecl *ND = Candidate.getCorrectionDecl();
  1804. if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  1805. return VD->hasGlobalStorage() &&
  1806. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1807. SemaRef.getCurScope());
  1808. }
  1809. return false;
  1810. }
  1811. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  1812. return llvm::make_unique<VarDeclFilterCCC>(*this);
  1813. }
  1814. };
  1815. class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
  1816. private:
  1817. Sema &SemaRef;
  1818. public:
  1819. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1820. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1821. NamedDecl *ND = Candidate.getCorrectionDecl();
  1822. if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
  1823. isa<FunctionDecl>(ND))) {
  1824. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1825. SemaRef.getCurScope());
  1826. }
  1827. return false;
  1828. }
  1829. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  1830. return llvm::make_unique<VarOrFuncDeclFilterCCC>(*this);
  1831. }
  1832. };
  1833. } // namespace
  1834. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  1835. CXXScopeSpec &ScopeSpec,
  1836. const DeclarationNameInfo &Id,
  1837. OpenMPDirectiveKind Kind) {
  1838. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  1839. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  1840. if (Lookup.isAmbiguous())
  1841. return ExprError();
  1842. VarDecl *VD;
  1843. if (!Lookup.isSingleResult()) {
  1844. VarDeclFilterCCC CCC(*this);
  1845. if (TypoCorrection Corrected =
  1846. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  1847. CTK_ErrorRecovery)) {
  1848. diagnoseTypo(Corrected,
  1849. PDiag(Lookup.empty()
  1850. ? diag::err_undeclared_var_use_suggest
  1851. : diag::err_omp_expected_var_arg_suggest)
  1852. << Id.getName());
  1853. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  1854. } else {
  1855. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  1856. : diag::err_omp_expected_var_arg)
  1857. << Id.getName();
  1858. return ExprError();
  1859. }
  1860. } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  1861. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  1862. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  1863. return ExprError();
  1864. }
  1865. Lookup.suppressDiagnostics();
  1866. // OpenMP [2.9.2, Syntax, C/C++]
  1867. // Variables must be file-scope, namespace-scope, or static block-scope.
  1868. if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
  1869. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  1870. << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
  1871. bool IsDecl =
  1872. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1873. Diag(VD->getLocation(),
  1874. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1875. << VD;
  1876. return ExprError();
  1877. }
  1878. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  1879. NamedDecl *ND = CanonicalVD;
  1880. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  1881. // A threadprivate directive for file-scope variables must appear outside
  1882. // any definition or declaration.
  1883. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  1884. !getCurLexicalContext()->isTranslationUnit()) {
  1885. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1886. << getOpenMPDirectiveName(Kind) << VD;
  1887. bool IsDecl =
  1888. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1889. Diag(VD->getLocation(),
  1890. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1891. << VD;
  1892. return ExprError();
  1893. }
  1894. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  1895. // A threadprivate directive for static class member variables must appear
  1896. // in the class definition, in the same scope in which the member
  1897. // variables are declared.
  1898. if (CanonicalVD->isStaticDataMember() &&
  1899. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  1900. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1901. << getOpenMPDirectiveName(Kind) << VD;
  1902. bool IsDecl =
  1903. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1904. Diag(VD->getLocation(),
  1905. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1906. << VD;
  1907. return ExprError();
  1908. }
  1909. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  1910. // A threadprivate directive for namespace-scope variables must appear
  1911. // outside any definition or declaration other than the namespace
  1912. // definition itself.
  1913. if (CanonicalVD->getDeclContext()->isNamespace() &&
  1914. (!getCurLexicalContext()->isFileContext() ||
  1915. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  1916. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1917. << getOpenMPDirectiveName(Kind) << VD;
  1918. bool IsDecl =
  1919. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1920. Diag(VD->getLocation(),
  1921. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1922. << VD;
  1923. return ExprError();
  1924. }
  1925. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  1926. // A threadprivate directive for static block-scope variables must appear
  1927. // in the scope of the variable and not in a nested scope.
  1928. if (CanonicalVD->isLocalVarDecl() && CurScope &&
  1929. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  1930. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1931. << getOpenMPDirectiveName(Kind) << VD;
  1932. bool IsDecl =
  1933. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1934. Diag(VD->getLocation(),
  1935. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1936. << VD;
  1937. return ExprError();
  1938. }
  1939. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  1940. // A threadprivate directive must lexically precede all references to any
  1941. // of the variables in its list.
  1942. if (Kind == OMPD_threadprivate && VD->isUsed() &&
  1943. !DSAStack->isThreadPrivate(VD)) {
  1944. Diag(Id.getLoc(), diag::err_omp_var_used)
  1945. << getOpenMPDirectiveName(Kind) << VD;
  1946. return ExprError();
  1947. }
  1948. QualType ExprType = VD->getType().getNonReferenceType();
  1949. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  1950. SourceLocation(), VD,
  1951. /*RefersToEnclosingVariableOrCapture=*/false,
  1952. Id.getLoc(), ExprType, VK_LValue);
  1953. }
  1954. Sema::DeclGroupPtrTy
  1955. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  1956. ArrayRef<Expr *> VarList) {
  1957. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  1958. CurContext->addDecl(D);
  1959. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1960. }
  1961. return nullptr;
  1962. }
  1963. namespace {
  1964. class LocalVarRefChecker final
  1965. : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  1966. Sema &SemaRef;
  1967. public:
  1968. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  1969. if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1970. if (VD->hasLocalStorage()) {
  1971. SemaRef.Diag(E->getBeginLoc(),
  1972. diag::err_omp_local_var_in_threadprivate_init)
  1973. << E->getSourceRange();
  1974. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  1975. << VD << VD->getSourceRange();
  1976. return true;
  1977. }
  1978. }
  1979. return false;
  1980. }
  1981. bool VisitStmt(const Stmt *S) {
  1982. for (const Stmt *Child : S->children()) {
  1983. if (Child && Visit(Child))
  1984. return true;
  1985. }
  1986. return false;
  1987. }
  1988. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  1989. };
  1990. } // namespace
  1991. OMPThreadPrivateDecl *
  1992. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  1993. SmallVector<Expr *, 8> Vars;
  1994. for (Expr *RefExpr : VarList) {
  1995. auto *DE = cast<DeclRefExpr>(RefExpr);
  1996. auto *VD = cast<VarDecl>(DE->getDecl());
  1997. SourceLocation ILoc = DE->getExprLoc();
  1998. // Mark variable as used.
  1999. VD->setReferenced();
  2000. VD->markUsed(Context);
  2001. QualType QType = VD->getType();
  2002. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  2003. // It will be analyzed later.
  2004. Vars.push_back(DE);
  2005. continue;
  2006. }
  2007. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  2008. // A threadprivate variable must not have an incomplete type.
  2009. if (RequireCompleteType(ILoc, VD->getType(),
  2010. diag::err_omp_threadprivate_incomplete_type)) {
  2011. continue;
  2012. }
  2013. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  2014. // A threadprivate variable must not have a reference type.
  2015. if (VD->getType()->isReferenceType()) {
  2016. Diag(ILoc, diag::err_omp_ref_type_arg)
  2017. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  2018. bool IsDecl =
  2019. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2020. Diag(VD->getLocation(),
  2021. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2022. << VD;
  2023. continue;
  2024. }
  2025. // Check if this is a TLS variable. If TLS is not being supported, produce
  2026. // the corresponding diagnostic.
  2027. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  2028. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  2029. getLangOpts().OpenMPUseTLS &&
  2030. getASTContext().getTargetInfo().isTLSSupported())) ||
  2031. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  2032. !VD->isLocalVarDecl())) {
  2033. Diag(ILoc, diag::err_omp_var_thread_local)
  2034. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  2035. bool IsDecl =
  2036. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2037. Diag(VD->getLocation(),
  2038. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2039. << VD;
  2040. continue;
  2041. }
  2042. // Check if initial value of threadprivate variable reference variable with
  2043. // local storage (it is not supported by runtime).
  2044. if (const Expr *Init = VD->getAnyInitializer()) {
  2045. LocalVarRefChecker Checker(*this);
  2046. if (Checker.Visit(Init))
  2047. continue;
  2048. }
  2049. Vars.push_back(RefExpr);
  2050. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  2051. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  2052. Context, SourceRange(Loc, Loc)));
  2053. if (ASTMutationListener *ML = Context.getASTMutationListener())
  2054. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  2055. }
  2056. OMPThreadPrivateDecl *D = nullptr;
  2057. if (!Vars.empty()) {
  2058. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  2059. Vars);
  2060. D->setAccess(AS_public);
  2061. }
  2062. return D;
  2063. }
  2064. static OMPAllocateDeclAttr::AllocatorTypeTy
  2065. getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
  2066. if (!Allocator)
  2067. return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  2068. if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  2069. Allocator->isInstantiationDependent() ||
  2070. Allocator->containsUnexpandedParameterPack())
  2071. return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  2072. auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  2073. const Expr *AE = Allocator->IgnoreParenImpCasts();
  2074. for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  2075. I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  2076. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  2077. const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
  2078. llvm::FoldingSetNodeID AEId, DAEId;
  2079. AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
  2080. DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
  2081. if (AEId == DAEId) {
  2082. AllocatorKindRes = AllocatorKind;
  2083. break;
  2084. }
  2085. }
  2086. return AllocatorKindRes;
  2087. }
  2088. static bool checkPreviousOMPAllocateAttribute(
  2089. Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
  2090. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
  2091. if (!VD->hasAttr<OMPAllocateDeclAttr>())
  2092. return false;
  2093. const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
  2094. Expr *PrevAllocator = A->getAllocator();
  2095. OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
  2096. getAllocatorKind(S, Stack, PrevAllocator);
  2097. bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
  2098. if (AllocatorsMatch &&
  2099. AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
  2100. Allocator && PrevAllocator) {
  2101. const Expr *AE = Allocator->IgnoreParenImpCasts();
  2102. const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
  2103. llvm::FoldingSetNodeID AEId, PAEId;
  2104. AE->Profile(AEId, S.Context, /*Canonical=*/true);
  2105. PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
  2106. AllocatorsMatch = AEId == PAEId;
  2107. }
  2108. if (!AllocatorsMatch) {
  2109. SmallString<256> AllocatorBuffer;
  2110. llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
  2111. if (Allocator)
  2112. Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
  2113. SmallString<256> PrevAllocatorBuffer;
  2114. llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
  2115. if (PrevAllocator)
  2116. PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
  2117. S.getPrintingPolicy());
  2118. SourceLocation AllocatorLoc =
  2119. Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
  2120. SourceRange AllocatorRange =
  2121. Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
  2122. SourceLocation PrevAllocatorLoc =
  2123. PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
  2124. SourceRange PrevAllocatorRange =
  2125. PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
  2126. S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
  2127. << (Allocator ? 1 : 0) << AllocatorStream.str()
  2128. << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
  2129. << AllocatorRange;
  2130. S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
  2131. << PrevAllocatorRange;
  2132. return true;
  2133. }
  2134. return false;
  2135. }
  2136. static void
  2137. applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
  2138. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
  2139. Expr *Allocator, SourceRange SR) {
  2140. if (VD->hasAttr<OMPAllocateDeclAttr>())
  2141. return;
  2142. if (Allocator &&
  2143. (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  2144. Allocator->isInstantiationDependent() ||
  2145. Allocator->containsUnexpandedParameterPack()))
  2146. return;
  2147. auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
  2148. Allocator, SR);
  2149. VD->addAttr(A);
  2150. if (ASTMutationListener *ML = S.Context.getASTMutationListener())
  2151. ML->DeclarationMarkedOpenMPAllocate(VD, A);
  2152. }
  2153. Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
  2154. SourceLocation Loc, ArrayRef<Expr *> VarList,
  2155. ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
  2156. assert(Clauses.size() <= 1 && "Expected at most one clause.");
  2157. Expr *Allocator = nullptr;
  2158. if (Clauses.empty()) {
  2159. // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
  2160. // allocate directives that appear in a target region must specify an
  2161. // allocator clause unless a requires directive with the dynamic_allocators
  2162. // clause is present in the same compilation unit.
  2163. if (LangOpts.OpenMPIsDevice &&
  2164. !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
  2165. targetDiag(Loc, diag::err_expected_allocator_clause);
  2166. } else {
  2167. Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
  2168. }
  2169. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  2170. getAllocatorKind(*this, DSAStack, Allocator);
  2171. SmallVector<Expr *, 8> Vars;
  2172. for (Expr *RefExpr : VarList) {
  2173. auto *DE = cast<DeclRefExpr>(RefExpr);
  2174. auto *VD = cast<VarDecl>(DE->getDecl());
  2175. // Check if this is a TLS variable or global register.
  2176. if (VD->getTLSKind() != VarDecl::TLS_None ||
  2177. VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
  2178. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  2179. !VD->isLocalVarDecl()))
  2180. continue;
  2181. // Do not apply for parameters.
  2182. if (isa<ParmVarDecl>(VD))
  2183. continue;
  2184. // If the used several times in the allocate directive, the same allocator
  2185. // must be used.
  2186. if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
  2187. AllocatorKind, Allocator))
  2188. continue;
  2189. // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
  2190. // If a list item has a static storage type, the allocator expression in the
  2191. // allocator clause must be a constant expression that evaluates to one of
  2192. // the predefined memory allocator values.
  2193. if (Allocator && VD->hasGlobalStorage()) {
  2194. if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
  2195. Diag(Allocator->getExprLoc(),
  2196. diag::err_omp_expected_predefined_allocator)
  2197. << Allocator->getSourceRange();
  2198. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  2199. VarDecl::DeclarationOnly;
  2200. Diag(VD->getLocation(),
  2201. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2202. << VD;
  2203. continue;
  2204. }
  2205. }
  2206. Vars.push_back(RefExpr);
  2207. applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
  2208. DE->getSourceRange());
  2209. }
  2210. if (Vars.empty())
  2211. return nullptr;
  2212. if (!Owner)
  2213. Owner = getCurLexicalContext();
  2214. auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
  2215. D->setAccess(AS_public);
  2216. Owner->addDecl(D);
  2217. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2218. }
  2219. Sema::DeclGroupPtrTy
  2220. Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
  2221. ArrayRef<OMPClause *> ClauseList) {
  2222. OMPRequiresDecl *D = nullptr;
  2223. if (!CurContext->isFileContext()) {
  2224. Diag(Loc, diag::err_omp_invalid_scope) << "requires";
  2225. } else {
  2226. D = CheckOMPRequiresDecl(Loc, ClauseList);
  2227. if (D) {
  2228. CurContext->addDecl(D);
  2229. DSAStack->addRequiresDecl(D);
  2230. }
  2231. }
  2232. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2233. }
  2234. OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
  2235. ArrayRef<OMPClause *> ClauseList) {
  2236. if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
  2237. return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
  2238. ClauseList);
  2239. return nullptr;
  2240. }
  2241. static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
  2242. const ValueDecl *D,
  2243. const DSAStackTy::DSAVarData &DVar,
  2244. bool IsLoopIterVar = false) {
  2245. if (DVar.RefExpr) {
  2246. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  2247. << getOpenMPClauseName(DVar.CKind);
  2248. return;
  2249. }
  2250. enum {
  2251. PDSA_StaticMemberShared,
  2252. PDSA_StaticLocalVarShared,
  2253. PDSA_LoopIterVarPrivate,
  2254. PDSA_LoopIterVarLinear,
  2255. PDSA_LoopIterVarLastprivate,
  2256. PDSA_ConstVarShared,
  2257. PDSA_GlobalVarShared,
  2258. PDSA_TaskVarFirstprivate,
  2259. PDSA_LocalVarPrivate,
  2260. PDSA_Implicit
  2261. } Reason = PDSA_Implicit;
  2262. bool ReportHint = false;
  2263. auto ReportLoc = D->getLocation();
  2264. auto *VD = dyn_cast<VarDecl>(D);
  2265. if (IsLoopIterVar) {
  2266. if (DVar.CKind == OMPC_private)
  2267. Reason = PDSA_LoopIterVarPrivate;
  2268. else if (DVar.CKind == OMPC_lastprivate)
  2269. Reason = PDSA_LoopIterVarLastprivate;
  2270. else
  2271. Reason = PDSA_LoopIterVarLinear;
  2272. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  2273. DVar.CKind == OMPC_firstprivate) {
  2274. Reason = PDSA_TaskVarFirstprivate;
  2275. ReportLoc = DVar.ImplicitDSALoc;
  2276. } else if (VD && VD->isStaticLocal())
  2277. Reason = PDSA_StaticLocalVarShared;
  2278. else if (VD && VD->isStaticDataMember())
  2279. Reason = PDSA_StaticMemberShared;
  2280. else if (VD && VD->isFileVarDecl())
  2281. Reason = PDSA_GlobalVarShared;
  2282. else if (D->getType().isConstant(SemaRef.getASTContext()))
  2283. Reason = PDSA_ConstVarShared;
  2284. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  2285. ReportHint = true;
  2286. Reason = PDSA_LocalVarPrivate;
  2287. }
  2288. if (Reason != PDSA_Implicit) {
  2289. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  2290. << Reason << ReportHint
  2291. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  2292. } else if (DVar.ImplicitDSALoc.isValid()) {
  2293. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  2294. << getOpenMPClauseName(DVar.CKind);
  2295. }
  2296. }
  2297. namespace {
  2298. class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
  2299. DSAStackTy *Stack;
  2300. Sema &SemaRef;
  2301. bool ErrorFound = false;
  2302. CapturedStmt *CS = nullptr;
  2303. llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
  2304. llvm::SmallVector<Expr *, 4> ImplicitMap;
  2305. Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
  2306. llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
  2307. void VisitSubCaptures(OMPExecutableDirective *S) {
  2308. // Check implicitly captured variables.
  2309. if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
  2310. return;
  2311. for (const CapturedStmt::Capture &Cap :
  2312. S->getInnermostCapturedStmt()->captures()) {
  2313. if (!Cap.capturesVariable())
  2314. continue;
  2315. VarDecl *VD = Cap.getCapturedVar();
  2316. // Do not try to map the variable if it or its sub-component was mapped
  2317. // already.
  2318. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  2319. Stack->checkMappableExprComponentListsForDecl(
  2320. VD, /*CurrentRegionOnly=*/true,
  2321. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  2322. OpenMPClauseKind) { return true; }))
  2323. continue;
  2324. DeclRefExpr *DRE = buildDeclRefExpr(
  2325. SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
  2326. Cap.getLocation(), /*RefersToCapture=*/true);
  2327. Visit(DRE);
  2328. }
  2329. }
  2330. public:
  2331. void VisitDeclRefExpr(DeclRefExpr *E) {
  2332. if (E->isTypeDependent() || E->isValueDependent() ||
  2333. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2334. return;
  2335. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2336. VD = VD->getCanonicalDecl();
  2337. // Skip internally declared variables.
  2338. if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
  2339. return;
  2340. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  2341. // Check if the variable has explicit DSA set and stop analysis if it so.
  2342. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  2343. return;
  2344. // Skip internally declared static variables.
  2345. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2346. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2347. if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
  2348. (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
  2349. return;
  2350. SourceLocation ELoc = E->getExprLoc();
  2351. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2352. // The default(none) clause requires that each variable that is referenced
  2353. // in the construct, and does not have a predetermined data-sharing
  2354. // attribute, must have its data-sharing attribute explicitly determined
  2355. // by being listed in a data-sharing attribute clause.
  2356. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  2357. isImplicitOrExplicitTaskingRegion(DKind) &&
  2358. VarsWithInheritedDSA.count(VD) == 0) {
  2359. VarsWithInheritedDSA[VD] = E;
  2360. return;
  2361. }
  2362. if (isOpenMPTargetExecutionDirective(DKind) &&
  2363. !Stack->isLoopControlVariable(VD).first) {
  2364. if (!Stack->checkMappableExprComponentListsForDecl(
  2365. VD, /*CurrentRegionOnly=*/true,
  2366. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2367. StackComponents,
  2368. OpenMPClauseKind) {
  2369. // Variable is used if it has been marked as an array, array
  2370. // section or the variable iself.
  2371. return StackComponents.size() == 1 ||
  2372. std::all_of(
  2373. std::next(StackComponents.rbegin()),
  2374. StackComponents.rend(),
  2375. [](const OMPClauseMappableExprCommon::
  2376. MappableComponent &MC) {
  2377. return MC.getAssociatedDeclaration() ==
  2378. nullptr &&
  2379. (isa<OMPArraySectionExpr>(
  2380. MC.getAssociatedExpression()) ||
  2381. isa<ArraySubscriptExpr>(
  2382. MC.getAssociatedExpression()));
  2383. });
  2384. })) {
  2385. bool IsFirstprivate = false;
  2386. // By default lambdas are captured as firstprivates.
  2387. if (const auto *RD =
  2388. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  2389. IsFirstprivate = RD->isLambda();
  2390. IsFirstprivate =
  2391. IsFirstprivate ||
  2392. (VD->getType().getNonReferenceType()->isScalarType() &&
  2393. Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
  2394. if (IsFirstprivate)
  2395. ImplicitFirstprivate.emplace_back(E);
  2396. else
  2397. ImplicitMap.emplace_back(E);
  2398. return;
  2399. }
  2400. }
  2401. // OpenMP [2.9.3.6, Restrictions, p.2]
  2402. // A list item that appears in a reduction clause of the innermost
  2403. // enclosing worksharing or parallel construct may not be accessed in an
  2404. // explicit task.
  2405. DVar = Stack->hasInnermostDSA(
  2406. VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2407. [](OpenMPDirectiveKind K) {
  2408. return isOpenMPParallelDirective(K) ||
  2409. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2410. },
  2411. /*FromParent=*/true);
  2412. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2413. ErrorFound = true;
  2414. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2415. reportOriginalDsa(SemaRef, Stack, VD, DVar);
  2416. return;
  2417. }
  2418. // Define implicit data-sharing attributes for task.
  2419. DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
  2420. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2421. !Stack->isLoopControlVariable(VD).first) {
  2422. ImplicitFirstprivate.push_back(E);
  2423. return;
  2424. }
  2425. // Store implicitly used globals with declare target link for parent
  2426. // target.
  2427. if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
  2428. *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  2429. Stack->addToParentTargetRegionLinkGlobals(E);
  2430. return;
  2431. }
  2432. }
  2433. }
  2434. void VisitMemberExpr(MemberExpr *E) {
  2435. if (E->isTypeDependent() || E->isValueDependent() ||
  2436. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2437. return;
  2438. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  2439. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2440. if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  2441. if (!FD)
  2442. return;
  2443. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
  2444. // Check if the variable has explicit DSA set and stop analysis if it
  2445. // so.
  2446. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  2447. return;
  2448. if (isOpenMPTargetExecutionDirective(DKind) &&
  2449. !Stack->isLoopControlVariable(FD).first &&
  2450. !Stack->checkMappableExprComponentListsForDecl(
  2451. FD, /*CurrentRegionOnly=*/true,
  2452. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2453. StackComponents,
  2454. OpenMPClauseKind) {
  2455. return isa<CXXThisExpr>(
  2456. cast<MemberExpr>(
  2457. StackComponents.back().getAssociatedExpression())
  2458. ->getBase()
  2459. ->IgnoreParens());
  2460. })) {
  2461. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  2462. // A bit-field cannot appear in a map clause.
  2463. //
  2464. if (FD->isBitField())
  2465. return;
  2466. // Check to see if the member expression is referencing a class that
  2467. // has already been explicitly mapped
  2468. if (Stack->isClassPreviouslyMapped(TE->getType()))
  2469. return;
  2470. ImplicitMap.emplace_back(E);
  2471. return;
  2472. }
  2473. SourceLocation ELoc = E->getExprLoc();
  2474. // OpenMP [2.9.3.6, Restrictions, p.2]
  2475. // A list item that appears in a reduction clause of the innermost
  2476. // enclosing worksharing or parallel construct may not be accessed in
  2477. // an explicit task.
  2478. DVar = Stack->hasInnermostDSA(
  2479. FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2480. [](OpenMPDirectiveKind K) {
  2481. return isOpenMPParallelDirective(K) ||
  2482. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2483. },
  2484. /*FromParent=*/true);
  2485. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2486. ErrorFound = true;
  2487. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2488. reportOriginalDsa(SemaRef, Stack, FD, DVar);
  2489. return;
  2490. }
  2491. // Define implicit data-sharing attributes for task.
  2492. DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
  2493. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2494. !Stack->isLoopControlVariable(FD).first) {
  2495. // Check if there is a captured expression for the current field in the
  2496. // region. Do not mark it as firstprivate unless there is no captured
  2497. // expression.
  2498. // TODO: try to make it firstprivate.
  2499. if (DVar.CKind != OMPC_unknown)
  2500. ImplicitFirstprivate.push_back(E);
  2501. }
  2502. return;
  2503. }
  2504. if (isOpenMPTargetExecutionDirective(DKind)) {
  2505. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  2506. if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  2507. /*NoDiagnose=*/true))
  2508. return;
  2509. const auto *VD = cast<ValueDecl>(
  2510. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  2511. if (!Stack->checkMappableExprComponentListsForDecl(
  2512. VD, /*CurrentRegionOnly=*/true,
  2513. [&CurComponents](
  2514. OMPClauseMappableExprCommon::MappableExprComponentListRef
  2515. StackComponents,
  2516. OpenMPClauseKind) {
  2517. auto CCI = CurComponents.rbegin();
  2518. auto CCE = CurComponents.rend();
  2519. for (const auto &SC : llvm::reverse(StackComponents)) {
  2520. // Do both expressions have the same kind?
  2521. if (CCI->getAssociatedExpression()->getStmtClass() !=
  2522. SC.getAssociatedExpression()->getStmtClass())
  2523. if (!(isa<OMPArraySectionExpr>(
  2524. SC.getAssociatedExpression()) &&
  2525. isa<ArraySubscriptExpr>(
  2526. CCI->getAssociatedExpression())))
  2527. return false;
  2528. const Decl *CCD = CCI->getAssociatedDeclaration();
  2529. const Decl *SCD = SC.getAssociatedDeclaration();
  2530. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  2531. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  2532. if (SCD != CCD)
  2533. return false;
  2534. std::advance(CCI, 1);
  2535. if (CCI == CCE)
  2536. break;
  2537. }
  2538. return true;
  2539. })) {
  2540. Visit(E->getBase());
  2541. }
  2542. } else {
  2543. Visit(E->getBase());
  2544. }
  2545. }
  2546. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  2547. for (OMPClause *C : S->clauses()) {
  2548. // Skip analysis of arguments of implicitly defined firstprivate clause
  2549. // for task|target directives.
  2550. // Skip analysis of arguments of implicitly defined map clause for target
  2551. // directives.
  2552. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  2553. C->isImplicit())) {
  2554. for (Stmt *CC : C->children()) {
  2555. if (CC)
  2556. Visit(CC);
  2557. }
  2558. }
  2559. }
  2560. // Check implicitly captured variables.
  2561. VisitSubCaptures(S);
  2562. }
  2563. void VisitStmt(Stmt *S) {
  2564. for (Stmt *C : S->children()) {
  2565. if (C) {
  2566. // Check implicitly captured variables in the task-based directives to
  2567. // check if they must be firstprivatized.
  2568. Visit(C);
  2569. }
  2570. }
  2571. }
  2572. bool isErrorFound() const { return ErrorFound; }
  2573. ArrayRef<Expr *> getImplicitFirstprivate() const {
  2574. return ImplicitFirstprivate;
  2575. }
  2576. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  2577. const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
  2578. return VarsWithInheritedDSA;
  2579. }
  2580. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  2581. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
  2582. // Process declare target link variables for the target directives.
  2583. if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
  2584. for (DeclRefExpr *E : Stack->getLinkGlobals())
  2585. Visit(E);
  2586. }
  2587. }
  2588. };
  2589. } // namespace
  2590. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  2591. switch (DKind) {
  2592. case OMPD_parallel:
  2593. case OMPD_parallel_for:
  2594. case OMPD_parallel_for_simd:
  2595. case OMPD_parallel_sections:
  2596. case OMPD_teams:
  2597. case OMPD_teams_distribute:
  2598. case OMPD_teams_distribute_simd: {
  2599. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2600. QualType KmpInt32PtrTy =
  2601. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2602. Sema::CapturedParamNameType Params[] = {
  2603. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2604. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2605. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2606. };
  2607. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2608. Params);
  2609. break;
  2610. }
  2611. case OMPD_target_teams:
  2612. case OMPD_target_parallel:
  2613. case OMPD_target_parallel_for:
  2614. case OMPD_target_parallel_for_simd:
  2615. case OMPD_target_teams_distribute:
  2616. case OMPD_target_teams_distribute_simd: {
  2617. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2618. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2619. QualType KmpInt32PtrTy =
  2620. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2621. QualType Args[] = {VoidPtrTy};
  2622. FunctionProtoType::ExtProtoInfo EPI;
  2623. EPI.Variadic = true;
  2624. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2625. Sema::CapturedParamNameType Params[] = {
  2626. std::make_pair(".global_tid.", KmpInt32Ty),
  2627. std::make_pair(".part_id.", KmpInt32PtrTy),
  2628. std::make_pair(".privates.", VoidPtrTy),
  2629. std::make_pair(
  2630. ".copy_fn.",
  2631. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2632. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2633. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2634. };
  2635. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2636. Params);
  2637. // Mark this captured region as inlined, because we don't use outlined
  2638. // function directly.
  2639. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2640. AlwaysInlineAttr::CreateImplicit(
  2641. Context, AlwaysInlineAttr::Keyword_forceinline));
  2642. Sema::CapturedParamNameType ParamsTarget[] = {
  2643. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2644. };
  2645. // Start a captured region for 'target' with no implicit parameters.
  2646. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2647. ParamsTarget);
  2648. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  2649. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2650. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2651. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2652. };
  2653. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2654. // the same implicit parameters.
  2655. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2656. ParamsTeamsOrParallel);
  2657. break;
  2658. }
  2659. case OMPD_target:
  2660. case OMPD_target_simd: {
  2661. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2662. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2663. QualType KmpInt32PtrTy =
  2664. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2665. QualType Args[] = {VoidPtrTy};
  2666. FunctionProtoType::ExtProtoInfo EPI;
  2667. EPI.Variadic = true;
  2668. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2669. Sema::CapturedParamNameType Params[] = {
  2670. std::make_pair(".global_tid.", KmpInt32Ty),
  2671. std::make_pair(".part_id.", KmpInt32PtrTy),
  2672. std::make_pair(".privates.", VoidPtrTy),
  2673. std::make_pair(
  2674. ".copy_fn.",
  2675. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2676. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2677. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2678. };
  2679. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2680. Params);
  2681. // Mark this captured region as inlined, because we don't use outlined
  2682. // function directly.
  2683. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2684. AlwaysInlineAttr::CreateImplicit(
  2685. Context, AlwaysInlineAttr::Keyword_forceinline));
  2686. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2687. std::make_pair(StringRef(), QualType()));
  2688. break;
  2689. }
  2690. case OMPD_simd:
  2691. case OMPD_for:
  2692. case OMPD_for_simd:
  2693. case OMPD_sections:
  2694. case OMPD_section:
  2695. case OMPD_single:
  2696. case OMPD_master:
  2697. case OMPD_critical:
  2698. case OMPD_taskgroup:
  2699. case OMPD_distribute:
  2700. case OMPD_distribute_simd:
  2701. case OMPD_ordered:
  2702. case OMPD_atomic:
  2703. case OMPD_target_data: {
  2704. Sema::CapturedParamNameType Params[] = {
  2705. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2706. };
  2707. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2708. Params);
  2709. break;
  2710. }
  2711. case OMPD_task: {
  2712. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2713. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2714. QualType KmpInt32PtrTy =
  2715. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2716. QualType Args[] = {VoidPtrTy};
  2717. FunctionProtoType::ExtProtoInfo EPI;
  2718. EPI.Variadic = true;
  2719. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2720. Sema::CapturedParamNameType Params[] = {
  2721. std::make_pair(".global_tid.", KmpInt32Ty),
  2722. std::make_pair(".part_id.", KmpInt32PtrTy),
  2723. std::make_pair(".privates.", VoidPtrTy),
  2724. std::make_pair(
  2725. ".copy_fn.",
  2726. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2727. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2728. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2729. };
  2730. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2731. Params);
  2732. // Mark this captured region as inlined, because we don't use outlined
  2733. // function directly.
  2734. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2735. AlwaysInlineAttr::CreateImplicit(
  2736. Context, AlwaysInlineAttr::Keyword_forceinline));
  2737. break;
  2738. }
  2739. case OMPD_taskloop:
  2740. case OMPD_taskloop_simd: {
  2741. QualType KmpInt32Ty =
  2742. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  2743. .withConst();
  2744. QualType KmpUInt64Ty =
  2745. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  2746. .withConst();
  2747. QualType KmpInt64Ty =
  2748. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  2749. .withConst();
  2750. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2751. QualType KmpInt32PtrTy =
  2752. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2753. QualType Args[] = {VoidPtrTy};
  2754. FunctionProtoType::ExtProtoInfo EPI;
  2755. EPI.Variadic = true;
  2756. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2757. Sema::CapturedParamNameType Params[] = {
  2758. std::make_pair(".global_tid.", KmpInt32Ty),
  2759. std::make_pair(".part_id.", KmpInt32PtrTy),
  2760. std::make_pair(".privates.", VoidPtrTy),
  2761. std::make_pair(
  2762. ".copy_fn.",
  2763. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2764. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2765. std::make_pair(".lb.", KmpUInt64Ty),
  2766. std::make_pair(".ub.", KmpUInt64Ty),
  2767. std::make_pair(".st.", KmpInt64Ty),
  2768. std::make_pair(".liter.", KmpInt32Ty),
  2769. std::make_pair(".reductions.", VoidPtrTy),
  2770. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2771. };
  2772. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2773. Params);
  2774. // Mark this captured region as inlined, because we don't use outlined
  2775. // function directly.
  2776. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2777. AlwaysInlineAttr::CreateImplicit(
  2778. Context, AlwaysInlineAttr::Keyword_forceinline));
  2779. break;
  2780. }
  2781. case OMPD_distribute_parallel_for_simd:
  2782. case OMPD_distribute_parallel_for: {
  2783. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2784. QualType KmpInt32PtrTy =
  2785. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2786. Sema::CapturedParamNameType Params[] = {
  2787. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2788. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2789. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2790. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2791. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2792. };
  2793. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2794. Params);
  2795. break;
  2796. }
  2797. case OMPD_target_teams_distribute_parallel_for:
  2798. case OMPD_target_teams_distribute_parallel_for_simd: {
  2799. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2800. QualType KmpInt32PtrTy =
  2801. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2802. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2803. QualType Args[] = {VoidPtrTy};
  2804. FunctionProtoType::ExtProtoInfo EPI;
  2805. EPI.Variadic = true;
  2806. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2807. Sema::CapturedParamNameType Params[] = {
  2808. std::make_pair(".global_tid.", KmpInt32Ty),
  2809. std::make_pair(".part_id.", KmpInt32PtrTy),
  2810. std::make_pair(".privates.", VoidPtrTy),
  2811. std::make_pair(
  2812. ".copy_fn.",
  2813. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2814. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2815. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2816. };
  2817. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2818. Params);
  2819. // Mark this captured region as inlined, because we don't use outlined
  2820. // function directly.
  2821. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2822. AlwaysInlineAttr::CreateImplicit(
  2823. Context, AlwaysInlineAttr::Keyword_forceinline));
  2824. Sema::CapturedParamNameType ParamsTarget[] = {
  2825. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2826. };
  2827. // Start a captured region for 'target' with no implicit parameters.
  2828. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2829. ParamsTarget);
  2830. Sema::CapturedParamNameType ParamsTeams[] = {
  2831. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2832. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2833. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2834. };
  2835. // Start a captured region for 'target' with no implicit parameters.
  2836. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2837. ParamsTeams);
  2838. Sema::CapturedParamNameType ParamsParallel[] = {
  2839. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2840. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2841. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2842. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2843. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2844. };
  2845. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2846. // the same implicit parameters.
  2847. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2848. ParamsParallel);
  2849. break;
  2850. }
  2851. case OMPD_teams_distribute_parallel_for:
  2852. case OMPD_teams_distribute_parallel_for_simd: {
  2853. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2854. QualType KmpInt32PtrTy =
  2855. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2856. Sema::CapturedParamNameType ParamsTeams[] = {
  2857. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2858. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2859. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2860. };
  2861. // Start a captured region for 'target' with no implicit parameters.
  2862. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2863. ParamsTeams);
  2864. Sema::CapturedParamNameType ParamsParallel[] = {
  2865. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2866. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2867. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2868. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2869. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2870. };
  2871. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2872. // the same implicit parameters.
  2873. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2874. ParamsParallel);
  2875. break;
  2876. }
  2877. case OMPD_target_update:
  2878. case OMPD_target_enter_data:
  2879. case OMPD_target_exit_data: {
  2880. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2881. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2882. QualType KmpInt32PtrTy =
  2883. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2884. QualType Args[] = {VoidPtrTy};
  2885. FunctionProtoType::ExtProtoInfo EPI;
  2886. EPI.Variadic = true;
  2887. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2888. Sema::CapturedParamNameType Params[] = {
  2889. std::make_pair(".global_tid.", KmpInt32Ty),
  2890. std::make_pair(".part_id.", KmpInt32PtrTy),
  2891. std::make_pair(".privates.", VoidPtrTy),
  2892. std::make_pair(
  2893. ".copy_fn.",
  2894. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2895. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2896. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2897. };
  2898. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2899. Params);
  2900. // Mark this captured region as inlined, because we don't use outlined
  2901. // function directly.
  2902. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2903. AlwaysInlineAttr::CreateImplicit(
  2904. Context, AlwaysInlineAttr::Keyword_forceinline));
  2905. break;
  2906. }
  2907. case OMPD_threadprivate:
  2908. case OMPD_allocate:
  2909. case OMPD_taskyield:
  2910. case OMPD_barrier:
  2911. case OMPD_taskwait:
  2912. case OMPD_cancellation_point:
  2913. case OMPD_cancel:
  2914. case OMPD_flush:
  2915. case OMPD_declare_reduction:
  2916. case OMPD_declare_mapper:
  2917. case OMPD_declare_simd:
  2918. case OMPD_declare_target:
  2919. case OMPD_end_declare_target:
  2920. case OMPD_requires:
  2921. llvm_unreachable("OpenMP Directive is not allowed");
  2922. case OMPD_unknown:
  2923. llvm_unreachable("Unknown OpenMP directive");
  2924. }
  2925. }
  2926. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  2927. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2928. getOpenMPCaptureRegions(CaptureRegions, DKind);
  2929. return CaptureRegions.size();
  2930. }
  2931. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  2932. Expr *CaptureExpr, bool WithInit,
  2933. bool AsExpression) {
  2934. assert(CaptureExpr);
  2935. ASTContext &C = S.getASTContext();
  2936. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  2937. QualType Ty = Init->getType();
  2938. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  2939. if (S.getLangOpts().CPlusPlus) {
  2940. Ty = C.getLValueReferenceType(Ty);
  2941. } else {
  2942. Ty = C.getPointerType(Ty);
  2943. ExprResult Res =
  2944. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  2945. if (!Res.isUsable())
  2946. return nullptr;
  2947. Init = Res.get();
  2948. }
  2949. WithInit = true;
  2950. }
  2951. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  2952. CaptureExpr->getBeginLoc());
  2953. if (!WithInit)
  2954. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
  2955. S.CurContext->addHiddenDecl(CED);
  2956. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  2957. return CED;
  2958. }
  2959. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  2960. bool WithInit) {
  2961. OMPCapturedExprDecl *CD;
  2962. if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
  2963. CD = cast<OMPCapturedExprDecl>(VD);
  2964. else
  2965. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  2966. /*AsExpression=*/false);
  2967. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2968. CaptureExpr->getExprLoc());
  2969. }
  2970. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  2971. CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
  2972. if (!Ref) {
  2973. OMPCapturedExprDecl *CD = buildCaptureDecl(
  2974. S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
  2975. /*WithInit=*/true, /*AsExpression=*/true);
  2976. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2977. CaptureExpr->getExprLoc());
  2978. }
  2979. ExprResult Res = Ref;
  2980. if (!S.getLangOpts().CPlusPlus &&
  2981. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  2982. Ref->getType()->isPointerType()) {
  2983. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  2984. if (!Res.isUsable())
  2985. return ExprError();
  2986. }
  2987. return S.DefaultLvalueConversion(Res.get());
  2988. }
  2989. namespace {
  2990. // OpenMP directives parsed in this section are represented as a
  2991. // CapturedStatement with an associated statement. If a syntax error
  2992. // is detected during the parsing of the associated statement, the
  2993. // compiler must abort processing and close the CapturedStatement.
  2994. //
  2995. // Combined directives such as 'target parallel' have more than one
  2996. // nested CapturedStatements. This RAII ensures that we unwind out
  2997. // of all the nested CapturedStatements when an error is found.
  2998. class CaptureRegionUnwinderRAII {
  2999. private:
  3000. Sema &S;
  3001. bool &ErrorFound;
  3002. OpenMPDirectiveKind DKind = OMPD_unknown;
  3003. public:
  3004. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  3005. OpenMPDirectiveKind DKind)
  3006. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  3007. ~CaptureRegionUnwinderRAII() {
  3008. if (ErrorFound) {
  3009. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  3010. while (--ThisCaptureLevel >= 0)
  3011. S.ActOnCapturedRegionError();
  3012. }
  3013. }
  3014. };
  3015. } // namespace
  3016. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  3017. ArrayRef<OMPClause *> Clauses) {
  3018. bool ErrorFound = false;
  3019. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  3020. *this, ErrorFound, DSAStack->getCurrentDirective());
  3021. if (!S.isUsable()) {
  3022. ErrorFound = true;
  3023. return StmtError();
  3024. }
  3025. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  3026. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  3027. OMPOrderedClause *OC = nullptr;
  3028. OMPScheduleClause *SC = nullptr;
  3029. SmallVector<const OMPLinearClause *, 4> LCs;
  3030. SmallVector<const OMPClauseWithPreInit *, 4> PICs;
  3031. // This is required for proper codegen.
  3032. for (OMPClause *Clause : Clauses) {
  3033. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  3034. Clause->getClauseKind() == OMPC_in_reduction) {
  3035. // Capture taskgroup task_reduction descriptors inside the tasking regions
  3036. // with the corresponding in_reduction items.
  3037. auto *IRC = cast<OMPInReductionClause>(Clause);
  3038. for (Expr *E : IRC->taskgroup_descriptors())
  3039. if (E)
  3040. MarkDeclarationsReferencedInExpr(E);
  3041. }
  3042. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  3043. Clause->getClauseKind() == OMPC_copyprivate ||
  3044. (getLangOpts().OpenMPUseTLS &&
  3045. getASTContext().getTargetInfo().isTLSSupported() &&
  3046. Clause->getClauseKind() == OMPC_copyin)) {
  3047. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  3048. // Mark all variables in private list clauses as used in inner region.
  3049. for (Stmt *VarRef : Clause->children()) {
  3050. if (auto *E = cast_or_null<Expr>(VarRef)) {
  3051. MarkDeclarationsReferencedInExpr(E);
  3052. }
  3053. }
  3054. DSAStack->setForceVarCapturing(/*V=*/false);
  3055. } else if (CaptureRegions.size() > 1 ||
  3056. CaptureRegions.back() != OMPD_unknown) {
  3057. if (auto *C = OMPClauseWithPreInit::get(Clause))
  3058. PICs.push_back(C);
  3059. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  3060. if (Expr *E = C->getPostUpdateExpr())
  3061. MarkDeclarationsReferencedInExpr(E);
  3062. }
  3063. }
  3064. if (Clause->getClauseKind() == OMPC_schedule)
  3065. SC = cast<OMPScheduleClause>(Clause);
  3066. else if (Clause->getClauseKind() == OMPC_ordered)
  3067. OC = cast<OMPOrderedClause>(Clause);
  3068. else if (Clause->getClauseKind() == OMPC_linear)
  3069. LCs.push_back(cast<OMPLinearClause>(Clause));
  3070. }
  3071. // OpenMP, 2.7.1 Loop Construct, Restrictions
  3072. // The nonmonotonic modifier cannot be specified if an ordered clause is
  3073. // specified.
  3074. if (SC &&
  3075. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  3076. SC->getSecondScheduleModifier() ==
  3077. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  3078. OC) {
  3079. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  3080. ? SC->getFirstScheduleModifierLoc()
  3081. : SC->getSecondScheduleModifierLoc(),
  3082. diag::err_omp_schedule_nonmonotonic_ordered)
  3083. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  3084. ErrorFound = true;
  3085. }
  3086. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  3087. for (const OMPLinearClause *C : LCs) {
  3088. Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
  3089. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  3090. }
  3091. ErrorFound = true;
  3092. }
  3093. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  3094. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  3095. OC->getNumForLoops()) {
  3096. Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
  3097. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  3098. ErrorFound = true;
  3099. }
  3100. if (ErrorFound) {
  3101. return StmtError();
  3102. }
  3103. StmtResult SR = S;
  3104. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  3105. // Mark all variables in private list clauses as used in inner region.
  3106. // Required for proper codegen of combined directives.
  3107. // TODO: add processing for other clauses.
  3108. if (ThisCaptureRegion != OMPD_unknown) {
  3109. for (const clang::OMPClauseWithPreInit *C : PICs) {
  3110. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  3111. // Find the particular capture region for the clause if the
  3112. // directive is a combined one with multiple capture regions.
  3113. // If the directive is not a combined one, the capture region
  3114. // associated with the clause is OMPD_unknown and is generated
  3115. // only once.
  3116. if (CaptureRegion == ThisCaptureRegion ||
  3117. CaptureRegion == OMPD_unknown) {
  3118. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  3119. for (Decl *D : DS->decls())
  3120. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  3121. }
  3122. }
  3123. }
  3124. }
  3125. SR = ActOnCapturedRegionEnd(SR.get());
  3126. }
  3127. return SR;
  3128. }
  3129. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  3130. OpenMPDirectiveKind CancelRegion,
  3131. SourceLocation StartLoc) {
  3132. // CancelRegion is only needed for cancel and cancellation_point.
  3133. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  3134. return false;
  3135. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  3136. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  3137. return false;
  3138. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  3139. << getOpenMPDirectiveName(CancelRegion);
  3140. return true;
  3141. }
  3142. static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
  3143. OpenMPDirectiveKind CurrentRegion,
  3144. const DeclarationNameInfo &CurrentName,
  3145. OpenMPDirectiveKind CancelRegion,
  3146. SourceLocation StartLoc) {
  3147. if (Stack->getCurScope()) {
  3148. OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
  3149. OpenMPDirectiveKind OffendingRegion = ParentRegion;
  3150. bool NestingProhibited = false;
  3151. bool CloseNesting = true;
  3152. bool OrphanSeen = false;
  3153. enum {
  3154. NoRecommend,
  3155. ShouldBeInParallelRegion,
  3156. ShouldBeInOrderedRegion,
  3157. ShouldBeInTargetRegion,
  3158. ShouldBeInTeamsRegion
  3159. } Recommend = NoRecommend;
  3160. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  3161. // OpenMP [2.16, Nesting of Regions]
  3162. // OpenMP constructs may not be nested inside a simd region.
  3163. // OpenMP [2.8.1,simd Construct, Restrictions]
  3164. // An ordered construct with the simd clause is the only OpenMP
  3165. // construct that can appear in the simd region.
  3166. // Allowing a SIMD construct nested in another SIMD construct is an
  3167. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  3168. // message.
  3169. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  3170. ? diag::err_omp_prohibited_region_simd
  3171. : diag::warn_omp_nesting_simd);
  3172. return CurrentRegion != OMPD_simd;
  3173. }
  3174. if (ParentRegion == OMPD_atomic) {
  3175. // OpenMP [2.16, Nesting of Regions]
  3176. // OpenMP constructs may not be nested inside an atomic region.
  3177. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  3178. return true;
  3179. }
  3180. if (CurrentRegion == OMPD_section) {
  3181. // OpenMP [2.7.2, sections Construct, Restrictions]
  3182. // Orphaned section directives are prohibited. That is, the section
  3183. // directives must appear within the sections construct and must not be
  3184. // encountered elsewhere in the sections region.
  3185. if (ParentRegion != OMPD_sections &&
  3186. ParentRegion != OMPD_parallel_sections) {
  3187. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  3188. << (ParentRegion != OMPD_unknown)
  3189. << getOpenMPDirectiveName(ParentRegion);
  3190. return true;
  3191. }
  3192. return false;
  3193. }
  3194. // Allow some constructs (except teams and cancellation constructs) to be
  3195. // orphaned (they could be used in functions, called from OpenMP regions
  3196. // with the required preconditions).
  3197. if (ParentRegion == OMPD_unknown &&
  3198. !isOpenMPNestingTeamsDirective(CurrentRegion) &&
  3199. CurrentRegion != OMPD_cancellation_point &&
  3200. CurrentRegion != OMPD_cancel)
  3201. return false;
  3202. if (CurrentRegion == OMPD_cancellation_point ||
  3203. CurrentRegion == OMPD_cancel) {
  3204. // OpenMP [2.16, Nesting of Regions]
  3205. // A cancellation point construct for which construct-type-clause is
  3206. // taskgroup must be nested inside a task construct. A cancellation
  3207. // point construct for which construct-type-clause is not taskgroup must
  3208. // be closely nested inside an OpenMP construct that matches the type
  3209. // specified in construct-type-clause.
  3210. // A cancel construct for which construct-type-clause is taskgroup must be
  3211. // nested inside a task construct. A cancel construct for which
  3212. // construct-type-clause is not taskgroup must be closely nested inside an
  3213. // OpenMP construct that matches the type specified in
  3214. // construct-type-clause.
  3215. NestingProhibited =
  3216. !((CancelRegion == OMPD_parallel &&
  3217. (ParentRegion == OMPD_parallel ||
  3218. ParentRegion == OMPD_target_parallel)) ||
  3219. (CancelRegion == OMPD_for &&
  3220. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  3221. ParentRegion == OMPD_target_parallel_for ||
  3222. ParentRegion == OMPD_distribute_parallel_for ||
  3223. ParentRegion == OMPD_teams_distribute_parallel_for ||
  3224. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  3225. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  3226. (CancelRegion == OMPD_sections &&
  3227. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  3228. ParentRegion == OMPD_parallel_sections)));
  3229. OrphanSeen = ParentRegion == OMPD_unknown;
  3230. } else if (CurrentRegion == OMPD_master) {
  3231. // OpenMP [2.16, Nesting of Regions]
  3232. // A master region may not be closely nested inside a worksharing,
  3233. // atomic, or explicit task region.
  3234. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3235. isOpenMPTaskingDirective(ParentRegion);
  3236. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  3237. // OpenMP [2.16, Nesting of Regions]
  3238. // A critical region may not be nested (closely or otherwise) inside a
  3239. // critical region with the same name. Note that this restriction is not
  3240. // sufficient to prevent deadlock.
  3241. SourceLocation PreviousCriticalLoc;
  3242. bool DeadLock = Stack->hasDirective(
  3243. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  3244. const DeclarationNameInfo &DNI,
  3245. SourceLocation Loc) {
  3246. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  3247. PreviousCriticalLoc = Loc;
  3248. return true;
  3249. }
  3250. return false;
  3251. },
  3252. false /* skip top directive */);
  3253. if (DeadLock) {
  3254. SemaRef.Diag(StartLoc,
  3255. diag::err_omp_prohibited_region_critical_same_name)
  3256. << CurrentName.getName();
  3257. if (PreviousCriticalLoc.isValid())
  3258. SemaRef.Diag(PreviousCriticalLoc,
  3259. diag::note_omp_previous_critical_region);
  3260. return true;
  3261. }
  3262. } else if (CurrentRegion == OMPD_barrier) {
  3263. // OpenMP [2.16, Nesting of Regions]
  3264. // A barrier region may not be closely nested inside a worksharing,
  3265. // explicit task, critical, ordered, atomic, or master region.
  3266. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3267. isOpenMPTaskingDirective(ParentRegion) ||
  3268. ParentRegion == OMPD_master ||
  3269. ParentRegion == OMPD_critical ||
  3270. ParentRegion == OMPD_ordered;
  3271. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  3272. !isOpenMPParallelDirective(CurrentRegion) &&
  3273. !isOpenMPTeamsDirective(CurrentRegion)) {
  3274. // OpenMP [2.16, Nesting of Regions]
  3275. // A worksharing region may not be closely nested inside a worksharing,
  3276. // explicit task, critical, ordered, atomic, or master region.
  3277. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3278. isOpenMPTaskingDirective(ParentRegion) ||
  3279. ParentRegion == OMPD_master ||
  3280. ParentRegion == OMPD_critical ||
  3281. ParentRegion == OMPD_ordered;
  3282. Recommend = ShouldBeInParallelRegion;
  3283. } else if (CurrentRegion == OMPD_ordered) {
  3284. // OpenMP [2.16, Nesting of Regions]
  3285. // An ordered region may not be closely nested inside a critical,
  3286. // atomic, or explicit task region.
  3287. // An ordered region must be closely nested inside a loop region (or
  3288. // parallel loop region) with an ordered clause.
  3289. // OpenMP [2.8.1,simd Construct, Restrictions]
  3290. // An ordered construct with the simd clause is the only OpenMP construct
  3291. // that can appear in the simd region.
  3292. NestingProhibited = ParentRegion == OMPD_critical ||
  3293. isOpenMPTaskingDirective(ParentRegion) ||
  3294. !(isOpenMPSimdDirective(ParentRegion) ||
  3295. Stack->isParentOrderedRegion());
  3296. Recommend = ShouldBeInOrderedRegion;
  3297. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  3298. // OpenMP [2.16, Nesting of Regions]
  3299. // If specified, a teams construct must be contained within a target
  3300. // construct.
  3301. NestingProhibited = ParentRegion != OMPD_target;
  3302. OrphanSeen = ParentRegion == OMPD_unknown;
  3303. Recommend = ShouldBeInTargetRegion;
  3304. }
  3305. if (!NestingProhibited &&
  3306. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  3307. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  3308. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  3309. // OpenMP [2.16, Nesting of Regions]
  3310. // distribute, parallel, parallel sections, parallel workshare, and the
  3311. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  3312. // constructs that can be closely nested in the teams region.
  3313. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  3314. !isOpenMPDistributeDirective(CurrentRegion);
  3315. Recommend = ShouldBeInParallelRegion;
  3316. }
  3317. if (!NestingProhibited &&
  3318. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  3319. // OpenMP 4.5 [2.17 Nesting of Regions]
  3320. // The region associated with the distribute construct must be strictly
  3321. // nested inside a teams region
  3322. NestingProhibited =
  3323. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  3324. Recommend = ShouldBeInTeamsRegion;
  3325. }
  3326. if (!NestingProhibited &&
  3327. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  3328. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  3329. // OpenMP 4.5 [2.17 Nesting of Regions]
  3330. // If a target, target update, target data, target enter data, or
  3331. // target exit data construct is encountered during execution of a
  3332. // target region, the behavior is unspecified.
  3333. NestingProhibited = Stack->hasDirective(
  3334. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  3335. SourceLocation) {
  3336. if (isOpenMPTargetExecutionDirective(K)) {
  3337. OffendingRegion = K;
  3338. return true;
  3339. }
  3340. return false;
  3341. },
  3342. false /* don't skip top directive */);
  3343. CloseNesting = false;
  3344. }
  3345. if (NestingProhibited) {
  3346. if (OrphanSeen) {
  3347. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  3348. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  3349. } else {
  3350. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  3351. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  3352. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  3353. }
  3354. return true;
  3355. }
  3356. }
  3357. return false;
  3358. }
  3359. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  3360. ArrayRef<OMPClause *> Clauses,
  3361. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  3362. bool ErrorFound = false;
  3363. unsigned NamedModifiersNumber = 0;
  3364. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  3365. OMPD_unknown + 1);
  3366. SmallVector<SourceLocation, 4> NameModifierLoc;
  3367. for (const OMPClause *C : Clauses) {
  3368. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  3369. // At most one if clause without a directive-name-modifier can appear on
  3370. // the directive.
  3371. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  3372. if (FoundNameModifiers[CurNM]) {
  3373. S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  3374. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  3375. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  3376. ErrorFound = true;
  3377. } else if (CurNM != OMPD_unknown) {
  3378. NameModifierLoc.push_back(IC->getNameModifierLoc());
  3379. ++NamedModifiersNumber;
  3380. }
  3381. FoundNameModifiers[CurNM] = IC;
  3382. if (CurNM == OMPD_unknown)
  3383. continue;
  3384. // Check if the specified name modifier is allowed for the current
  3385. // directive.
  3386. // At most one if clause with the particular directive-name-modifier can
  3387. // appear on the directive.
  3388. bool MatchFound = false;
  3389. for (auto NM : AllowedNameModifiers) {
  3390. if (CurNM == NM) {
  3391. MatchFound = true;
  3392. break;
  3393. }
  3394. }
  3395. if (!MatchFound) {
  3396. S.Diag(IC->getNameModifierLoc(),
  3397. diag::err_omp_wrong_if_directive_name_modifier)
  3398. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  3399. ErrorFound = true;
  3400. }
  3401. }
  3402. }
  3403. // If any if clause on the directive includes a directive-name-modifier then
  3404. // all if clauses on the directive must include a directive-name-modifier.
  3405. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  3406. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  3407. S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
  3408. diag::err_omp_no_more_if_clause);
  3409. } else {
  3410. std::string Values;
  3411. std::string Sep(", ");
  3412. unsigned AllowedCnt = 0;
  3413. unsigned TotalAllowedNum =
  3414. AllowedNameModifiers.size() - NamedModifiersNumber;
  3415. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  3416. ++Cnt) {
  3417. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  3418. if (!FoundNameModifiers[NM]) {
  3419. Values += "'";
  3420. Values += getOpenMPDirectiveName(NM);
  3421. Values += "'";
  3422. if (AllowedCnt + 2 == TotalAllowedNum)
  3423. Values += " or ";
  3424. else if (AllowedCnt + 1 != TotalAllowedNum)
  3425. Values += Sep;
  3426. ++AllowedCnt;
  3427. }
  3428. }
  3429. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
  3430. diag::err_omp_unnamed_if_clause)
  3431. << (TotalAllowedNum > 1) << Values;
  3432. }
  3433. for (SourceLocation Loc : NameModifierLoc) {
  3434. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  3435. }
  3436. ErrorFound = true;
  3437. }
  3438. return ErrorFound;
  3439. }
  3440. static std::pair<ValueDecl *, bool>
  3441. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  3442. SourceRange &ERange, bool AllowArraySection = false) {
  3443. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  3444. RefExpr->containsUnexpandedParameterPack())
  3445. return std::make_pair(nullptr, true);
  3446. // OpenMP [3.1, C/C++]
  3447. // A list item is a variable name.
  3448. // OpenMP [2.9.3.3, Restrictions, p.1]
  3449. // A variable that is part of another variable (as an array or
  3450. // structure element) cannot appear in a private clause.
  3451. RefExpr = RefExpr->IgnoreParens();
  3452. enum {
  3453. NoArrayExpr = -1,
  3454. ArraySubscript = 0,
  3455. OMPArraySection = 1
  3456. } IsArrayExpr = NoArrayExpr;
  3457. if (AllowArraySection) {
  3458. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  3459. Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  3460. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  3461. Base = TempASE->getBase()->IgnoreParenImpCasts();
  3462. RefExpr = Base;
  3463. IsArrayExpr = ArraySubscript;
  3464. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  3465. Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  3466. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  3467. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  3468. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  3469. Base = TempASE->getBase()->IgnoreParenImpCasts();
  3470. RefExpr = Base;
  3471. IsArrayExpr = OMPArraySection;
  3472. }
  3473. }
  3474. ELoc = RefExpr->getExprLoc();
  3475. ERange = RefExpr->getSourceRange();
  3476. RefExpr = RefExpr->IgnoreParenImpCasts();
  3477. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  3478. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  3479. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  3480. (S.getCurrentThisType().isNull() || !ME ||
  3481. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  3482. !isa<FieldDecl>(ME->getMemberDecl()))) {
  3483. if (IsArrayExpr != NoArrayExpr) {
  3484. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  3485. << ERange;
  3486. } else {
  3487. S.Diag(ELoc,
  3488. AllowArraySection
  3489. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  3490. : diag::err_omp_expected_var_name_member_expr)
  3491. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  3492. }
  3493. return std::make_pair(nullptr, false);
  3494. }
  3495. return std::make_pair(
  3496. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  3497. }
  3498. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  3499. ArrayRef<OMPClause *> Clauses) {
  3500. assert(!S.CurContext->isDependentContext() &&
  3501. "Expected non-dependent context.");
  3502. auto AllocateRange =
  3503. llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
  3504. llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
  3505. DeclToCopy;
  3506. auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
  3507. return isOpenMPPrivate(C->getClauseKind());
  3508. });
  3509. for (OMPClause *Cl : PrivateRange) {
  3510. MutableArrayRef<Expr *>::iterator I, It, Et;
  3511. if (Cl->getClauseKind() == OMPC_private) {
  3512. auto *PC = cast<OMPPrivateClause>(Cl);
  3513. I = PC->private_copies().begin();
  3514. It = PC->varlist_begin();
  3515. Et = PC->varlist_end();
  3516. } else if (Cl->getClauseKind() == OMPC_firstprivate) {
  3517. auto *PC = cast<OMPFirstprivateClause>(Cl);
  3518. I = PC->private_copies().begin();
  3519. It = PC->varlist_begin();
  3520. Et = PC->varlist_end();
  3521. } else if (Cl->getClauseKind() == OMPC_lastprivate) {
  3522. auto *PC = cast<OMPLastprivateClause>(Cl);
  3523. I = PC->private_copies().begin();
  3524. It = PC->varlist_begin();
  3525. Et = PC->varlist_end();
  3526. } else if (Cl->getClauseKind() == OMPC_linear) {
  3527. auto *PC = cast<OMPLinearClause>(Cl);
  3528. I = PC->privates().begin();
  3529. It = PC->varlist_begin();
  3530. Et = PC->varlist_end();
  3531. } else if (Cl->getClauseKind() == OMPC_reduction) {
  3532. auto *PC = cast<OMPReductionClause>(Cl);
  3533. I = PC->privates().begin();
  3534. It = PC->varlist_begin();
  3535. Et = PC->varlist_end();
  3536. } else if (Cl->getClauseKind() == OMPC_task_reduction) {
  3537. auto *PC = cast<OMPTaskReductionClause>(Cl);
  3538. I = PC->privates().begin();
  3539. It = PC->varlist_begin();
  3540. Et = PC->varlist_end();
  3541. } else if (Cl->getClauseKind() == OMPC_in_reduction) {
  3542. auto *PC = cast<OMPInReductionClause>(Cl);
  3543. I = PC->privates().begin();
  3544. It = PC->varlist_begin();
  3545. Et = PC->varlist_end();
  3546. } else {
  3547. llvm_unreachable("Expected private clause.");
  3548. }
  3549. for (Expr *E : llvm::make_range(It, Et)) {
  3550. if (!*I) {
  3551. ++I;
  3552. continue;
  3553. }
  3554. SourceLocation ELoc;
  3555. SourceRange ERange;
  3556. Expr *SimpleRefExpr = E;
  3557. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  3558. /*AllowArraySection=*/true);
  3559. DeclToCopy.try_emplace(Res.first,
  3560. cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
  3561. ++I;
  3562. }
  3563. }
  3564. for (OMPClause *C : AllocateRange) {
  3565. auto *AC = cast<OMPAllocateClause>(C);
  3566. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  3567. getAllocatorKind(S, Stack, AC->getAllocator());
  3568. // OpenMP, 2.11.4 allocate Clause, Restrictions.
  3569. // For task, taskloop or target directives, allocation requests to memory
  3570. // allocators with the trait access set to thread result in unspecified
  3571. // behavior.
  3572. if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
  3573. (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  3574. isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
  3575. S.Diag(AC->getAllocator()->getExprLoc(),
  3576. diag::warn_omp_allocate_thread_on_task_target_directive)
  3577. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  3578. }
  3579. for (Expr *E : AC->varlists()) {
  3580. SourceLocation ELoc;
  3581. SourceRange ERange;
  3582. Expr *SimpleRefExpr = E;
  3583. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
  3584. ValueDecl *VD = Res.first;
  3585. DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
  3586. if (!isOpenMPPrivate(Data.CKind)) {
  3587. S.Diag(E->getExprLoc(),
  3588. diag::err_omp_expected_private_copy_for_allocate);
  3589. continue;
  3590. }
  3591. VarDecl *PrivateVD = DeclToCopy[VD];
  3592. if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
  3593. AllocatorKind, AC->getAllocator()))
  3594. continue;
  3595. applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
  3596. E->getSourceRange());
  3597. }
  3598. }
  3599. }
  3600. StmtResult Sema::ActOnOpenMPExecutableDirective(
  3601. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  3602. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  3603. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  3604. StmtResult Res = StmtError();
  3605. // First check CancelRegion which is then used in checkNestingOfRegions.
  3606. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  3607. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  3608. StartLoc))
  3609. return StmtError();
  3610. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  3611. VarsWithInheritedDSAType VarsWithInheritedDSA;
  3612. bool ErrorFound = false;
  3613. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  3614. if (AStmt && !CurContext->isDependentContext()) {
  3615. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3616. // Check default data sharing attributes for referenced variables.
  3617. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  3618. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  3619. Stmt *S = AStmt;
  3620. while (--ThisCaptureLevel >= 0)
  3621. S = cast<CapturedStmt>(S)->getCapturedStmt();
  3622. DSAChecker.Visit(S);
  3623. if (DSAChecker.isErrorFound())
  3624. return StmtError();
  3625. // Generate list of implicitly defined firstprivate variables.
  3626. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  3627. SmallVector<Expr *, 4> ImplicitFirstprivates(
  3628. DSAChecker.getImplicitFirstprivate().begin(),
  3629. DSAChecker.getImplicitFirstprivate().end());
  3630. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  3631. DSAChecker.getImplicitMap().end());
  3632. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  3633. for (OMPClause *C : Clauses) {
  3634. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  3635. for (Expr *E : IRC->taskgroup_descriptors())
  3636. if (E)
  3637. ImplicitFirstprivates.emplace_back(E);
  3638. }
  3639. }
  3640. if (!ImplicitFirstprivates.empty()) {
  3641. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  3642. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  3643. SourceLocation())) {
  3644. ClausesWithImplicit.push_back(Implicit);
  3645. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  3646. ImplicitFirstprivates.size();
  3647. } else {
  3648. ErrorFound = true;
  3649. }
  3650. }
  3651. if (!ImplicitMaps.empty()) {
  3652. CXXScopeSpec MapperIdScopeSpec;
  3653. DeclarationNameInfo MapperId;
  3654. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  3655. llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
  3656. OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
  3657. SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
  3658. ClausesWithImplicit.emplace_back(Implicit);
  3659. ErrorFound |=
  3660. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  3661. } else {
  3662. ErrorFound = true;
  3663. }
  3664. }
  3665. }
  3666. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  3667. switch (Kind) {
  3668. case OMPD_parallel:
  3669. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  3670. EndLoc);
  3671. AllowedNameModifiers.push_back(OMPD_parallel);
  3672. break;
  3673. case OMPD_simd:
  3674. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  3675. VarsWithInheritedDSA);
  3676. break;
  3677. case OMPD_for:
  3678. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  3679. VarsWithInheritedDSA);
  3680. break;
  3681. case OMPD_for_simd:
  3682. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3683. EndLoc, VarsWithInheritedDSA);
  3684. break;
  3685. case OMPD_sections:
  3686. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  3687. EndLoc);
  3688. break;
  3689. case OMPD_section:
  3690. assert(ClausesWithImplicit.empty() &&
  3691. "No clauses are allowed for 'omp section' directive");
  3692. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  3693. break;
  3694. case OMPD_single:
  3695. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  3696. EndLoc);
  3697. break;
  3698. case OMPD_master:
  3699. assert(ClausesWithImplicit.empty() &&
  3700. "No clauses are allowed for 'omp master' directive");
  3701. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  3702. break;
  3703. case OMPD_critical:
  3704. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  3705. StartLoc, EndLoc);
  3706. break;
  3707. case OMPD_parallel_for:
  3708. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  3709. EndLoc, VarsWithInheritedDSA);
  3710. AllowedNameModifiers.push_back(OMPD_parallel);
  3711. break;
  3712. case OMPD_parallel_for_simd:
  3713. Res = ActOnOpenMPParallelForSimdDirective(
  3714. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3715. AllowedNameModifiers.push_back(OMPD_parallel);
  3716. break;
  3717. case OMPD_parallel_sections:
  3718. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  3719. StartLoc, EndLoc);
  3720. AllowedNameModifiers.push_back(OMPD_parallel);
  3721. break;
  3722. case OMPD_task:
  3723. Res =
  3724. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  3725. AllowedNameModifiers.push_back(OMPD_task);
  3726. break;
  3727. case OMPD_taskyield:
  3728. assert(ClausesWithImplicit.empty() &&
  3729. "No clauses are allowed for 'omp taskyield' directive");
  3730. assert(AStmt == nullptr &&
  3731. "No associated statement allowed for 'omp taskyield' directive");
  3732. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  3733. break;
  3734. case OMPD_barrier:
  3735. assert(ClausesWithImplicit.empty() &&
  3736. "No clauses are allowed for 'omp barrier' directive");
  3737. assert(AStmt == nullptr &&
  3738. "No associated statement allowed for 'omp barrier' directive");
  3739. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  3740. break;
  3741. case OMPD_taskwait:
  3742. assert(ClausesWithImplicit.empty() &&
  3743. "No clauses are allowed for 'omp taskwait' directive");
  3744. assert(AStmt == nullptr &&
  3745. "No associated statement allowed for 'omp taskwait' directive");
  3746. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  3747. break;
  3748. case OMPD_taskgroup:
  3749. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  3750. EndLoc);
  3751. break;
  3752. case OMPD_flush:
  3753. assert(AStmt == nullptr &&
  3754. "No associated statement allowed for 'omp flush' directive");
  3755. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  3756. break;
  3757. case OMPD_ordered:
  3758. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  3759. EndLoc);
  3760. break;
  3761. case OMPD_atomic:
  3762. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  3763. EndLoc);
  3764. break;
  3765. case OMPD_teams:
  3766. Res =
  3767. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  3768. break;
  3769. case OMPD_target:
  3770. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  3771. EndLoc);
  3772. AllowedNameModifiers.push_back(OMPD_target);
  3773. break;
  3774. case OMPD_target_parallel:
  3775. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  3776. StartLoc, EndLoc);
  3777. AllowedNameModifiers.push_back(OMPD_target);
  3778. AllowedNameModifiers.push_back(OMPD_parallel);
  3779. break;
  3780. case OMPD_target_parallel_for:
  3781. Res = ActOnOpenMPTargetParallelForDirective(
  3782. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3783. AllowedNameModifiers.push_back(OMPD_target);
  3784. AllowedNameModifiers.push_back(OMPD_parallel);
  3785. break;
  3786. case OMPD_cancellation_point:
  3787. assert(ClausesWithImplicit.empty() &&
  3788. "No clauses are allowed for 'omp cancellation point' directive");
  3789. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  3790. "cancellation point' directive");
  3791. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  3792. break;
  3793. case OMPD_cancel:
  3794. assert(AStmt == nullptr &&
  3795. "No associated statement allowed for 'omp cancel' directive");
  3796. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  3797. CancelRegion);
  3798. AllowedNameModifiers.push_back(OMPD_cancel);
  3799. break;
  3800. case OMPD_target_data:
  3801. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  3802. EndLoc);
  3803. AllowedNameModifiers.push_back(OMPD_target_data);
  3804. break;
  3805. case OMPD_target_enter_data:
  3806. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  3807. EndLoc, AStmt);
  3808. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  3809. break;
  3810. case OMPD_target_exit_data:
  3811. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  3812. EndLoc, AStmt);
  3813. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  3814. break;
  3815. case OMPD_taskloop:
  3816. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  3817. EndLoc, VarsWithInheritedDSA);
  3818. AllowedNameModifiers.push_back(OMPD_taskloop);
  3819. break;
  3820. case OMPD_taskloop_simd:
  3821. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3822. EndLoc, VarsWithInheritedDSA);
  3823. AllowedNameModifiers.push_back(OMPD_taskloop);
  3824. break;
  3825. case OMPD_distribute:
  3826. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  3827. EndLoc, VarsWithInheritedDSA);
  3828. break;
  3829. case OMPD_target_update:
  3830. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  3831. EndLoc, AStmt);
  3832. AllowedNameModifiers.push_back(OMPD_target_update);
  3833. break;
  3834. case OMPD_distribute_parallel_for:
  3835. Res = ActOnOpenMPDistributeParallelForDirective(
  3836. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3837. AllowedNameModifiers.push_back(OMPD_parallel);
  3838. break;
  3839. case OMPD_distribute_parallel_for_simd:
  3840. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  3841. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3842. AllowedNameModifiers.push_back(OMPD_parallel);
  3843. break;
  3844. case OMPD_distribute_simd:
  3845. Res = ActOnOpenMPDistributeSimdDirective(
  3846. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3847. break;
  3848. case OMPD_target_parallel_for_simd:
  3849. Res = ActOnOpenMPTargetParallelForSimdDirective(
  3850. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3851. AllowedNameModifiers.push_back(OMPD_target);
  3852. AllowedNameModifiers.push_back(OMPD_parallel);
  3853. break;
  3854. case OMPD_target_simd:
  3855. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3856. EndLoc, VarsWithInheritedDSA);
  3857. AllowedNameModifiers.push_back(OMPD_target);
  3858. break;
  3859. case OMPD_teams_distribute:
  3860. Res = ActOnOpenMPTeamsDistributeDirective(
  3861. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3862. break;
  3863. case OMPD_teams_distribute_simd:
  3864. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  3865. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3866. break;
  3867. case OMPD_teams_distribute_parallel_for_simd:
  3868. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  3869. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3870. AllowedNameModifiers.push_back(OMPD_parallel);
  3871. break;
  3872. case OMPD_teams_distribute_parallel_for:
  3873. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  3874. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3875. AllowedNameModifiers.push_back(OMPD_parallel);
  3876. break;
  3877. case OMPD_target_teams:
  3878. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  3879. EndLoc);
  3880. AllowedNameModifiers.push_back(OMPD_target);
  3881. break;
  3882. case OMPD_target_teams_distribute:
  3883. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  3884. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3885. AllowedNameModifiers.push_back(OMPD_target);
  3886. break;
  3887. case OMPD_target_teams_distribute_parallel_for:
  3888. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  3889. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3890. AllowedNameModifiers.push_back(OMPD_target);
  3891. AllowedNameModifiers.push_back(OMPD_parallel);
  3892. break;
  3893. case OMPD_target_teams_distribute_parallel_for_simd:
  3894. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  3895. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3896. AllowedNameModifiers.push_back(OMPD_target);
  3897. AllowedNameModifiers.push_back(OMPD_parallel);
  3898. break;
  3899. case OMPD_target_teams_distribute_simd:
  3900. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  3901. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3902. AllowedNameModifiers.push_back(OMPD_target);
  3903. break;
  3904. case OMPD_declare_target:
  3905. case OMPD_end_declare_target:
  3906. case OMPD_threadprivate:
  3907. case OMPD_allocate:
  3908. case OMPD_declare_reduction:
  3909. case OMPD_declare_mapper:
  3910. case OMPD_declare_simd:
  3911. case OMPD_requires:
  3912. llvm_unreachable("OpenMP Directive is not allowed");
  3913. case OMPD_unknown:
  3914. llvm_unreachable("Unknown OpenMP directive");
  3915. }
  3916. ErrorFound = Res.isInvalid() || ErrorFound;
  3917. for (const auto &P : VarsWithInheritedDSA) {
  3918. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  3919. << P.first << P.second->getSourceRange();
  3920. }
  3921. ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
  3922. if (!AllowedNameModifiers.empty())
  3923. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  3924. ErrorFound;
  3925. if (ErrorFound)
  3926. return StmtError();
  3927. if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
  3928. Res.getAs<OMPExecutableDirective>()
  3929. ->getStructuredBlock()
  3930. ->setIsOMPStructuredBlock(true);
  3931. }
  3932. return Res;
  3933. }
  3934. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  3935. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  3936. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  3937. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  3938. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  3939. assert(Aligneds.size() == Alignments.size());
  3940. assert(Linears.size() == LinModifiers.size());
  3941. assert(Linears.size() == Steps.size());
  3942. if (!DG || DG.get().isNull())
  3943. return DeclGroupPtrTy();
  3944. if (!DG.get().isSingleDecl()) {
  3945. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
  3946. return DG;
  3947. }
  3948. Decl *ADecl = DG.get().getSingleDecl();
  3949. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  3950. ADecl = FTD->getTemplatedDecl();
  3951. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  3952. if (!FD) {
  3953. Diag(ADecl->getLocation(), diag::err_omp_function_expected);
  3954. return DeclGroupPtrTy();
  3955. }
  3956. // OpenMP [2.8.2, declare simd construct, Description]
  3957. // The parameter of the simdlen clause must be a constant positive integer
  3958. // expression.
  3959. ExprResult SL;
  3960. if (Simdlen)
  3961. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  3962. // OpenMP [2.8.2, declare simd construct, Description]
  3963. // The special this pointer can be used as if was one of the arguments to the
  3964. // function in any of the linear, aligned, or uniform clauses.
  3965. // The uniform clause declares one or more arguments to have an invariant
  3966. // value for all concurrent invocations of the function in the execution of a
  3967. // single SIMD loop.
  3968. llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
  3969. const Expr *UniformedLinearThis = nullptr;
  3970. for (const Expr *E : Uniforms) {
  3971. E = E->IgnoreParenImpCasts();
  3972. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3973. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  3974. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3975. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3976. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  3977. UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
  3978. continue;
  3979. }
  3980. if (isa<CXXThisExpr>(E)) {
  3981. UniformedLinearThis = E;
  3982. continue;
  3983. }
  3984. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3985. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3986. }
  3987. // OpenMP [2.8.2, declare simd construct, Description]
  3988. // The aligned clause declares that the object to which each list item points
  3989. // is aligned to the number of bytes expressed in the optional parameter of
  3990. // the aligned clause.
  3991. // The special this pointer can be used as if was one of the arguments to the
  3992. // function in any of the linear, aligned, or uniform clauses.
  3993. // The type of list items appearing in the aligned clause must be array,
  3994. // pointer, reference to array, or reference to pointer.
  3995. llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
  3996. const Expr *AlignedThis = nullptr;
  3997. for (const Expr *E : Aligneds) {
  3998. E = E->IgnoreParenImpCasts();
  3999. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4000. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4001. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4002. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4003. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4004. ->getCanonicalDecl() == CanonPVD) {
  4005. // OpenMP [2.8.1, simd construct, Restrictions]
  4006. // A list-item cannot appear in more than one aligned clause.
  4007. if (AlignedArgs.count(CanonPVD) > 0) {
  4008. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  4009. << 1 << E->getSourceRange();
  4010. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  4011. diag::note_omp_explicit_dsa)
  4012. << getOpenMPClauseName(OMPC_aligned);
  4013. continue;
  4014. }
  4015. AlignedArgs[CanonPVD] = E;
  4016. QualType QTy = PVD->getType()
  4017. .getNonReferenceType()
  4018. .getUnqualifiedType()
  4019. .getCanonicalType();
  4020. const Type *Ty = QTy.getTypePtrOrNull();
  4021. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  4022. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  4023. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  4024. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  4025. }
  4026. continue;
  4027. }
  4028. }
  4029. if (isa<CXXThisExpr>(E)) {
  4030. if (AlignedThis) {
  4031. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  4032. << 2 << E->getSourceRange();
  4033. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  4034. << getOpenMPClauseName(OMPC_aligned);
  4035. }
  4036. AlignedThis = E;
  4037. continue;
  4038. }
  4039. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4040. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4041. }
  4042. // The optional parameter of the aligned clause, alignment, must be a constant
  4043. // positive integer expression. If no optional parameter is specified,
  4044. // implementation-defined default alignments for SIMD instructions on the
  4045. // target platforms are assumed.
  4046. SmallVector<const Expr *, 4> NewAligns;
  4047. for (Expr *E : Alignments) {
  4048. ExprResult Align;
  4049. if (E)
  4050. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  4051. NewAligns.push_back(Align.get());
  4052. }
  4053. // OpenMP [2.8.2, declare simd construct, Description]
  4054. // The linear clause declares one or more list items to be private to a SIMD
  4055. // lane and to have a linear relationship with respect to the iteration space
  4056. // of a loop.
  4057. // The special this pointer can be used as if was one of the arguments to the
  4058. // function in any of the linear, aligned, or uniform clauses.
  4059. // When a linear-step expression is specified in a linear clause it must be
  4060. // either a constant integer expression or an integer-typed parameter that is
  4061. // specified in a uniform clause on the directive.
  4062. llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
  4063. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  4064. auto MI = LinModifiers.begin();
  4065. for (const Expr *E : Linears) {
  4066. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  4067. ++MI;
  4068. E = E->IgnoreParenImpCasts();
  4069. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  4070. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4071. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4072. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  4073. FD->getParamDecl(PVD->getFunctionScopeIndex())
  4074. ->getCanonicalDecl() == CanonPVD) {
  4075. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  4076. // A list-item cannot appear in more than one linear clause.
  4077. if (LinearArgs.count(CanonPVD) > 0) {
  4078. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4079. << getOpenMPClauseName(OMPC_linear)
  4080. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  4081. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  4082. diag::note_omp_explicit_dsa)
  4083. << getOpenMPClauseName(OMPC_linear);
  4084. continue;
  4085. }
  4086. // Each argument can appear in at most one uniform or linear clause.
  4087. if (UniformedArgs.count(CanonPVD) > 0) {
  4088. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4089. << getOpenMPClauseName(OMPC_linear)
  4090. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  4091. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  4092. diag::note_omp_explicit_dsa)
  4093. << getOpenMPClauseName(OMPC_uniform);
  4094. continue;
  4095. }
  4096. LinearArgs[CanonPVD] = E;
  4097. if (E->isValueDependent() || E->isTypeDependent() ||
  4098. E->isInstantiationDependent() ||
  4099. E->containsUnexpandedParameterPack())
  4100. continue;
  4101. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  4102. PVD->getOriginalType());
  4103. continue;
  4104. }
  4105. }
  4106. if (isa<CXXThisExpr>(E)) {
  4107. if (UniformedLinearThis) {
  4108. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  4109. << getOpenMPClauseName(OMPC_linear)
  4110. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  4111. << E->getSourceRange();
  4112. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  4113. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  4114. : OMPC_linear);
  4115. continue;
  4116. }
  4117. UniformedLinearThis = E;
  4118. if (E->isValueDependent() || E->isTypeDependent() ||
  4119. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  4120. continue;
  4121. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  4122. E->getType());
  4123. continue;
  4124. }
  4125. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  4126. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  4127. }
  4128. Expr *Step = nullptr;
  4129. Expr *NewStep = nullptr;
  4130. SmallVector<Expr *, 4> NewSteps;
  4131. for (Expr *E : Steps) {
  4132. // Skip the same step expression, it was checked already.
  4133. if (Step == E || !E) {
  4134. NewSteps.push_back(E ? NewStep : nullptr);
  4135. continue;
  4136. }
  4137. Step = E;
  4138. if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
  4139. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  4140. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  4141. if (UniformedArgs.count(CanonPVD) == 0) {
  4142. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  4143. << Step->getSourceRange();
  4144. } else if (E->isValueDependent() || E->isTypeDependent() ||
  4145. E->isInstantiationDependent() ||
  4146. E->containsUnexpandedParameterPack() ||
  4147. CanonPVD->getType()->hasIntegerRepresentation()) {
  4148. NewSteps.push_back(Step);
  4149. } else {
  4150. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  4151. << Step->getSourceRange();
  4152. }
  4153. continue;
  4154. }
  4155. NewStep = Step;
  4156. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  4157. !Step->isInstantiationDependent() &&
  4158. !Step->containsUnexpandedParameterPack()) {
  4159. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  4160. .get();
  4161. if (NewStep)
  4162. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  4163. }
  4164. NewSteps.push_back(NewStep);
  4165. }
  4166. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  4167. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  4168. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  4169. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  4170. const_cast<Expr **>(Linears.data()), Linears.size(),
  4171. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  4172. NewSteps.data(), NewSteps.size(), SR);
  4173. ADecl->addAttr(NewAttr);
  4174. return ConvertDeclToDeclGroup(ADecl);
  4175. }
  4176. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  4177. Stmt *AStmt,
  4178. SourceLocation StartLoc,
  4179. SourceLocation EndLoc) {
  4180. if (!AStmt)
  4181. return StmtError();
  4182. auto *CS = cast<CapturedStmt>(AStmt);
  4183. // 1.2.2 OpenMP Language Terminology
  4184. // Structured block - An executable statement with a single entry at the
  4185. // top and a single exit at the bottom.
  4186. // The point of exit cannot be a branch out of the structured block.
  4187. // longjmp() and throw() must not violate the entry/exit criteria.
  4188. CS->getCapturedDecl()->setNothrow();
  4189. setFunctionHasBranchProtectedScope();
  4190. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4191. DSAStack->isCancelRegion());
  4192. }
  4193. namespace {
  4194. /// Helper class for checking canonical form of the OpenMP loops and
  4195. /// extracting iteration space of each loop in the loop nest, that will be used
  4196. /// for IR generation.
  4197. class OpenMPIterationSpaceChecker {
  4198. /// Reference to Sema.
  4199. Sema &SemaRef;
  4200. /// A location for diagnostics (when there is no some better location).
  4201. SourceLocation DefaultLoc;
  4202. /// A location for diagnostics (when increment is not compatible).
  4203. SourceLocation ConditionLoc;
  4204. /// A source location for referring to loop init later.
  4205. SourceRange InitSrcRange;
  4206. /// A source location for referring to condition later.
  4207. SourceRange ConditionSrcRange;
  4208. /// A source location for referring to increment later.
  4209. SourceRange IncrementSrcRange;
  4210. /// Loop variable.
  4211. ValueDecl *LCDecl = nullptr;
  4212. /// Reference to loop variable.
  4213. Expr *LCRef = nullptr;
  4214. /// Lower bound (initializer for the var).
  4215. Expr *LB = nullptr;
  4216. /// Upper bound.
  4217. Expr *UB = nullptr;
  4218. /// Loop step (increment).
  4219. Expr *Step = nullptr;
  4220. /// This flag is true when condition is one of:
  4221. /// Var < UB
  4222. /// Var <= UB
  4223. /// UB > Var
  4224. /// UB >= Var
  4225. /// This will have no value when the condition is !=
  4226. llvm::Optional<bool> TestIsLessOp;
  4227. /// This flag is true when condition is strict ( < or > ).
  4228. bool TestIsStrictOp = false;
  4229. /// This flag is true when step is subtracted on each iteration.
  4230. bool SubtractStep = false;
  4231. public:
  4232. OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
  4233. : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
  4234. /// Check init-expr for canonical loop form and save loop counter
  4235. /// variable - #Var and its initialization value - #LB.
  4236. bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
  4237. /// Check test-expr for canonical form, save upper-bound (#UB), flags
  4238. /// for less/greater and for strict/non-strict comparison.
  4239. bool checkAndSetCond(Expr *S);
  4240. /// Check incr-expr for canonical loop form and return true if it
  4241. /// does not conform, otherwise save loop step (#Step).
  4242. bool checkAndSetInc(Expr *S);
  4243. /// Return the loop counter variable.
  4244. ValueDecl *getLoopDecl() const { return LCDecl; }
  4245. /// Return the reference expression to loop counter variable.
  4246. Expr *getLoopDeclRefExpr() const { return LCRef; }
  4247. /// Source range of the loop init.
  4248. SourceRange getInitSrcRange() const { return InitSrcRange; }
  4249. /// Source range of the loop condition.
  4250. SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
  4251. /// Source range of the loop increment.
  4252. SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
  4253. /// True if the step should be subtracted.
  4254. bool shouldSubtractStep() const { return SubtractStep; }
  4255. /// True, if the compare operator is strict (<, > or !=).
  4256. bool isStrictTestOp() const { return TestIsStrictOp; }
  4257. /// Build the expression to calculate the number of iterations.
  4258. Expr *buildNumIterations(
  4259. Scope *S, const bool LimitedType,
  4260. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  4261. /// Build the precondition expression for the loops.
  4262. Expr *
  4263. buildPreCond(Scope *S, Expr *Cond,
  4264. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  4265. /// Build reference expression to the counter be used for codegen.
  4266. DeclRefExpr *
  4267. buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  4268. DSAStackTy &DSA) const;
  4269. /// Build reference expression to the private counter be used for
  4270. /// codegen.
  4271. Expr *buildPrivateCounterVar() const;
  4272. /// Build initialization of the counter be used for codegen.
  4273. Expr *buildCounterInit() const;
  4274. /// Build step of the counter be used for codegen.
  4275. Expr *buildCounterStep() const;
  4276. /// Build loop data with counter value for depend clauses in ordered
  4277. /// directives.
  4278. Expr *
  4279. buildOrderedLoopData(Scope *S, Expr *Counter,
  4280. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  4281. SourceLocation Loc, Expr *Inc = nullptr,
  4282. OverloadedOperatorKind OOK = OO_Amp);
  4283. /// Return true if any expression is dependent.
  4284. bool dependent() const;
  4285. private:
  4286. /// Check the right-hand side of an assignment in the increment
  4287. /// expression.
  4288. bool checkAndSetIncRHS(Expr *RHS);
  4289. /// Helper to set loop counter variable and its initializer.
  4290. bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
  4291. /// Helper to set upper bound.
  4292. bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
  4293. SourceRange SR, SourceLocation SL);
  4294. /// Helper to set loop increment.
  4295. bool setStep(Expr *NewStep, bool Subtract);
  4296. };
  4297. bool OpenMPIterationSpaceChecker::dependent() const {
  4298. if (!LCDecl) {
  4299. assert(!LB && !UB && !Step);
  4300. return false;
  4301. }
  4302. return LCDecl->getType()->isDependentType() ||
  4303. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  4304. (Step && Step->isValueDependent());
  4305. }
  4306. bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
  4307. Expr *NewLCRefExpr,
  4308. Expr *NewLB) {
  4309. // State consistency checking to ensure correct usage.
  4310. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  4311. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  4312. if (!NewLCDecl || !NewLB)
  4313. return true;
  4314. LCDecl = getCanonicalDecl(NewLCDecl);
  4315. LCRef = NewLCRefExpr;
  4316. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  4317. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  4318. if ((Ctor->isCopyOrMoveConstructor() ||
  4319. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  4320. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  4321. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  4322. LB = NewLB;
  4323. return false;
  4324. }
  4325. bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
  4326. llvm::Optional<bool> LessOp,
  4327. bool StrictOp, SourceRange SR,
  4328. SourceLocation SL) {
  4329. // State consistency checking to ensure correct usage.
  4330. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  4331. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  4332. if (!NewUB)
  4333. return true;
  4334. UB = NewUB;
  4335. if (LessOp)
  4336. TestIsLessOp = LessOp;
  4337. TestIsStrictOp = StrictOp;
  4338. ConditionSrcRange = SR;
  4339. ConditionLoc = SL;
  4340. return false;
  4341. }
  4342. bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
  4343. // State consistency checking to ensure correct usage.
  4344. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  4345. if (!NewStep)
  4346. return true;
  4347. if (!NewStep->isValueDependent()) {
  4348. // Check that the step is integer expression.
  4349. SourceLocation StepLoc = NewStep->getBeginLoc();
  4350. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  4351. StepLoc, getExprAsWritten(NewStep));
  4352. if (Val.isInvalid())
  4353. return true;
  4354. NewStep = Val.get();
  4355. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  4356. // If test-expr is of form var relational-op b and relational-op is < or
  4357. // <= then incr-expr must cause var to increase on each iteration of the
  4358. // loop. If test-expr is of form var relational-op b and relational-op is
  4359. // > or >= then incr-expr must cause var to decrease on each iteration of
  4360. // the loop.
  4361. // If test-expr is of form b relational-op var and relational-op is < or
  4362. // <= then incr-expr must cause var to decrease on each iteration of the
  4363. // loop. If test-expr is of form b relational-op var and relational-op is
  4364. // > or >= then incr-expr must cause var to increase on each iteration of
  4365. // the loop.
  4366. llvm::APSInt Result;
  4367. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  4368. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  4369. bool IsConstNeg =
  4370. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  4371. bool IsConstPos =
  4372. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  4373. bool IsConstZero = IsConstant && !Result.getBoolValue();
  4374. // != with increment is treated as <; != with decrement is treated as >
  4375. if (!TestIsLessOp.hasValue())
  4376. TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
  4377. if (UB && (IsConstZero ||
  4378. (TestIsLessOp.getValue() ?
  4379. (IsConstNeg || (IsUnsigned && Subtract)) :
  4380. (IsConstPos || (IsUnsigned && !Subtract))))) {
  4381. SemaRef.Diag(NewStep->getExprLoc(),
  4382. diag::err_omp_loop_incr_not_compatible)
  4383. << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
  4384. SemaRef.Diag(ConditionLoc,
  4385. diag::note_omp_loop_cond_requres_compatible_incr)
  4386. << TestIsLessOp.getValue() << ConditionSrcRange;
  4387. return true;
  4388. }
  4389. if (TestIsLessOp.getValue() == Subtract) {
  4390. NewStep =
  4391. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  4392. .get();
  4393. Subtract = !Subtract;
  4394. }
  4395. }
  4396. Step = NewStep;
  4397. SubtractStep = Subtract;
  4398. return false;
  4399. }
  4400. bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
  4401. // Check init-expr for canonical loop form and save loop counter
  4402. // variable - #Var and its initialization value - #LB.
  4403. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  4404. // var = lb
  4405. // integer-type var = lb
  4406. // random-access-iterator-type var = lb
  4407. // pointer-type var = lb
  4408. //
  4409. if (!S) {
  4410. if (EmitDiags) {
  4411. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  4412. }
  4413. return true;
  4414. }
  4415. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  4416. if (!ExprTemp->cleanupsHaveSideEffects())
  4417. S = ExprTemp->getSubExpr();
  4418. InitSrcRange = S->getSourceRange();
  4419. if (Expr *E = dyn_cast<Expr>(S))
  4420. S = E->IgnoreParens();
  4421. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  4422. if (BO->getOpcode() == BO_Assign) {
  4423. Expr *LHS = BO->getLHS()->IgnoreParens();
  4424. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  4425. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  4426. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  4427. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  4428. return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
  4429. }
  4430. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  4431. if (ME->isArrow() &&
  4432. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  4433. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  4434. }
  4435. }
  4436. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  4437. if (DS->isSingleDecl()) {
  4438. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  4439. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  4440. // Accept non-canonical init form here but emit ext. warning.
  4441. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  4442. SemaRef.Diag(S->getBeginLoc(),
  4443. diag::ext_omp_loop_not_canonical_init)
  4444. << S->getSourceRange();
  4445. return setLCDeclAndLB(
  4446. Var,
  4447. buildDeclRefExpr(SemaRef, Var,
  4448. Var->getType().getNonReferenceType(),
  4449. DS->getBeginLoc()),
  4450. Var->getInit());
  4451. }
  4452. }
  4453. }
  4454. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  4455. if (CE->getOperator() == OO_Equal) {
  4456. Expr *LHS = CE->getArg(0);
  4457. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  4458. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  4459. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  4460. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  4461. return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
  4462. }
  4463. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  4464. if (ME->isArrow() &&
  4465. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  4466. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  4467. }
  4468. }
  4469. }
  4470. if (dependent() || SemaRef.CurContext->isDependentContext())
  4471. return false;
  4472. if (EmitDiags) {
  4473. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
  4474. << S->getSourceRange();
  4475. }
  4476. return true;
  4477. }
  4478. /// Ignore parenthesizes, implicit casts, copy constructor and return the
  4479. /// variable (which may be the loop variable) if possible.
  4480. static const ValueDecl *getInitLCDecl(const Expr *E) {
  4481. if (!E)
  4482. return nullptr;
  4483. E = getExprAsWritten(E);
  4484. if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  4485. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  4486. if ((Ctor->isCopyOrMoveConstructor() ||
  4487. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  4488. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  4489. E = CE->getArg(0)->IgnoreParenImpCasts();
  4490. if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  4491. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  4492. return getCanonicalDecl(VD);
  4493. }
  4494. if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
  4495. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  4496. return getCanonicalDecl(ME->getMemberDecl());
  4497. return nullptr;
  4498. }
  4499. bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
  4500. // Check test-expr for canonical form, save upper-bound UB, flags for
  4501. // less/greater and for strict/non-strict comparison.
  4502. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  4503. // var relational-op b
  4504. // b relational-op var
  4505. //
  4506. if (!S) {
  4507. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
  4508. return true;
  4509. }
  4510. S = getExprAsWritten(S);
  4511. SourceLocation CondLoc = S->getBeginLoc();
  4512. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  4513. if (BO->isRelationalOp()) {
  4514. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4515. return setUB(BO->getRHS(),
  4516. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  4517. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  4518. BO->getSourceRange(), BO->getOperatorLoc());
  4519. if (getInitLCDecl(BO->getRHS()) == LCDecl)
  4520. return setUB(BO->getLHS(),
  4521. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  4522. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  4523. BO->getSourceRange(), BO->getOperatorLoc());
  4524. } else if (BO->getOpcode() == BO_NE)
  4525. return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
  4526. BO->getRHS() : BO->getLHS(),
  4527. /*LessOp=*/llvm::None,
  4528. /*StrictOp=*/true,
  4529. BO->getSourceRange(), BO->getOperatorLoc());
  4530. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  4531. if (CE->getNumArgs() == 2) {
  4532. auto Op = CE->getOperator();
  4533. switch (Op) {
  4534. case OO_Greater:
  4535. case OO_GreaterEqual:
  4536. case OO_Less:
  4537. case OO_LessEqual:
  4538. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4539. return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  4540. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  4541. CE->getOperatorLoc());
  4542. if (getInitLCDecl(CE->getArg(1)) == LCDecl)
  4543. return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  4544. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  4545. CE->getOperatorLoc());
  4546. break;
  4547. case OO_ExclaimEqual:
  4548. return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
  4549. CE->getArg(1) : CE->getArg(0),
  4550. /*LessOp=*/llvm::None,
  4551. /*StrictOp=*/true,
  4552. CE->getSourceRange(),
  4553. CE->getOperatorLoc());
  4554. break;
  4555. default:
  4556. break;
  4557. }
  4558. }
  4559. }
  4560. if (dependent() || SemaRef.CurContext->isDependentContext())
  4561. return false;
  4562. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  4563. << S->getSourceRange() << LCDecl;
  4564. return true;
  4565. }
  4566. bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
  4567. // RHS of canonical loop form increment can be:
  4568. // var + incr
  4569. // incr + var
  4570. // var - incr
  4571. //
  4572. RHS = RHS->IgnoreParenImpCasts();
  4573. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  4574. if (BO->isAdditiveOp()) {
  4575. bool IsAdd = BO->getOpcode() == BO_Add;
  4576. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4577. return setStep(BO->getRHS(), !IsAdd);
  4578. if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
  4579. return setStep(BO->getLHS(), /*Subtract=*/false);
  4580. }
  4581. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  4582. bool IsAdd = CE->getOperator() == OO_Plus;
  4583. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  4584. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4585. return setStep(CE->getArg(1), !IsAdd);
  4586. if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
  4587. return setStep(CE->getArg(0), /*Subtract=*/false);
  4588. }
  4589. }
  4590. if (dependent() || SemaRef.CurContext->isDependentContext())
  4591. return false;
  4592. SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  4593. << RHS->getSourceRange() << LCDecl;
  4594. return true;
  4595. }
  4596. bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
  4597. // Check incr-expr for canonical loop form and return true if it
  4598. // does not conform.
  4599. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  4600. // ++var
  4601. // var++
  4602. // --var
  4603. // var--
  4604. // var += incr
  4605. // var -= incr
  4606. // var = var + incr
  4607. // var = incr + var
  4608. // var = var - incr
  4609. //
  4610. if (!S) {
  4611. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  4612. return true;
  4613. }
  4614. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  4615. if (!ExprTemp->cleanupsHaveSideEffects())
  4616. S = ExprTemp->getSubExpr();
  4617. IncrementSrcRange = S->getSourceRange();
  4618. S = S->IgnoreParens();
  4619. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  4620. if (UO->isIncrementDecrementOp() &&
  4621. getInitLCDecl(UO->getSubExpr()) == LCDecl)
  4622. return setStep(SemaRef
  4623. .ActOnIntegerConstant(UO->getBeginLoc(),
  4624. (UO->isDecrementOp() ? -1 : 1))
  4625. .get(),
  4626. /*Subtract=*/false);
  4627. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  4628. switch (BO->getOpcode()) {
  4629. case BO_AddAssign:
  4630. case BO_SubAssign:
  4631. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4632. return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  4633. break;
  4634. case BO_Assign:
  4635. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4636. return checkAndSetIncRHS(BO->getRHS());
  4637. break;
  4638. default:
  4639. break;
  4640. }
  4641. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  4642. switch (CE->getOperator()) {
  4643. case OO_PlusPlus:
  4644. case OO_MinusMinus:
  4645. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4646. return setStep(SemaRef
  4647. .ActOnIntegerConstant(
  4648. CE->getBeginLoc(),
  4649. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  4650. .get(),
  4651. /*Subtract=*/false);
  4652. break;
  4653. case OO_PlusEqual:
  4654. case OO_MinusEqual:
  4655. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4656. return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  4657. break;
  4658. case OO_Equal:
  4659. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4660. return checkAndSetIncRHS(CE->getArg(1));
  4661. break;
  4662. default:
  4663. break;
  4664. }
  4665. }
  4666. if (dependent() || SemaRef.CurContext->isDependentContext())
  4667. return false;
  4668. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  4669. << S->getSourceRange() << LCDecl;
  4670. return true;
  4671. }
  4672. static ExprResult
  4673. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  4674. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4675. if (SemaRef.CurContext->isDependentContext())
  4676. return ExprResult(Capture);
  4677. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  4678. return SemaRef.PerformImplicitConversion(
  4679. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  4680. /*AllowExplicit=*/true);
  4681. auto I = Captures.find(Capture);
  4682. if (I != Captures.end())
  4683. return buildCapture(SemaRef, Capture, I->second);
  4684. DeclRefExpr *Ref = nullptr;
  4685. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  4686. Captures[Capture] = Ref;
  4687. return Res;
  4688. }
  4689. /// Build the expression to calculate the number of iterations.
  4690. Expr *OpenMPIterationSpaceChecker::buildNumIterations(
  4691. Scope *S, const bool LimitedType,
  4692. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  4693. ExprResult Diff;
  4694. QualType VarType = LCDecl->getType().getNonReferenceType();
  4695. if (VarType->isIntegerType() || VarType->isPointerType() ||
  4696. SemaRef.getLangOpts().CPlusPlus) {
  4697. // Upper - Lower
  4698. Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
  4699. Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
  4700. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  4701. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  4702. if (!Upper || !Lower)
  4703. return nullptr;
  4704. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  4705. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  4706. // BuildBinOp already emitted error, this one is to point user to upper
  4707. // and lower bound, and to tell what is passed to 'operator-'.
  4708. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  4709. << Upper->getSourceRange() << Lower->getSourceRange();
  4710. return nullptr;
  4711. }
  4712. }
  4713. if (!Diff.isUsable())
  4714. return nullptr;
  4715. // Upper - Lower [- 1]
  4716. if (TestIsStrictOp)
  4717. Diff = SemaRef.BuildBinOp(
  4718. S, DefaultLoc, BO_Sub, Diff.get(),
  4719. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4720. if (!Diff.isUsable())
  4721. return nullptr;
  4722. // Upper - Lower [- 1] + Step
  4723. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  4724. if (!NewStep.isUsable())
  4725. return nullptr;
  4726. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  4727. if (!Diff.isUsable())
  4728. return nullptr;
  4729. // Parentheses (for dumping/debugging purposes only).
  4730. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  4731. if (!Diff.isUsable())
  4732. return nullptr;
  4733. // (Upper - Lower [- 1] + Step) / Step
  4734. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  4735. if (!Diff.isUsable())
  4736. return nullptr;
  4737. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  4738. QualType Type = Diff.get()->getType();
  4739. ASTContext &C = SemaRef.Context;
  4740. bool UseVarType = VarType->hasIntegerRepresentation() &&
  4741. C.getTypeSize(Type) > C.getTypeSize(VarType);
  4742. if (!Type->isIntegerType() || UseVarType) {
  4743. unsigned NewSize =
  4744. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  4745. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  4746. : Type->hasSignedIntegerRepresentation();
  4747. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  4748. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  4749. Diff = SemaRef.PerformImplicitConversion(
  4750. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  4751. if (!Diff.isUsable())
  4752. return nullptr;
  4753. }
  4754. }
  4755. if (LimitedType) {
  4756. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  4757. if (NewSize != C.getTypeSize(Type)) {
  4758. if (NewSize < C.getTypeSize(Type)) {
  4759. assert(NewSize == 64 && "incorrect loop var size");
  4760. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  4761. << InitSrcRange << ConditionSrcRange;
  4762. }
  4763. QualType NewType = C.getIntTypeForBitwidth(
  4764. NewSize, Type->hasSignedIntegerRepresentation() ||
  4765. C.getTypeSize(Type) < NewSize);
  4766. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  4767. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  4768. Sema::AA_Converting, true);
  4769. if (!Diff.isUsable())
  4770. return nullptr;
  4771. }
  4772. }
  4773. }
  4774. return Diff.get();
  4775. }
  4776. Expr *OpenMPIterationSpaceChecker::buildPreCond(
  4777. Scope *S, Expr *Cond,
  4778. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  4779. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  4780. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4781. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4782. ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
  4783. ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
  4784. if (!NewLB.isUsable() || !NewUB.isUsable())
  4785. return nullptr;
  4786. ExprResult CondExpr =
  4787. SemaRef.BuildBinOp(S, DefaultLoc,
  4788. TestIsLessOp.getValue() ?
  4789. (TestIsStrictOp ? BO_LT : BO_LE) :
  4790. (TestIsStrictOp ? BO_GT : BO_GE),
  4791. NewLB.get(), NewUB.get());
  4792. if (CondExpr.isUsable()) {
  4793. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  4794. SemaRef.Context.BoolTy))
  4795. CondExpr = SemaRef.PerformImplicitConversion(
  4796. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  4797. /*AllowExplicit=*/true);
  4798. }
  4799. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4800. // Otherwise use original loop condition and evaluate it in runtime.
  4801. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  4802. }
  4803. /// Build reference expression to the counter be used for codegen.
  4804. DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
  4805. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  4806. DSAStackTy &DSA) const {
  4807. auto *VD = dyn_cast<VarDecl>(LCDecl);
  4808. if (!VD) {
  4809. VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
  4810. DeclRefExpr *Ref = buildDeclRefExpr(
  4811. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  4812. const DSAStackTy::DSAVarData Data =
  4813. DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  4814. // If the loop control decl is explicitly marked as private, do not mark it
  4815. // as captured again.
  4816. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  4817. Captures.insert(std::make_pair(LCRef, Ref));
  4818. return Ref;
  4819. }
  4820. return cast<DeclRefExpr>(LCRef);
  4821. }
  4822. Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
  4823. if (LCDecl && !LCDecl->isInvalidDecl()) {
  4824. QualType Type = LCDecl->getType().getNonReferenceType();
  4825. VarDecl *PrivateVar = buildVarDecl(
  4826. SemaRef, DefaultLoc, Type, LCDecl->getName(),
  4827. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
  4828. isa<VarDecl>(LCDecl)
  4829. ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
  4830. : nullptr);
  4831. if (PrivateVar->isInvalidDecl())
  4832. return nullptr;
  4833. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  4834. }
  4835. return nullptr;
  4836. }
  4837. /// Build initialization of the counter to be used for codegen.
  4838. Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
  4839. /// Build step of the counter be used for codegen.
  4840. Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
  4841. Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
  4842. Scope *S, Expr *Counter,
  4843. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
  4844. Expr *Inc, OverloadedOperatorKind OOK) {
  4845. Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
  4846. if (!Cnt)
  4847. return nullptr;
  4848. if (Inc) {
  4849. assert((OOK == OO_Plus || OOK == OO_Minus) &&
  4850. "Expected only + or - operations for depend clauses.");
  4851. BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
  4852. Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
  4853. if (!Cnt)
  4854. return nullptr;
  4855. }
  4856. ExprResult Diff;
  4857. QualType VarType = LCDecl->getType().getNonReferenceType();
  4858. if (VarType->isIntegerType() || VarType->isPointerType() ||
  4859. SemaRef.getLangOpts().CPlusPlus) {
  4860. // Upper - Lower
  4861. Expr *Upper = TestIsLessOp.getValue()
  4862. ? Cnt
  4863. : tryBuildCapture(SemaRef, UB, Captures).get();
  4864. Expr *Lower = TestIsLessOp.getValue()
  4865. ? tryBuildCapture(SemaRef, LB, Captures).get()
  4866. : Cnt;
  4867. if (!Upper || !Lower)
  4868. return nullptr;
  4869. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  4870. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  4871. // BuildBinOp already emitted error, this one is to point user to upper
  4872. // and lower bound, and to tell what is passed to 'operator-'.
  4873. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  4874. << Upper->getSourceRange() << Lower->getSourceRange();
  4875. return nullptr;
  4876. }
  4877. }
  4878. if (!Diff.isUsable())
  4879. return nullptr;
  4880. // Parentheses (for dumping/debugging purposes only).
  4881. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  4882. if (!Diff.isUsable())
  4883. return nullptr;
  4884. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  4885. if (!NewStep.isUsable())
  4886. return nullptr;
  4887. // (Upper - Lower) / Step
  4888. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  4889. if (!Diff.isUsable())
  4890. return nullptr;
  4891. return Diff.get();
  4892. }
  4893. /// Iteration space of a single for loop.
  4894. struct LoopIterationSpace final {
  4895. /// True if the condition operator is the strict compare operator (<, > or
  4896. /// !=).
  4897. bool IsStrictCompare = false;
  4898. /// Condition of the loop.
  4899. Expr *PreCond = nullptr;
  4900. /// This expression calculates the number of iterations in the loop.
  4901. /// It is always possible to calculate it before starting the loop.
  4902. Expr *NumIterations = nullptr;
  4903. /// The loop counter variable.
  4904. Expr *CounterVar = nullptr;
  4905. /// Private loop counter variable.
  4906. Expr *PrivateCounterVar = nullptr;
  4907. /// This is initializer for the initial value of #CounterVar.
  4908. Expr *CounterInit = nullptr;
  4909. /// This is step for the #CounterVar used to generate its update:
  4910. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  4911. Expr *CounterStep = nullptr;
  4912. /// Should step be subtracted?
  4913. bool Subtract = false;
  4914. /// Source range of the loop init.
  4915. SourceRange InitSrcRange;
  4916. /// Source range of the loop condition.
  4917. SourceRange CondSrcRange;
  4918. /// Source range of the loop increment.
  4919. SourceRange IncSrcRange;
  4920. };
  4921. } // namespace
  4922. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  4923. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  4924. assert(Init && "Expected loop in canonical form.");
  4925. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  4926. if (AssociatedLoops > 0 &&
  4927. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  4928. DSAStack->loopStart();
  4929. OpenMPIterationSpaceChecker ISC(*this, ForLoc);
  4930. if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
  4931. if (ValueDecl *D = ISC.getLoopDecl()) {
  4932. auto *VD = dyn_cast<VarDecl>(D);
  4933. if (!VD) {
  4934. if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
  4935. VD = Private;
  4936. } else {
  4937. DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
  4938. /*WithInit=*/false);
  4939. VD = cast<VarDecl>(Ref->getDecl());
  4940. }
  4941. }
  4942. DSAStack->addLoopControlVariable(D, VD);
  4943. const Decl *LD = DSAStack->getPossiblyLoopCunter();
  4944. if (LD != D->getCanonicalDecl()) {
  4945. DSAStack->resetPossibleLoopCounter();
  4946. if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
  4947. MarkDeclarationsReferencedInExpr(
  4948. buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
  4949. Var->getType().getNonLValueExprType(Context),
  4950. ForLoc, /*RefersToCapture=*/true));
  4951. }
  4952. }
  4953. }
  4954. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  4955. }
  4956. }
  4957. /// Called on a for stmt to check and extract its iteration space
  4958. /// for further processing (such as collapsing).
  4959. static bool checkOpenMPIterationSpace(
  4960. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  4961. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  4962. unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
  4963. Expr *OrderedLoopCountExpr,
  4964. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  4965. LoopIterationSpace &ResultIterSpace,
  4966. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4967. // OpenMP [2.6, Canonical Loop Form]
  4968. // for (init-expr; test-expr; incr-expr) structured-block
  4969. auto *For = dyn_cast_or_null<ForStmt>(S);
  4970. if (!For) {
  4971. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
  4972. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  4973. << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
  4974. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  4975. if (TotalNestedLoopCount > 1) {
  4976. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  4977. SemaRef.Diag(DSA.getConstructLoc(),
  4978. diag::note_omp_collapse_ordered_expr)
  4979. << 2 << CollapseLoopCountExpr->getSourceRange()
  4980. << OrderedLoopCountExpr->getSourceRange();
  4981. else if (CollapseLoopCountExpr)
  4982. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4983. diag::note_omp_collapse_ordered_expr)
  4984. << 0 << CollapseLoopCountExpr->getSourceRange();
  4985. else
  4986. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4987. diag::note_omp_collapse_ordered_expr)
  4988. << 1 << OrderedLoopCountExpr->getSourceRange();
  4989. }
  4990. return true;
  4991. }
  4992. assert(For->getBody());
  4993. OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
  4994. // Check init.
  4995. Stmt *Init = For->getInit();
  4996. if (ISC.checkAndSetInit(Init))
  4997. return true;
  4998. bool HasErrors = false;
  4999. // Check loop variable's type.
  5000. if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
  5001. Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
  5002. // OpenMP [2.6, Canonical Loop Form]
  5003. // Var is one of the following:
  5004. // A variable of signed or unsigned integer type.
  5005. // For C++, a variable of a random access iterator type.
  5006. // For C, a variable of a pointer type.
  5007. QualType VarType = LCDecl->getType().getNonReferenceType();
  5008. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  5009. !VarType->isPointerType() &&
  5010. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  5011. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
  5012. << SemaRef.getLangOpts().CPlusPlus;
  5013. HasErrors = true;
  5014. }
  5015. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  5016. // a Construct
  5017. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  5018. // parallel for construct is (are) private.
  5019. // The loop iteration variable in the associated for-loop of a simd
  5020. // construct with just one associated for-loop is linear with a
  5021. // constant-linear-step that is the increment of the associated for-loop.
  5022. // Exclude loop var from the list of variables with implicitly defined data
  5023. // sharing attributes.
  5024. VarsWithImplicitDSA.erase(LCDecl);
  5025. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  5026. // in a Construct, C/C++].
  5027. // The loop iteration variable in the associated for-loop of a simd
  5028. // construct with just one associated for-loop may be listed in a linear
  5029. // clause with a constant-linear-step that is the increment of the
  5030. // associated for-loop.
  5031. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  5032. // parallel for construct may be listed in a private or lastprivate clause.
  5033. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
  5034. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  5035. // declared in the loop and it is predetermined as a private.
  5036. OpenMPClauseKind PredeterminedCKind =
  5037. isOpenMPSimdDirective(DKind)
  5038. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  5039. : OMPC_private;
  5040. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  5041. DVar.CKind != PredeterminedCKind) ||
  5042. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  5043. isOpenMPDistributeDirective(DKind)) &&
  5044. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  5045. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  5046. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  5047. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
  5048. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  5049. << getOpenMPClauseName(PredeterminedCKind);
  5050. if (DVar.RefExpr == nullptr)
  5051. DVar.CKind = PredeterminedCKind;
  5052. reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
  5053. HasErrors = true;
  5054. } else if (LoopDeclRefExpr != nullptr) {
  5055. // Make the loop iteration variable private (for worksharing constructs),
  5056. // linear (for simd directives with the only one associated loop) or
  5057. // lastprivate (for simd directives with several collapsed or ordered
  5058. // loops).
  5059. if (DVar.CKind == OMPC_unknown)
  5060. DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
  5061. }
  5062. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  5063. // Check test-expr.
  5064. HasErrors |= ISC.checkAndSetCond(For->getCond());
  5065. // Check incr-expr.
  5066. HasErrors |= ISC.checkAndSetInc(For->getInc());
  5067. }
  5068. if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  5069. return HasErrors;
  5070. // Build the loop's iteration space representation.
  5071. ResultIterSpace.PreCond =
  5072. ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
  5073. ResultIterSpace.NumIterations = ISC.buildNumIterations(
  5074. DSA.getCurScope(),
  5075. (isOpenMPWorksharingDirective(DKind) ||
  5076. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
  5077. Captures);
  5078. ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
  5079. ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
  5080. ResultIterSpace.CounterInit = ISC.buildCounterInit();
  5081. ResultIterSpace.CounterStep = ISC.buildCounterStep();
  5082. ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
  5083. ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
  5084. ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
  5085. ResultIterSpace.Subtract = ISC.shouldSubtractStep();
  5086. ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
  5087. HasErrors |= (ResultIterSpace.PreCond == nullptr ||
  5088. ResultIterSpace.NumIterations == nullptr ||
  5089. ResultIterSpace.CounterVar == nullptr ||
  5090. ResultIterSpace.PrivateCounterVar == nullptr ||
  5091. ResultIterSpace.CounterInit == nullptr ||
  5092. ResultIterSpace.CounterStep == nullptr);
  5093. if (!HasErrors && DSA.isOrderedRegion()) {
  5094. if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
  5095. if (CurrentNestedLoopCount <
  5096. DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
  5097. DSA.getOrderedRegionParam().second->setLoopNumIterations(
  5098. CurrentNestedLoopCount, ResultIterSpace.NumIterations);
  5099. DSA.getOrderedRegionParam().second->setLoopCounter(
  5100. CurrentNestedLoopCount, ResultIterSpace.CounterVar);
  5101. }
  5102. }
  5103. for (auto &Pair : DSA.getDoacrossDependClauses()) {
  5104. if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
  5105. // Erroneous case - clause has some problems.
  5106. continue;
  5107. }
  5108. if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
  5109. Pair.second.size() <= CurrentNestedLoopCount) {
  5110. // Erroneous case - clause has some problems.
  5111. Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
  5112. continue;
  5113. }
  5114. Expr *CntValue;
  5115. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  5116. CntValue = ISC.buildOrderedLoopData(
  5117. DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
  5118. Pair.first->getDependencyLoc());
  5119. else
  5120. CntValue = ISC.buildOrderedLoopData(
  5121. DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
  5122. Pair.first->getDependencyLoc(),
  5123. Pair.second[CurrentNestedLoopCount].first,
  5124. Pair.second[CurrentNestedLoopCount].second);
  5125. Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
  5126. }
  5127. }
  5128. return HasErrors;
  5129. }
  5130. /// Build 'VarRef = Start.
  5131. static ExprResult
  5132. buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  5133. ExprResult Start,
  5134. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  5135. // Build 'VarRef = Start.
  5136. ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
  5137. if (!NewStart.isUsable())
  5138. return ExprError();
  5139. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  5140. VarRef.get()->getType())) {
  5141. NewStart = SemaRef.PerformImplicitConversion(
  5142. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  5143. /*AllowExplicit=*/true);
  5144. if (!NewStart.isUsable())
  5145. return ExprError();
  5146. }
  5147. ExprResult Init =
  5148. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  5149. return Init;
  5150. }
  5151. /// Build 'VarRef = Start + Iter * Step'.
  5152. static ExprResult buildCounterUpdate(
  5153. Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  5154. ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
  5155. llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
  5156. // Add parentheses (for debugging purposes only).
  5157. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  5158. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  5159. !Step.isUsable())
  5160. return ExprError();
  5161. ExprResult NewStep = Step;
  5162. if (Captures)
  5163. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  5164. if (NewStep.isInvalid())
  5165. return ExprError();
  5166. ExprResult Update =
  5167. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  5168. if (!Update.isUsable())
  5169. return ExprError();
  5170. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  5171. // 'VarRef = Start (+|-) Iter * Step'.
  5172. ExprResult NewStart = Start;
  5173. if (Captures)
  5174. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  5175. if (NewStart.isInvalid())
  5176. return ExprError();
  5177. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  5178. ExprResult SavedUpdate = Update;
  5179. ExprResult UpdateVal;
  5180. if (VarRef.get()->getType()->isOverloadableType() ||
  5181. NewStart.get()->getType()->isOverloadableType() ||
  5182. Update.get()->getType()->isOverloadableType()) {
  5183. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  5184. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  5185. Update =
  5186. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  5187. if (Update.isUsable()) {
  5188. UpdateVal =
  5189. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  5190. VarRef.get(), SavedUpdate.get());
  5191. if (UpdateVal.isUsable()) {
  5192. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  5193. UpdateVal.get());
  5194. }
  5195. }
  5196. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  5197. }
  5198. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  5199. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  5200. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  5201. NewStart.get(), SavedUpdate.get());
  5202. if (!Update.isUsable())
  5203. return ExprError();
  5204. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  5205. VarRef.get()->getType())) {
  5206. Update = SemaRef.PerformImplicitConversion(
  5207. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  5208. if (!Update.isUsable())
  5209. return ExprError();
  5210. }
  5211. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  5212. }
  5213. return Update;
  5214. }
  5215. /// Convert integer expression \a E to make it have at least \a Bits
  5216. /// bits.
  5217. static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  5218. if (E == nullptr)
  5219. return ExprError();
  5220. ASTContext &C = SemaRef.Context;
  5221. QualType OldType = E->getType();
  5222. unsigned HasBits = C.getTypeSize(OldType);
  5223. if (HasBits >= Bits)
  5224. return ExprResult(E);
  5225. // OK to convert to signed, because new type has more bits than old.
  5226. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  5227. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  5228. true);
  5229. }
  5230. /// Check if the given expression \a E is a constant integer that fits
  5231. /// into \a Bits bits.
  5232. static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
  5233. if (E == nullptr)
  5234. return false;
  5235. llvm::APSInt Result;
  5236. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  5237. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  5238. return false;
  5239. }
  5240. /// Build preinits statement for the given declarations.
  5241. static Stmt *buildPreInits(ASTContext &Context,
  5242. MutableArrayRef<Decl *> PreInits) {
  5243. if (!PreInits.empty()) {
  5244. return new (Context) DeclStmt(
  5245. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  5246. SourceLocation(), SourceLocation());
  5247. }
  5248. return nullptr;
  5249. }
  5250. /// Build preinits statement for the given declarations.
  5251. static Stmt *
  5252. buildPreInits(ASTContext &Context,
  5253. const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  5254. if (!Captures.empty()) {
  5255. SmallVector<Decl *, 16> PreInits;
  5256. for (const auto &Pair : Captures)
  5257. PreInits.push_back(Pair.second->getDecl());
  5258. return buildPreInits(Context, PreInits);
  5259. }
  5260. return nullptr;
  5261. }
  5262. /// Build postupdate expression for the given list of postupdates expressions.
  5263. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  5264. Expr *PostUpdate = nullptr;
  5265. if (!PostUpdates.empty()) {
  5266. for (Expr *E : PostUpdates) {
  5267. Expr *ConvE = S.BuildCStyleCastExpr(
  5268. E->getExprLoc(),
  5269. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  5270. E->getExprLoc(), E)
  5271. .get();
  5272. PostUpdate = PostUpdate
  5273. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  5274. PostUpdate, ConvE)
  5275. .get()
  5276. : ConvE;
  5277. }
  5278. }
  5279. return PostUpdate;
  5280. }
  5281. /// Called on a for stmt to check itself and nested loops (if any).
  5282. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  5283. /// number of collapsed loops otherwise.
  5284. static unsigned
  5285. checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  5286. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  5287. DSAStackTy &DSA,
  5288. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  5289. OMPLoopDirective::HelperExprs &Built) {
  5290. unsigned NestedLoopCount = 1;
  5291. if (CollapseLoopCountExpr) {
  5292. // Found 'collapse' clause - calculate collapse number.
  5293. Expr::EvalResult Result;
  5294. if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
  5295. NestedLoopCount = Result.Val.getInt().getLimitedValue();
  5296. }
  5297. unsigned OrderedLoopCount = 1;
  5298. if (OrderedLoopCountExpr) {
  5299. // Found 'ordered' clause - calculate collapse number.
  5300. Expr::EvalResult EVResult;
  5301. if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
  5302. llvm::APSInt Result = EVResult.Val.getInt();
  5303. if (Result.getLimitedValue() < NestedLoopCount) {
  5304. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  5305. diag::err_omp_wrong_ordered_loop_count)
  5306. << OrderedLoopCountExpr->getSourceRange();
  5307. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  5308. diag::note_collapse_loop_count)
  5309. << CollapseLoopCountExpr->getSourceRange();
  5310. }
  5311. OrderedLoopCount = Result.getLimitedValue();
  5312. }
  5313. }
  5314. // This is helper routine for loop directives (e.g., 'for', 'simd',
  5315. // 'for simd', etc.).
  5316. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  5317. SmallVector<LoopIterationSpace, 4> IterSpaces(
  5318. std::max(OrderedLoopCount, NestedLoopCount));
  5319. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  5320. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  5321. if (checkOpenMPIterationSpace(
  5322. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  5323. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  5324. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
  5325. Captures))
  5326. return 0;
  5327. // Move on to the next nested for loop, or to the loop body.
  5328. // OpenMP [2.8.1, simd construct, Restrictions]
  5329. // All loops associated with the construct must be perfectly nested; that
  5330. // is, there must be no intervening code nor any OpenMP directive between
  5331. // any two loops.
  5332. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  5333. }
  5334. for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
  5335. if (checkOpenMPIterationSpace(
  5336. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  5337. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  5338. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
  5339. Captures))
  5340. return 0;
  5341. if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
  5342. // Handle initialization of captured loop iterator variables.
  5343. auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
  5344. if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
  5345. Captures[DRE] = DRE;
  5346. }
  5347. }
  5348. // Move on to the next nested for loop, or to the loop body.
  5349. // OpenMP [2.8.1, simd construct, Restrictions]
  5350. // All loops associated with the construct must be perfectly nested; that
  5351. // is, there must be no intervening code nor any OpenMP directive between
  5352. // any two loops.
  5353. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  5354. }
  5355. Built.clear(/* size */ NestedLoopCount);
  5356. if (SemaRef.CurContext->isDependentContext())
  5357. return NestedLoopCount;
  5358. // An example of what is generated for the following code:
  5359. //
  5360. // #pragma omp simd collapse(2) ordered(2)
  5361. // for (i = 0; i < NI; ++i)
  5362. // for (k = 0; k < NK; ++k)
  5363. // for (j = J0; j < NJ; j+=2) {
  5364. // <loop body>
  5365. // }
  5366. //
  5367. // We generate the code below.
  5368. // Note: the loop body may be outlined in CodeGen.
  5369. // Note: some counters may be C++ classes, operator- is used to find number of
  5370. // iterations and operator+= to calculate counter value.
  5371. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  5372. // or i64 is currently supported).
  5373. //
  5374. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  5375. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  5376. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  5377. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  5378. // // similar updates for vars in clauses (e.g. 'linear')
  5379. // <loop body (using local i and j)>
  5380. // }
  5381. // i = NI; // assign final values of counters
  5382. // j = NJ;
  5383. //
  5384. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  5385. // the iteration counts of the collapsed for loops.
  5386. // Precondition tests if there is at least one iteration (all conditions are
  5387. // true).
  5388. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  5389. Expr *N0 = IterSpaces[0].NumIterations;
  5390. ExprResult LastIteration32 =
  5391. widenIterationCount(/*Bits=*/32,
  5392. SemaRef
  5393. .PerformImplicitConversion(
  5394. N0->IgnoreImpCasts(), N0->getType(),
  5395. Sema::AA_Converting, /*AllowExplicit=*/true)
  5396. .get(),
  5397. SemaRef);
  5398. ExprResult LastIteration64 = widenIterationCount(
  5399. /*Bits=*/64,
  5400. SemaRef
  5401. .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
  5402. Sema::AA_Converting,
  5403. /*AllowExplicit=*/true)
  5404. .get(),
  5405. SemaRef);
  5406. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  5407. return NestedLoopCount;
  5408. ASTContext &C = SemaRef.Context;
  5409. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  5410. Scope *CurScope = DSA.getCurScope();
  5411. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  5412. if (PreCond.isUsable()) {
  5413. PreCond =
  5414. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  5415. PreCond.get(), IterSpaces[Cnt].PreCond);
  5416. }
  5417. Expr *N = IterSpaces[Cnt].NumIterations;
  5418. SourceLocation Loc = N->getExprLoc();
  5419. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  5420. if (LastIteration32.isUsable())
  5421. LastIteration32 = SemaRef.BuildBinOp(
  5422. CurScope, Loc, BO_Mul, LastIteration32.get(),
  5423. SemaRef
  5424. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  5425. Sema::AA_Converting,
  5426. /*AllowExplicit=*/true)
  5427. .get());
  5428. if (LastIteration64.isUsable())
  5429. LastIteration64 = SemaRef.BuildBinOp(
  5430. CurScope, Loc, BO_Mul, LastIteration64.get(),
  5431. SemaRef
  5432. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  5433. Sema::AA_Converting,
  5434. /*AllowExplicit=*/true)
  5435. .get());
  5436. }
  5437. // Choose either the 32-bit or 64-bit version.
  5438. ExprResult LastIteration = LastIteration64;
  5439. if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
  5440. (LastIteration32.isUsable() &&
  5441. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  5442. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  5443. fitsInto(
  5444. /*Bits=*/32,
  5445. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  5446. LastIteration64.get(), SemaRef))))
  5447. LastIteration = LastIteration32;
  5448. QualType VType = LastIteration.get()->getType();
  5449. QualType RealVType = VType;
  5450. QualType StrideVType = VType;
  5451. if (isOpenMPTaskLoopDirective(DKind)) {
  5452. VType =
  5453. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  5454. StrideVType =
  5455. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  5456. }
  5457. if (!LastIteration.isUsable())
  5458. return 0;
  5459. // Save the number of iterations.
  5460. ExprResult NumIterations = LastIteration;
  5461. {
  5462. LastIteration = SemaRef.BuildBinOp(
  5463. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  5464. LastIteration.get(),
  5465. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5466. if (!LastIteration.isUsable())
  5467. return 0;
  5468. }
  5469. // Calculate the last iteration number beforehand instead of doing this on
  5470. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  5471. llvm::APSInt Result;
  5472. bool IsConstant =
  5473. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  5474. ExprResult CalcLastIteration;
  5475. if (!IsConstant) {
  5476. ExprResult SaveRef =
  5477. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  5478. LastIteration = SaveRef;
  5479. // Prepare SaveRef + 1.
  5480. NumIterations = SemaRef.BuildBinOp(
  5481. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  5482. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5483. if (!NumIterations.isUsable())
  5484. return 0;
  5485. }
  5486. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  5487. // Build variables passed into runtime, necessary for worksharing directives.
  5488. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  5489. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  5490. isOpenMPDistributeDirective(DKind)) {
  5491. // Lower bound variable, initialized with zero.
  5492. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  5493. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  5494. SemaRef.AddInitializerToDecl(LBDecl,
  5495. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  5496. /*DirectInit*/ false);
  5497. // Upper bound variable, initialized with last iteration number.
  5498. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  5499. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  5500. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  5501. /*DirectInit*/ false);
  5502. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  5503. // This will be used to implement clause 'lastprivate'.
  5504. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  5505. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  5506. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  5507. SemaRef.AddInitializerToDecl(ILDecl,
  5508. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  5509. /*DirectInit*/ false);
  5510. // Stride variable returned by runtime (we initialize it to 1 by default).
  5511. VarDecl *STDecl =
  5512. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  5513. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  5514. SemaRef.AddInitializerToDecl(STDecl,
  5515. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  5516. /*DirectInit*/ false);
  5517. // Build expression: UB = min(UB, LastIteration)
  5518. // It is necessary for CodeGen of directives with static scheduling.
  5519. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  5520. UB.get(), LastIteration.get());
  5521. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  5522. LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
  5523. LastIteration.get(), UB.get());
  5524. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  5525. CondOp.get());
  5526. EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
  5527. // If we have a combined directive that combines 'distribute', 'for' or
  5528. // 'simd' we need to be able to access the bounds of the schedule of the
  5529. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  5530. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  5531. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5532. // Lower bound variable, initialized with zero.
  5533. VarDecl *CombLBDecl =
  5534. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  5535. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  5536. SemaRef.AddInitializerToDecl(
  5537. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  5538. /*DirectInit*/ false);
  5539. // Upper bound variable, initialized with last iteration number.
  5540. VarDecl *CombUBDecl =
  5541. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  5542. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  5543. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  5544. /*DirectInit*/ false);
  5545. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  5546. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  5547. ExprResult CombCondOp =
  5548. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  5549. LastIteration.get(), CombUB.get());
  5550. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  5551. CombCondOp.get());
  5552. CombEUB =
  5553. SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
  5554. const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  5555. // We expect to have at least 2 more parameters than the 'parallel'
  5556. // directive does - the lower and upper bounds of the previous schedule.
  5557. assert(CD->getNumParams() >= 4 &&
  5558. "Unexpected number of parameters in loop combined directive");
  5559. // Set the proper type for the bounds given what we learned from the
  5560. // enclosed loops.
  5561. ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  5562. ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  5563. // Previous lower and upper bounds are obtained from the region
  5564. // parameters.
  5565. PrevLB =
  5566. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  5567. PrevUB =
  5568. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  5569. }
  5570. }
  5571. // Build the iteration variable and its initialization before loop.
  5572. ExprResult IV;
  5573. ExprResult Init, CombInit;
  5574. {
  5575. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  5576. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  5577. Expr *RHS =
  5578. (isOpenMPWorksharingDirective(DKind) ||
  5579. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  5580. ? LB.get()
  5581. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  5582. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  5583. Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
  5584. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5585. Expr *CombRHS =
  5586. (isOpenMPWorksharingDirective(DKind) ||
  5587. isOpenMPTaskLoopDirective(DKind) ||
  5588. isOpenMPDistributeDirective(DKind))
  5589. ? CombLB.get()
  5590. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  5591. CombInit =
  5592. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  5593. CombInit =
  5594. SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
  5595. }
  5596. }
  5597. bool UseStrictCompare =
  5598. RealVType->hasUnsignedIntegerRepresentation() &&
  5599. llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
  5600. return LIS.IsStrictCompare;
  5601. });
  5602. // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
  5603. // unsigned IV)) for worksharing loops.
  5604. SourceLocation CondLoc = AStmt->getBeginLoc();
  5605. Expr *BoundUB = UB.get();
  5606. if (UseStrictCompare) {
  5607. BoundUB =
  5608. SemaRef
  5609. .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
  5610. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  5611. .get();
  5612. BoundUB =
  5613. SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
  5614. }
  5615. ExprResult Cond =
  5616. (isOpenMPWorksharingDirective(DKind) ||
  5617. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  5618. ? SemaRef.BuildBinOp(CurScope, CondLoc,
  5619. UseStrictCompare ? BO_LT : BO_LE, IV.get(),
  5620. BoundUB)
  5621. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  5622. NumIterations.get());
  5623. ExprResult CombDistCond;
  5624. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5625. CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  5626. NumIterations.get());
  5627. }
  5628. ExprResult CombCond;
  5629. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5630. Expr *BoundCombUB = CombUB.get();
  5631. if (UseStrictCompare) {
  5632. BoundCombUB =
  5633. SemaRef
  5634. .BuildBinOp(
  5635. CurScope, CondLoc, BO_Add, BoundCombUB,
  5636. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  5637. .get();
  5638. BoundCombUB =
  5639. SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
  5640. .get();
  5641. }
  5642. CombCond =
  5643. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  5644. IV.get(), BoundCombUB);
  5645. }
  5646. // Loop increment (IV = IV + 1)
  5647. SourceLocation IncLoc = AStmt->getBeginLoc();
  5648. ExprResult Inc =
  5649. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  5650. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  5651. if (!Inc.isUsable())
  5652. return 0;
  5653. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  5654. Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
  5655. if (!Inc.isUsable())
  5656. return 0;
  5657. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  5658. // Used for directives with static scheduling.
  5659. // In combined construct, add combined version that use CombLB and CombUB
  5660. // base variables for the update
  5661. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  5662. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  5663. isOpenMPDistributeDirective(DKind)) {
  5664. // LB + ST
  5665. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  5666. if (!NextLB.isUsable())
  5667. return 0;
  5668. // LB = LB + ST
  5669. NextLB =
  5670. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  5671. NextLB =
  5672. SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
  5673. if (!NextLB.isUsable())
  5674. return 0;
  5675. // UB + ST
  5676. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  5677. if (!NextUB.isUsable())
  5678. return 0;
  5679. // UB = UB + ST
  5680. NextUB =
  5681. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  5682. NextUB =
  5683. SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
  5684. if (!NextUB.isUsable())
  5685. return 0;
  5686. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5687. CombNextLB =
  5688. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  5689. if (!NextLB.isUsable())
  5690. return 0;
  5691. // LB = LB + ST
  5692. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  5693. CombNextLB.get());
  5694. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
  5695. /*DiscardedValue*/ false);
  5696. if (!CombNextLB.isUsable())
  5697. return 0;
  5698. // UB + ST
  5699. CombNextUB =
  5700. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  5701. if (!CombNextUB.isUsable())
  5702. return 0;
  5703. // UB = UB + ST
  5704. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  5705. CombNextUB.get());
  5706. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
  5707. /*DiscardedValue*/ false);
  5708. if (!CombNextUB.isUsable())
  5709. return 0;
  5710. }
  5711. }
  5712. // Create increment expression for distribute loop when combined in a same
  5713. // directive with for as IV = IV + ST; ensure upper bound expression based
  5714. // on PrevUB instead of NumIterations - used to implement 'for' when found
  5715. // in combination with 'distribute', like in 'distribute parallel for'
  5716. SourceLocation DistIncLoc = AStmt->getBeginLoc();
  5717. ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
  5718. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5719. DistCond = SemaRef.BuildBinOp(
  5720. CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
  5721. assert(DistCond.isUsable() && "distribute cond expr was not built");
  5722. DistInc =
  5723. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  5724. assert(DistInc.isUsable() && "distribute inc expr was not built");
  5725. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  5726. DistInc.get());
  5727. DistInc =
  5728. SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
  5729. assert(DistInc.isUsable() && "distribute inc expr was not built");
  5730. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  5731. // construct
  5732. SourceLocation DistEUBLoc = AStmt->getBeginLoc();
  5733. ExprResult IsUBGreater =
  5734. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  5735. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  5736. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  5737. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  5738. CondOp.get());
  5739. PrevEUB =
  5740. SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
  5741. // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
  5742. // parallel for is in combination with a distribute directive with
  5743. // schedule(static, 1)
  5744. Expr *BoundPrevUB = PrevUB.get();
  5745. if (UseStrictCompare) {
  5746. BoundPrevUB =
  5747. SemaRef
  5748. .BuildBinOp(
  5749. CurScope, CondLoc, BO_Add, BoundPrevUB,
  5750. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  5751. .get();
  5752. BoundPrevUB =
  5753. SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
  5754. .get();
  5755. }
  5756. ParForInDistCond =
  5757. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  5758. IV.get(), BoundPrevUB);
  5759. }
  5760. // Build updates and final values of the loop counters.
  5761. bool HasErrors = false;
  5762. Built.Counters.resize(NestedLoopCount);
  5763. Built.Inits.resize(NestedLoopCount);
  5764. Built.Updates.resize(NestedLoopCount);
  5765. Built.Finals.resize(NestedLoopCount);
  5766. {
  5767. // We implement the following algorithm for obtaining the
  5768. // original loop iteration variable values based on the
  5769. // value of the collapsed loop iteration variable IV.
  5770. //
  5771. // Let n+1 be the number of collapsed loops in the nest.
  5772. // Iteration variables (I0, I1, .... In)
  5773. // Iteration counts (N0, N1, ... Nn)
  5774. //
  5775. // Acc = IV;
  5776. //
  5777. // To compute Ik for loop k, 0 <= k <= n, generate:
  5778. // Prod = N(k+1) * N(k+2) * ... * Nn;
  5779. // Ik = Acc / Prod;
  5780. // Acc -= Ik * Prod;
  5781. //
  5782. ExprResult Acc = IV;
  5783. for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  5784. LoopIterationSpace &IS = IterSpaces[Cnt];
  5785. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  5786. ExprResult Iter;
  5787. // Compute prod
  5788. ExprResult Prod =
  5789. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  5790. for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
  5791. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
  5792. IterSpaces[K].NumIterations);
  5793. // Iter = Acc / Prod
  5794. // If there is at least one more inner loop to avoid
  5795. // multiplication by 1.
  5796. if (Cnt + 1 < NestedLoopCount)
  5797. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
  5798. Acc.get(), Prod.get());
  5799. else
  5800. Iter = Acc;
  5801. if (!Iter.isUsable()) {
  5802. HasErrors = true;
  5803. break;
  5804. }
  5805. // Update Acc:
  5806. // Acc -= Iter * Prod
  5807. // Check if there is at least one more inner loop to avoid
  5808. // multiplication by 1.
  5809. if (Cnt + 1 < NestedLoopCount)
  5810. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
  5811. Iter.get(), Prod.get());
  5812. else
  5813. Prod = Iter;
  5814. Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
  5815. Acc.get(), Prod.get());
  5816. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  5817. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  5818. DeclRefExpr *CounterVar = buildDeclRefExpr(
  5819. SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  5820. /*RefersToCapture=*/true);
  5821. ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  5822. IS.CounterInit, Captures);
  5823. if (!Init.isUsable()) {
  5824. HasErrors = true;
  5825. break;
  5826. }
  5827. ExprResult Update = buildCounterUpdate(
  5828. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  5829. IS.CounterStep, IS.Subtract, &Captures);
  5830. if (!Update.isUsable()) {
  5831. HasErrors = true;
  5832. break;
  5833. }
  5834. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  5835. ExprResult Final = buildCounterUpdate(
  5836. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
  5837. IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
  5838. if (!Final.isUsable()) {
  5839. HasErrors = true;
  5840. break;
  5841. }
  5842. if (!Update.isUsable() || !Final.isUsable()) {
  5843. HasErrors = true;
  5844. break;
  5845. }
  5846. // Save results
  5847. Built.Counters[Cnt] = IS.CounterVar;
  5848. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  5849. Built.Inits[Cnt] = Init.get();
  5850. Built.Updates[Cnt] = Update.get();
  5851. Built.Finals[Cnt] = Final.get();
  5852. }
  5853. }
  5854. if (HasErrors)
  5855. return 0;
  5856. // Save results
  5857. Built.IterationVarRef = IV.get();
  5858. Built.LastIteration = LastIteration.get();
  5859. Built.NumIterations = NumIterations.get();
  5860. Built.CalcLastIteration = SemaRef
  5861. .ActOnFinishFullExpr(CalcLastIteration.get(),
  5862. /*DiscardedValue*/ false)
  5863. .get();
  5864. Built.PreCond = PreCond.get();
  5865. Built.PreInits = buildPreInits(C, Captures);
  5866. Built.Cond = Cond.get();
  5867. Built.Init = Init.get();
  5868. Built.Inc = Inc.get();
  5869. Built.LB = LB.get();
  5870. Built.UB = UB.get();
  5871. Built.IL = IL.get();
  5872. Built.ST = ST.get();
  5873. Built.EUB = EUB.get();
  5874. Built.NLB = NextLB.get();
  5875. Built.NUB = NextUB.get();
  5876. Built.PrevLB = PrevLB.get();
  5877. Built.PrevUB = PrevUB.get();
  5878. Built.DistInc = DistInc.get();
  5879. Built.PrevEUB = PrevEUB.get();
  5880. Built.DistCombinedFields.LB = CombLB.get();
  5881. Built.DistCombinedFields.UB = CombUB.get();
  5882. Built.DistCombinedFields.EUB = CombEUB.get();
  5883. Built.DistCombinedFields.Init = CombInit.get();
  5884. Built.DistCombinedFields.Cond = CombCond.get();
  5885. Built.DistCombinedFields.NLB = CombNextLB.get();
  5886. Built.DistCombinedFields.NUB = CombNextUB.get();
  5887. Built.DistCombinedFields.DistCond = CombDistCond.get();
  5888. Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
  5889. return NestedLoopCount;
  5890. }
  5891. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  5892. auto CollapseClauses =
  5893. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  5894. if (CollapseClauses.begin() != CollapseClauses.end())
  5895. return (*CollapseClauses.begin())->getNumForLoops();
  5896. return nullptr;
  5897. }
  5898. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  5899. auto OrderedClauses =
  5900. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  5901. if (OrderedClauses.begin() != OrderedClauses.end())
  5902. return (*OrderedClauses.begin())->getNumForLoops();
  5903. return nullptr;
  5904. }
  5905. static bool checkSimdlenSafelenSpecified(Sema &S,
  5906. const ArrayRef<OMPClause *> Clauses) {
  5907. const OMPSafelenClause *Safelen = nullptr;
  5908. const OMPSimdlenClause *Simdlen = nullptr;
  5909. for (const OMPClause *Clause : Clauses) {
  5910. if (Clause->getClauseKind() == OMPC_safelen)
  5911. Safelen = cast<OMPSafelenClause>(Clause);
  5912. else if (Clause->getClauseKind() == OMPC_simdlen)
  5913. Simdlen = cast<OMPSimdlenClause>(Clause);
  5914. if (Safelen && Simdlen)
  5915. break;
  5916. }
  5917. if (Simdlen && Safelen) {
  5918. const Expr *SimdlenLength = Simdlen->getSimdlen();
  5919. const Expr *SafelenLength = Safelen->getSafelen();
  5920. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  5921. SimdlenLength->isInstantiationDependent() ||
  5922. SimdlenLength->containsUnexpandedParameterPack())
  5923. return false;
  5924. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  5925. SafelenLength->isInstantiationDependent() ||
  5926. SafelenLength->containsUnexpandedParameterPack())
  5927. return false;
  5928. Expr::EvalResult SimdlenResult, SafelenResult;
  5929. SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
  5930. SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
  5931. llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
  5932. llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
  5933. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  5934. // If both simdlen and safelen clauses are specified, the value of the
  5935. // simdlen parameter must be less than or equal to the value of the safelen
  5936. // parameter.
  5937. if (SimdlenRes > SafelenRes) {
  5938. S.Diag(SimdlenLength->getExprLoc(),
  5939. diag::err_omp_wrong_simdlen_safelen_values)
  5940. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  5941. return true;
  5942. }
  5943. }
  5944. return false;
  5945. }
  5946. StmtResult
  5947. Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  5948. SourceLocation StartLoc, SourceLocation EndLoc,
  5949. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5950. if (!AStmt)
  5951. return StmtError();
  5952. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5953. OMPLoopDirective::HelperExprs B;
  5954. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5955. // define the nested loops number.
  5956. unsigned NestedLoopCount = checkOpenMPLoop(
  5957. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  5958. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  5959. if (NestedLoopCount == 0)
  5960. return StmtError();
  5961. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5962. "omp simd loop exprs were not built");
  5963. if (!CurContext->isDependentContext()) {
  5964. // Finalize the clauses that need pre-built expressions for CodeGen.
  5965. for (OMPClause *C : Clauses) {
  5966. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5967. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5968. B.NumIterations, *this, CurScope,
  5969. DSAStack))
  5970. return StmtError();
  5971. }
  5972. }
  5973. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5974. return StmtError();
  5975. setFunctionHasBranchProtectedScope();
  5976. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5977. Clauses, AStmt, B);
  5978. }
  5979. StmtResult
  5980. Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  5981. SourceLocation StartLoc, SourceLocation EndLoc,
  5982. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5983. if (!AStmt)
  5984. return StmtError();
  5985. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5986. OMPLoopDirective::HelperExprs B;
  5987. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5988. // define the nested loops number.
  5989. unsigned NestedLoopCount = checkOpenMPLoop(
  5990. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  5991. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  5992. if (NestedLoopCount == 0)
  5993. return StmtError();
  5994. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5995. "omp for loop exprs were not built");
  5996. if (!CurContext->isDependentContext()) {
  5997. // Finalize the clauses that need pre-built expressions for CodeGen.
  5998. for (OMPClause *C : Clauses) {
  5999. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6000. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6001. B.NumIterations, *this, CurScope,
  6002. DSAStack))
  6003. return StmtError();
  6004. }
  6005. }
  6006. setFunctionHasBranchProtectedScope();
  6007. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  6008. Clauses, AStmt, B, DSAStack->isCancelRegion());
  6009. }
  6010. StmtResult Sema::ActOnOpenMPForSimdDirective(
  6011. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6012. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6013. if (!AStmt)
  6014. return StmtError();
  6015. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6016. OMPLoopDirective::HelperExprs B;
  6017. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6018. // define the nested loops number.
  6019. unsigned NestedLoopCount =
  6020. checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  6021. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  6022. VarsWithImplicitDSA, B);
  6023. if (NestedLoopCount == 0)
  6024. return StmtError();
  6025. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6026. "omp for simd loop exprs were not built");
  6027. if (!CurContext->isDependentContext()) {
  6028. // Finalize the clauses that need pre-built expressions for CodeGen.
  6029. for (OMPClause *C : Clauses) {
  6030. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6031. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6032. B.NumIterations, *this, CurScope,
  6033. DSAStack))
  6034. return StmtError();
  6035. }
  6036. }
  6037. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6038. return StmtError();
  6039. setFunctionHasBranchProtectedScope();
  6040. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  6041. Clauses, AStmt, B);
  6042. }
  6043. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  6044. Stmt *AStmt,
  6045. SourceLocation StartLoc,
  6046. SourceLocation EndLoc) {
  6047. if (!AStmt)
  6048. return StmtError();
  6049. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6050. auto BaseStmt = AStmt;
  6051. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  6052. BaseStmt = CS->getCapturedStmt();
  6053. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  6054. auto S = C->children();
  6055. if (S.begin() == S.end())
  6056. return StmtError();
  6057. // All associated statements must be '#pragma omp section' except for
  6058. // the first one.
  6059. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  6060. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  6061. if (SectionStmt)
  6062. Diag(SectionStmt->getBeginLoc(),
  6063. diag::err_omp_sections_substmt_not_section);
  6064. return StmtError();
  6065. }
  6066. cast<OMPSectionDirective>(SectionStmt)
  6067. ->setHasCancel(DSAStack->isCancelRegion());
  6068. }
  6069. } else {
  6070. Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
  6071. return StmtError();
  6072. }
  6073. setFunctionHasBranchProtectedScope();
  6074. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  6075. DSAStack->isCancelRegion());
  6076. }
  6077. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  6078. SourceLocation StartLoc,
  6079. SourceLocation EndLoc) {
  6080. if (!AStmt)
  6081. return StmtError();
  6082. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6083. setFunctionHasBranchProtectedScope();
  6084. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  6085. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  6086. DSAStack->isCancelRegion());
  6087. }
  6088. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  6089. Stmt *AStmt,
  6090. SourceLocation StartLoc,
  6091. SourceLocation EndLoc) {
  6092. if (!AStmt)
  6093. return StmtError();
  6094. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6095. setFunctionHasBranchProtectedScope();
  6096. // OpenMP [2.7.3, single Construct, Restrictions]
  6097. // The copyprivate clause must not be used with the nowait clause.
  6098. const OMPClause *Nowait = nullptr;
  6099. const OMPClause *Copyprivate = nullptr;
  6100. for (const OMPClause *Clause : Clauses) {
  6101. if (Clause->getClauseKind() == OMPC_nowait)
  6102. Nowait = Clause;
  6103. else if (Clause->getClauseKind() == OMPC_copyprivate)
  6104. Copyprivate = Clause;
  6105. if (Copyprivate && Nowait) {
  6106. Diag(Copyprivate->getBeginLoc(),
  6107. diag::err_omp_single_copyprivate_with_nowait);
  6108. Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
  6109. return StmtError();
  6110. }
  6111. }
  6112. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6113. }
  6114. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  6115. SourceLocation StartLoc,
  6116. SourceLocation EndLoc) {
  6117. if (!AStmt)
  6118. return StmtError();
  6119. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6120. setFunctionHasBranchProtectedScope();
  6121. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  6122. }
  6123. StmtResult Sema::ActOnOpenMPCriticalDirective(
  6124. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  6125. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  6126. if (!AStmt)
  6127. return StmtError();
  6128. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6129. bool ErrorFound = false;
  6130. llvm::APSInt Hint;
  6131. SourceLocation HintLoc;
  6132. bool DependentHint = false;
  6133. for (const OMPClause *C : Clauses) {
  6134. if (C->getClauseKind() == OMPC_hint) {
  6135. if (!DirName.getName()) {
  6136. Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
  6137. ErrorFound = true;
  6138. }
  6139. Expr *E = cast<OMPHintClause>(C)->getHint();
  6140. if (E->isTypeDependent() || E->isValueDependent() ||
  6141. E->isInstantiationDependent()) {
  6142. DependentHint = true;
  6143. } else {
  6144. Hint = E->EvaluateKnownConstInt(Context);
  6145. HintLoc = C->getBeginLoc();
  6146. }
  6147. }
  6148. }
  6149. if (ErrorFound)
  6150. return StmtError();
  6151. const auto Pair = DSAStack->getCriticalWithHint(DirName);
  6152. if (Pair.first && DirName.getName() && !DependentHint) {
  6153. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  6154. Diag(StartLoc, diag::err_omp_critical_with_hint);
  6155. if (HintLoc.isValid())
  6156. Diag(HintLoc, diag::note_omp_critical_hint_here)
  6157. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  6158. else
  6159. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  6160. if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  6161. Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
  6162. << 1
  6163. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  6164. /*Radix=*/10, /*Signed=*/false);
  6165. } else {
  6166. Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
  6167. }
  6168. }
  6169. }
  6170. setFunctionHasBranchProtectedScope();
  6171. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  6172. Clauses, AStmt);
  6173. if (!Pair.first && DirName.getName() && !DependentHint)
  6174. DSAStack->addCriticalWithHint(Dir, Hint);
  6175. return Dir;
  6176. }
  6177. StmtResult Sema::ActOnOpenMPParallelForDirective(
  6178. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6179. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6180. if (!AStmt)
  6181. return StmtError();
  6182. auto *CS = cast<CapturedStmt>(AStmt);
  6183. // 1.2.2 OpenMP Language Terminology
  6184. // Structured block - An executable statement with a single entry at the
  6185. // top and a single exit at the bottom.
  6186. // The point of exit cannot be a branch out of the structured block.
  6187. // longjmp() and throw() must not violate the entry/exit criteria.
  6188. CS->getCapturedDecl()->setNothrow();
  6189. OMPLoopDirective::HelperExprs B;
  6190. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6191. // define the nested loops number.
  6192. unsigned NestedLoopCount =
  6193. checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  6194. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  6195. VarsWithImplicitDSA, B);
  6196. if (NestedLoopCount == 0)
  6197. return StmtError();
  6198. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6199. "omp parallel for loop exprs were not built");
  6200. if (!CurContext->isDependentContext()) {
  6201. // Finalize the clauses that need pre-built expressions for CodeGen.
  6202. for (OMPClause *C : Clauses) {
  6203. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6204. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6205. B.NumIterations, *this, CurScope,
  6206. DSAStack))
  6207. return StmtError();
  6208. }
  6209. }
  6210. setFunctionHasBranchProtectedScope();
  6211. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  6212. NestedLoopCount, Clauses, AStmt, B,
  6213. DSAStack->isCancelRegion());
  6214. }
  6215. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  6216. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6217. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6218. if (!AStmt)
  6219. return StmtError();
  6220. auto *CS = cast<CapturedStmt>(AStmt);
  6221. // 1.2.2 OpenMP Language Terminology
  6222. // Structured block - An executable statement with a single entry at the
  6223. // top and a single exit at the bottom.
  6224. // The point of exit cannot be a branch out of the structured block.
  6225. // longjmp() and throw() must not violate the entry/exit criteria.
  6226. CS->getCapturedDecl()->setNothrow();
  6227. OMPLoopDirective::HelperExprs B;
  6228. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6229. // define the nested loops number.
  6230. unsigned NestedLoopCount =
  6231. checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  6232. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  6233. VarsWithImplicitDSA, B);
  6234. if (NestedLoopCount == 0)
  6235. return StmtError();
  6236. if (!CurContext->isDependentContext()) {
  6237. // Finalize the clauses that need pre-built expressions for CodeGen.
  6238. for (OMPClause *C : Clauses) {
  6239. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6240. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6241. B.NumIterations, *this, CurScope,
  6242. DSAStack))
  6243. return StmtError();
  6244. }
  6245. }
  6246. if (checkSimdlenSafelenSpecified(*this, Clauses))
  6247. return StmtError();
  6248. setFunctionHasBranchProtectedScope();
  6249. return OMPParallelForSimdDirective::Create(
  6250. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  6251. }
  6252. StmtResult
  6253. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  6254. Stmt *AStmt, SourceLocation StartLoc,
  6255. SourceLocation EndLoc) {
  6256. if (!AStmt)
  6257. return StmtError();
  6258. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6259. auto BaseStmt = AStmt;
  6260. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  6261. BaseStmt = CS->getCapturedStmt();
  6262. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  6263. auto S = C->children();
  6264. if (S.begin() == S.end())
  6265. return StmtError();
  6266. // All associated statements must be '#pragma omp section' except for
  6267. // the first one.
  6268. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  6269. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  6270. if (SectionStmt)
  6271. Diag(SectionStmt->getBeginLoc(),
  6272. diag::err_omp_parallel_sections_substmt_not_section);
  6273. return StmtError();
  6274. }
  6275. cast<OMPSectionDirective>(SectionStmt)
  6276. ->setHasCancel(DSAStack->isCancelRegion());
  6277. }
  6278. } else {
  6279. Diag(AStmt->getBeginLoc(),
  6280. diag::err_omp_parallel_sections_not_compound_stmt);
  6281. return StmtError();
  6282. }
  6283. setFunctionHasBranchProtectedScope();
  6284. return OMPParallelSectionsDirective::Create(
  6285. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  6286. }
  6287. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  6288. Stmt *AStmt, SourceLocation StartLoc,
  6289. SourceLocation EndLoc) {
  6290. if (!AStmt)
  6291. return StmtError();
  6292. auto *CS = cast<CapturedStmt>(AStmt);
  6293. // 1.2.2 OpenMP Language Terminology
  6294. // Structured block - An executable statement with a single entry at the
  6295. // top and a single exit at the bottom.
  6296. // The point of exit cannot be a branch out of the structured block.
  6297. // longjmp() and throw() must not violate the entry/exit criteria.
  6298. CS->getCapturedDecl()->setNothrow();
  6299. setFunctionHasBranchProtectedScope();
  6300. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  6301. DSAStack->isCancelRegion());
  6302. }
  6303. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  6304. SourceLocation EndLoc) {
  6305. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  6306. }
  6307. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  6308. SourceLocation EndLoc) {
  6309. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  6310. }
  6311. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  6312. SourceLocation EndLoc) {
  6313. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  6314. }
  6315. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  6316. Stmt *AStmt,
  6317. SourceLocation StartLoc,
  6318. SourceLocation EndLoc) {
  6319. if (!AStmt)
  6320. return StmtError();
  6321. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6322. setFunctionHasBranchProtectedScope();
  6323. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6324. AStmt,
  6325. DSAStack->getTaskgroupReductionRef());
  6326. }
  6327. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  6328. SourceLocation StartLoc,
  6329. SourceLocation EndLoc) {
  6330. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  6331. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  6332. }
  6333. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  6334. Stmt *AStmt,
  6335. SourceLocation StartLoc,
  6336. SourceLocation EndLoc) {
  6337. const OMPClause *DependFound = nullptr;
  6338. const OMPClause *DependSourceClause = nullptr;
  6339. const OMPClause *DependSinkClause = nullptr;
  6340. bool ErrorFound = false;
  6341. const OMPThreadsClause *TC = nullptr;
  6342. const OMPSIMDClause *SC = nullptr;
  6343. for (const OMPClause *C : Clauses) {
  6344. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  6345. DependFound = C;
  6346. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  6347. if (DependSourceClause) {
  6348. Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  6349. << getOpenMPDirectiveName(OMPD_ordered)
  6350. << getOpenMPClauseName(OMPC_depend) << 2;
  6351. ErrorFound = true;
  6352. } else {
  6353. DependSourceClause = C;
  6354. }
  6355. if (DependSinkClause) {
  6356. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  6357. << 0;
  6358. ErrorFound = true;
  6359. }
  6360. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  6361. if (DependSourceClause) {
  6362. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  6363. << 1;
  6364. ErrorFound = true;
  6365. }
  6366. DependSinkClause = C;
  6367. }
  6368. } else if (C->getClauseKind() == OMPC_threads) {
  6369. TC = cast<OMPThreadsClause>(C);
  6370. } else if (C->getClauseKind() == OMPC_simd) {
  6371. SC = cast<OMPSIMDClause>(C);
  6372. }
  6373. }
  6374. if (!ErrorFound && !SC &&
  6375. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  6376. // OpenMP [2.8.1,simd Construct, Restrictions]
  6377. // An ordered construct with the simd clause is the only OpenMP construct
  6378. // that can appear in the simd region.
  6379. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  6380. ErrorFound = true;
  6381. } else if (DependFound && (TC || SC)) {
  6382. Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
  6383. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  6384. ErrorFound = true;
  6385. } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
  6386. Diag(DependFound->getBeginLoc(),
  6387. diag::err_omp_ordered_directive_without_param);
  6388. ErrorFound = true;
  6389. } else if (TC || Clauses.empty()) {
  6390. if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
  6391. SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
  6392. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  6393. << (TC != nullptr);
  6394. Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
  6395. ErrorFound = true;
  6396. }
  6397. }
  6398. if ((!AStmt && !DependFound) || ErrorFound)
  6399. return StmtError();
  6400. if (AStmt) {
  6401. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6402. setFunctionHasBranchProtectedScope();
  6403. }
  6404. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6405. }
  6406. namespace {
  6407. /// Helper class for checking expression in 'omp atomic [update]'
  6408. /// construct.
  6409. class OpenMPAtomicUpdateChecker {
  6410. /// Error results for atomic update expressions.
  6411. enum ExprAnalysisErrorCode {
  6412. /// A statement is not an expression statement.
  6413. NotAnExpression,
  6414. /// Expression is not builtin binary or unary operation.
  6415. NotABinaryOrUnaryExpression,
  6416. /// Unary operation is not post-/pre- increment/decrement operation.
  6417. NotAnUnaryIncDecExpression,
  6418. /// An expression is not of scalar type.
  6419. NotAScalarType,
  6420. /// A binary operation is not an assignment operation.
  6421. NotAnAssignmentOp,
  6422. /// RHS part of the binary operation is not a binary expression.
  6423. NotABinaryExpression,
  6424. /// RHS part is not additive/multiplicative/shift/biwise binary
  6425. /// expression.
  6426. NotABinaryOperator,
  6427. /// RHS binary operation does not have reference to the updated LHS
  6428. /// part.
  6429. NotAnUpdateExpression,
  6430. /// No errors is found.
  6431. NoError
  6432. };
  6433. /// Reference to Sema.
  6434. Sema &SemaRef;
  6435. /// A location for note diagnostics (when error is found).
  6436. SourceLocation NoteLoc;
  6437. /// 'x' lvalue part of the source atomic expression.
  6438. Expr *X;
  6439. /// 'expr' rvalue part of the source atomic expression.
  6440. Expr *E;
  6441. /// Helper expression of the form
  6442. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  6443. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  6444. Expr *UpdateExpr;
  6445. /// Is 'x' a LHS in a RHS part of full update expression. It is
  6446. /// important for non-associative operations.
  6447. bool IsXLHSInRHSPart;
  6448. BinaryOperatorKind Op;
  6449. SourceLocation OpLoc;
  6450. /// true if the source expression is a postfix unary operation, false
  6451. /// if it is a prefix unary operation.
  6452. bool IsPostfixUpdate;
  6453. public:
  6454. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  6455. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  6456. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  6457. /// Check specified statement that it is suitable for 'atomic update'
  6458. /// constructs and extract 'x', 'expr' and Operation from the original
  6459. /// expression. If DiagId and NoteId == 0, then only check is performed
  6460. /// without error notification.
  6461. /// \param DiagId Diagnostic which should be emitted if error is found.
  6462. /// \param NoteId Diagnostic note for the main error message.
  6463. /// \return true if statement is not an update expression, false otherwise.
  6464. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  6465. /// Return the 'x' lvalue part of the source atomic expression.
  6466. Expr *getX() const { return X; }
  6467. /// Return the 'expr' rvalue part of the source atomic expression.
  6468. Expr *getExpr() const { return E; }
  6469. /// Return the update expression used in calculation of the updated
  6470. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  6471. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  6472. Expr *getUpdateExpr() const { return UpdateExpr; }
  6473. /// Return true if 'x' is LHS in RHS part of full update expression,
  6474. /// false otherwise.
  6475. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  6476. /// true if the source expression is a postfix unary operation, false
  6477. /// if it is a prefix unary operation.
  6478. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  6479. private:
  6480. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  6481. unsigned NoteId = 0);
  6482. };
  6483. } // namespace
  6484. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  6485. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  6486. ExprAnalysisErrorCode ErrorFound = NoError;
  6487. SourceLocation ErrorLoc, NoteLoc;
  6488. SourceRange ErrorRange, NoteRange;
  6489. // Allowed constructs are:
  6490. // x = x binop expr;
  6491. // x = expr binop x;
  6492. if (AtomicBinOp->getOpcode() == BO_Assign) {
  6493. X = AtomicBinOp->getLHS();
  6494. if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  6495. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  6496. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  6497. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  6498. AtomicInnerBinOp->isBitwiseOp()) {
  6499. Op = AtomicInnerBinOp->getOpcode();
  6500. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  6501. Expr *LHS = AtomicInnerBinOp->getLHS();
  6502. Expr *RHS = AtomicInnerBinOp->getRHS();
  6503. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  6504. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  6505. /*Canonical=*/true);
  6506. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  6507. /*Canonical=*/true);
  6508. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  6509. /*Canonical=*/true);
  6510. if (XId == LHSId) {
  6511. E = RHS;
  6512. IsXLHSInRHSPart = true;
  6513. } else if (XId == RHSId) {
  6514. E = LHS;
  6515. IsXLHSInRHSPart = false;
  6516. } else {
  6517. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  6518. ErrorRange = AtomicInnerBinOp->getSourceRange();
  6519. NoteLoc = X->getExprLoc();
  6520. NoteRange = X->getSourceRange();
  6521. ErrorFound = NotAnUpdateExpression;
  6522. }
  6523. } else {
  6524. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  6525. ErrorRange = AtomicInnerBinOp->getSourceRange();
  6526. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  6527. NoteRange = SourceRange(NoteLoc, NoteLoc);
  6528. ErrorFound = NotABinaryOperator;
  6529. }
  6530. } else {
  6531. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  6532. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  6533. ErrorFound = NotABinaryExpression;
  6534. }
  6535. } else {
  6536. ErrorLoc = AtomicBinOp->getExprLoc();
  6537. ErrorRange = AtomicBinOp->getSourceRange();
  6538. NoteLoc = AtomicBinOp->getOperatorLoc();
  6539. NoteRange = SourceRange(NoteLoc, NoteLoc);
  6540. ErrorFound = NotAnAssignmentOp;
  6541. }
  6542. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  6543. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  6544. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  6545. return true;
  6546. }
  6547. if (SemaRef.CurContext->isDependentContext())
  6548. E = X = UpdateExpr = nullptr;
  6549. return ErrorFound != NoError;
  6550. }
  6551. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  6552. unsigned NoteId) {
  6553. ExprAnalysisErrorCode ErrorFound = NoError;
  6554. SourceLocation ErrorLoc, NoteLoc;
  6555. SourceRange ErrorRange, NoteRange;
  6556. // Allowed constructs are:
  6557. // x++;
  6558. // x--;
  6559. // ++x;
  6560. // --x;
  6561. // x binop= expr;
  6562. // x = x binop expr;
  6563. // x = expr binop x;
  6564. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  6565. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  6566. if (AtomicBody->getType()->isScalarType() ||
  6567. AtomicBody->isInstantiationDependent()) {
  6568. if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  6569. AtomicBody->IgnoreParenImpCasts())) {
  6570. // Check for Compound Assignment Operation
  6571. Op = BinaryOperator::getOpForCompoundAssignment(
  6572. AtomicCompAssignOp->getOpcode());
  6573. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  6574. E = AtomicCompAssignOp->getRHS();
  6575. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  6576. IsXLHSInRHSPart = true;
  6577. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  6578. AtomicBody->IgnoreParenImpCasts())) {
  6579. // Check for Binary Operation
  6580. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  6581. return true;
  6582. } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  6583. AtomicBody->IgnoreParenImpCasts())) {
  6584. // Check for Unary Operation
  6585. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  6586. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  6587. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  6588. OpLoc = AtomicUnaryOp->getOperatorLoc();
  6589. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  6590. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  6591. IsXLHSInRHSPart = true;
  6592. } else {
  6593. ErrorFound = NotAnUnaryIncDecExpression;
  6594. ErrorLoc = AtomicUnaryOp->getExprLoc();
  6595. ErrorRange = AtomicUnaryOp->getSourceRange();
  6596. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  6597. NoteRange = SourceRange(NoteLoc, NoteLoc);
  6598. }
  6599. } else if (!AtomicBody->isInstantiationDependent()) {
  6600. ErrorFound = NotABinaryOrUnaryExpression;
  6601. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  6602. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  6603. }
  6604. } else {
  6605. ErrorFound = NotAScalarType;
  6606. NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
  6607. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6608. }
  6609. } else {
  6610. ErrorFound = NotAnExpression;
  6611. NoteLoc = ErrorLoc = S->getBeginLoc();
  6612. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6613. }
  6614. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  6615. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  6616. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  6617. return true;
  6618. }
  6619. if (SemaRef.CurContext->isDependentContext())
  6620. E = X = UpdateExpr = nullptr;
  6621. if (ErrorFound == NoError && E && X) {
  6622. // Build an update expression of form 'OpaqueValueExpr(x) binop
  6623. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  6624. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  6625. auto *OVEX = new (SemaRef.getASTContext())
  6626. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  6627. auto *OVEExpr = new (SemaRef.getASTContext())
  6628. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  6629. ExprResult Update =
  6630. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  6631. IsXLHSInRHSPart ? OVEExpr : OVEX);
  6632. if (Update.isInvalid())
  6633. return true;
  6634. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  6635. Sema::AA_Casting);
  6636. if (Update.isInvalid())
  6637. return true;
  6638. UpdateExpr = Update.get();
  6639. }
  6640. return ErrorFound != NoError;
  6641. }
  6642. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  6643. Stmt *AStmt,
  6644. SourceLocation StartLoc,
  6645. SourceLocation EndLoc) {
  6646. if (!AStmt)
  6647. return StmtError();
  6648. auto *CS = cast<CapturedStmt>(AStmt);
  6649. // 1.2.2 OpenMP Language Terminology
  6650. // Structured block - An executable statement with a single entry at the
  6651. // top and a single exit at the bottom.
  6652. // The point of exit cannot be a branch out of the structured block.
  6653. // longjmp() and throw() must not violate the entry/exit criteria.
  6654. OpenMPClauseKind AtomicKind = OMPC_unknown;
  6655. SourceLocation AtomicKindLoc;
  6656. for (const OMPClause *C : Clauses) {
  6657. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  6658. C->getClauseKind() == OMPC_update ||
  6659. C->getClauseKind() == OMPC_capture) {
  6660. if (AtomicKind != OMPC_unknown) {
  6661. Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
  6662. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  6663. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  6664. << getOpenMPClauseName(AtomicKind);
  6665. } else {
  6666. AtomicKind = C->getClauseKind();
  6667. AtomicKindLoc = C->getBeginLoc();
  6668. }
  6669. }
  6670. }
  6671. Stmt *Body = CS->getCapturedStmt();
  6672. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  6673. Body = EWC->getSubExpr();
  6674. Expr *X = nullptr;
  6675. Expr *V = nullptr;
  6676. Expr *E = nullptr;
  6677. Expr *UE = nullptr;
  6678. bool IsXLHSInRHSPart = false;
  6679. bool IsPostfixUpdate = false;
  6680. // OpenMP [2.12.6, atomic Construct]
  6681. // In the next expressions:
  6682. // * x and v (as applicable) are both l-value expressions with scalar type.
  6683. // * During the execution of an atomic region, multiple syntactic
  6684. // occurrences of x must designate the same storage location.
  6685. // * Neither of v and expr (as applicable) may access the storage location
  6686. // designated by x.
  6687. // * Neither of x and expr (as applicable) may access the storage location
  6688. // designated by v.
  6689. // * expr is an expression with scalar type.
  6690. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  6691. // * binop, binop=, ++, and -- are not overloaded operators.
  6692. // * The expression x binop expr must be numerically equivalent to x binop
  6693. // (expr). This requirement is satisfied if the operators in expr have
  6694. // precedence greater than binop, or by using parentheses around expr or
  6695. // subexpressions of expr.
  6696. // * The expression expr binop x must be numerically equivalent to (expr)
  6697. // binop x. This requirement is satisfied if the operators in expr have
  6698. // precedence equal to or greater than binop, or by using parentheses around
  6699. // expr or subexpressions of expr.
  6700. // * For forms that allow multiple occurrences of x, the number of times
  6701. // that x is evaluated is unspecified.
  6702. if (AtomicKind == OMPC_read) {
  6703. enum {
  6704. NotAnExpression,
  6705. NotAnAssignmentOp,
  6706. NotAScalarType,
  6707. NotAnLValue,
  6708. NoError
  6709. } ErrorFound = NoError;
  6710. SourceLocation ErrorLoc, NoteLoc;
  6711. SourceRange ErrorRange, NoteRange;
  6712. // If clause is read:
  6713. // v = x;
  6714. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6715. const auto *AtomicBinOp =
  6716. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6717. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6718. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  6719. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  6720. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  6721. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  6722. if (!X->isLValue() || !V->isLValue()) {
  6723. const Expr *NotLValueExpr = X->isLValue() ? V : X;
  6724. ErrorFound = NotAnLValue;
  6725. ErrorLoc = AtomicBinOp->getExprLoc();
  6726. ErrorRange = AtomicBinOp->getSourceRange();
  6727. NoteLoc = NotLValueExpr->getExprLoc();
  6728. NoteRange = NotLValueExpr->getSourceRange();
  6729. }
  6730. } else if (!X->isInstantiationDependent() ||
  6731. !V->isInstantiationDependent()) {
  6732. const Expr *NotScalarExpr =
  6733. (X->isInstantiationDependent() || X->getType()->isScalarType())
  6734. ? V
  6735. : X;
  6736. ErrorFound = NotAScalarType;
  6737. ErrorLoc = AtomicBinOp->getExprLoc();
  6738. ErrorRange = AtomicBinOp->getSourceRange();
  6739. NoteLoc = NotScalarExpr->getExprLoc();
  6740. NoteRange = NotScalarExpr->getSourceRange();
  6741. }
  6742. } else if (!AtomicBody->isInstantiationDependent()) {
  6743. ErrorFound = NotAnAssignmentOp;
  6744. ErrorLoc = AtomicBody->getExprLoc();
  6745. ErrorRange = AtomicBody->getSourceRange();
  6746. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6747. : AtomicBody->getExprLoc();
  6748. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6749. : AtomicBody->getSourceRange();
  6750. }
  6751. } else {
  6752. ErrorFound = NotAnExpression;
  6753. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6754. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6755. }
  6756. if (ErrorFound != NoError) {
  6757. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  6758. << ErrorRange;
  6759. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  6760. << NoteRange;
  6761. return StmtError();
  6762. }
  6763. if (CurContext->isDependentContext())
  6764. V = X = nullptr;
  6765. } else if (AtomicKind == OMPC_write) {
  6766. enum {
  6767. NotAnExpression,
  6768. NotAnAssignmentOp,
  6769. NotAScalarType,
  6770. NotAnLValue,
  6771. NoError
  6772. } ErrorFound = NoError;
  6773. SourceLocation ErrorLoc, NoteLoc;
  6774. SourceRange ErrorRange, NoteRange;
  6775. // If clause is write:
  6776. // x = expr;
  6777. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6778. const auto *AtomicBinOp =
  6779. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6780. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6781. X = AtomicBinOp->getLHS();
  6782. E = AtomicBinOp->getRHS();
  6783. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  6784. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  6785. if (!X->isLValue()) {
  6786. ErrorFound = NotAnLValue;
  6787. ErrorLoc = AtomicBinOp->getExprLoc();
  6788. ErrorRange = AtomicBinOp->getSourceRange();
  6789. NoteLoc = X->getExprLoc();
  6790. NoteRange = X->getSourceRange();
  6791. }
  6792. } else if (!X->isInstantiationDependent() ||
  6793. !E->isInstantiationDependent()) {
  6794. const Expr *NotScalarExpr =
  6795. (X->isInstantiationDependent() || X->getType()->isScalarType())
  6796. ? E
  6797. : X;
  6798. ErrorFound = NotAScalarType;
  6799. ErrorLoc = AtomicBinOp->getExprLoc();
  6800. ErrorRange = AtomicBinOp->getSourceRange();
  6801. NoteLoc = NotScalarExpr->getExprLoc();
  6802. NoteRange = NotScalarExpr->getSourceRange();
  6803. }
  6804. } else if (!AtomicBody->isInstantiationDependent()) {
  6805. ErrorFound = NotAnAssignmentOp;
  6806. ErrorLoc = AtomicBody->getExprLoc();
  6807. ErrorRange = AtomicBody->getSourceRange();
  6808. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6809. : AtomicBody->getExprLoc();
  6810. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6811. : AtomicBody->getSourceRange();
  6812. }
  6813. } else {
  6814. ErrorFound = NotAnExpression;
  6815. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6816. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6817. }
  6818. if (ErrorFound != NoError) {
  6819. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  6820. << ErrorRange;
  6821. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  6822. << NoteRange;
  6823. return StmtError();
  6824. }
  6825. if (CurContext->isDependentContext())
  6826. E = X = nullptr;
  6827. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  6828. // If clause is update:
  6829. // x++;
  6830. // x--;
  6831. // ++x;
  6832. // --x;
  6833. // x binop= expr;
  6834. // x = x binop expr;
  6835. // x = expr binop x;
  6836. OpenMPAtomicUpdateChecker Checker(*this);
  6837. if (Checker.checkStatement(
  6838. Body, (AtomicKind == OMPC_update)
  6839. ? diag::err_omp_atomic_update_not_expression_statement
  6840. : diag::err_omp_atomic_not_expression_statement,
  6841. diag::note_omp_atomic_update))
  6842. return StmtError();
  6843. if (!CurContext->isDependentContext()) {
  6844. E = Checker.getExpr();
  6845. X = Checker.getX();
  6846. UE = Checker.getUpdateExpr();
  6847. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6848. }
  6849. } else if (AtomicKind == OMPC_capture) {
  6850. enum {
  6851. NotAnAssignmentOp,
  6852. NotACompoundStatement,
  6853. NotTwoSubstatements,
  6854. NotASpecificExpression,
  6855. NoError
  6856. } ErrorFound = NoError;
  6857. SourceLocation ErrorLoc, NoteLoc;
  6858. SourceRange ErrorRange, NoteRange;
  6859. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6860. // If clause is a capture:
  6861. // v = x++;
  6862. // v = x--;
  6863. // v = ++x;
  6864. // v = --x;
  6865. // v = x binop= expr;
  6866. // v = x = x binop expr;
  6867. // v = x = expr binop x;
  6868. const auto *AtomicBinOp =
  6869. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6870. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6871. V = AtomicBinOp->getLHS();
  6872. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  6873. OpenMPAtomicUpdateChecker Checker(*this);
  6874. if (Checker.checkStatement(
  6875. Body, diag::err_omp_atomic_capture_not_expression_statement,
  6876. diag::note_omp_atomic_update))
  6877. return StmtError();
  6878. E = Checker.getExpr();
  6879. X = Checker.getX();
  6880. UE = Checker.getUpdateExpr();
  6881. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6882. IsPostfixUpdate = Checker.isPostfixUpdate();
  6883. } else if (!AtomicBody->isInstantiationDependent()) {
  6884. ErrorLoc = AtomicBody->getExprLoc();
  6885. ErrorRange = AtomicBody->getSourceRange();
  6886. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6887. : AtomicBody->getExprLoc();
  6888. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6889. : AtomicBody->getSourceRange();
  6890. ErrorFound = NotAnAssignmentOp;
  6891. }
  6892. if (ErrorFound != NoError) {
  6893. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  6894. << ErrorRange;
  6895. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  6896. return StmtError();
  6897. }
  6898. if (CurContext->isDependentContext())
  6899. UE = V = E = X = nullptr;
  6900. } else {
  6901. // If clause is a capture:
  6902. // { v = x; x = expr; }
  6903. // { v = x; x++; }
  6904. // { v = x; x--; }
  6905. // { v = x; ++x; }
  6906. // { v = x; --x; }
  6907. // { v = x; x binop= expr; }
  6908. // { v = x; x = x binop expr; }
  6909. // { v = x; x = expr binop x; }
  6910. // { x++; v = x; }
  6911. // { x--; v = x; }
  6912. // { ++x; v = x; }
  6913. // { --x; v = x; }
  6914. // { x binop= expr; v = x; }
  6915. // { x = x binop expr; v = x; }
  6916. // { x = expr binop x; v = x; }
  6917. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  6918. // Check that this is { expr1; expr2; }
  6919. if (CS->size() == 2) {
  6920. Stmt *First = CS->body_front();
  6921. Stmt *Second = CS->body_back();
  6922. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  6923. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  6924. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  6925. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  6926. // Need to find what subexpression is 'v' and what is 'x'.
  6927. OpenMPAtomicUpdateChecker Checker(*this);
  6928. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  6929. BinaryOperator *BinOp = nullptr;
  6930. if (IsUpdateExprFound) {
  6931. BinOp = dyn_cast<BinaryOperator>(First);
  6932. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  6933. }
  6934. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  6935. // { v = x; x++; }
  6936. // { v = x; x--; }
  6937. // { v = x; ++x; }
  6938. // { v = x; --x; }
  6939. // { v = x; x binop= expr; }
  6940. // { v = x; x = x binop expr; }
  6941. // { v = x; x = expr binop x; }
  6942. // Check that the first expression has form v = x.
  6943. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  6944. llvm::FoldingSetNodeID XId, PossibleXId;
  6945. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  6946. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  6947. IsUpdateExprFound = XId == PossibleXId;
  6948. if (IsUpdateExprFound) {
  6949. V = BinOp->getLHS();
  6950. X = Checker.getX();
  6951. E = Checker.getExpr();
  6952. UE = Checker.getUpdateExpr();
  6953. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6954. IsPostfixUpdate = true;
  6955. }
  6956. }
  6957. if (!IsUpdateExprFound) {
  6958. IsUpdateExprFound = !Checker.checkStatement(First);
  6959. BinOp = nullptr;
  6960. if (IsUpdateExprFound) {
  6961. BinOp = dyn_cast<BinaryOperator>(Second);
  6962. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  6963. }
  6964. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  6965. // { x++; v = x; }
  6966. // { x--; v = x; }
  6967. // { ++x; v = x; }
  6968. // { --x; v = x; }
  6969. // { x binop= expr; v = x; }
  6970. // { x = x binop expr; v = x; }
  6971. // { x = expr binop x; v = x; }
  6972. // Check that the second expression has form v = x.
  6973. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  6974. llvm::FoldingSetNodeID XId, PossibleXId;
  6975. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  6976. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  6977. IsUpdateExprFound = XId == PossibleXId;
  6978. if (IsUpdateExprFound) {
  6979. V = BinOp->getLHS();
  6980. X = Checker.getX();
  6981. E = Checker.getExpr();
  6982. UE = Checker.getUpdateExpr();
  6983. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6984. IsPostfixUpdate = false;
  6985. }
  6986. }
  6987. }
  6988. if (!IsUpdateExprFound) {
  6989. // { v = x; x = expr; }
  6990. auto *FirstExpr = dyn_cast<Expr>(First);
  6991. auto *SecondExpr = dyn_cast<Expr>(Second);
  6992. if (!FirstExpr || !SecondExpr ||
  6993. !(FirstExpr->isInstantiationDependent() ||
  6994. SecondExpr->isInstantiationDependent())) {
  6995. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  6996. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  6997. ErrorFound = NotAnAssignmentOp;
  6998. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  6999. : First->getBeginLoc();
  7000. NoteRange = ErrorRange = FirstBinOp
  7001. ? FirstBinOp->getSourceRange()
  7002. : SourceRange(ErrorLoc, ErrorLoc);
  7003. } else {
  7004. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  7005. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  7006. ErrorFound = NotAnAssignmentOp;
  7007. NoteLoc = ErrorLoc = SecondBinOp
  7008. ? SecondBinOp->getOperatorLoc()
  7009. : Second->getBeginLoc();
  7010. NoteRange = ErrorRange =
  7011. SecondBinOp ? SecondBinOp->getSourceRange()
  7012. : SourceRange(ErrorLoc, ErrorLoc);
  7013. } else {
  7014. Expr *PossibleXRHSInFirst =
  7015. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  7016. Expr *PossibleXLHSInSecond =
  7017. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  7018. llvm::FoldingSetNodeID X1Id, X2Id;
  7019. PossibleXRHSInFirst->Profile(X1Id, Context,
  7020. /*Canonical=*/true);
  7021. PossibleXLHSInSecond->Profile(X2Id, Context,
  7022. /*Canonical=*/true);
  7023. IsUpdateExprFound = X1Id == X2Id;
  7024. if (IsUpdateExprFound) {
  7025. V = FirstBinOp->getLHS();
  7026. X = SecondBinOp->getLHS();
  7027. E = SecondBinOp->getRHS();
  7028. UE = nullptr;
  7029. IsXLHSInRHSPart = false;
  7030. IsPostfixUpdate = true;
  7031. } else {
  7032. ErrorFound = NotASpecificExpression;
  7033. ErrorLoc = FirstBinOp->getExprLoc();
  7034. ErrorRange = FirstBinOp->getSourceRange();
  7035. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  7036. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  7037. }
  7038. }
  7039. }
  7040. }
  7041. }
  7042. } else {
  7043. NoteLoc = ErrorLoc = Body->getBeginLoc();
  7044. NoteRange = ErrorRange =
  7045. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  7046. ErrorFound = NotTwoSubstatements;
  7047. }
  7048. } else {
  7049. NoteLoc = ErrorLoc = Body->getBeginLoc();
  7050. NoteRange = ErrorRange =
  7051. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  7052. ErrorFound = NotACompoundStatement;
  7053. }
  7054. if (ErrorFound != NoError) {
  7055. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  7056. << ErrorRange;
  7057. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  7058. return StmtError();
  7059. }
  7060. if (CurContext->isDependentContext())
  7061. UE = V = E = X = nullptr;
  7062. }
  7063. }
  7064. setFunctionHasBranchProtectedScope();
  7065. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  7066. X, V, E, UE, IsXLHSInRHSPart,
  7067. IsPostfixUpdate);
  7068. }
  7069. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  7070. Stmt *AStmt,
  7071. SourceLocation StartLoc,
  7072. SourceLocation EndLoc) {
  7073. if (!AStmt)
  7074. return StmtError();
  7075. auto *CS = cast<CapturedStmt>(AStmt);
  7076. // 1.2.2 OpenMP Language Terminology
  7077. // Structured block - An executable statement with a single entry at the
  7078. // top and a single exit at the bottom.
  7079. // The point of exit cannot be a branch out of the structured block.
  7080. // longjmp() and throw() must not violate the entry/exit criteria.
  7081. CS->getCapturedDecl()->setNothrow();
  7082. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
  7083. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7084. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7085. // 1.2.2 OpenMP Language Terminology
  7086. // Structured block - An executable statement with a single entry at the
  7087. // top and a single exit at the bottom.
  7088. // The point of exit cannot be a branch out of the structured block.
  7089. // longjmp() and throw() must not violate the entry/exit criteria.
  7090. CS->getCapturedDecl()->setNothrow();
  7091. }
  7092. // OpenMP [2.16, Nesting of Regions]
  7093. // If specified, a teams construct must be contained within a target
  7094. // construct. That target construct must contain no statements or directives
  7095. // outside of the teams construct.
  7096. if (DSAStack->hasInnerTeamsRegion()) {
  7097. const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
  7098. bool OMPTeamsFound = true;
  7099. if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
  7100. auto I = CS->body_begin();
  7101. while (I != CS->body_end()) {
  7102. const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  7103. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
  7104. OMPTeamsFound) {
  7105. OMPTeamsFound = false;
  7106. break;
  7107. }
  7108. ++I;
  7109. }
  7110. assert(I != CS->body_end() && "Not found statement");
  7111. S = *I;
  7112. } else {
  7113. const auto *OED = dyn_cast<OMPExecutableDirective>(S);
  7114. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  7115. }
  7116. if (!OMPTeamsFound) {
  7117. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  7118. Diag(DSAStack->getInnerTeamsRegionLoc(),
  7119. diag::note_omp_nested_teams_construct_here);
  7120. Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
  7121. << isa<OMPExecutableDirective>(S);
  7122. return StmtError();
  7123. }
  7124. }
  7125. setFunctionHasBranchProtectedScope();
  7126. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  7127. }
  7128. StmtResult
  7129. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  7130. Stmt *AStmt, SourceLocation StartLoc,
  7131. SourceLocation EndLoc) {
  7132. if (!AStmt)
  7133. return StmtError();
  7134. auto *CS = cast<CapturedStmt>(AStmt);
  7135. // 1.2.2 OpenMP Language Terminology
  7136. // Structured block - An executable statement with a single entry at the
  7137. // top and a single exit at the bottom.
  7138. // The point of exit cannot be a branch out of the structured block.
  7139. // longjmp() and throw() must not violate the entry/exit criteria.
  7140. CS->getCapturedDecl()->setNothrow();
  7141. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
  7142. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7143. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7144. // 1.2.2 OpenMP Language Terminology
  7145. // Structured block - An executable statement with a single entry at the
  7146. // top and a single exit at the bottom.
  7147. // The point of exit cannot be a branch out of the structured block.
  7148. // longjmp() and throw() must not violate the entry/exit criteria.
  7149. CS->getCapturedDecl()->setNothrow();
  7150. }
  7151. setFunctionHasBranchProtectedScope();
  7152. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7153. AStmt);
  7154. }
  7155. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  7156. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7157. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7158. if (!AStmt)
  7159. return StmtError();
  7160. auto *CS = cast<CapturedStmt>(AStmt);
  7161. // 1.2.2 OpenMP Language Terminology
  7162. // Structured block - An executable statement with a single entry at the
  7163. // top and a single exit at the bottom.
  7164. // The point of exit cannot be a branch out of the structured block.
  7165. // longjmp() and throw() must not violate the entry/exit criteria.
  7166. CS->getCapturedDecl()->setNothrow();
  7167. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  7168. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7169. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7170. // 1.2.2 OpenMP Language Terminology
  7171. // Structured block - An executable statement with a single entry at the
  7172. // top and a single exit at the bottom.
  7173. // The point of exit cannot be a branch out of the structured block.
  7174. // longjmp() and throw() must not violate the entry/exit criteria.
  7175. CS->getCapturedDecl()->setNothrow();
  7176. }
  7177. OMPLoopDirective::HelperExprs B;
  7178. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7179. // define the nested loops number.
  7180. unsigned NestedLoopCount =
  7181. checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  7182. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  7183. VarsWithImplicitDSA, B);
  7184. if (NestedLoopCount == 0)
  7185. return StmtError();
  7186. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7187. "omp target parallel for loop exprs were not built");
  7188. if (!CurContext->isDependentContext()) {
  7189. // Finalize the clauses that need pre-built expressions for CodeGen.
  7190. for (OMPClause *C : Clauses) {
  7191. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7192. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7193. B.NumIterations, *this, CurScope,
  7194. DSAStack))
  7195. return StmtError();
  7196. }
  7197. }
  7198. setFunctionHasBranchProtectedScope();
  7199. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  7200. NestedLoopCount, Clauses, AStmt,
  7201. B, DSAStack->isCancelRegion());
  7202. }
  7203. /// Check for existence of a map clause in the list of clauses.
  7204. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  7205. const OpenMPClauseKind K) {
  7206. return llvm::any_of(
  7207. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  7208. }
  7209. template <typename... Params>
  7210. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  7211. const Params... ClauseTypes) {
  7212. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  7213. }
  7214. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  7215. Stmt *AStmt,
  7216. SourceLocation StartLoc,
  7217. SourceLocation EndLoc) {
  7218. if (!AStmt)
  7219. return StmtError();
  7220. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7221. // OpenMP [2.10.1, Restrictions, p. 97]
  7222. // At least one map clause must appear on the directive.
  7223. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  7224. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  7225. << "'map' or 'use_device_ptr'"
  7226. << getOpenMPDirectiveName(OMPD_target_data);
  7227. return StmtError();
  7228. }
  7229. setFunctionHasBranchProtectedScope();
  7230. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7231. AStmt);
  7232. }
  7233. StmtResult
  7234. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  7235. SourceLocation StartLoc,
  7236. SourceLocation EndLoc, Stmt *AStmt) {
  7237. if (!AStmt)
  7238. return StmtError();
  7239. auto *CS = cast<CapturedStmt>(AStmt);
  7240. // 1.2.2 OpenMP Language Terminology
  7241. // Structured block - An executable statement with a single entry at the
  7242. // top and a single exit at the bottom.
  7243. // The point of exit cannot be a branch out of the structured block.
  7244. // longjmp() and throw() must not violate the entry/exit criteria.
  7245. CS->getCapturedDecl()->setNothrow();
  7246. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  7247. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7248. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7249. // 1.2.2 OpenMP Language Terminology
  7250. // Structured block - An executable statement with a single entry at the
  7251. // top and a single exit at the bottom.
  7252. // The point of exit cannot be a branch out of the structured block.
  7253. // longjmp() and throw() must not violate the entry/exit criteria.
  7254. CS->getCapturedDecl()->setNothrow();
  7255. }
  7256. // OpenMP [2.10.2, Restrictions, p. 99]
  7257. // At least one map clause must appear on the directive.
  7258. if (!hasClauses(Clauses, OMPC_map)) {
  7259. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  7260. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  7261. return StmtError();
  7262. }
  7263. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7264. AStmt);
  7265. }
  7266. StmtResult
  7267. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  7268. SourceLocation StartLoc,
  7269. SourceLocation EndLoc, Stmt *AStmt) {
  7270. if (!AStmt)
  7271. return StmtError();
  7272. auto *CS = cast<CapturedStmt>(AStmt);
  7273. // 1.2.2 OpenMP Language Terminology
  7274. // Structured block - An executable statement with a single entry at the
  7275. // top and a single exit at the bottom.
  7276. // The point of exit cannot be a branch out of the structured block.
  7277. // longjmp() and throw() must not violate the entry/exit criteria.
  7278. CS->getCapturedDecl()->setNothrow();
  7279. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  7280. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7281. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7282. // 1.2.2 OpenMP Language Terminology
  7283. // Structured block - An executable statement with a single entry at the
  7284. // top and a single exit at the bottom.
  7285. // The point of exit cannot be a branch out of the structured block.
  7286. // longjmp() and throw() must not violate the entry/exit criteria.
  7287. CS->getCapturedDecl()->setNothrow();
  7288. }
  7289. // OpenMP [2.10.3, Restrictions, p. 102]
  7290. // At least one map clause must appear on the directive.
  7291. if (!hasClauses(Clauses, OMPC_map)) {
  7292. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  7293. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  7294. return StmtError();
  7295. }
  7296. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7297. AStmt);
  7298. }
  7299. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  7300. SourceLocation StartLoc,
  7301. SourceLocation EndLoc,
  7302. Stmt *AStmt) {
  7303. if (!AStmt)
  7304. return StmtError();
  7305. auto *CS = cast<CapturedStmt>(AStmt);
  7306. // 1.2.2 OpenMP Language Terminology
  7307. // Structured block - An executable statement with a single entry at the
  7308. // top and a single exit at the bottom.
  7309. // The point of exit cannot be a branch out of the structured block.
  7310. // longjmp() and throw() must not violate the entry/exit criteria.
  7311. CS->getCapturedDecl()->setNothrow();
  7312. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  7313. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7314. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7315. // 1.2.2 OpenMP Language Terminology
  7316. // Structured block - An executable statement with a single entry at the
  7317. // top and a single exit at the bottom.
  7318. // The point of exit cannot be a branch out of the structured block.
  7319. // longjmp() and throw() must not violate the entry/exit criteria.
  7320. CS->getCapturedDecl()->setNothrow();
  7321. }
  7322. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  7323. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  7324. return StmtError();
  7325. }
  7326. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7327. AStmt);
  7328. }
  7329. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  7330. Stmt *AStmt, SourceLocation StartLoc,
  7331. SourceLocation EndLoc) {
  7332. if (!AStmt)
  7333. return StmtError();
  7334. auto *CS = cast<CapturedStmt>(AStmt);
  7335. // 1.2.2 OpenMP Language Terminology
  7336. // Structured block - An executable statement with a single entry at the
  7337. // top and a single exit at the bottom.
  7338. // The point of exit cannot be a branch out of the structured block.
  7339. // longjmp() and throw() must not violate the entry/exit criteria.
  7340. CS->getCapturedDecl()->setNothrow();
  7341. setFunctionHasBranchProtectedScope();
  7342. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7343. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  7344. }
  7345. StmtResult
  7346. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  7347. SourceLocation EndLoc,
  7348. OpenMPDirectiveKind CancelRegion) {
  7349. if (DSAStack->isParentNowaitRegion()) {
  7350. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  7351. return StmtError();
  7352. }
  7353. if (DSAStack->isParentOrderedRegion()) {
  7354. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  7355. return StmtError();
  7356. }
  7357. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  7358. CancelRegion);
  7359. }
  7360. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  7361. SourceLocation StartLoc,
  7362. SourceLocation EndLoc,
  7363. OpenMPDirectiveKind CancelRegion) {
  7364. if (DSAStack->isParentNowaitRegion()) {
  7365. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  7366. return StmtError();
  7367. }
  7368. if (DSAStack->isParentOrderedRegion()) {
  7369. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  7370. return StmtError();
  7371. }
  7372. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  7373. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7374. CancelRegion);
  7375. }
  7376. static bool checkGrainsizeNumTasksClauses(Sema &S,
  7377. ArrayRef<OMPClause *> Clauses) {
  7378. const OMPClause *PrevClause = nullptr;
  7379. bool ErrorFound = false;
  7380. for (const OMPClause *C : Clauses) {
  7381. if (C->getClauseKind() == OMPC_grainsize ||
  7382. C->getClauseKind() == OMPC_num_tasks) {
  7383. if (!PrevClause)
  7384. PrevClause = C;
  7385. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  7386. S.Diag(C->getBeginLoc(),
  7387. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  7388. << getOpenMPClauseName(C->getClauseKind())
  7389. << getOpenMPClauseName(PrevClause->getClauseKind());
  7390. S.Diag(PrevClause->getBeginLoc(),
  7391. diag::note_omp_previous_grainsize_num_tasks)
  7392. << getOpenMPClauseName(PrevClause->getClauseKind());
  7393. ErrorFound = true;
  7394. }
  7395. }
  7396. }
  7397. return ErrorFound;
  7398. }
  7399. static bool checkReductionClauseWithNogroup(Sema &S,
  7400. ArrayRef<OMPClause *> Clauses) {
  7401. const OMPClause *ReductionClause = nullptr;
  7402. const OMPClause *NogroupClause = nullptr;
  7403. for (const OMPClause *C : Clauses) {
  7404. if (C->getClauseKind() == OMPC_reduction) {
  7405. ReductionClause = C;
  7406. if (NogroupClause)
  7407. break;
  7408. continue;
  7409. }
  7410. if (C->getClauseKind() == OMPC_nogroup) {
  7411. NogroupClause = C;
  7412. if (ReductionClause)
  7413. break;
  7414. continue;
  7415. }
  7416. }
  7417. if (ReductionClause && NogroupClause) {
  7418. S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
  7419. << SourceRange(NogroupClause->getBeginLoc(),
  7420. NogroupClause->getEndLoc());
  7421. return true;
  7422. }
  7423. return false;
  7424. }
  7425. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  7426. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7427. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7428. if (!AStmt)
  7429. return StmtError();
  7430. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7431. OMPLoopDirective::HelperExprs B;
  7432. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7433. // define the nested loops number.
  7434. unsigned NestedLoopCount =
  7435. checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  7436. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  7437. VarsWithImplicitDSA, B);
  7438. if (NestedLoopCount == 0)
  7439. return StmtError();
  7440. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7441. "omp for loop exprs were not built");
  7442. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  7443. // The grainsize clause and num_tasks clause are mutually exclusive and may
  7444. // not appear on the same taskloop directive.
  7445. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  7446. return StmtError();
  7447. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  7448. // If a reduction clause is present on the taskloop directive, the nogroup
  7449. // clause must not be specified.
  7450. if (checkReductionClauseWithNogroup(*this, Clauses))
  7451. return StmtError();
  7452. setFunctionHasBranchProtectedScope();
  7453. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  7454. NestedLoopCount, Clauses, AStmt, B);
  7455. }
  7456. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  7457. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7458. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7459. if (!AStmt)
  7460. return StmtError();
  7461. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7462. OMPLoopDirective::HelperExprs B;
  7463. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7464. // define the nested loops number.
  7465. unsigned NestedLoopCount =
  7466. checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  7467. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  7468. VarsWithImplicitDSA, B);
  7469. if (NestedLoopCount == 0)
  7470. return StmtError();
  7471. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7472. "omp for loop exprs were not built");
  7473. if (!CurContext->isDependentContext()) {
  7474. // Finalize the clauses that need pre-built expressions for CodeGen.
  7475. for (OMPClause *C : Clauses) {
  7476. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7477. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7478. B.NumIterations, *this, CurScope,
  7479. DSAStack))
  7480. return StmtError();
  7481. }
  7482. }
  7483. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  7484. // The grainsize clause and num_tasks clause are mutually exclusive and may
  7485. // not appear on the same taskloop directive.
  7486. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  7487. return StmtError();
  7488. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  7489. // If a reduction clause is present on the taskloop directive, the nogroup
  7490. // clause must not be specified.
  7491. if (checkReductionClauseWithNogroup(*this, Clauses))
  7492. return StmtError();
  7493. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7494. return StmtError();
  7495. setFunctionHasBranchProtectedScope();
  7496. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  7497. NestedLoopCount, Clauses, AStmt, B);
  7498. }
  7499. StmtResult Sema::ActOnOpenMPDistributeDirective(
  7500. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7501. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7502. if (!AStmt)
  7503. return StmtError();
  7504. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7505. OMPLoopDirective::HelperExprs B;
  7506. // In presence of clause 'collapse' with number of loops, it will
  7507. // define the nested loops number.
  7508. unsigned NestedLoopCount =
  7509. checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  7510. nullptr /*ordered not a clause on distribute*/, AStmt,
  7511. *this, *DSAStack, VarsWithImplicitDSA, B);
  7512. if (NestedLoopCount == 0)
  7513. return StmtError();
  7514. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7515. "omp for loop exprs were not built");
  7516. setFunctionHasBranchProtectedScope();
  7517. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  7518. NestedLoopCount, Clauses, AStmt, B);
  7519. }
  7520. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  7521. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7522. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7523. if (!AStmt)
  7524. return StmtError();
  7525. auto *CS = cast<CapturedStmt>(AStmt);
  7526. // 1.2.2 OpenMP Language Terminology
  7527. // Structured block - An executable statement with a single entry at the
  7528. // top and a single exit at the bottom.
  7529. // The point of exit cannot be a branch out of the structured block.
  7530. // longjmp() and throw() must not violate the entry/exit criteria.
  7531. CS->getCapturedDecl()->setNothrow();
  7532. for (int ThisCaptureLevel =
  7533. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  7534. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7535. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7536. // 1.2.2 OpenMP Language Terminology
  7537. // Structured block - An executable statement with a single entry at the
  7538. // top and a single exit at the bottom.
  7539. // The point of exit cannot be a branch out of the structured block.
  7540. // longjmp() and throw() must not violate the entry/exit criteria.
  7541. CS->getCapturedDecl()->setNothrow();
  7542. }
  7543. OMPLoopDirective::HelperExprs B;
  7544. // In presence of clause 'collapse' with number of loops, it will
  7545. // define the nested loops number.
  7546. unsigned NestedLoopCount = checkOpenMPLoop(
  7547. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  7548. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7549. VarsWithImplicitDSA, B);
  7550. if (NestedLoopCount == 0)
  7551. return StmtError();
  7552. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7553. "omp for loop exprs were not built");
  7554. setFunctionHasBranchProtectedScope();
  7555. return OMPDistributeParallelForDirective::Create(
  7556. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  7557. DSAStack->isCancelRegion());
  7558. }
  7559. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  7560. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7561. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7562. if (!AStmt)
  7563. return StmtError();
  7564. auto *CS = cast<CapturedStmt>(AStmt);
  7565. // 1.2.2 OpenMP Language Terminology
  7566. // Structured block - An executable statement with a single entry at the
  7567. // top and a single exit at the bottom.
  7568. // The point of exit cannot be a branch out of the structured block.
  7569. // longjmp() and throw() must not violate the entry/exit criteria.
  7570. CS->getCapturedDecl()->setNothrow();
  7571. for (int ThisCaptureLevel =
  7572. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  7573. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7574. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7575. // 1.2.2 OpenMP Language Terminology
  7576. // Structured block - An executable statement with a single entry at the
  7577. // top and a single exit at the bottom.
  7578. // The point of exit cannot be a branch out of the structured block.
  7579. // longjmp() and throw() must not violate the entry/exit criteria.
  7580. CS->getCapturedDecl()->setNothrow();
  7581. }
  7582. OMPLoopDirective::HelperExprs B;
  7583. // In presence of clause 'collapse' with number of loops, it will
  7584. // define the nested loops number.
  7585. unsigned NestedLoopCount = checkOpenMPLoop(
  7586. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7587. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7588. VarsWithImplicitDSA, B);
  7589. if (NestedLoopCount == 0)
  7590. return StmtError();
  7591. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7592. "omp for loop exprs were not built");
  7593. if (!CurContext->isDependentContext()) {
  7594. // Finalize the clauses that need pre-built expressions for CodeGen.
  7595. for (OMPClause *C : Clauses) {
  7596. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7597. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7598. B.NumIterations, *this, CurScope,
  7599. DSAStack))
  7600. return StmtError();
  7601. }
  7602. }
  7603. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7604. return StmtError();
  7605. setFunctionHasBranchProtectedScope();
  7606. return OMPDistributeParallelForSimdDirective::Create(
  7607. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7608. }
  7609. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  7610. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7611. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7612. if (!AStmt)
  7613. return StmtError();
  7614. auto *CS = cast<CapturedStmt>(AStmt);
  7615. // 1.2.2 OpenMP Language Terminology
  7616. // Structured block - An executable statement with a single entry at the
  7617. // top and a single exit at the bottom.
  7618. // The point of exit cannot be a branch out of the structured block.
  7619. // longjmp() and throw() must not violate the entry/exit criteria.
  7620. CS->getCapturedDecl()->setNothrow();
  7621. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  7622. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7623. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7624. // 1.2.2 OpenMP Language Terminology
  7625. // Structured block - An executable statement with a single entry at the
  7626. // top and a single exit at the bottom.
  7627. // The point of exit cannot be a branch out of the structured block.
  7628. // longjmp() and throw() must not violate the entry/exit criteria.
  7629. CS->getCapturedDecl()->setNothrow();
  7630. }
  7631. OMPLoopDirective::HelperExprs B;
  7632. // In presence of clause 'collapse' with number of loops, it will
  7633. // define the nested loops number.
  7634. unsigned NestedLoopCount =
  7635. checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  7636. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7637. *DSAStack, VarsWithImplicitDSA, B);
  7638. if (NestedLoopCount == 0)
  7639. return StmtError();
  7640. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7641. "omp for loop exprs were not built");
  7642. if (!CurContext->isDependentContext()) {
  7643. // Finalize the clauses that need pre-built expressions for CodeGen.
  7644. for (OMPClause *C : Clauses) {
  7645. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7646. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7647. B.NumIterations, *this, CurScope,
  7648. DSAStack))
  7649. return StmtError();
  7650. }
  7651. }
  7652. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7653. return StmtError();
  7654. setFunctionHasBranchProtectedScope();
  7655. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  7656. NestedLoopCount, Clauses, AStmt, B);
  7657. }
  7658. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  7659. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7660. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7661. if (!AStmt)
  7662. return StmtError();
  7663. auto *CS = cast<CapturedStmt>(AStmt);
  7664. // 1.2.2 OpenMP Language Terminology
  7665. // Structured block - An executable statement with a single entry at the
  7666. // top and a single exit at the bottom.
  7667. // The point of exit cannot be a branch out of the structured block.
  7668. // longjmp() and throw() must not violate the entry/exit criteria.
  7669. CS->getCapturedDecl()->setNothrow();
  7670. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  7671. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7672. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7673. // 1.2.2 OpenMP Language Terminology
  7674. // Structured block - An executable statement with a single entry at the
  7675. // top and a single exit at the bottom.
  7676. // The point of exit cannot be a branch out of the structured block.
  7677. // longjmp() and throw() must not violate the entry/exit criteria.
  7678. CS->getCapturedDecl()->setNothrow();
  7679. }
  7680. OMPLoopDirective::HelperExprs B;
  7681. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7682. // define the nested loops number.
  7683. unsigned NestedLoopCount = checkOpenMPLoop(
  7684. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7685. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  7686. VarsWithImplicitDSA, B);
  7687. if (NestedLoopCount == 0)
  7688. return StmtError();
  7689. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7690. "omp target parallel for simd loop exprs were not built");
  7691. if (!CurContext->isDependentContext()) {
  7692. // Finalize the clauses that need pre-built expressions for CodeGen.
  7693. for (OMPClause *C : Clauses) {
  7694. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7695. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7696. B.NumIterations, *this, CurScope,
  7697. DSAStack))
  7698. return StmtError();
  7699. }
  7700. }
  7701. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7702. return StmtError();
  7703. setFunctionHasBranchProtectedScope();
  7704. return OMPTargetParallelForSimdDirective::Create(
  7705. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7706. }
  7707. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  7708. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7709. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7710. if (!AStmt)
  7711. return StmtError();
  7712. auto *CS = cast<CapturedStmt>(AStmt);
  7713. // 1.2.2 OpenMP Language Terminology
  7714. // Structured block - An executable statement with a single entry at the
  7715. // top and a single exit at the bottom.
  7716. // The point of exit cannot be a branch out of the structured block.
  7717. // longjmp() and throw() must not violate the entry/exit criteria.
  7718. CS->getCapturedDecl()->setNothrow();
  7719. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  7720. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7721. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7722. // 1.2.2 OpenMP Language Terminology
  7723. // Structured block - An executable statement with a single entry at the
  7724. // top and a single exit at the bottom.
  7725. // The point of exit cannot be a branch out of the structured block.
  7726. // longjmp() and throw() must not violate the entry/exit criteria.
  7727. CS->getCapturedDecl()->setNothrow();
  7728. }
  7729. OMPLoopDirective::HelperExprs B;
  7730. // In presence of clause 'collapse' with number of loops, it will define the
  7731. // nested loops number.
  7732. unsigned NestedLoopCount =
  7733. checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  7734. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  7735. VarsWithImplicitDSA, B);
  7736. if (NestedLoopCount == 0)
  7737. return StmtError();
  7738. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7739. "omp target simd loop exprs were not built");
  7740. if (!CurContext->isDependentContext()) {
  7741. // Finalize the clauses that need pre-built expressions for CodeGen.
  7742. for (OMPClause *C : Clauses) {
  7743. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7744. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7745. B.NumIterations, *this, CurScope,
  7746. DSAStack))
  7747. return StmtError();
  7748. }
  7749. }
  7750. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7751. return StmtError();
  7752. setFunctionHasBranchProtectedScope();
  7753. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  7754. NestedLoopCount, Clauses, AStmt, B);
  7755. }
  7756. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  7757. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7758. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7759. if (!AStmt)
  7760. return StmtError();
  7761. auto *CS = cast<CapturedStmt>(AStmt);
  7762. // 1.2.2 OpenMP Language Terminology
  7763. // Structured block - An executable statement with a single entry at the
  7764. // top and a single exit at the bottom.
  7765. // The point of exit cannot be a branch out of the structured block.
  7766. // longjmp() and throw() must not violate the entry/exit criteria.
  7767. CS->getCapturedDecl()->setNothrow();
  7768. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  7769. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7770. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7771. // 1.2.2 OpenMP Language Terminology
  7772. // Structured block - An executable statement with a single entry at the
  7773. // top and a single exit at the bottom.
  7774. // The point of exit cannot be a branch out of the structured block.
  7775. // longjmp() and throw() must not violate the entry/exit criteria.
  7776. CS->getCapturedDecl()->setNothrow();
  7777. }
  7778. OMPLoopDirective::HelperExprs B;
  7779. // In presence of clause 'collapse' with number of loops, it will
  7780. // define the nested loops number.
  7781. unsigned NestedLoopCount =
  7782. checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  7783. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7784. *DSAStack, VarsWithImplicitDSA, B);
  7785. if (NestedLoopCount == 0)
  7786. return StmtError();
  7787. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7788. "omp teams distribute loop exprs were not built");
  7789. setFunctionHasBranchProtectedScope();
  7790. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7791. return OMPTeamsDistributeDirective::Create(
  7792. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7793. }
  7794. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  7795. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7796. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7797. if (!AStmt)
  7798. return StmtError();
  7799. auto *CS = cast<CapturedStmt>(AStmt);
  7800. // 1.2.2 OpenMP Language Terminology
  7801. // Structured block - An executable statement with a single entry at the
  7802. // top and a single exit at the bottom.
  7803. // The point of exit cannot be a branch out of the structured block.
  7804. // longjmp() and throw() must not violate the entry/exit criteria.
  7805. CS->getCapturedDecl()->setNothrow();
  7806. for (int ThisCaptureLevel =
  7807. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  7808. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7809. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7810. // 1.2.2 OpenMP Language Terminology
  7811. // Structured block - An executable statement with a single entry at the
  7812. // top and a single exit at the bottom.
  7813. // The point of exit cannot be a branch out of the structured block.
  7814. // longjmp() and throw() must not violate the entry/exit criteria.
  7815. CS->getCapturedDecl()->setNothrow();
  7816. }
  7817. OMPLoopDirective::HelperExprs B;
  7818. // In presence of clause 'collapse' with number of loops, it will
  7819. // define the nested loops number.
  7820. unsigned NestedLoopCount = checkOpenMPLoop(
  7821. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  7822. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7823. VarsWithImplicitDSA, B);
  7824. if (NestedLoopCount == 0)
  7825. return StmtError();
  7826. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7827. "omp teams distribute simd loop exprs were not built");
  7828. if (!CurContext->isDependentContext()) {
  7829. // Finalize the clauses that need pre-built expressions for CodeGen.
  7830. for (OMPClause *C : Clauses) {
  7831. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7832. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7833. B.NumIterations, *this, CurScope,
  7834. DSAStack))
  7835. return StmtError();
  7836. }
  7837. }
  7838. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7839. return StmtError();
  7840. setFunctionHasBranchProtectedScope();
  7841. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7842. return OMPTeamsDistributeSimdDirective::Create(
  7843. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7844. }
  7845. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  7846. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7847. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7848. if (!AStmt)
  7849. return StmtError();
  7850. auto *CS = cast<CapturedStmt>(AStmt);
  7851. // 1.2.2 OpenMP Language Terminology
  7852. // Structured block - An executable statement with a single entry at the
  7853. // top and a single exit at the bottom.
  7854. // The point of exit cannot be a branch out of the structured block.
  7855. // longjmp() and throw() must not violate the entry/exit criteria.
  7856. CS->getCapturedDecl()->setNothrow();
  7857. for (int ThisCaptureLevel =
  7858. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  7859. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7860. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7861. // 1.2.2 OpenMP Language Terminology
  7862. // Structured block - An executable statement with a single entry at the
  7863. // top and a single exit at the bottom.
  7864. // The point of exit cannot be a branch out of the structured block.
  7865. // longjmp() and throw() must not violate the entry/exit criteria.
  7866. CS->getCapturedDecl()->setNothrow();
  7867. }
  7868. OMPLoopDirective::HelperExprs B;
  7869. // In presence of clause 'collapse' with number of loops, it will
  7870. // define the nested loops number.
  7871. unsigned NestedLoopCount = checkOpenMPLoop(
  7872. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7873. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7874. VarsWithImplicitDSA, B);
  7875. if (NestedLoopCount == 0)
  7876. return StmtError();
  7877. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7878. "omp for loop exprs were not built");
  7879. if (!CurContext->isDependentContext()) {
  7880. // Finalize the clauses that need pre-built expressions for CodeGen.
  7881. for (OMPClause *C : Clauses) {
  7882. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7883. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7884. B.NumIterations, *this, CurScope,
  7885. DSAStack))
  7886. return StmtError();
  7887. }
  7888. }
  7889. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7890. return StmtError();
  7891. setFunctionHasBranchProtectedScope();
  7892. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7893. return OMPTeamsDistributeParallelForSimdDirective::Create(
  7894. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7895. }
  7896. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  7897. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7898. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7899. if (!AStmt)
  7900. return StmtError();
  7901. auto *CS = cast<CapturedStmt>(AStmt);
  7902. // 1.2.2 OpenMP Language Terminology
  7903. // Structured block - An executable statement with a single entry at the
  7904. // top and a single exit at the bottom.
  7905. // The point of exit cannot be a branch out of the structured block.
  7906. // longjmp() and throw() must not violate the entry/exit criteria.
  7907. CS->getCapturedDecl()->setNothrow();
  7908. for (int ThisCaptureLevel =
  7909. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  7910. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7911. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7912. // 1.2.2 OpenMP Language Terminology
  7913. // Structured block - An executable statement with a single entry at the
  7914. // top and a single exit at the bottom.
  7915. // The point of exit cannot be a branch out of the structured block.
  7916. // longjmp() and throw() must not violate the entry/exit criteria.
  7917. CS->getCapturedDecl()->setNothrow();
  7918. }
  7919. OMPLoopDirective::HelperExprs B;
  7920. // In presence of clause 'collapse' with number of loops, it will
  7921. // define the nested loops number.
  7922. unsigned NestedLoopCount = checkOpenMPLoop(
  7923. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  7924. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7925. VarsWithImplicitDSA, B);
  7926. if (NestedLoopCount == 0)
  7927. return StmtError();
  7928. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7929. "omp for loop exprs were not built");
  7930. setFunctionHasBranchProtectedScope();
  7931. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7932. return OMPTeamsDistributeParallelForDirective::Create(
  7933. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  7934. DSAStack->isCancelRegion());
  7935. }
  7936. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  7937. Stmt *AStmt,
  7938. SourceLocation StartLoc,
  7939. SourceLocation EndLoc) {
  7940. if (!AStmt)
  7941. return StmtError();
  7942. auto *CS = cast<CapturedStmt>(AStmt);
  7943. // 1.2.2 OpenMP Language Terminology
  7944. // Structured block - An executable statement with a single entry at the
  7945. // top and a single exit at the bottom.
  7946. // The point of exit cannot be a branch out of the structured block.
  7947. // longjmp() and throw() must not violate the entry/exit criteria.
  7948. CS->getCapturedDecl()->setNothrow();
  7949. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  7950. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7951. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7952. // 1.2.2 OpenMP Language Terminology
  7953. // Structured block - An executable statement with a single entry at the
  7954. // top and a single exit at the bottom.
  7955. // The point of exit cannot be a branch out of the structured block.
  7956. // longjmp() and throw() must not violate the entry/exit criteria.
  7957. CS->getCapturedDecl()->setNothrow();
  7958. }
  7959. setFunctionHasBranchProtectedScope();
  7960. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7961. AStmt);
  7962. }
  7963. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  7964. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7965. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7966. if (!AStmt)
  7967. return StmtError();
  7968. auto *CS = cast<CapturedStmt>(AStmt);
  7969. // 1.2.2 OpenMP Language Terminology
  7970. // Structured block - An executable statement with a single entry at the
  7971. // top and a single exit at the bottom.
  7972. // The point of exit cannot be a branch out of the structured block.
  7973. // longjmp() and throw() must not violate the entry/exit criteria.
  7974. CS->getCapturedDecl()->setNothrow();
  7975. for (int ThisCaptureLevel =
  7976. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  7977. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7978. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7979. // 1.2.2 OpenMP Language Terminology
  7980. // Structured block - An executable statement with a single entry at the
  7981. // top and a single exit at the bottom.
  7982. // The point of exit cannot be a branch out of the structured block.
  7983. // longjmp() and throw() must not violate the entry/exit criteria.
  7984. CS->getCapturedDecl()->setNothrow();
  7985. }
  7986. OMPLoopDirective::HelperExprs B;
  7987. // In presence of clause 'collapse' with number of loops, it will
  7988. // define the nested loops number.
  7989. unsigned NestedLoopCount = checkOpenMPLoop(
  7990. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  7991. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7992. VarsWithImplicitDSA, B);
  7993. if (NestedLoopCount == 0)
  7994. return StmtError();
  7995. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7996. "omp target teams distribute loop exprs were not built");
  7997. setFunctionHasBranchProtectedScope();
  7998. return OMPTargetTeamsDistributeDirective::Create(
  7999. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8000. }
  8001. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  8002. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8003. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8004. if (!AStmt)
  8005. return StmtError();
  8006. auto *CS = cast<CapturedStmt>(AStmt);
  8007. // 1.2.2 OpenMP Language Terminology
  8008. // Structured block - An executable statement with a single entry at the
  8009. // top and a single exit at the bottom.
  8010. // The point of exit cannot be a branch out of the structured block.
  8011. // longjmp() and throw() must not violate the entry/exit criteria.
  8012. CS->getCapturedDecl()->setNothrow();
  8013. for (int ThisCaptureLevel =
  8014. getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
  8015. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8016. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8017. // 1.2.2 OpenMP Language Terminology
  8018. // Structured block - An executable statement with a single entry at the
  8019. // top and a single exit at the bottom.
  8020. // The point of exit cannot be a branch out of the structured block.
  8021. // longjmp() and throw() must not violate the entry/exit criteria.
  8022. CS->getCapturedDecl()->setNothrow();
  8023. }
  8024. OMPLoopDirective::HelperExprs B;
  8025. // In presence of clause 'collapse' with number of loops, it will
  8026. // define the nested loops number.
  8027. unsigned NestedLoopCount = checkOpenMPLoop(
  8028. OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  8029. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8030. VarsWithImplicitDSA, B);
  8031. if (NestedLoopCount == 0)
  8032. return StmtError();
  8033. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8034. "omp target teams distribute parallel for loop exprs were not built");
  8035. if (!CurContext->isDependentContext()) {
  8036. // Finalize the clauses that need pre-built expressions for CodeGen.
  8037. for (OMPClause *C : Clauses) {
  8038. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8039. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8040. B.NumIterations, *this, CurScope,
  8041. DSAStack))
  8042. return StmtError();
  8043. }
  8044. }
  8045. setFunctionHasBranchProtectedScope();
  8046. return OMPTargetTeamsDistributeParallelForDirective::Create(
  8047. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  8048. DSAStack->isCancelRegion());
  8049. }
  8050. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  8051. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8052. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8053. if (!AStmt)
  8054. return StmtError();
  8055. auto *CS = cast<CapturedStmt>(AStmt);
  8056. // 1.2.2 OpenMP Language Terminology
  8057. // Structured block - An executable statement with a single entry at the
  8058. // top and a single exit at the bottom.
  8059. // The point of exit cannot be a branch out of the structured block.
  8060. // longjmp() and throw() must not violate the entry/exit criteria.
  8061. CS->getCapturedDecl()->setNothrow();
  8062. for (int ThisCaptureLevel = getOpenMPCaptureLevels(
  8063. OMPD_target_teams_distribute_parallel_for_simd);
  8064. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8065. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8066. // 1.2.2 OpenMP Language Terminology
  8067. // Structured block - An executable statement with a single entry at the
  8068. // top and a single exit at the bottom.
  8069. // The point of exit cannot be a branch out of the structured block.
  8070. // longjmp() and throw() must not violate the entry/exit criteria.
  8071. CS->getCapturedDecl()->setNothrow();
  8072. }
  8073. OMPLoopDirective::HelperExprs B;
  8074. // In presence of clause 'collapse' with number of loops, it will
  8075. // define the nested loops number.
  8076. unsigned NestedLoopCount =
  8077. checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
  8078. getCollapseNumberExpr(Clauses),
  8079. nullptr /*ordered not a clause on distribute*/, CS, *this,
  8080. *DSAStack, VarsWithImplicitDSA, B);
  8081. if (NestedLoopCount == 0)
  8082. return StmtError();
  8083. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8084. "omp target teams distribute parallel for simd loop exprs were not "
  8085. "built");
  8086. if (!CurContext->isDependentContext()) {
  8087. // Finalize the clauses that need pre-built expressions for CodeGen.
  8088. for (OMPClause *C : Clauses) {
  8089. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8090. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8091. B.NumIterations, *this, CurScope,
  8092. DSAStack))
  8093. return StmtError();
  8094. }
  8095. }
  8096. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8097. return StmtError();
  8098. setFunctionHasBranchProtectedScope();
  8099. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  8100. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8101. }
  8102. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  8103. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  8104. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  8105. if (!AStmt)
  8106. return StmtError();
  8107. auto *CS = cast<CapturedStmt>(AStmt);
  8108. // 1.2.2 OpenMP Language Terminology
  8109. // Structured block - An executable statement with a single entry at the
  8110. // top and a single exit at the bottom.
  8111. // The point of exit cannot be a branch out of the structured block.
  8112. // longjmp() and throw() must not violate the entry/exit criteria.
  8113. CS->getCapturedDecl()->setNothrow();
  8114. for (int ThisCaptureLevel =
  8115. getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
  8116. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  8117. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  8118. // 1.2.2 OpenMP Language Terminology
  8119. // Structured block - An executable statement with a single entry at the
  8120. // top and a single exit at the bottom.
  8121. // The point of exit cannot be a branch out of the structured block.
  8122. // longjmp() and throw() must not violate the entry/exit criteria.
  8123. CS->getCapturedDecl()->setNothrow();
  8124. }
  8125. OMPLoopDirective::HelperExprs B;
  8126. // In presence of clause 'collapse' with number of loops, it will
  8127. // define the nested loops number.
  8128. unsigned NestedLoopCount = checkOpenMPLoop(
  8129. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  8130. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  8131. VarsWithImplicitDSA, B);
  8132. if (NestedLoopCount == 0)
  8133. return StmtError();
  8134. assert((CurContext->isDependentContext() || B.builtAll()) &&
  8135. "omp target teams distribute simd loop exprs were not built");
  8136. if (!CurContext->isDependentContext()) {
  8137. // Finalize the clauses that need pre-built expressions for CodeGen.
  8138. for (OMPClause *C : Clauses) {
  8139. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  8140. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  8141. B.NumIterations, *this, CurScope,
  8142. DSAStack))
  8143. return StmtError();
  8144. }
  8145. }
  8146. if (checkSimdlenSafelenSpecified(*this, Clauses))
  8147. return StmtError();
  8148. setFunctionHasBranchProtectedScope();
  8149. return OMPTargetTeamsDistributeSimdDirective::Create(
  8150. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  8151. }
  8152. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  8153. SourceLocation StartLoc,
  8154. SourceLocation LParenLoc,
  8155. SourceLocation EndLoc) {
  8156. OMPClause *Res = nullptr;
  8157. switch (Kind) {
  8158. case OMPC_final:
  8159. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  8160. break;
  8161. case OMPC_num_threads:
  8162. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  8163. break;
  8164. case OMPC_safelen:
  8165. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  8166. break;
  8167. case OMPC_simdlen:
  8168. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  8169. break;
  8170. case OMPC_allocator:
  8171. Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
  8172. break;
  8173. case OMPC_collapse:
  8174. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  8175. break;
  8176. case OMPC_ordered:
  8177. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  8178. break;
  8179. case OMPC_device:
  8180. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  8181. break;
  8182. case OMPC_num_teams:
  8183. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  8184. break;
  8185. case OMPC_thread_limit:
  8186. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  8187. break;
  8188. case OMPC_priority:
  8189. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  8190. break;
  8191. case OMPC_grainsize:
  8192. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  8193. break;
  8194. case OMPC_num_tasks:
  8195. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  8196. break;
  8197. case OMPC_hint:
  8198. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  8199. break;
  8200. case OMPC_if:
  8201. case OMPC_default:
  8202. case OMPC_proc_bind:
  8203. case OMPC_schedule:
  8204. case OMPC_private:
  8205. case OMPC_firstprivate:
  8206. case OMPC_lastprivate:
  8207. case OMPC_shared:
  8208. case OMPC_reduction:
  8209. case OMPC_task_reduction:
  8210. case OMPC_in_reduction:
  8211. case OMPC_linear:
  8212. case OMPC_aligned:
  8213. case OMPC_copyin:
  8214. case OMPC_copyprivate:
  8215. case OMPC_nowait:
  8216. case OMPC_untied:
  8217. case OMPC_mergeable:
  8218. case OMPC_threadprivate:
  8219. case OMPC_allocate:
  8220. case OMPC_flush:
  8221. case OMPC_read:
  8222. case OMPC_write:
  8223. case OMPC_update:
  8224. case OMPC_capture:
  8225. case OMPC_seq_cst:
  8226. case OMPC_depend:
  8227. case OMPC_threads:
  8228. case OMPC_simd:
  8229. case OMPC_map:
  8230. case OMPC_nogroup:
  8231. case OMPC_dist_schedule:
  8232. case OMPC_defaultmap:
  8233. case OMPC_unknown:
  8234. case OMPC_uniform:
  8235. case OMPC_to:
  8236. case OMPC_from:
  8237. case OMPC_use_device_ptr:
  8238. case OMPC_is_device_ptr:
  8239. case OMPC_unified_address:
  8240. case OMPC_unified_shared_memory:
  8241. case OMPC_reverse_offload:
  8242. case OMPC_dynamic_allocators:
  8243. case OMPC_atomic_default_mem_order:
  8244. llvm_unreachable("Clause is not allowed.");
  8245. }
  8246. return Res;
  8247. }
  8248. // An OpenMP directive such as 'target parallel' has two captured regions:
  8249. // for the 'target' and 'parallel' respectively. This function returns
  8250. // the region in which to capture expressions associated with a clause.
  8251. // A return value of OMPD_unknown signifies that the expression should not
  8252. // be captured.
  8253. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  8254. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  8255. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  8256. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  8257. switch (CKind) {
  8258. case OMPC_if:
  8259. switch (DKind) {
  8260. case OMPD_target_parallel:
  8261. case OMPD_target_parallel_for:
  8262. case OMPD_target_parallel_for_simd:
  8263. // If this clause applies to the nested 'parallel' region, capture within
  8264. // the 'target' region, otherwise do not capture.
  8265. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  8266. CaptureRegion = OMPD_target;
  8267. break;
  8268. case OMPD_target_teams_distribute_parallel_for:
  8269. case OMPD_target_teams_distribute_parallel_for_simd:
  8270. // If this clause applies to the nested 'parallel' region, capture within
  8271. // the 'teams' region, otherwise do not capture.
  8272. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  8273. CaptureRegion = OMPD_teams;
  8274. break;
  8275. case OMPD_teams_distribute_parallel_for:
  8276. case OMPD_teams_distribute_parallel_for_simd:
  8277. CaptureRegion = OMPD_teams;
  8278. break;
  8279. case OMPD_target_update:
  8280. case OMPD_target_enter_data:
  8281. case OMPD_target_exit_data:
  8282. CaptureRegion = OMPD_task;
  8283. break;
  8284. case OMPD_cancel:
  8285. case OMPD_parallel:
  8286. case OMPD_parallel_sections:
  8287. case OMPD_parallel_for:
  8288. case OMPD_parallel_for_simd:
  8289. case OMPD_target:
  8290. case OMPD_target_simd:
  8291. case OMPD_target_teams:
  8292. case OMPD_target_teams_distribute:
  8293. case OMPD_target_teams_distribute_simd:
  8294. case OMPD_distribute_parallel_for:
  8295. case OMPD_distribute_parallel_for_simd:
  8296. case OMPD_task:
  8297. case OMPD_taskloop:
  8298. case OMPD_taskloop_simd:
  8299. case OMPD_target_data:
  8300. // Do not capture if-clause expressions.
  8301. break;
  8302. case OMPD_threadprivate:
  8303. case OMPD_allocate:
  8304. case OMPD_taskyield:
  8305. case OMPD_barrier:
  8306. case OMPD_taskwait:
  8307. case OMPD_cancellation_point:
  8308. case OMPD_flush:
  8309. case OMPD_declare_reduction:
  8310. case OMPD_declare_mapper:
  8311. case OMPD_declare_simd:
  8312. case OMPD_declare_target:
  8313. case OMPD_end_declare_target:
  8314. case OMPD_teams:
  8315. case OMPD_simd:
  8316. case OMPD_for:
  8317. case OMPD_for_simd:
  8318. case OMPD_sections:
  8319. case OMPD_section:
  8320. case OMPD_single:
  8321. case OMPD_master:
  8322. case OMPD_critical:
  8323. case OMPD_taskgroup:
  8324. case OMPD_distribute:
  8325. case OMPD_ordered:
  8326. case OMPD_atomic:
  8327. case OMPD_distribute_simd:
  8328. case OMPD_teams_distribute:
  8329. case OMPD_teams_distribute_simd:
  8330. case OMPD_requires:
  8331. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  8332. case OMPD_unknown:
  8333. llvm_unreachable("Unknown OpenMP directive");
  8334. }
  8335. break;
  8336. case OMPC_num_threads:
  8337. switch (DKind) {
  8338. case OMPD_target_parallel:
  8339. case OMPD_target_parallel_for:
  8340. case OMPD_target_parallel_for_simd:
  8341. CaptureRegion = OMPD_target;
  8342. break;
  8343. case OMPD_teams_distribute_parallel_for:
  8344. case OMPD_teams_distribute_parallel_for_simd:
  8345. case OMPD_target_teams_distribute_parallel_for:
  8346. case OMPD_target_teams_distribute_parallel_for_simd:
  8347. CaptureRegion = OMPD_teams;
  8348. break;
  8349. case OMPD_parallel:
  8350. case OMPD_parallel_sections:
  8351. case OMPD_parallel_for:
  8352. case OMPD_parallel_for_simd:
  8353. case OMPD_distribute_parallel_for:
  8354. case OMPD_distribute_parallel_for_simd:
  8355. // Do not capture num_threads-clause expressions.
  8356. break;
  8357. case OMPD_target_data:
  8358. case OMPD_target_enter_data:
  8359. case OMPD_target_exit_data:
  8360. case OMPD_target_update:
  8361. case OMPD_target:
  8362. case OMPD_target_simd:
  8363. case OMPD_target_teams:
  8364. case OMPD_target_teams_distribute:
  8365. case OMPD_target_teams_distribute_simd:
  8366. case OMPD_cancel:
  8367. case OMPD_task:
  8368. case OMPD_taskloop:
  8369. case OMPD_taskloop_simd:
  8370. case OMPD_threadprivate:
  8371. case OMPD_allocate:
  8372. case OMPD_taskyield:
  8373. case OMPD_barrier:
  8374. case OMPD_taskwait:
  8375. case OMPD_cancellation_point:
  8376. case OMPD_flush:
  8377. case OMPD_declare_reduction:
  8378. case OMPD_declare_mapper:
  8379. case OMPD_declare_simd:
  8380. case OMPD_declare_target:
  8381. case OMPD_end_declare_target:
  8382. case OMPD_teams:
  8383. case OMPD_simd:
  8384. case OMPD_for:
  8385. case OMPD_for_simd:
  8386. case OMPD_sections:
  8387. case OMPD_section:
  8388. case OMPD_single:
  8389. case OMPD_master:
  8390. case OMPD_critical:
  8391. case OMPD_taskgroup:
  8392. case OMPD_distribute:
  8393. case OMPD_ordered:
  8394. case OMPD_atomic:
  8395. case OMPD_distribute_simd:
  8396. case OMPD_teams_distribute:
  8397. case OMPD_teams_distribute_simd:
  8398. case OMPD_requires:
  8399. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  8400. case OMPD_unknown:
  8401. llvm_unreachable("Unknown OpenMP directive");
  8402. }
  8403. break;
  8404. case OMPC_num_teams:
  8405. switch (DKind) {
  8406. case OMPD_target_teams:
  8407. case OMPD_target_teams_distribute:
  8408. case OMPD_target_teams_distribute_simd:
  8409. case OMPD_target_teams_distribute_parallel_for:
  8410. case OMPD_target_teams_distribute_parallel_for_simd:
  8411. CaptureRegion = OMPD_target;
  8412. break;
  8413. case OMPD_teams_distribute_parallel_for:
  8414. case OMPD_teams_distribute_parallel_for_simd:
  8415. case OMPD_teams:
  8416. case OMPD_teams_distribute:
  8417. case OMPD_teams_distribute_simd:
  8418. // Do not capture num_teams-clause expressions.
  8419. break;
  8420. case OMPD_distribute_parallel_for:
  8421. case OMPD_distribute_parallel_for_simd:
  8422. case OMPD_task:
  8423. case OMPD_taskloop:
  8424. case OMPD_taskloop_simd:
  8425. case OMPD_target_data:
  8426. case OMPD_target_enter_data:
  8427. case OMPD_target_exit_data:
  8428. case OMPD_target_update:
  8429. case OMPD_cancel:
  8430. case OMPD_parallel:
  8431. case OMPD_parallel_sections:
  8432. case OMPD_parallel_for:
  8433. case OMPD_parallel_for_simd:
  8434. case OMPD_target:
  8435. case OMPD_target_simd:
  8436. case OMPD_target_parallel:
  8437. case OMPD_target_parallel_for:
  8438. case OMPD_target_parallel_for_simd:
  8439. case OMPD_threadprivate:
  8440. case OMPD_allocate:
  8441. case OMPD_taskyield:
  8442. case OMPD_barrier:
  8443. case OMPD_taskwait:
  8444. case OMPD_cancellation_point:
  8445. case OMPD_flush:
  8446. case OMPD_declare_reduction:
  8447. case OMPD_declare_mapper:
  8448. case OMPD_declare_simd:
  8449. case OMPD_declare_target:
  8450. case OMPD_end_declare_target:
  8451. case OMPD_simd:
  8452. case OMPD_for:
  8453. case OMPD_for_simd:
  8454. case OMPD_sections:
  8455. case OMPD_section:
  8456. case OMPD_single:
  8457. case OMPD_master:
  8458. case OMPD_critical:
  8459. case OMPD_taskgroup:
  8460. case OMPD_distribute:
  8461. case OMPD_ordered:
  8462. case OMPD_atomic:
  8463. case OMPD_distribute_simd:
  8464. case OMPD_requires:
  8465. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  8466. case OMPD_unknown:
  8467. llvm_unreachable("Unknown OpenMP directive");
  8468. }
  8469. break;
  8470. case OMPC_thread_limit:
  8471. switch (DKind) {
  8472. case OMPD_target_teams:
  8473. case OMPD_target_teams_distribute:
  8474. case OMPD_target_teams_distribute_simd:
  8475. case OMPD_target_teams_distribute_parallel_for:
  8476. case OMPD_target_teams_distribute_parallel_for_simd:
  8477. CaptureRegion = OMPD_target;
  8478. break;
  8479. case OMPD_teams_distribute_parallel_for:
  8480. case OMPD_teams_distribute_parallel_for_simd:
  8481. case OMPD_teams:
  8482. case OMPD_teams_distribute:
  8483. case OMPD_teams_distribute_simd:
  8484. // Do not capture thread_limit-clause expressions.
  8485. break;
  8486. case OMPD_distribute_parallel_for:
  8487. case OMPD_distribute_parallel_for_simd:
  8488. case OMPD_task:
  8489. case OMPD_taskloop:
  8490. case OMPD_taskloop_simd:
  8491. case OMPD_target_data:
  8492. case OMPD_target_enter_data:
  8493. case OMPD_target_exit_data:
  8494. case OMPD_target_update:
  8495. case OMPD_cancel:
  8496. case OMPD_parallel:
  8497. case OMPD_parallel_sections:
  8498. case OMPD_parallel_for:
  8499. case OMPD_parallel_for_simd:
  8500. case OMPD_target:
  8501. case OMPD_target_simd:
  8502. case OMPD_target_parallel:
  8503. case OMPD_target_parallel_for:
  8504. case OMPD_target_parallel_for_simd:
  8505. case OMPD_threadprivate:
  8506. case OMPD_allocate:
  8507. case OMPD_taskyield:
  8508. case OMPD_barrier:
  8509. case OMPD_taskwait:
  8510. case OMPD_cancellation_point:
  8511. case OMPD_flush:
  8512. case OMPD_declare_reduction:
  8513. case OMPD_declare_mapper:
  8514. case OMPD_declare_simd:
  8515. case OMPD_declare_target:
  8516. case OMPD_end_declare_target:
  8517. case OMPD_simd:
  8518. case OMPD_for:
  8519. case OMPD_for_simd:
  8520. case OMPD_sections:
  8521. case OMPD_section:
  8522. case OMPD_single:
  8523. case OMPD_master:
  8524. case OMPD_critical:
  8525. case OMPD_taskgroup:
  8526. case OMPD_distribute:
  8527. case OMPD_ordered:
  8528. case OMPD_atomic:
  8529. case OMPD_distribute_simd:
  8530. case OMPD_requires:
  8531. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  8532. case OMPD_unknown:
  8533. llvm_unreachable("Unknown OpenMP directive");
  8534. }
  8535. break;
  8536. case OMPC_schedule:
  8537. switch (DKind) {
  8538. case OMPD_parallel_for:
  8539. case OMPD_parallel_for_simd:
  8540. case OMPD_distribute_parallel_for:
  8541. case OMPD_distribute_parallel_for_simd:
  8542. case OMPD_teams_distribute_parallel_for:
  8543. case OMPD_teams_distribute_parallel_for_simd:
  8544. case OMPD_target_parallel_for:
  8545. case OMPD_target_parallel_for_simd:
  8546. case OMPD_target_teams_distribute_parallel_for:
  8547. case OMPD_target_teams_distribute_parallel_for_simd:
  8548. CaptureRegion = OMPD_parallel;
  8549. break;
  8550. case OMPD_for:
  8551. case OMPD_for_simd:
  8552. // Do not capture schedule-clause expressions.
  8553. break;
  8554. case OMPD_task:
  8555. case OMPD_taskloop:
  8556. case OMPD_taskloop_simd:
  8557. case OMPD_target_data:
  8558. case OMPD_target_enter_data:
  8559. case OMPD_target_exit_data:
  8560. case OMPD_target_update:
  8561. case OMPD_teams:
  8562. case OMPD_teams_distribute:
  8563. case OMPD_teams_distribute_simd:
  8564. case OMPD_target_teams_distribute:
  8565. case OMPD_target_teams_distribute_simd:
  8566. case OMPD_target:
  8567. case OMPD_target_simd:
  8568. case OMPD_target_parallel:
  8569. case OMPD_cancel:
  8570. case OMPD_parallel:
  8571. case OMPD_parallel_sections:
  8572. case OMPD_threadprivate:
  8573. case OMPD_allocate:
  8574. case OMPD_taskyield:
  8575. case OMPD_barrier:
  8576. case OMPD_taskwait:
  8577. case OMPD_cancellation_point:
  8578. case OMPD_flush:
  8579. case OMPD_declare_reduction:
  8580. case OMPD_declare_mapper:
  8581. case OMPD_declare_simd:
  8582. case OMPD_declare_target:
  8583. case OMPD_end_declare_target:
  8584. case OMPD_simd:
  8585. case OMPD_sections:
  8586. case OMPD_section:
  8587. case OMPD_single:
  8588. case OMPD_master:
  8589. case OMPD_critical:
  8590. case OMPD_taskgroup:
  8591. case OMPD_distribute:
  8592. case OMPD_ordered:
  8593. case OMPD_atomic:
  8594. case OMPD_distribute_simd:
  8595. case OMPD_target_teams:
  8596. case OMPD_requires:
  8597. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  8598. case OMPD_unknown:
  8599. llvm_unreachable("Unknown OpenMP directive");
  8600. }
  8601. break;
  8602. case OMPC_dist_schedule:
  8603. switch (DKind) {
  8604. case OMPD_teams_distribute_parallel_for:
  8605. case OMPD_teams_distribute_parallel_for_simd:
  8606. case OMPD_teams_distribute:
  8607. case OMPD_teams_distribute_simd:
  8608. case OMPD_target_teams_distribute_parallel_for:
  8609. case OMPD_target_teams_distribute_parallel_for_simd:
  8610. case OMPD_target_teams_distribute:
  8611. case OMPD_target_teams_distribute_simd:
  8612. CaptureRegion = OMPD_teams;
  8613. break;
  8614. case OMPD_distribute_parallel_for:
  8615. case OMPD_distribute_parallel_for_simd:
  8616. case OMPD_distribute:
  8617. case OMPD_distribute_simd:
  8618. // Do not capture thread_limit-clause expressions.
  8619. break;
  8620. case OMPD_parallel_for:
  8621. case OMPD_parallel_for_simd:
  8622. case OMPD_target_parallel_for_simd:
  8623. case OMPD_target_parallel_for:
  8624. case OMPD_task:
  8625. case OMPD_taskloop:
  8626. case OMPD_taskloop_simd:
  8627. case OMPD_target_data:
  8628. case OMPD_target_enter_data:
  8629. case OMPD_target_exit_data:
  8630. case OMPD_target_update:
  8631. case OMPD_teams:
  8632. case OMPD_target:
  8633. case OMPD_target_simd:
  8634. case OMPD_target_parallel:
  8635. case OMPD_cancel:
  8636. case OMPD_parallel:
  8637. case OMPD_parallel_sections:
  8638. case OMPD_threadprivate:
  8639. case OMPD_allocate:
  8640. case OMPD_taskyield:
  8641. case OMPD_barrier:
  8642. case OMPD_taskwait:
  8643. case OMPD_cancellation_point:
  8644. case OMPD_flush:
  8645. case OMPD_declare_reduction:
  8646. case OMPD_declare_mapper:
  8647. case OMPD_declare_simd:
  8648. case OMPD_declare_target:
  8649. case OMPD_end_declare_target:
  8650. case OMPD_simd:
  8651. case OMPD_for:
  8652. case OMPD_for_simd:
  8653. case OMPD_sections:
  8654. case OMPD_section:
  8655. case OMPD_single:
  8656. case OMPD_master:
  8657. case OMPD_critical:
  8658. case OMPD_taskgroup:
  8659. case OMPD_ordered:
  8660. case OMPD_atomic:
  8661. case OMPD_target_teams:
  8662. case OMPD_requires:
  8663. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  8664. case OMPD_unknown:
  8665. llvm_unreachable("Unknown OpenMP directive");
  8666. }
  8667. break;
  8668. case OMPC_device:
  8669. switch (DKind) {
  8670. case OMPD_target_update:
  8671. case OMPD_target_enter_data:
  8672. case OMPD_target_exit_data:
  8673. case OMPD_target:
  8674. case OMPD_target_simd:
  8675. case OMPD_target_teams:
  8676. case OMPD_target_parallel:
  8677. case OMPD_target_teams_distribute:
  8678. case OMPD_target_teams_distribute_simd:
  8679. case OMPD_target_parallel_for:
  8680. case OMPD_target_parallel_for_simd:
  8681. case OMPD_target_teams_distribute_parallel_for:
  8682. case OMPD_target_teams_distribute_parallel_for_simd:
  8683. CaptureRegion = OMPD_task;
  8684. break;
  8685. case OMPD_target_data:
  8686. // Do not capture device-clause expressions.
  8687. break;
  8688. case OMPD_teams_distribute_parallel_for:
  8689. case OMPD_teams_distribute_parallel_for_simd:
  8690. case OMPD_teams:
  8691. case OMPD_teams_distribute:
  8692. case OMPD_teams_distribute_simd:
  8693. case OMPD_distribute_parallel_for:
  8694. case OMPD_distribute_parallel_for_simd:
  8695. case OMPD_task:
  8696. case OMPD_taskloop:
  8697. case OMPD_taskloop_simd:
  8698. case OMPD_cancel:
  8699. case OMPD_parallel:
  8700. case OMPD_parallel_sections:
  8701. case OMPD_parallel_for:
  8702. case OMPD_parallel_for_simd:
  8703. case OMPD_threadprivate:
  8704. case OMPD_allocate:
  8705. case OMPD_taskyield:
  8706. case OMPD_barrier:
  8707. case OMPD_taskwait:
  8708. case OMPD_cancellation_point:
  8709. case OMPD_flush:
  8710. case OMPD_declare_reduction:
  8711. case OMPD_declare_mapper:
  8712. case OMPD_declare_simd:
  8713. case OMPD_declare_target:
  8714. case OMPD_end_declare_target:
  8715. case OMPD_simd:
  8716. case OMPD_for:
  8717. case OMPD_for_simd:
  8718. case OMPD_sections:
  8719. case OMPD_section:
  8720. case OMPD_single:
  8721. case OMPD_master:
  8722. case OMPD_critical:
  8723. case OMPD_taskgroup:
  8724. case OMPD_distribute:
  8725. case OMPD_ordered:
  8726. case OMPD_atomic:
  8727. case OMPD_distribute_simd:
  8728. case OMPD_requires:
  8729. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  8730. case OMPD_unknown:
  8731. llvm_unreachable("Unknown OpenMP directive");
  8732. }
  8733. break;
  8734. case OMPC_firstprivate:
  8735. case OMPC_lastprivate:
  8736. case OMPC_reduction:
  8737. case OMPC_task_reduction:
  8738. case OMPC_in_reduction:
  8739. case OMPC_linear:
  8740. case OMPC_default:
  8741. case OMPC_proc_bind:
  8742. case OMPC_final:
  8743. case OMPC_safelen:
  8744. case OMPC_simdlen:
  8745. case OMPC_allocator:
  8746. case OMPC_collapse:
  8747. case OMPC_private:
  8748. case OMPC_shared:
  8749. case OMPC_aligned:
  8750. case OMPC_copyin:
  8751. case OMPC_copyprivate:
  8752. case OMPC_ordered:
  8753. case OMPC_nowait:
  8754. case OMPC_untied:
  8755. case OMPC_mergeable:
  8756. case OMPC_threadprivate:
  8757. case OMPC_allocate:
  8758. case OMPC_flush:
  8759. case OMPC_read:
  8760. case OMPC_write:
  8761. case OMPC_update:
  8762. case OMPC_capture:
  8763. case OMPC_seq_cst:
  8764. case OMPC_depend:
  8765. case OMPC_threads:
  8766. case OMPC_simd:
  8767. case OMPC_map:
  8768. case OMPC_priority:
  8769. case OMPC_grainsize:
  8770. case OMPC_nogroup:
  8771. case OMPC_num_tasks:
  8772. case OMPC_hint:
  8773. case OMPC_defaultmap:
  8774. case OMPC_unknown:
  8775. case OMPC_uniform:
  8776. case OMPC_to:
  8777. case OMPC_from:
  8778. case OMPC_use_device_ptr:
  8779. case OMPC_is_device_ptr:
  8780. case OMPC_unified_address:
  8781. case OMPC_unified_shared_memory:
  8782. case OMPC_reverse_offload:
  8783. case OMPC_dynamic_allocators:
  8784. case OMPC_atomic_default_mem_order:
  8785. llvm_unreachable("Unexpected OpenMP clause.");
  8786. }
  8787. return CaptureRegion;
  8788. }
  8789. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  8790. Expr *Condition, SourceLocation StartLoc,
  8791. SourceLocation LParenLoc,
  8792. SourceLocation NameModifierLoc,
  8793. SourceLocation ColonLoc,
  8794. SourceLocation EndLoc) {
  8795. Expr *ValExpr = Condition;
  8796. Stmt *HelperValStmt = nullptr;
  8797. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  8798. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  8799. !Condition->isInstantiationDependent() &&
  8800. !Condition->containsUnexpandedParameterPack()) {
  8801. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  8802. if (Val.isInvalid())
  8803. return nullptr;
  8804. ValExpr = Val.get();
  8805. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  8806. CaptureRegion =
  8807. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  8808. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  8809. ValExpr = MakeFullExpr(ValExpr).get();
  8810. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8811. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8812. HelperValStmt = buildPreInits(Context, Captures);
  8813. }
  8814. }
  8815. return new (Context)
  8816. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  8817. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  8818. }
  8819. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  8820. SourceLocation StartLoc,
  8821. SourceLocation LParenLoc,
  8822. SourceLocation EndLoc) {
  8823. Expr *ValExpr = Condition;
  8824. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  8825. !Condition->isInstantiationDependent() &&
  8826. !Condition->containsUnexpandedParameterPack()) {
  8827. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  8828. if (Val.isInvalid())
  8829. return nullptr;
  8830. ValExpr = MakeFullExpr(Val.get()).get();
  8831. }
  8832. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  8833. }
  8834. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  8835. Expr *Op) {
  8836. if (!Op)
  8837. return ExprError();
  8838. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  8839. public:
  8840. IntConvertDiagnoser()
  8841. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  8842. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  8843. QualType T) override {
  8844. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  8845. }
  8846. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  8847. QualType T) override {
  8848. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  8849. }
  8850. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  8851. QualType T,
  8852. QualType ConvTy) override {
  8853. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  8854. }
  8855. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  8856. QualType ConvTy) override {
  8857. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  8858. << ConvTy->isEnumeralType() << ConvTy;
  8859. }
  8860. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  8861. QualType T) override {
  8862. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  8863. }
  8864. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  8865. QualType ConvTy) override {
  8866. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  8867. << ConvTy->isEnumeralType() << ConvTy;
  8868. }
  8869. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  8870. QualType) override {
  8871. llvm_unreachable("conversion functions are permitted");
  8872. }
  8873. } ConvertDiagnoser;
  8874. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  8875. }
  8876. static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  8877. OpenMPClauseKind CKind,
  8878. bool StrictlyPositive) {
  8879. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  8880. !ValExpr->isInstantiationDependent()) {
  8881. SourceLocation Loc = ValExpr->getExprLoc();
  8882. ExprResult Value =
  8883. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  8884. if (Value.isInvalid())
  8885. return false;
  8886. ValExpr = Value.get();
  8887. // The expression must evaluate to a non-negative integer value.
  8888. llvm::APSInt Result;
  8889. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  8890. Result.isSigned() &&
  8891. !((!StrictlyPositive && Result.isNonNegative()) ||
  8892. (StrictlyPositive && Result.isStrictlyPositive()))) {
  8893. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  8894. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  8895. << ValExpr->getSourceRange();
  8896. return false;
  8897. }
  8898. }
  8899. return true;
  8900. }
  8901. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  8902. SourceLocation StartLoc,
  8903. SourceLocation LParenLoc,
  8904. SourceLocation EndLoc) {
  8905. Expr *ValExpr = NumThreads;
  8906. Stmt *HelperValStmt = nullptr;
  8907. // OpenMP [2.5, Restrictions]
  8908. // The num_threads expression must evaluate to a positive integer value.
  8909. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  8910. /*StrictlyPositive=*/true))
  8911. return nullptr;
  8912. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  8913. OpenMPDirectiveKind CaptureRegion =
  8914. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  8915. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  8916. ValExpr = MakeFullExpr(ValExpr).get();
  8917. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8918. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8919. HelperValStmt = buildPreInits(Context, Captures);
  8920. }
  8921. return new (Context) OMPNumThreadsClause(
  8922. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  8923. }
  8924. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  8925. OpenMPClauseKind CKind,
  8926. bool StrictlyPositive) {
  8927. if (!E)
  8928. return ExprError();
  8929. if (E->isValueDependent() || E->isTypeDependent() ||
  8930. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  8931. return E;
  8932. llvm::APSInt Result;
  8933. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  8934. if (ICE.isInvalid())
  8935. return ExprError();
  8936. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  8937. (!StrictlyPositive && !Result.isNonNegative())) {
  8938. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  8939. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  8940. << E->getSourceRange();
  8941. return ExprError();
  8942. }
  8943. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  8944. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  8945. << E->getSourceRange();
  8946. return ExprError();
  8947. }
  8948. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  8949. DSAStack->setAssociatedLoops(Result.getExtValue());
  8950. else if (CKind == OMPC_ordered)
  8951. DSAStack->setAssociatedLoops(Result.getExtValue());
  8952. return ICE;
  8953. }
  8954. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  8955. SourceLocation LParenLoc,
  8956. SourceLocation EndLoc) {
  8957. // OpenMP [2.8.1, simd construct, Description]
  8958. // The parameter of the safelen clause must be a constant
  8959. // positive integer expression.
  8960. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  8961. if (Safelen.isInvalid())
  8962. return nullptr;
  8963. return new (Context)
  8964. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  8965. }
  8966. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  8967. SourceLocation LParenLoc,
  8968. SourceLocation EndLoc) {
  8969. // OpenMP [2.8.1, simd construct, Description]
  8970. // The parameter of the simdlen clause must be a constant
  8971. // positive integer expression.
  8972. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  8973. if (Simdlen.isInvalid())
  8974. return nullptr;
  8975. return new (Context)
  8976. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  8977. }
  8978. /// Tries to find omp_allocator_handle_t type.
  8979. static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
  8980. DSAStackTy *Stack) {
  8981. QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
  8982. if (!OMPAllocatorHandleT.isNull())
  8983. return true;
  8984. // Build the predefined allocator expressions.
  8985. bool ErrorFound = false;
  8986. for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
  8987. I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  8988. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  8989. StringRef Allocator =
  8990. OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
  8991. DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
  8992. auto *VD = dyn_cast_or_null<ValueDecl>(
  8993. S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
  8994. if (!VD) {
  8995. ErrorFound = true;
  8996. break;
  8997. }
  8998. QualType AllocatorType =
  8999. VD->getType().getNonLValueExprType(S.getASTContext());
  9000. ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
  9001. if (!Res.isUsable()) {
  9002. ErrorFound = true;
  9003. break;
  9004. }
  9005. if (OMPAllocatorHandleT.isNull())
  9006. OMPAllocatorHandleT = AllocatorType;
  9007. if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
  9008. ErrorFound = true;
  9009. break;
  9010. }
  9011. Stack->setAllocator(AllocatorKind, Res.get());
  9012. }
  9013. if (ErrorFound) {
  9014. S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
  9015. return false;
  9016. }
  9017. OMPAllocatorHandleT.addConst();
  9018. Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
  9019. return true;
  9020. }
  9021. OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
  9022. SourceLocation LParenLoc,
  9023. SourceLocation EndLoc) {
  9024. // OpenMP [2.11.3, allocate Directive, Description]
  9025. // allocator is an expression of omp_allocator_handle_t type.
  9026. if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
  9027. return nullptr;
  9028. ExprResult Allocator = DefaultLvalueConversion(A);
  9029. if (Allocator.isInvalid())
  9030. return nullptr;
  9031. Allocator = PerformImplicitConversion(Allocator.get(),
  9032. DSAStack->getOMPAllocatorHandleT(),
  9033. Sema::AA_Initializing,
  9034. /*AllowExplicit=*/true);
  9035. if (Allocator.isInvalid())
  9036. return nullptr;
  9037. return new (Context)
  9038. OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
  9039. }
  9040. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  9041. SourceLocation StartLoc,
  9042. SourceLocation LParenLoc,
  9043. SourceLocation EndLoc) {
  9044. // OpenMP [2.7.1, loop construct, Description]
  9045. // OpenMP [2.8.1, simd construct, Description]
  9046. // OpenMP [2.9.6, distribute construct, Description]
  9047. // The parameter of the collapse clause must be a constant
  9048. // positive integer expression.
  9049. ExprResult NumForLoopsResult =
  9050. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  9051. if (NumForLoopsResult.isInvalid())
  9052. return nullptr;
  9053. return new (Context)
  9054. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  9055. }
  9056. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  9057. SourceLocation EndLoc,
  9058. SourceLocation LParenLoc,
  9059. Expr *NumForLoops) {
  9060. // OpenMP [2.7.1, loop construct, Description]
  9061. // OpenMP [2.8.1, simd construct, Description]
  9062. // OpenMP [2.9.6, distribute construct, Description]
  9063. // The parameter of the ordered clause must be a constant
  9064. // positive integer expression if any.
  9065. if (NumForLoops && LParenLoc.isValid()) {
  9066. ExprResult NumForLoopsResult =
  9067. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  9068. if (NumForLoopsResult.isInvalid())
  9069. return nullptr;
  9070. NumForLoops = NumForLoopsResult.get();
  9071. } else {
  9072. NumForLoops = nullptr;
  9073. }
  9074. auto *Clause = OMPOrderedClause::Create(
  9075. Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
  9076. StartLoc, LParenLoc, EndLoc);
  9077. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
  9078. return Clause;
  9079. }
  9080. OMPClause *Sema::ActOnOpenMPSimpleClause(
  9081. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  9082. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  9083. OMPClause *Res = nullptr;
  9084. switch (Kind) {
  9085. case OMPC_default:
  9086. Res =
  9087. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  9088. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  9089. break;
  9090. case OMPC_proc_bind:
  9091. Res = ActOnOpenMPProcBindClause(
  9092. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  9093. LParenLoc, EndLoc);
  9094. break;
  9095. case OMPC_atomic_default_mem_order:
  9096. Res = ActOnOpenMPAtomicDefaultMemOrderClause(
  9097. static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
  9098. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  9099. break;
  9100. case OMPC_if:
  9101. case OMPC_final:
  9102. case OMPC_num_threads:
  9103. case OMPC_safelen:
  9104. case OMPC_simdlen:
  9105. case OMPC_allocator:
  9106. case OMPC_collapse:
  9107. case OMPC_schedule:
  9108. case OMPC_private:
  9109. case OMPC_firstprivate:
  9110. case OMPC_lastprivate:
  9111. case OMPC_shared:
  9112. case OMPC_reduction:
  9113. case OMPC_task_reduction:
  9114. case OMPC_in_reduction:
  9115. case OMPC_linear:
  9116. case OMPC_aligned:
  9117. case OMPC_copyin:
  9118. case OMPC_copyprivate:
  9119. case OMPC_ordered:
  9120. case OMPC_nowait:
  9121. case OMPC_untied:
  9122. case OMPC_mergeable:
  9123. case OMPC_threadprivate:
  9124. case OMPC_allocate:
  9125. case OMPC_flush:
  9126. case OMPC_read:
  9127. case OMPC_write:
  9128. case OMPC_update:
  9129. case OMPC_capture:
  9130. case OMPC_seq_cst:
  9131. case OMPC_depend:
  9132. case OMPC_device:
  9133. case OMPC_threads:
  9134. case OMPC_simd:
  9135. case OMPC_map:
  9136. case OMPC_num_teams:
  9137. case OMPC_thread_limit:
  9138. case OMPC_priority:
  9139. case OMPC_grainsize:
  9140. case OMPC_nogroup:
  9141. case OMPC_num_tasks:
  9142. case OMPC_hint:
  9143. case OMPC_dist_schedule:
  9144. case OMPC_defaultmap:
  9145. case OMPC_unknown:
  9146. case OMPC_uniform:
  9147. case OMPC_to:
  9148. case OMPC_from:
  9149. case OMPC_use_device_ptr:
  9150. case OMPC_is_device_ptr:
  9151. case OMPC_unified_address:
  9152. case OMPC_unified_shared_memory:
  9153. case OMPC_reverse_offload:
  9154. case OMPC_dynamic_allocators:
  9155. llvm_unreachable("Clause is not allowed.");
  9156. }
  9157. return Res;
  9158. }
  9159. static std::string
  9160. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  9161. ArrayRef<unsigned> Exclude = llvm::None) {
  9162. SmallString<256> Buffer;
  9163. llvm::raw_svector_ostream Out(Buffer);
  9164. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  9165. unsigned Skipped = Exclude.size();
  9166. auto S = Exclude.begin(), E = Exclude.end();
  9167. for (unsigned I = First; I < Last; ++I) {
  9168. if (std::find(S, E, I) != E) {
  9169. --Skipped;
  9170. continue;
  9171. }
  9172. Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
  9173. if (I == Bound - Skipped)
  9174. Out << " or ";
  9175. else if (I != Bound + 1 - Skipped)
  9176. Out << ", ";
  9177. }
  9178. return Out.str();
  9179. }
  9180. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  9181. SourceLocation KindKwLoc,
  9182. SourceLocation StartLoc,
  9183. SourceLocation LParenLoc,
  9184. SourceLocation EndLoc) {
  9185. if (Kind == OMPC_DEFAULT_unknown) {
  9186. static_assert(OMPC_DEFAULT_unknown > 0,
  9187. "OMPC_DEFAULT_unknown not greater than 0");
  9188. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  9189. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  9190. /*Last=*/OMPC_DEFAULT_unknown)
  9191. << getOpenMPClauseName(OMPC_default);
  9192. return nullptr;
  9193. }
  9194. switch (Kind) {
  9195. case OMPC_DEFAULT_none:
  9196. DSAStack->setDefaultDSANone(KindKwLoc);
  9197. break;
  9198. case OMPC_DEFAULT_shared:
  9199. DSAStack->setDefaultDSAShared(KindKwLoc);
  9200. break;
  9201. case OMPC_DEFAULT_unknown:
  9202. llvm_unreachable("Clause kind is not allowed.");
  9203. break;
  9204. }
  9205. return new (Context)
  9206. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  9207. }
  9208. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  9209. SourceLocation KindKwLoc,
  9210. SourceLocation StartLoc,
  9211. SourceLocation LParenLoc,
  9212. SourceLocation EndLoc) {
  9213. if (Kind == OMPC_PROC_BIND_unknown) {
  9214. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  9215. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  9216. /*Last=*/OMPC_PROC_BIND_unknown)
  9217. << getOpenMPClauseName(OMPC_proc_bind);
  9218. return nullptr;
  9219. }
  9220. return new (Context)
  9221. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  9222. }
  9223. OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
  9224. OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
  9225. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  9226. if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
  9227. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  9228. << getListOfPossibleValues(
  9229. OMPC_atomic_default_mem_order, /*First=*/0,
  9230. /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
  9231. << getOpenMPClauseName(OMPC_atomic_default_mem_order);
  9232. return nullptr;
  9233. }
  9234. return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
  9235. LParenLoc, EndLoc);
  9236. }
  9237. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  9238. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  9239. SourceLocation StartLoc, SourceLocation LParenLoc,
  9240. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  9241. SourceLocation EndLoc) {
  9242. OMPClause *Res = nullptr;
  9243. switch (Kind) {
  9244. case OMPC_schedule:
  9245. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  9246. assert(Argument.size() == NumberOfElements &&
  9247. ArgumentLoc.size() == NumberOfElements);
  9248. Res = ActOnOpenMPScheduleClause(
  9249. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  9250. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  9251. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  9252. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  9253. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  9254. break;
  9255. case OMPC_if:
  9256. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  9257. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  9258. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  9259. DelimLoc, EndLoc);
  9260. break;
  9261. case OMPC_dist_schedule:
  9262. Res = ActOnOpenMPDistScheduleClause(
  9263. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  9264. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  9265. break;
  9266. case OMPC_defaultmap:
  9267. enum { Modifier, DefaultmapKind };
  9268. Res = ActOnOpenMPDefaultmapClause(
  9269. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  9270. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  9271. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  9272. EndLoc);
  9273. break;
  9274. case OMPC_final:
  9275. case OMPC_num_threads:
  9276. case OMPC_safelen:
  9277. case OMPC_simdlen:
  9278. case OMPC_allocator:
  9279. case OMPC_collapse:
  9280. case OMPC_default:
  9281. case OMPC_proc_bind:
  9282. case OMPC_private:
  9283. case OMPC_firstprivate:
  9284. case OMPC_lastprivate:
  9285. case OMPC_shared:
  9286. case OMPC_reduction:
  9287. case OMPC_task_reduction:
  9288. case OMPC_in_reduction:
  9289. case OMPC_linear:
  9290. case OMPC_aligned:
  9291. case OMPC_copyin:
  9292. case OMPC_copyprivate:
  9293. case OMPC_ordered:
  9294. case OMPC_nowait:
  9295. case OMPC_untied:
  9296. case OMPC_mergeable:
  9297. case OMPC_threadprivate:
  9298. case OMPC_allocate:
  9299. case OMPC_flush:
  9300. case OMPC_read:
  9301. case OMPC_write:
  9302. case OMPC_update:
  9303. case OMPC_capture:
  9304. case OMPC_seq_cst:
  9305. case OMPC_depend:
  9306. case OMPC_device:
  9307. case OMPC_threads:
  9308. case OMPC_simd:
  9309. case OMPC_map:
  9310. case OMPC_num_teams:
  9311. case OMPC_thread_limit:
  9312. case OMPC_priority:
  9313. case OMPC_grainsize:
  9314. case OMPC_nogroup:
  9315. case OMPC_num_tasks:
  9316. case OMPC_hint:
  9317. case OMPC_unknown:
  9318. case OMPC_uniform:
  9319. case OMPC_to:
  9320. case OMPC_from:
  9321. case OMPC_use_device_ptr:
  9322. case OMPC_is_device_ptr:
  9323. case OMPC_unified_address:
  9324. case OMPC_unified_shared_memory:
  9325. case OMPC_reverse_offload:
  9326. case OMPC_dynamic_allocators:
  9327. case OMPC_atomic_default_mem_order:
  9328. llvm_unreachable("Clause is not allowed.");
  9329. }
  9330. return Res;
  9331. }
  9332. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  9333. OpenMPScheduleClauseModifier M2,
  9334. SourceLocation M1Loc, SourceLocation M2Loc) {
  9335. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  9336. SmallVector<unsigned, 2> Excluded;
  9337. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  9338. Excluded.push_back(M2);
  9339. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  9340. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  9341. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  9342. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  9343. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  9344. << getListOfPossibleValues(OMPC_schedule,
  9345. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  9346. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  9347. Excluded)
  9348. << getOpenMPClauseName(OMPC_schedule);
  9349. return true;
  9350. }
  9351. return false;
  9352. }
  9353. OMPClause *Sema::ActOnOpenMPScheduleClause(
  9354. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  9355. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  9356. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  9357. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  9358. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  9359. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  9360. return nullptr;
  9361. // OpenMP, 2.7.1, Loop Construct, Restrictions
  9362. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  9363. // but not both.
  9364. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  9365. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  9366. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  9367. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  9368. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  9369. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  9370. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  9371. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  9372. return nullptr;
  9373. }
  9374. if (Kind == OMPC_SCHEDULE_unknown) {
  9375. std::string Values;
  9376. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  9377. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  9378. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  9379. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  9380. Exclude);
  9381. } else {
  9382. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  9383. /*Last=*/OMPC_SCHEDULE_unknown);
  9384. }
  9385. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  9386. << Values << getOpenMPClauseName(OMPC_schedule);
  9387. return nullptr;
  9388. }
  9389. // OpenMP, 2.7.1, Loop Construct, Restrictions
  9390. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  9391. // schedule(guided).
  9392. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  9393. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  9394. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  9395. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  9396. diag::err_omp_schedule_nonmonotonic_static);
  9397. return nullptr;
  9398. }
  9399. Expr *ValExpr = ChunkSize;
  9400. Stmt *HelperValStmt = nullptr;
  9401. if (ChunkSize) {
  9402. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  9403. !ChunkSize->isInstantiationDependent() &&
  9404. !ChunkSize->containsUnexpandedParameterPack()) {
  9405. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  9406. ExprResult Val =
  9407. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  9408. if (Val.isInvalid())
  9409. return nullptr;
  9410. ValExpr = Val.get();
  9411. // OpenMP [2.7.1, Restrictions]
  9412. // chunk_size must be a loop invariant integer expression with a positive
  9413. // value.
  9414. llvm::APSInt Result;
  9415. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  9416. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  9417. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  9418. << "schedule" << 1 << ChunkSize->getSourceRange();
  9419. return nullptr;
  9420. }
  9421. } else if (getOpenMPCaptureRegionForClause(
  9422. DSAStack->getCurrentDirective(), OMPC_schedule) !=
  9423. OMPD_unknown &&
  9424. !CurContext->isDependentContext()) {
  9425. ValExpr = MakeFullExpr(ValExpr).get();
  9426. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  9427. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  9428. HelperValStmt = buildPreInits(Context, Captures);
  9429. }
  9430. }
  9431. }
  9432. return new (Context)
  9433. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  9434. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  9435. }
  9436. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  9437. SourceLocation StartLoc,
  9438. SourceLocation EndLoc) {
  9439. OMPClause *Res = nullptr;
  9440. switch (Kind) {
  9441. case OMPC_ordered:
  9442. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  9443. break;
  9444. case OMPC_nowait:
  9445. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  9446. break;
  9447. case OMPC_untied:
  9448. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  9449. break;
  9450. case OMPC_mergeable:
  9451. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  9452. break;
  9453. case OMPC_read:
  9454. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  9455. break;
  9456. case OMPC_write:
  9457. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  9458. break;
  9459. case OMPC_update:
  9460. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  9461. break;
  9462. case OMPC_capture:
  9463. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  9464. break;
  9465. case OMPC_seq_cst:
  9466. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  9467. break;
  9468. case OMPC_threads:
  9469. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  9470. break;
  9471. case OMPC_simd:
  9472. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  9473. break;
  9474. case OMPC_nogroup:
  9475. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  9476. break;
  9477. case OMPC_unified_address:
  9478. Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
  9479. break;
  9480. case OMPC_unified_shared_memory:
  9481. Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  9482. break;
  9483. case OMPC_reverse_offload:
  9484. Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
  9485. break;
  9486. case OMPC_dynamic_allocators:
  9487. Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
  9488. break;
  9489. case OMPC_if:
  9490. case OMPC_final:
  9491. case OMPC_num_threads:
  9492. case OMPC_safelen:
  9493. case OMPC_simdlen:
  9494. case OMPC_allocator:
  9495. case OMPC_collapse:
  9496. case OMPC_schedule:
  9497. case OMPC_private:
  9498. case OMPC_firstprivate:
  9499. case OMPC_lastprivate:
  9500. case OMPC_shared:
  9501. case OMPC_reduction:
  9502. case OMPC_task_reduction:
  9503. case OMPC_in_reduction:
  9504. case OMPC_linear:
  9505. case OMPC_aligned:
  9506. case OMPC_copyin:
  9507. case OMPC_copyprivate:
  9508. case OMPC_default:
  9509. case OMPC_proc_bind:
  9510. case OMPC_threadprivate:
  9511. case OMPC_allocate:
  9512. case OMPC_flush:
  9513. case OMPC_depend:
  9514. case OMPC_device:
  9515. case OMPC_map:
  9516. case OMPC_num_teams:
  9517. case OMPC_thread_limit:
  9518. case OMPC_priority:
  9519. case OMPC_grainsize:
  9520. case OMPC_num_tasks:
  9521. case OMPC_hint:
  9522. case OMPC_dist_schedule:
  9523. case OMPC_defaultmap:
  9524. case OMPC_unknown:
  9525. case OMPC_uniform:
  9526. case OMPC_to:
  9527. case OMPC_from:
  9528. case OMPC_use_device_ptr:
  9529. case OMPC_is_device_ptr:
  9530. case OMPC_atomic_default_mem_order:
  9531. llvm_unreachable("Clause is not allowed.");
  9532. }
  9533. return Res;
  9534. }
  9535. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  9536. SourceLocation EndLoc) {
  9537. DSAStack->setNowaitRegion();
  9538. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  9539. }
  9540. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  9541. SourceLocation EndLoc) {
  9542. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  9543. }
  9544. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  9545. SourceLocation EndLoc) {
  9546. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  9547. }
  9548. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  9549. SourceLocation EndLoc) {
  9550. return new (Context) OMPReadClause(StartLoc, EndLoc);
  9551. }
  9552. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  9553. SourceLocation EndLoc) {
  9554. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  9555. }
  9556. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  9557. SourceLocation EndLoc) {
  9558. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  9559. }
  9560. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  9561. SourceLocation EndLoc) {
  9562. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  9563. }
  9564. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  9565. SourceLocation EndLoc) {
  9566. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  9567. }
  9568. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  9569. SourceLocation EndLoc) {
  9570. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  9571. }
  9572. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  9573. SourceLocation EndLoc) {
  9574. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  9575. }
  9576. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  9577. SourceLocation EndLoc) {
  9578. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  9579. }
  9580. OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
  9581. SourceLocation EndLoc) {
  9582. return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
  9583. }
  9584. OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
  9585. SourceLocation EndLoc) {
  9586. return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  9587. }
  9588. OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
  9589. SourceLocation EndLoc) {
  9590. return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
  9591. }
  9592. OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
  9593. SourceLocation EndLoc) {
  9594. return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
  9595. }
  9596. OMPClause *Sema::ActOnOpenMPVarListClause(
  9597. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  9598. const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
  9599. CXXScopeSpec &ReductionOrMapperIdScopeSpec,
  9600. DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
  9601. OpenMPLinearClauseKind LinKind,
  9602. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  9603. ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
  9604. bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
  9605. SourceLocation StartLoc = Locs.StartLoc;
  9606. SourceLocation LParenLoc = Locs.LParenLoc;
  9607. SourceLocation EndLoc = Locs.EndLoc;
  9608. OMPClause *Res = nullptr;
  9609. switch (Kind) {
  9610. case OMPC_private:
  9611. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  9612. break;
  9613. case OMPC_firstprivate:
  9614. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  9615. break;
  9616. case OMPC_lastprivate:
  9617. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  9618. break;
  9619. case OMPC_shared:
  9620. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  9621. break;
  9622. case OMPC_reduction:
  9623. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  9624. EndLoc, ReductionOrMapperIdScopeSpec,
  9625. ReductionOrMapperId);
  9626. break;
  9627. case OMPC_task_reduction:
  9628. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  9629. EndLoc, ReductionOrMapperIdScopeSpec,
  9630. ReductionOrMapperId);
  9631. break;
  9632. case OMPC_in_reduction:
  9633. Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  9634. EndLoc, ReductionOrMapperIdScopeSpec,
  9635. ReductionOrMapperId);
  9636. break;
  9637. case OMPC_linear:
  9638. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  9639. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  9640. break;
  9641. case OMPC_aligned:
  9642. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  9643. ColonLoc, EndLoc);
  9644. break;
  9645. case OMPC_copyin:
  9646. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  9647. break;
  9648. case OMPC_copyprivate:
  9649. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  9650. break;
  9651. case OMPC_flush:
  9652. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  9653. break;
  9654. case OMPC_depend:
  9655. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  9656. StartLoc, LParenLoc, EndLoc);
  9657. break;
  9658. case OMPC_map:
  9659. Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
  9660. ReductionOrMapperIdScopeSpec,
  9661. ReductionOrMapperId, MapType, IsMapTypeImplicit,
  9662. DepLinMapLoc, ColonLoc, VarList, Locs);
  9663. break;
  9664. case OMPC_to:
  9665. Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
  9666. ReductionOrMapperId, Locs);
  9667. break;
  9668. case OMPC_from:
  9669. Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
  9670. ReductionOrMapperId, Locs);
  9671. break;
  9672. case OMPC_use_device_ptr:
  9673. Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
  9674. break;
  9675. case OMPC_is_device_ptr:
  9676. Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
  9677. break;
  9678. case OMPC_allocate:
  9679. Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
  9680. ColonLoc, EndLoc);
  9681. break;
  9682. case OMPC_if:
  9683. case OMPC_final:
  9684. case OMPC_num_threads:
  9685. case OMPC_safelen:
  9686. case OMPC_simdlen:
  9687. case OMPC_allocator:
  9688. case OMPC_collapse:
  9689. case OMPC_default:
  9690. case OMPC_proc_bind:
  9691. case OMPC_schedule:
  9692. case OMPC_ordered:
  9693. case OMPC_nowait:
  9694. case OMPC_untied:
  9695. case OMPC_mergeable:
  9696. case OMPC_threadprivate:
  9697. case OMPC_read:
  9698. case OMPC_write:
  9699. case OMPC_update:
  9700. case OMPC_capture:
  9701. case OMPC_seq_cst:
  9702. case OMPC_device:
  9703. case OMPC_threads:
  9704. case OMPC_simd:
  9705. case OMPC_num_teams:
  9706. case OMPC_thread_limit:
  9707. case OMPC_priority:
  9708. case OMPC_grainsize:
  9709. case OMPC_nogroup:
  9710. case OMPC_num_tasks:
  9711. case OMPC_hint:
  9712. case OMPC_dist_schedule:
  9713. case OMPC_defaultmap:
  9714. case OMPC_unknown:
  9715. case OMPC_uniform:
  9716. case OMPC_unified_address:
  9717. case OMPC_unified_shared_memory:
  9718. case OMPC_reverse_offload:
  9719. case OMPC_dynamic_allocators:
  9720. case OMPC_atomic_default_mem_order:
  9721. llvm_unreachable("Clause is not allowed.");
  9722. }
  9723. return Res;
  9724. }
  9725. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  9726. ExprObjectKind OK, SourceLocation Loc) {
  9727. ExprResult Res = BuildDeclRefExpr(
  9728. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  9729. if (!Res.isUsable())
  9730. return ExprError();
  9731. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  9732. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  9733. if (!Res.isUsable())
  9734. return ExprError();
  9735. }
  9736. if (VK != VK_LValue && Res.get()->isGLValue()) {
  9737. Res = DefaultLvalueConversion(Res.get());
  9738. if (!Res.isUsable())
  9739. return ExprError();
  9740. }
  9741. return Res;
  9742. }
  9743. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  9744. SourceLocation StartLoc,
  9745. SourceLocation LParenLoc,
  9746. SourceLocation EndLoc) {
  9747. SmallVector<Expr *, 8> Vars;
  9748. SmallVector<Expr *, 8> PrivateCopies;
  9749. for (Expr *RefExpr : VarList) {
  9750. assert(RefExpr && "NULL expr in OpenMP private clause.");
  9751. SourceLocation ELoc;
  9752. SourceRange ERange;
  9753. Expr *SimpleRefExpr = RefExpr;
  9754. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9755. if (Res.second) {
  9756. // It will be analyzed later.
  9757. Vars.push_back(RefExpr);
  9758. PrivateCopies.push_back(nullptr);
  9759. }
  9760. ValueDecl *D = Res.first;
  9761. if (!D)
  9762. continue;
  9763. QualType Type = D->getType();
  9764. auto *VD = dyn_cast<VarDecl>(D);
  9765. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  9766. // A variable that appears in a private clause must not have an incomplete
  9767. // type or a reference type.
  9768. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  9769. continue;
  9770. Type = Type.getNonReferenceType();
  9771. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  9772. // A variable that is privatized must not have a const-qualified type
  9773. // unless it is of class type with a mutable member. This restriction does
  9774. // not apply to the firstprivate clause.
  9775. //
  9776. // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
  9777. // A variable that appears in a private clause must not have a
  9778. // const-qualified type unless it is of class type with a mutable member.
  9779. if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
  9780. continue;
  9781. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9782. // in a Construct]
  9783. // Variables with the predetermined data-sharing attributes may not be
  9784. // listed in data-sharing attributes clauses, except for the cases
  9785. // listed below. For these exceptions only, listing a predetermined
  9786. // variable in a data-sharing attribute clause is allowed and overrides
  9787. // the variable's predetermined data-sharing attributes.
  9788. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  9789. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  9790. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  9791. << getOpenMPClauseName(OMPC_private);
  9792. reportOriginalDsa(*this, DSAStack, D, DVar);
  9793. continue;
  9794. }
  9795. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9796. // Variably modified types are not supported for tasks.
  9797. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  9798. isOpenMPTaskingDirective(CurrDir)) {
  9799. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  9800. << getOpenMPClauseName(OMPC_private) << Type
  9801. << getOpenMPDirectiveName(CurrDir);
  9802. bool IsDecl =
  9803. !VD ||
  9804. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9805. Diag(D->getLocation(),
  9806. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9807. << D;
  9808. continue;
  9809. }
  9810. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  9811. // A list item cannot appear in both a map clause and a data-sharing
  9812. // attribute clause on the same construct
  9813. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  9814. OpenMPClauseKind ConflictKind;
  9815. if (DSAStack->checkMappableExprComponentListsForDecl(
  9816. VD, /*CurrentRegionOnly=*/true,
  9817. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  9818. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  9819. ConflictKind = WhereFoundClauseKind;
  9820. return true;
  9821. })) {
  9822. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  9823. << getOpenMPClauseName(OMPC_private)
  9824. << getOpenMPClauseName(ConflictKind)
  9825. << getOpenMPDirectiveName(CurrDir);
  9826. reportOriginalDsa(*this, DSAStack, D, DVar);
  9827. continue;
  9828. }
  9829. }
  9830. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  9831. // A variable of class type (or array thereof) that appears in a private
  9832. // clause requires an accessible, unambiguous default constructor for the
  9833. // class type.
  9834. // Generate helper private variable and initialize it with the default
  9835. // value. The address of the original variable is replaced by the address of
  9836. // the new private variable in CodeGen. This new variable is not added to
  9837. // IdResolver, so the code in the OpenMP region uses original variable for
  9838. // proper diagnostics.
  9839. Type = Type.getUnqualifiedType();
  9840. VarDecl *VDPrivate =
  9841. buildVarDecl(*this, ELoc, Type, D->getName(),
  9842. D->hasAttrs() ? &D->getAttrs() : nullptr,
  9843. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  9844. ActOnUninitializedDecl(VDPrivate);
  9845. if (VDPrivate->isInvalidDecl())
  9846. continue;
  9847. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  9848. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  9849. DeclRefExpr *Ref = nullptr;
  9850. if (!VD && !CurContext->isDependentContext())
  9851. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  9852. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  9853. Vars.push_back((VD || CurContext->isDependentContext())
  9854. ? RefExpr->IgnoreParens()
  9855. : Ref);
  9856. PrivateCopies.push_back(VDPrivateRefExpr);
  9857. }
  9858. if (Vars.empty())
  9859. return nullptr;
  9860. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  9861. PrivateCopies);
  9862. }
  9863. namespace {
  9864. class DiagsUninitializedSeveretyRAII {
  9865. private:
  9866. DiagnosticsEngine &Diags;
  9867. SourceLocation SavedLoc;
  9868. bool IsIgnored = false;
  9869. public:
  9870. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  9871. bool IsIgnored)
  9872. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  9873. if (!IsIgnored) {
  9874. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  9875. /*Map*/ diag::Severity::Ignored, Loc);
  9876. }
  9877. }
  9878. ~DiagsUninitializedSeveretyRAII() {
  9879. if (!IsIgnored)
  9880. Diags.popMappings(SavedLoc);
  9881. }
  9882. };
  9883. }
  9884. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  9885. SourceLocation StartLoc,
  9886. SourceLocation LParenLoc,
  9887. SourceLocation EndLoc) {
  9888. SmallVector<Expr *, 8> Vars;
  9889. SmallVector<Expr *, 8> PrivateCopies;
  9890. SmallVector<Expr *, 8> Inits;
  9891. SmallVector<Decl *, 4> ExprCaptures;
  9892. bool IsImplicitClause =
  9893. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  9894. SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
  9895. for (Expr *RefExpr : VarList) {
  9896. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  9897. SourceLocation ELoc;
  9898. SourceRange ERange;
  9899. Expr *SimpleRefExpr = RefExpr;
  9900. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9901. if (Res.second) {
  9902. // It will be analyzed later.
  9903. Vars.push_back(RefExpr);
  9904. PrivateCopies.push_back(nullptr);
  9905. Inits.push_back(nullptr);
  9906. }
  9907. ValueDecl *D = Res.first;
  9908. if (!D)
  9909. continue;
  9910. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  9911. QualType Type = D->getType();
  9912. auto *VD = dyn_cast<VarDecl>(D);
  9913. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  9914. // A variable that appears in a private clause must not have an incomplete
  9915. // type or a reference type.
  9916. if (RequireCompleteType(ELoc, Type,
  9917. diag::err_omp_firstprivate_incomplete_type))
  9918. continue;
  9919. Type = Type.getNonReferenceType();
  9920. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  9921. // A variable of class type (or array thereof) that appears in a private
  9922. // clause requires an accessible, unambiguous copy constructor for the
  9923. // class type.
  9924. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  9925. // If an implicit firstprivate variable found it was checked already.
  9926. DSAStackTy::DSAVarData TopDVar;
  9927. if (!IsImplicitClause) {
  9928. DSAStackTy::DSAVarData DVar =
  9929. DSAStack->getTopDSA(D, /*FromParent=*/false);
  9930. TopDVar = DVar;
  9931. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9932. bool IsConstant = ElemType.isConstant(Context);
  9933. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  9934. // A list item that specifies a given variable may not appear in more
  9935. // than one clause on the same directive, except that a variable may be
  9936. // specified in both firstprivate and lastprivate clauses.
  9937. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  9938. // A list item may appear in a firstprivate or lastprivate clause but not
  9939. // both.
  9940. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  9941. (isOpenMPDistributeDirective(CurrDir) ||
  9942. DVar.CKind != OMPC_lastprivate) &&
  9943. DVar.RefExpr) {
  9944. Diag(ELoc, diag::err_omp_wrong_dsa)
  9945. << getOpenMPClauseName(DVar.CKind)
  9946. << getOpenMPClauseName(OMPC_firstprivate);
  9947. reportOriginalDsa(*this, DSAStack, D, DVar);
  9948. continue;
  9949. }
  9950. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9951. // in a Construct]
  9952. // Variables with the predetermined data-sharing attributes may not be
  9953. // listed in data-sharing attributes clauses, except for the cases
  9954. // listed below. For these exceptions only, listing a predetermined
  9955. // variable in a data-sharing attribute clause is allowed and overrides
  9956. // the variable's predetermined data-sharing attributes.
  9957. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9958. // in a Construct, C/C++, p.2]
  9959. // Variables with const-qualified type having no mutable member may be
  9960. // listed in a firstprivate clause, even if they are static data members.
  9961. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  9962. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  9963. Diag(ELoc, diag::err_omp_wrong_dsa)
  9964. << getOpenMPClauseName(DVar.CKind)
  9965. << getOpenMPClauseName(OMPC_firstprivate);
  9966. reportOriginalDsa(*this, DSAStack, D, DVar);
  9967. continue;
  9968. }
  9969. // OpenMP [2.9.3.4, Restrictions, p.2]
  9970. // A list item that is private within a parallel region must not appear
  9971. // in a firstprivate clause on a worksharing construct if any of the
  9972. // worksharing regions arising from the worksharing construct ever bind
  9973. // to any of the parallel regions arising from the parallel construct.
  9974. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  9975. // A list item that is private within a teams region must not appear in a
  9976. // firstprivate clause on a distribute construct if any of the distribute
  9977. // regions arising from the distribute construct ever bind to any of the
  9978. // teams regions arising from the teams construct.
  9979. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  9980. // A list item that appears in a reduction clause of a teams construct
  9981. // must not appear in a firstprivate clause on a distribute construct if
  9982. // any of the distribute regions arising from the distribute construct
  9983. // ever bind to any of the teams regions arising from the teams construct.
  9984. if ((isOpenMPWorksharingDirective(CurrDir) ||
  9985. isOpenMPDistributeDirective(CurrDir)) &&
  9986. !isOpenMPParallelDirective(CurrDir) &&
  9987. !isOpenMPTeamsDirective(CurrDir)) {
  9988. DVar = DSAStack->getImplicitDSA(D, true);
  9989. if (DVar.CKind != OMPC_shared &&
  9990. (isOpenMPParallelDirective(DVar.DKind) ||
  9991. isOpenMPTeamsDirective(DVar.DKind) ||
  9992. DVar.DKind == OMPD_unknown)) {
  9993. Diag(ELoc, diag::err_omp_required_access)
  9994. << getOpenMPClauseName(OMPC_firstprivate)
  9995. << getOpenMPClauseName(OMPC_shared);
  9996. reportOriginalDsa(*this, DSAStack, D, DVar);
  9997. continue;
  9998. }
  9999. }
  10000. // OpenMP [2.9.3.4, Restrictions, p.3]
  10001. // A list item that appears in a reduction clause of a parallel construct
  10002. // must not appear in a firstprivate clause on a worksharing or task
  10003. // construct if any of the worksharing or task regions arising from the
  10004. // worksharing or task construct ever bind to any of the parallel regions
  10005. // arising from the parallel construct.
  10006. // OpenMP [2.9.3.4, Restrictions, p.4]
  10007. // A list item that appears in a reduction clause in worksharing
  10008. // construct must not appear in a firstprivate clause in a task construct
  10009. // encountered during execution of any of the worksharing regions arising
  10010. // from the worksharing construct.
  10011. if (isOpenMPTaskingDirective(CurrDir)) {
  10012. DVar = DSAStack->hasInnermostDSA(
  10013. D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  10014. [](OpenMPDirectiveKind K) {
  10015. return isOpenMPParallelDirective(K) ||
  10016. isOpenMPWorksharingDirective(K) ||
  10017. isOpenMPTeamsDirective(K);
  10018. },
  10019. /*FromParent=*/true);
  10020. if (DVar.CKind == OMPC_reduction &&
  10021. (isOpenMPParallelDirective(DVar.DKind) ||
  10022. isOpenMPWorksharingDirective(DVar.DKind) ||
  10023. isOpenMPTeamsDirective(DVar.DKind))) {
  10024. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  10025. << getOpenMPDirectiveName(DVar.DKind);
  10026. reportOriginalDsa(*this, DSAStack, D, DVar);
  10027. continue;
  10028. }
  10029. }
  10030. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  10031. // A list item cannot appear in both a map clause and a data-sharing
  10032. // attribute clause on the same construct
  10033. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  10034. OpenMPClauseKind ConflictKind;
  10035. if (DSAStack->checkMappableExprComponentListsForDecl(
  10036. VD, /*CurrentRegionOnly=*/true,
  10037. [&ConflictKind](
  10038. OMPClauseMappableExprCommon::MappableExprComponentListRef,
  10039. OpenMPClauseKind WhereFoundClauseKind) {
  10040. ConflictKind = WhereFoundClauseKind;
  10041. return true;
  10042. })) {
  10043. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  10044. << getOpenMPClauseName(OMPC_firstprivate)
  10045. << getOpenMPClauseName(ConflictKind)
  10046. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  10047. reportOriginalDsa(*this, DSAStack, D, DVar);
  10048. continue;
  10049. }
  10050. }
  10051. }
  10052. // Variably modified types are not supported for tasks.
  10053. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  10054. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  10055. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  10056. << getOpenMPClauseName(OMPC_firstprivate) << Type
  10057. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  10058. bool IsDecl =
  10059. !VD ||
  10060. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10061. Diag(D->getLocation(),
  10062. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10063. << D;
  10064. continue;
  10065. }
  10066. Type = Type.getUnqualifiedType();
  10067. VarDecl *VDPrivate =
  10068. buildVarDecl(*this, ELoc, Type, D->getName(),
  10069. D->hasAttrs() ? &D->getAttrs() : nullptr,
  10070. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  10071. // Generate helper private variable and initialize it with the value of the
  10072. // original variable. The address of the original variable is replaced by
  10073. // the address of the new private variable in the CodeGen. This new variable
  10074. // is not added to IdResolver, so the code in the OpenMP region uses
  10075. // original variable for proper diagnostics and variable capturing.
  10076. Expr *VDInitRefExpr = nullptr;
  10077. // For arrays generate initializer for single element and replace it by the
  10078. // original array element in CodeGen.
  10079. if (Type->isArrayType()) {
  10080. VarDecl *VDInit =
  10081. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  10082. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  10083. Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
  10084. ElemType = ElemType.getUnqualifiedType();
  10085. VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  10086. ".firstprivate.temp");
  10087. InitializedEntity Entity =
  10088. InitializedEntity::InitializeVariable(VDInitTemp);
  10089. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  10090. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  10091. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  10092. if (Result.isInvalid())
  10093. VDPrivate->setInvalidDecl();
  10094. else
  10095. VDPrivate->setInit(Result.getAs<Expr>());
  10096. // Remove temp variable declaration.
  10097. Context.Deallocate(VDInitTemp);
  10098. } else {
  10099. VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  10100. ".firstprivate.temp");
  10101. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  10102. RefExpr->getExprLoc());
  10103. AddInitializerToDecl(VDPrivate,
  10104. DefaultLvalueConversion(VDInitRefExpr).get(),
  10105. /*DirectInit=*/false);
  10106. }
  10107. if (VDPrivate->isInvalidDecl()) {
  10108. if (IsImplicitClause) {
  10109. Diag(RefExpr->getExprLoc(),
  10110. diag::note_omp_task_predetermined_firstprivate_here);
  10111. }
  10112. continue;
  10113. }
  10114. CurContext->addDecl(VDPrivate);
  10115. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  10116. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  10117. RefExpr->getExprLoc());
  10118. DeclRefExpr *Ref = nullptr;
  10119. if (!VD && !CurContext->isDependentContext()) {
  10120. if (TopDVar.CKind == OMPC_lastprivate) {
  10121. Ref = TopDVar.PrivateCopy;
  10122. } else {
  10123. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  10124. if (!isOpenMPCapturedDecl(D))
  10125. ExprCaptures.push_back(Ref->getDecl());
  10126. }
  10127. }
  10128. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  10129. Vars.push_back((VD || CurContext->isDependentContext())
  10130. ? RefExpr->IgnoreParens()
  10131. : Ref);
  10132. PrivateCopies.push_back(VDPrivateRefExpr);
  10133. Inits.push_back(VDInitRefExpr);
  10134. }
  10135. if (Vars.empty())
  10136. return nullptr;
  10137. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10138. Vars, PrivateCopies, Inits,
  10139. buildPreInits(Context, ExprCaptures));
  10140. }
  10141. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  10142. SourceLocation StartLoc,
  10143. SourceLocation LParenLoc,
  10144. SourceLocation EndLoc) {
  10145. SmallVector<Expr *, 8> Vars;
  10146. SmallVector<Expr *, 8> SrcExprs;
  10147. SmallVector<Expr *, 8> DstExprs;
  10148. SmallVector<Expr *, 8> AssignmentOps;
  10149. SmallVector<Decl *, 4> ExprCaptures;
  10150. SmallVector<Expr *, 4> ExprPostUpdates;
  10151. for (Expr *RefExpr : VarList) {
  10152. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  10153. SourceLocation ELoc;
  10154. SourceRange ERange;
  10155. Expr *SimpleRefExpr = RefExpr;
  10156. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10157. if (Res.second) {
  10158. // It will be analyzed later.
  10159. Vars.push_back(RefExpr);
  10160. SrcExprs.push_back(nullptr);
  10161. DstExprs.push_back(nullptr);
  10162. AssignmentOps.push_back(nullptr);
  10163. }
  10164. ValueDecl *D = Res.first;
  10165. if (!D)
  10166. continue;
  10167. QualType Type = D->getType();
  10168. auto *VD = dyn_cast<VarDecl>(D);
  10169. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  10170. // A variable that appears in a lastprivate clause must not have an
  10171. // incomplete type or a reference type.
  10172. if (RequireCompleteType(ELoc, Type,
  10173. diag::err_omp_lastprivate_incomplete_type))
  10174. continue;
  10175. Type = Type.getNonReferenceType();
  10176. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  10177. // A variable that is privatized must not have a const-qualified type
  10178. // unless it is of class type with a mutable member. This restriction does
  10179. // not apply to the firstprivate clause.
  10180. //
  10181. // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
  10182. // A variable that appears in a lastprivate clause must not have a
  10183. // const-qualified type unless it is of class type with a mutable member.
  10184. if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
  10185. continue;
  10186. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  10187. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  10188. // in a Construct]
  10189. // Variables with the predetermined data-sharing attributes may not be
  10190. // listed in data-sharing attributes clauses, except for the cases
  10191. // listed below.
  10192. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  10193. // A list item may appear in a firstprivate or lastprivate clause but not
  10194. // both.
  10195. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  10196. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  10197. (isOpenMPDistributeDirective(CurrDir) ||
  10198. DVar.CKind != OMPC_firstprivate) &&
  10199. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  10200. Diag(ELoc, diag::err_omp_wrong_dsa)
  10201. << getOpenMPClauseName(DVar.CKind)
  10202. << getOpenMPClauseName(OMPC_lastprivate);
  10203. reportOriginalDsa(*this, DSAStack, D, DVar);
  10204. continue;
  10205. }
  10206. // OpenMP [2.14.3.5, Restrictions, p.2]
  10207. // A list item that is private within a parallel region, or that appears in
  10208. // the reduction clause of a parallel construct, must not appear in a
  10209. // lastprivate clause on a worksharing construct if any of the corresponding
  10210. // worksharing regions ever binds to any of the corresponding parallel
  10211. // regions.
  10212. DSAStackTy::DSAVarData TopDVar = DVar;
  10213. if (isOpenMPWorksharingDirective(CurrDir) &&
  10214. !isOpenMPParallelDirective(CurrDir) &&
  10215. !isOpenMPTeamsDirective(CurrDir)) {
  10216. DVar = DSAStack->getImplicitDSA(D, true);
  10217. if (DVar.CKind != OMPC_shared) {
  10218. Diag(ELoc, diag::err_omp_required_access)
  10219. << getOpenMPClauseName(OMPC_lastprivate)
  10220. << getOpenMPClauseName(OMPC_shared);
  10221. reportOriginalDsa(*this, DSAStack, D, DVar);
  10222. continue;
  10223. }
  10224. }
  10225. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  10226. // A variable of class type (or array thereof) that appears in a
  10227. // lastprivate clause requires an accessible, unambiguous default
  10228. // constructor for the class type, unless the list item is also specified
  10229. // in a firstprivate clause.
  10230. // A variable of class type (or array thereof) that appears in a
  10231. // lastprivate clause requires an accessible, unambiguous copy assignment
  10232. // operator for the class type.
  10233. Type = Context.getBaseElementType(Type).getNonReferenceType();
  10234. VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  10235. Type.getUnqualifiedType(), ".lastprivate.src",
  10236. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10237. DeclRefExpr *PseudoSrcExpr =
  10238. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  10239. VarDecl *DstVD =
  10240. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  10241. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10242. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  10243. // For arrays generate assignment operation for single element and replace
  10244. // it by the original array element in CodeGen.
  10245. ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  10246. PseudoDstExpr, PseudoSrcExpr);
  10247. if (AssignmentOp.isInvalid())
  10248. continue;
  10249. AssignmentOp =
  10250. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  10251. if (AssignmentOp.isInvalid())
  10252. continue;
  10253. DeclRefExpr *Ref = nullptr;
  10254. if (!VD && !CurContext->isDependentContext()) {
  10255. if (TopDVar.CKind == OMPC_firstprivate) {
  10256. Ref = TopDVar.PrivateCopy;
  10257. } else {
  10258. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  10259. if (!isOpenMPCapturedDecl(D))
  10260. ExprCaptures.push_back(Ref->getDecl());
  10261. }
  10262. if (TopDVar.CKind == OMPC_firstprivate ||
  10263. (!isOpenMPCapturedDecl(D) &&
  10264. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  10265. ExprResult RefRes = DefaultLvalueConversion(Ref);
  10266. if (!RefRes.isUsable())
  10267. continue;
  10268. ExprResult PostUpdateRes =
  10269. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  10270. RefRes.get());
  10271. if (!PostUpdateRes.isUsable())
  10272. continue;
  10273. ExprPostUpdates.push_back(
  10274. IgnoredValueConversions(PostUpdateRes.get()).get());
  10275. }
  10276. }
  10277. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  10278. Vars.push_back((VD || CurContext->isDependentContext())
  10279. ? RefExpr->IgnoreParens()
  10280. : Ref);
  10281. SrcExprs.push_back(PseudoSrcExpr);
  10282. DstExprs.push_back(PseudoDstExpr);
  10283. AssignmentOps.push_back(AssignmentOp.get());
  10284. }
  10285. if (Vars.empty())
  10286. return nullptr;
  10287. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  10288. Vars, SrcExprs, DstExprs, AssignmentOps,
  10289. buildPreInits(Context, ExprCaptures),
  10290. buildPostUpdate(*this, ExprPostUpdates));
  10291. }
  10292. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  10293. SourceLocation StartLoc,
  10294. SourceLocation LParenLoc,
  10295. SourceLocation EndLoc) {
  10296. SmallVector<Expr *, 8> Vars;
  10297. for (Expr *RefExpr : VarList) {
  10298. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  10299. SourceLocation ELoc;
  10300. SourceRange ERange;
  10301. Expr *SimpleRefExpr = RefExpr;
  10302. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10303. if (Res.second) {
  10304. // It will be analyzed later.
  10305. Vars.push_back(RefExpr);
  10306. }
  10307. ValueDecl *D = Res.first;
  10308. if (!D)
  10309. continue;
  10310. auto *VD = dyn_cast<VarDecl>(D);
  10311. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  10312. // in a Construct]
  10313. // Variables with the predetermined data-sharing attributes may not be
  10314. // listed in data-sharing attributes clauses, except for the cases
  10315. // listed below. For these exceptions only, listing a predetermined
  10316. // variable in a data-sharing attribute clause is allowed and overrides
  10317. // the variable's predetermined data-sharing attributes.
  10318. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  10319. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  10320. DVar.RefExpr) {
  10321. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  10322. << getOpenMPClauseName(OMPC_shared);
  10323. reportOriginalDsa(*this, DSAStack, D, DVar);
  10324. continue;
  10325. }
  10326. DeclRefExpr *Ref = nullptr;
  10327. if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  10328. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  10329. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  10330. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  10331. ? RefExpr->IgnoreParens()
  10332. : Ref);
  10333. }
  10334. if (Vars.empty())
  10335. return nullptr;
  10336. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  10337. }
  10338. namespace {
  10339. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  10340. DSAStackTy *Stack;
  10341. public:
  10342. bool VisitDeclRefExpr(DeclRefExpr *E) {
  10343. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  10344. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  10345. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  10346. return false;
  10347. if (DVar.CKind != OMPC_unknown)
  10348. return true;
  10349. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  10350. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
  10351. /*FromParent=*/true);
  10352. return DVarPrivate.CKind != OMPC_unknown;
  10353. }
  10354. return false;
  10355. }
  10356. bool VisitStmt(Stmt *S) {
  10357. for (Stmt *Child : S->children()) {
  10358. if (Child && Visit(Child))
  10359. return true;
  10360. }
  10361. return false;
  10362. }
  10363. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  10364. };
  10365. } // namespace
  10366. namespace {
  10367. // Transform MemberExpression for specified FieldDecl of current class to
  10368. // DeclRefExpr to specified OMPCapturedExprDecl.
  10369. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  10370. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  10371. ValueDecl *Field = nullptr;
  10372. DeclRefExpr *CapturedExpr = nullptr;
  10373. public:
  10374. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  10375. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  10376. ExprResult TransformMemberExpr(MemberExpr *E) {
  10377. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  10378. E->getMemberDecl() == Field) {
  10379. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  10380. return CapturedExpr;
  10381. }
  10382. return BaseTransform::TransformMemberExpr(E);
  10383. }
  10384. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  10385. };
  10386. } // namespace
  10387. template <typename T, typename U>
  10388. static T filterLookupForUDReductionAndMapper(
  10389. SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
  10390. for (U &Set : Lookups) {
  10391. for (auto *D : Set) {
  10392. if (T Res = Gen(cast<ValueDecl>(D)))
  10393. return Res;
  10394. }
  10395. }
  10396. return T();
  10397. }
  10398. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
  10399. assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
  10400. for (auto RD : D->redecls()) {
  10401. // Don't bother with extra checks if we already know this one isn't visible.
  10402. if (RD == D)
  10403. continue;
  10404. auto ND = cast<NamedDecl>(RD);
  10405. if (LookupResult::isVisible(SemaRef, ND))
  10406. return ND;
  10407. }
  10408. return nullptr;
  10409. }
  10410. static void
  10411. argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
  10412. SourceLocation Loc, QualType Ty,
  10413. SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
  10414. // Find all of the associated namespaces and classes based on the
  10415. // arguments we have.
  10416. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  10417. Sema::AssociatedClassSet AssociatedClasses;
  10418. OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
  10419. SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
  10420. AssociatedClasses);
  10421. // C++ [basic.lookup.argdep]p3:
  10422. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  10423. // and let Y be the lookup set produced by argument dependent
  10424. // lookup (defined as follows). If X contains [...] then Y is
  10425. // empty. Otherwise Y is the set of declarations found in the
  10426. // namespaces associated with the argument types as described
  10427. // below. The set of declarations found by the lookup of the name
  10428. // is the union of X and Y.
  10429. //
  10430. // Here, we compute Y and add its members to the overloaded
  10431. // candidate set.
  10432. for (auto *NS : AssociatedNamespaces) {
  10433. // When considering an associated namespace, the lookup is the
  10434. // same as the lookup performed when the associated namespace is
  10435. // used as a qualifier (3.4.3.2) except that:
  10436. //
  10437. // -- Any using-directives in the associated namespace are
  10438. // ignored.
  10439. //
  10440. // -- Any namespace-scope friend functions declared in
  10441. // associated classes are visible within their respective
  10442. // namespaces even if they are not visible during an ordinary
  10443. // lookup (11.4).
  10444. DeclContext::lookup_result R = NS->lookup(Id.getName());
  10445. for (auto *D : R) {
  10446. auto *Underlying = D;
  10447. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  10448. Underlying = USD->getTargetDecl();
  10449. if (!isa<OMPDeclareReductionDecl>(Underlying) &&
  10450. !isa<OMPDeclareMapperDecl>(Underlying))
  10451. continue;
  10452. if (!SemaRef.isVisible(D)) {
  10453. D = findAcceptableDecl(SemaRef, D);
  10454. if (!D)
  10455. continue;
  10456. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  10457. Underlying = USD->getTargetDecl();
  10458. }
  10459. Lookups.emplace_back();
  10460. Lookups.back().addDecl(Underlying);
  10461. }
  10462. }
  10463. }
  10464. static ExprResult
  10465. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  10466. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  10467. const DeclarationNameInfo &ReductionId, QualType Ty,
  10468. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  10469. if (ReductionIdScopeSpec.isInvalid())
  10470. return ExprError();
  10471. SmallVector<UnresolvedSet<8>, 4> Lookups;
  10472. if (S) {
  10473. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  10474. Lookup.suppressDiagnostics();
  10475. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  10476. NamedDecl *D = Lookup.getRepresentativeDecl();
  10477. do {
  10478. S = S->getParent();
  10479. } while (S && !S->isDeclScope(D));
  10480. if (S)
  10481. S = S->getParent();
  10482. Lookups.emplace_back();
  10483. Lookups.back().append(Lookup.begin(), Lookup.end());
  10484. Lookup.clear();
  10485. }
  10486. } else if (auto *ULE =
  10487. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  10488. Lookups.push_back(UnresolvedSet<8>());
  10489. Decl *PrevD = nullptr;
  10490. for (NamedDecl *D : ULE->decls()) {
  10491. if (D == PrevD)
  10492. Lookups.push_back(UnresolvedSet<8>());
  10493. else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
  10494. Lookups.back().addDecl(DRD);
  10495. PrevD = D;
  10496. }
  10497. }
  10498. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  10499. Ty->isInstantiationDependentType() ||
  10500. Ty->containsUnexpandedParameterPack() ||
  10501. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  10502. return !D->isInvalidDecl() &&
  10503. (D->getType()->isDependentType() ||
  10504. D->getType()->isInstantiationDependentType() ||
  10505. D->getType()->containsUnexpandedParameterPack());
  10506. })) {
  10507. UnresolvedSet<8> ResSet;
  10508. for (const UnresolvedSet<8> &Set : Lookups) {
  10509. if (Set.empty())
  10510. continue;
  10511. ResSet.append(Set.begin(), Set.end());
  10512. // The last item marks the end of all declarations at the specified scope.
  10513. ResSet.addDecl(Set[Set.size() - 1]);
  10514. }
  10515. return UnresolvedLookupExpr::Create(
  10516. SemaRef.Context, /*NamingClass=*/nullptr,
  10517. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  10518. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  10519. }
  10520. // Lookup inside the classes.
  10521. // C++ [over.match.oper]p3:
  10522. // For a unary operator @ with an operand of a type whose
  10523. // cv-unqualified version is T1, and for a binary operator @ with
  10524. // a left operand of a type whose cv-unqualified version is T1 and
  10525. // a right operand of a type whose cv-unqualified version is T2,
  10526. // three sets of candidate functions, designated member
  10527. // candidates, non-member candidates and built-in candidates, are
  10528. // constructed as follows:
  10529. // -- If T1 is a complete class type or a class currently being
  10530. // defined, the set of member candidates is the result of the
  10531. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  10532. // the set of member candidates is empty.
  10533. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  10534. Lookup.suppressDiagnostics();
  10535. if (const auto *TyRec = Ty->getAs<RecordType>()) {
  10536. // Complete the type if it can be completed.
  10537. // If the type is neither complete nor being defined, bail out now.
  10538. if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
  10539. TyRec->getDecl()->getDefinition()) {
  10540. Lookup.clear();
  10541. SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
  10542. if (Lookup.empty()) {
  10543. Lookups.emplace_back();
  10544. Lookups.back().append(Lookup.begin(), Lookup.end());
  10545. }
  10546. }
  10547. }
  10548. // Perform ADL.
  10549. if (SemaRef.getLangOpts().CPlusPlus) {
  10550. argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
  10551. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  10552. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  10553. if (!D->isInvalidDecl() &&
  10554. SemaRef.Context.hasSameType(D->getType(), Ty))
  10555. return D;
  10556. return nullptr;
  10557. }))
  10558. return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
  10559. VK_LValue, Loc);
  10560. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  10561. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  10562. if (!D->isInvalidDecl() &&
  10563. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  10564. !Ty.isMoreQualifiedThan(D->getType()))
  10565. return D;
  10566. return nullptr;
  10567. })) {
  10568. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  10569. /*DetectVirtual=*/false);
  10570. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  10571. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  10572. VD->getType().getUnqualifiedType()))) {
  10573. if (SemaRef.CheckBaseClassAccess(
  10574. Loc, VD->getType(), Ty, Paths.front(),
  10575. /*DiagID=*/0) != Sema::AR_inaccessible) {
  10576. SemaRef.BuildBasePathArray(Paths, BasePath);
  10577. return SemaRef.BuildDeclRefExpr(
  10578. VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
  10579. }
  10580. }
  10581. }
  10582. }
  10583. }
  10584. if (ReductionIdScopeSpec.isSet()) {
  10585. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  10586. return ExprError();
  10587. }
  10588. return ExprEmpty();
  10589. }
  10590. namespace {
  10591. /// Data for the reduction-based clauses.
  10592. struct ReductionData {
  10593. /// List of original reduction items.
  10594. SmallVector<Expr *, 8> Vars;
  10595. /// List of private copies of the reduction items.
  10596. SmallVector<Expr *, 8> Privates;
  10597. /// LHS expressions for the reduction_op expressions.
  10598. SmallVector<Expr *, 8> LHSs;
  10599. /// RHS expressions for the reduction_op expressions.
  10600. SmallVector<Expr *, 8> RHSs;
  10601. /// Reduction operation expression.
  10602. SmallVector<Expr *, 8> ReductionOps;
  10603. /// Taskgroup descriptors for the corresponding reduction items in
  10604. /// in_reduction clauses.
  10605. SmallVector<Expr *, 8> TaskgroupDescriptors;
  10606. /// List of captures for clause.
  10607. SmallVector<Decl *, 4> ExprCaptures;
  10608. /// List of postupdate expressions.
  10609. SmallVector<Expr *, 4> ExprPostUpdates;
  10610. ReductionData() = delete;
  10611. /// Reserves required memory for the reduction data.
  10612. ReductionData(unsigned Size) {
  10613. Vars.reserve(Size);
  10614. Privates.reserve(Size);
  10615. LHSs.reserve(Size);
  10616. RHSs.reserve(Size);
  10617. ReductionOps.reserve(Size);
  10618. TaskgroupDescriptors.reserve(Size);
  10619. ExprCaptures.reserve(Size);
  10620. ExprPostUpdates.reserve(Size);
  10621. }
  10622. /// Stores reduction item and reduction operation only (required for dependent
  10623. /// reduction item).
  10624. void push(Expr *Item, Expr *ReductionOp) {
  10625. Vars.emplace_back(Item);
  10626. Privates.emplace_back(nullptr);
  10627. LHSs.emplace_back(nullptr);
  10628. RHSs.emplace_back(nullptr);
  10629. ReductionOps.emplace_back(ReductionOp);
  10630. TaskgroupDescriptors.emplace_back(nullptr);
  10631. }
  10632. /// Stores reduction data.
  10633. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  10634. Expr *TaskgroupDescriptor) {
  10635. Vars.emplace_back(Item);
  10636. Privates.emplace_back(Private);
  10637. LHSs.emplace_back(LHS);
  10638. RHSs.emplace_back(RHS);
  10639. ReductionOps.emplace_back(ReductionOp);
  10640. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  10641. }
  10642. };
  10643. } // namespace
  10644. static bool checkOMPArraySectionConstantForReduction(
  10645. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  10646. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  10647. const Expr *Length = OASE->getLength();
  10648. if (Length == nullptr) {
  10649. // For array sections of the form [1:] or [:], we would need to analyze
  10650. // the lower bound...
  10651. if (OASE->getColonLoc().isValid())
  10652. return false;
  10653. // This is an array subscript which has implicit length 1!
  10654. SingleElement = true;
  10655. ArraySizes.push_back(llvm::APSInt::get(1));
  10656. } else {
  10657. Expr::EvalResult Result;
  10658. if (!Length->EvaluateAsInt(Result, Context))
  10659. return false;
  10660. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  10661. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  10662. ArraySizes.push_back(ConstantLengthValue);
  10663. }
  10664. // Get the base of this array section and walk up from there.
  10665. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  10666. // We require length = 1 for all array sections except the right-most to
  10667. // guarantee that the memory region is contiguous and has no holes in it.
  10668. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  10669. Length = TempOASE->getLength();
  10670. if (Length == nullptr) {
  10671. // For array sections of the form [1:] or [:], we would need to analyze
  10672. // the lower bound...
  10673. if (OASE->getColonLoc().isValid())
  10674. return false;
  10675. // This is an array subscript which has implicit length 1!
  10676. ArraySizes.push_back(llvm::APSInt::get(1));
  10677. } else {
  10678. Expr::EvalResult Result;
  10679. if (!Length->EvaluateAsInt(Result, Context))
  10680. return false;
  10681. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  10682. if (ConstantLengthValue.getSExtValue() != 1)
  10683. return false;
  10684. ArraySizes.push_back(ConstantLengthValue);
  10685. }
  10686. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  10687. }
  10688. // If we have a single element, we don't need to add the implicit lengths.
  10689. if (!SingleElement) {
  10690. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  10691. // Has implicit length 1!
  10692. ArraySizes.push_back(llvm::APSInt::get(1));
  10693. Base = TempASE->getBase()->IgnoreParenImpCasts();
  10694. }
  10695. }
  10696. // This array section can be privatized as a single value or as a constant
  10697. // sized array.
  10698. return true;
  10699. }
  10700. static bool actOnOMPReductionKindClause(
  10701. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  10702. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10703. SourceLocation ColonLoc, SourceLocation EndLoc,
  10704. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10705. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  10706. DeclarationName DN = ReductionId.getName();
  10707. OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
  10708. BinaryOperatorKind BOK = BO_Comma;
  10709. ASTContext &Context = S.Context;
  10710. // OpenMP [2.14.3.6, reduction clause]
  10711. // C
  10712. // reduction-identifier is either an identifier or one of the following
  10713. // operators: +, -, *, &, |, ^, && and ||
  10714. // C++
  10715. // reduction-identifier is either an id-expression or one of the following
  10716. // operators: +, -, *, &, |, ^, && and ||
  10717. switch (OOK) {
  10718. case OO_Plus:
  10719. case OO_Minus:
  10720. BOK = BO_Add;
  10721. break;
  10722. case OO_Star:
  10723. BOK = BO_Mul;
  10724. break;
  10725. case OO_Amp:
  10726. BOK = BO_And;
  10727. break;
  10728. case OO_Pipe:
  10729. BOK = BO_Or;
  10730. break;
  10731. case OO_Caret:
  10732. BOK = BO_Xor;
  10733. break;
  10734. case OO_AmpAmp:
  10735. BOK = BO_LAnd;
  10736. break;
  10737. case OO_PipePipe:
  10738. BOK = BO_LOr;
  10739. break;
  10740. case OO_New:
  10741. case OO_Delete:
  10742. case OO_Array_New:
  10743. case OO_Array_Delete:
  10744. case OO_Slash:
  10745. case OO_Percent:
  10746. case OO_Tilde:
  10747. case OO_Exclaim:
  10748. case OO_Equal:
  10749. case OO_Less:
  10750. case OO_Greater:
  10751. case OO_LessEqual:
  10752. case OO_GreaterEqual:
  10753. case OO_PlusEqual:
  10754. case OO_MinusEqual:
  10755. case OO_StarEqual:
  10756. case OO_SlashEqual:
  10757. case OO_PercentEqual:
  10758. case OO_CaretEqual:
  10759. case OO_AmpEqual:
  10760. case OO_PipeEqual:
  10761. case OO_LessLess:
  10762. case OO_GreaterGreater:
  10763. case OO_LessLessEqual:
  10764. case OO_GreaterGreaterEqual:
  10765. case OO_EqualEqual:
  10766. case OO_ExclaimEqual:
  10767. case OO_Spaceship:
  10768. case OO_PlusPlus:
  10769. case OO_MinusMinus:
  10770. case OO_Comma:
  10771. case OO_ArrowStar:
  10772. case OO_Arrow:
  10773. case OO_Call:
  10774. case OO_Subscript:
  10775. case OO_Conditional:
  10776. case OO_Coawait:
  10777. case NUM_OVERLOADED_OPERATORS:
  10778. llvm_unreachable("Unexpected reduction identifier");
  10779. case OO_None:
  10780. if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
  10781. if (II->isStr("max"))
  10782. BOK = BO_GT;
  10783. else if (II->isStr("min"))
  10784. BOK = BO_LT;
  10785. }
  10786. break;
  10787. }
  10788. SourceRange ReductionIdRange;
  10789. if (ReductionIdScopeSpec.isValid())
  10790. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  10791. else
  10792. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  10793. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  10794. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  10795. bool FirstIter = true;
  10796. for (Expr *RefExpr : VarList) {
  10797. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  10798. // OpenMP [2.1, C/C++]
  10799. // A list item is a variable or array section, subject to the restrictions
  10800. // specified in Section 2.4 on page 42 and in each of the sections
  10801. // describing clauses and directives for which a list appears.
  10802. // OpenMP [2.14.3.3, Restrictions, p.1]
  10803. // A variable that is part of another variable (as an array or
  10804. // structure element) cannot appear in a private clause.
  10805. if (!FirstIter && IR != ER)
  10806. ++IR;
  10807. FirstIter = false;
  10808. SourceLocation ELoc;
  10809. SourceRange ERange;
  10810. Expr *SimpleRefExpr = RefExpr;
  10811. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  10812. /*AllowArraySection=*/true);
  10813. if (Res.second) {
  10814. // Try to find 'declare reduction' corresponding construct before using
  10815. // builtin/overloaded operators.
  10816. QualType Type = Context.DependentTy;
  10817. CXXCastPath BasePath;
  10818. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  10819. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  10820. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  10821. Expr *ReductionOp = nullptr;
  10822. if (S.CurContext->isDependentContext() &&
  10823. (DeclareReductionRef.isUnset() ||
  10824. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  10825. ReductionOp = DeclareReductionRef.get();
  10826. // It will be analyzed later.
  10827. RD.push(RefExpr, ReductionOp);
  10828. }
  10829. ValueDecl *D = Res.first;
  10830. if (!D)
  10831. continue;
  10832. Expr *TaskgroupDescriptor = nullptr;
  10833. QualType Type;
  10834. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  10835. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  10836. if (ASE) {
  10837. Type = ASE->getType().getNonReferenceType();
  10838. } else if (OASE) {
  10839. QualType BaseType =
  10840. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  10841. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  10842. Type = ATy->getElementType();
  10843. else
  10844. Type = BaseType->getPointeeType();
  10845. Type = Type.getNonReferenceType();
  10846. } else {
  10847. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  10848. }
  10849. auto *VD = dyn_cast<VarDecl>(D);
  10850. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  10851. // A variable that appears in a private clause must not have an incomplete
  10852. // type or a reference type.
  10853. if (S.RequireCompleteType(ELoc, D->getType(),
  10854. diag::err_omp_reduction_incomplete_type))
  10855. continue;
  10856. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  10857. // A list item that appears in a reduction clause must not be
  10858. // const-qualified.
  10859. if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
  10860. /*AcceptIfMutable*/ false, ASE || OASE))
  10861. continue;
  10862. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  10863. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  10864. // If a list-item is a reference type then it must bind to the same object
  10865. // for all threads of the team.
  10866. if (!ASE && !OASE) {
  10867. if (VD) {
  10868. VarDecl *VDDef = VD->getDefinition();
  10869. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  10870. DSARefChecker Check(Stack);
  10871. if (Check.Visit(VDDef->getInit())) {
  10872. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  10873. << getOpenMPClauseName(ClauseKind) << ERange;
  10874. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  10875. continue;
  10876. }
  10877. }
  10878. }
  10879. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  10880. // in a Construct]
  10881. // Variables with the predetermined data-sharing attributes may not be
  10882. // listed in data-sharing attributes clauses, except for the cases
  10883. // listed below. For these exceptions only, listing a predetermined
  10884. // variable in a data-sharing attribute clause is allowed and overrides
  10885. // the variable's predetermined data-sharing attributes.
  10886. // OpenMP [2.14.3.6, Restrictions, p.3]
  10887. // Any number of reduction clauses can be specified on the directive,
  10888. // but a list item can appear only once in the reduction clauses for that
  10889. // directive.
  10890. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
  10891. if (DVar.CKind == OMPC_reduction) {
  10892. S.Diag(ELoc, diag::err_omp_once_referenced)
  10893. << getOpenMPClauseName(ClauseKind);
  10894. if (DVar.RefExpr)
  10895. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  10896. continue;
  10897. }
  10898. if (DVar.CKind != OMPC_unknown) {
  10899. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  10900. << getOpenMPClauseName(DVar.CKind)
  10901. << getOpenMPClauseName(OMPC_reduction);
  10902. reportOriginalDsa(S, Stack, D, DVar);
  10903. continue;
  10904. }
  10905. // OpenMP [2.14.3.6, Restrictions, p.1]
  10906. // A list item that appears in a reduction clause of a worksharing
  10907. // construct must be shared in the parallel regions to which any of the
  10908. // worksharing regions arising from the worksharing construct bind.
  10909. if (isOpenMPWorksharingDirective(CurrDir) &&
  10910. !isOpenMPParallelDirective(CurrDir) &&
  10911. !isOpenMPTeamsDirective(CurrDir)) {
  10912. DVar = Stack->getImplicitDSA(D, true);
  10913. if (DVar.CKind != OMPC_shared) {
  10914. S.Diag(ELoc, diag::err_omp_required_access)
  10915. << getOpenMPClauseName(OMPC_reduction)
  10916. << getOpenMPClauseName(OMPC_shared);
  10917. reportOriginalDsa(S, Stack, D, DVar);
  10918. continue;
  10919. }
  10920. }
  10921. }
  10922. // Try to find 'declare reduction' corresponding construct before using
  10923. // builtin/overloaded operators.
  10924. CXXCastPath BasePath;
  10925. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  10926. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  10927. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  10928. if (DeclareReductionRef.isInvalid())
  10929. continue;
  10930. if (S.CurContext->isDependentContext() &&
  10931. (DeclareReductionRef.isUnset() ||
  10932. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  10933. RD.push(RefExpr, DeclareReductionRef.get());
  10934. continue;
  10935. }
  10936. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  10937. // Not allowed reduction identifier is found.
  10938. S.Diag(ReductionId.getBeginLoc(),
  10939. diag::err_omp_unknown_reduction_identifier)
  10940. << Type << ReductionIdRange;
  10941. continue;
  10942. }
  10943. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  10944. // The type of a list item that appears in a reduction clause must be valid
  10945. // for the reduction-identifier. For a max or min reduction in C, the type
  10946. // of the list item must be an allowed arithmetic data type: char, int,
  10947. // float, double, or _Bool, possibly modified with long, short, signed, or
  10948. // unsigned. For a max or min reduction in C++, the type of the list item
  10949. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  10950. // double, or bool, possibly modified with long, short, signed, or unsigned.
  10951. if (DeclareReductionRef.isUnset()) {
  10952. if ((BOK == BO_GT || BOK == BO_LT) &&
  10953. !(Type->isScalarType() ||
  10954. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  10955. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  10956. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  10957. if (!ASE && !OASE) {
  10958. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10959. VarDecl::DeclarationOnly;
  10960. S.Diag(D->getLocation(),
  10961. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10962. << D;
  10963. }
  10964. continue;
  10965. }
  10966. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  10967. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  10968. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  10969. << getOpenMPClauseName(ClauseKind);
  10970. if (!ASE && !OASE) {
  10971. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10972. VarDecl::DeclarationOnly;
  10973. S.Diag(D->getLocation(),
  10974. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10975. << D;
  10976. }
  10977. continue;
  10978. }
  10979. }
  10980. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  10981. VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  10982. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10983. VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  10984. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10985. QualType PrivateTy = Type;
  10986. // Try if we can determine constant lengths for all array sections and avoid
  10987. // the VLA.
  10988. bool ConstantLengthOASE = false;
  10989. if (OASE) {
  10990. bool SingleElement;
  10991. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  10992. ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
  10993. Context, OASE, SingleElement, ArraySizes);
  10994. // If we don't have a single element, we must emit a constant array type.
  10995. if (ConstantLengthOASE && !SingleElement) {
  10996. for (llvm::APSInt &Size : ArraySizes)
  10997. PrivateTy = Context.getConstantArrayType(
  10998. PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
  10999. }
  11000. }
  11001. if ((OASE && !ConstantLengthOASE) ||
  11002. (!OASE && !ASE &&
  11003. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  11004. if (!Context.getTargetInfo().isVLASupported() &&
  11005. S.shouldDiagnoseTargetSupportFromOpenMP()) {
  11006. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  11007. S.Diag(ELoc, diag::note_vla_unsupported);
  11008. continue;
  11009. }
  11010. // For arrays/array sections only:
  11011. // Create pseudo array type for private copy. The size for this array will
  11012. // be generated during codegen.
  11013. // For array subscripts or single variables Private Ty is the same as Type
  11014. // (type of the variable or single array element).
  11015. PrivateTy = Context.getVariableArrayType(
  11016. Type,
  11017. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  11018. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  11019. } else if (!ASE && !OASE &&
  11020. Context.getAsArrayType(D->getType().getNonReferenceType())) {
  11021. PrivateTy = D->getType().getNonReferenceType();
  11022. }
  11023. // Private copy.
  11024. VarDecl *PrivateVD =
  11025. buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  11026. D->hasAttrs() ? &D->getAttrs() : nullptr,
  11027. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  11028. // Add initializer for private variable.
  11029. Expr *Init = nullptr;
  11030. DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  11031. DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  11032. if (DeclareReductionRef.isUsable()) {
  11033. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  11034. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  11035. if (DRD->getInitializer()) {
  11036. Init = DRDRef;
  11037. RHSVD->setInit(DRDRef);
  11038. RHSVD->setInitStyle(VarDecl::CallInit);
  11039. }
  11040. } else {
  11041. switch (BOK) {
  11042. case BO_Add:
  11043. case BO_Xor:
  11044. case BO_Or:
  11045. case BO_LOr:
  11046. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  11047. if (Type->isScalarType() || Type->isAnyComplexType())
  11048. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  11049. break;
  11050. case BO_Mul:
  11051. case BO_LAnd:
  11052. if (Type->isScalarType() || Type->isAnyComplexType()) {
  11053. // '*' and '&&' reduction ops - initializer is '1'.
  11054. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  11055. }
  11056. break;
  11057. case BO_And: {
  11058. // '&' reduction op - initializer is '~0'.
  11059. QualType OrigType = Type;
  11060. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  11061. Type = ComplexTy->getElementType();
  11062. if (Type->isRealFloatingType()) {
  11063. llvm::APFloat InitValue =
  11064. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  11065. /*isIEEE=*/true);
  11066. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  11067. Type, ELoc);
  11068. } else if (Type->isScalarType()) {
  11069. uint64_t Size = Context.getTypeSize(Type);
  11070. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  11071. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  11072. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  11073. }
  11074. if (Init && OrigType->isAnyComplexType()) {
  11075. // Init = 0xFFFF + 0xFFFFi;
  11076. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  11077. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  11078. }
  11079. Type = OrigType;
  11080. break;
  11081. }
  11082. case BO_LT:
  11083. case BO_GT: {
  11084. // 'min' reduction op - initializer is 'Largest representable number in
  11085. // the reduction list item type'.
  11086. // 'max' reduction op - initializer is 'Least representable number in
  11087. // the reduction list item type'.
  11088. if (Type->isIntegerType() || Type->isPointerType()) {
  11089. bool IsSigned = Type->hasSignedIntegerRepresentation();
  11090. uint64_t Size = Context.getTypeSize(Type);
  11091. QualType IntTy =
  11092. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  11093. llvm::APInt InitValue =
  11094. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  11095. : llvm::APInt::getMinValue(Size)
  11096. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  11097. : llvm::APInt::getMaxValue(Size);
  11098. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  11099. if (Type->isPointerType()) {
  11100. // Cast to pointer type.
  11101. ExprResult CastExpr = S.BuildCStyleCastExpr(
  11102. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  11103. if (CastExpr.isInvalid())
  11104. continue;
  11105. Init = CastExpr.get();
  11106. }
  11107. } else if (Type->isRealFloatingType()) {
  11108. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  11109. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  11110. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  11111. Type, ELoc);
  11112. }
  11113. break;
  11114. }
  11115. case BO_PtrMemD:
  11116. case BO_PtrMemI:
  11117. case BO_MulAssign:
  11118. case BO_Div:
  11119. case BO_Rem:
  11120. case BO_Sub:
  11121. case BO_Shl:
  11122. case BO_Shr:
  11123. case BO_LE:
  11124. case BO_GE:
  11125. case BO_EQ:
  11126. case BO_NE:
  11127. case BO_Cmp:
  11128. case BO_AndAssign:
  11129. case BO_XorAssign:
  11130. case BO_OrAssign:
  11131. case BO_Assign:
  11132. case BO_AddAssign:
  11133. case BO_SubAssign:
  11134. case BO_DivAssign:
  11135. case BO_RemAssign:
  11136. case BO_ShlAssign:
  11137. case BO_ShrAssign:
  11138. case BO_Comma:
  11139. llvm_unreachable("Unexpected reduction operation");
  11140. }
  11141. }
  11142. if (Init && DeclareReductionRef.isUnset())
  11143. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  11144. else if (!Init)
  11145. S.ActOnUninitializedDecl(RHSVD);
  11146. if (RHSVD->isInvalidDecl())
  11147. continue;
  11148. if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
  11149. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  11150. << Type << ReductionIdRange;
  11151. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  11152. VarDecl::DeclarationOnly;
  11153. S.Diag(D->getLocation(),
  11154. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11155. << D;
  11156. continue;
  11157. }
  11158. // Store initializer for single element in private copy. Will be used during
  11159. // codegen.
  11160. PrivateVD->setInit(RHSVD->getInit());
  11161. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  11162. DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  11163. ExprResult ReductionOp;
  11164. if (DeclareReductionRef.isUsable()) {
  11165. QualType RedTy = DeclareReductionRef.get()->getType();
  11166. QualType PtrRedTy = Context.getPointerType(RedTy);
  11167. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  11168. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  11169. if (!BasePath.empty()) {
  11170. LHS = S.DefaultLvalueConversion(LHS.get());
  11171. RHS = S.DefaultLvalueConversion(RHS.get());
  11172. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  11173. CK_UncheckedDerivedToBase, LHS.get(),
  11174. &BasePath, LHS.get()->getValueKind());
  11175. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  11176. CK_UncheckedDerivedToBase, RHS.get(),
  11177. &BasePath, RHS.get()->getValueKind());
  11178. }
  11179. FunctionProtoType::ExtProtoInfo EPI;
  11180. QualType Params[] = {PtrRedTy, PtrRedTy};
  11181. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  11182. auto *OVE = new (Context) OpaqueValueExpr(
  11183. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  11184. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  11185. Expr *Args[] = {LHS.get(), RHS.get()};
  11186. ReductionOp =
  11187. CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  11188. } else {
  11189. ReductionOp = S.BuildBinOp(
  11190. Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
  11191. if (ReductionOp.isUsable()) {
  11192. if (BOK != BO_LT && BOK != BO_GT) {
  11193. ReductionOp =
  11194. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  11195. BO_Assign, LHSDRE, ReductionOp.get());
  11196. } else {
  11197. auto *ConditionalOp = new (Context)
  11198. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  11199. Type, VK_LValue, OK_Ordinary);
  11200. ReductionOp =
  11201. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  11202. BO_Assign, LHSDRE, ConditionalOp);
  11203. }
  11204. if (ReductionOp.isUsable())
  11205. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
  11206. /*DiscardedValue*/ false);
  11207. }
  11208. if (!ReductionOp.isUsable())
  11209. continue;
  11210. }
  11211. // OpenMP [2.15.4.6, Restrictions, p.2]
  11212. // A list item that appears in an in_reduction clause of a task construct
  11213. // must appear in a task_reduction clause of a construct associated with a
  11214. // taskgroup region that includes the participating task in its taskgroup
  11215. // set. The construct associated with the innermost region that meets this
  11216. // condition must specify the same reduction-identifier as the in_reduction
  11217. // clause.
  11218. if (ClauseKind == OMPC_in_reduction) {
  11219. SourceRange ParentSR;
  11220. BinaryOperatorKind ParentBOK;
  11221. const Expr *ParentReductionOp;
  11222. Expr *ParentBOKTD, *ParentReductionOpTD;
  11223. DSAStackTy::DSAVarData ParentBOKDSA =
  11224. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  11225. ParentBOKTD);
  11226. DSAStackTy::DSAVarData ParentReductionOpDSA =
  11227. Stack->getTopMostTaskgroupReductionData(
  11228. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  11229. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  11230. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  11231. if (!IsParentBOK && !IsParentReductionOp) {
  11232. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  11233. continue;
  11234. }
  11235. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  11236. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  11237. IsParentReductionOp) {
  11238. bool EmitError = true;
  11239. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  11240. llvm::FoldingSetNodeID RedId, ParentRedId;
  11241. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  11242. DeclareReductionRef.get()->Profile(RedId, Context,
  11243. /*Canonical=*/true);
  11244. EmitError = RedId != ParentRedId;
  11245. }
  11246. if (EmitError) {
  11247. S.Diag(ReductionId.getBeginLoc(),
  11248. diag::err_omp_reduction_identifier_mismatch)
  11249. << ReductionIdRange << RefExpr->getSourceRange();
  11250. S.Diag(ParentSR.getBegin(),
  11251. diag::note_omp_previous_reduction_identifier)
  11252. << ParentSR
  11253. << (IsParentBOK ? ParentBOKDSA.RefExpr
  11254. : ParentReductionOpDSA.RefExpr)
  11255. ->getSourceRange();
  11256. continue;
  11257. }
  11258. }
  11259. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  11260. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  11261. }
  11262. DeclRefExpr *Ref = nullptr;
  11263. Expr *VarsExpr = RefExpr->IgnoreParens();
  11264. if (!VD && !S.CurContext->isDependentContext()) {
  11265. if (ASE || OASE) {
  11266. TransformExprToCaptures RebuildToCapture(S, D);
  11267. VarsExpr =
  11268. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  11269. Ref = RebuildToCapture.getCapturedExpr();
  11270. } else {
  11271. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  11272. }
  11273. if (!S.isOpenMPCapturedDecl(D)) {
  11274. RD.ExprCaptures.emplace_back(Ref->getDecl());
  11275. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  11276. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  11277. if (!RefRes.isUsable())
  11278. continue;
  11279. ExprResult PostUpdateRes =
  11280. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  11281. RefRes.get());
  11282. if (!PostUpdateRes.isUsable())
  11283. continue;
  11284. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  11285. Stack->getCurrentDirective() == OMPD_taskgroup) {
  11286. S.Diag(RefExpr->getExprLoc(),
  11287. diag::err_omp_reduction_non_addressable_expression)
  11288. << RefExpr->getSourceRange();
  11289. continue;
  11290. }
  11291. RD.ExprPostUpdates.emplace_back(
  11292. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  11293. }
  11294. }
  11295. }
  11296. // All reduction items are still marked as reduction (to do not increase
  11297. // code base size).
  11298. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  11299. if (CurrDir == OMPD_taskgroup) {
  11300. if (DeclareReductionRef.isUsable())
  11301. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  11302. DeclareReductionRef.get());
  11303. else
  11304. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  11305. }
  11306. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  11307. TaskgroupDescriptor);
  11308. }
  11309. return RD.Vars.empty();
  11310. }
  11311. OMPClause *Sema::ActOnOpenMPReductionClause(
  11312. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  11313. SourceLocation ColonLoc, SourceLocation EndLoc,
  11314. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  11315. ArrayRef<Expr *> UnresolvedReductions) {
  11316. ReductionData RD(VarList.size());
  11317. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  11318. StartLoc, LParenLoc, ColonLoc, EndLoc,
  11319. ReductionIdScopeSpec, ReductionId,
  11320. UnresolvedReductions, RD))
  11321. return nullptr;
  11322. return OMPReductionClause::Create(
  11323. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  11324. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  11325. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  11326. buildPreInits(Context, RD.ExprCaptures),
  11327. buildPostUpdate(*this, RD.ExprPostUpdates));
  11328. }
  11329. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  11330. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  11331. SourceLocation ColonLoc, SourceLocation EndLoc,
  11332. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  11333. ArrayRef<Expr *> UnresolvedReductions) {
  11334. ReductionData RD(VarList.size());
  11335. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
  11336. StartLoc, LParenLoc, ColonLoc, EndLoc,
  11337. ReductionIdScopeSpec, ReductionId,
  11338. UnresolvedReductions, RD))
  11339. return nullptr;
  11340. return OMPTaskReductionClause::Create(
  11341. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  11342. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  11343. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  11344. buildPreInits(Context, RD.ExprCaptures),
  11345. buildPostUpdate(*this, RD.ExprPostUpdates));
  11346. }
  11347. OMPClause *Sema::ActOnOpenMPInReductionClause(
  11348. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  11349. SourceLocation ColonLoc, SourceLocation EndLoc,
  11350. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  11351. ArrayRef<Expr *> UnresolvedReductions) {
  11352. ReductionData RD(VarList.size());
  11353. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  11354. StartLoc, LParenLoc, ColonLoc, EndLoc,
  11355. ReductionIdScopeSpec, ReductionId,
  11356. UnresolvedReductions, RD))
  11357. return nullptr;
  11358. return OMPInReductionClause::Create(
  11359. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  11360. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  11361. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  11362. buildPreInits(Context, RD.ExprCaptures),
  11363. buildPostUpdate(*this, RD.ExprPostUpdates));
  11364. }
  11365. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  11366. SourceLocation LinLoc) {
  11367. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  11368. LinKind == OMPC_LINEAR_unknown) {
  11369. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  11370. return true;
  11371. }
  11372. return false;
  11373. }
  11374. bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
  11375. OpenMPLinearClauseKind LinKind,
  11376. QualType Type) {
  11377. const auto *VD = dyn_cast_or_null<VarDecl>(D);
  11378. // A variable must not have an incomplete type or a reference type.
  11379. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  11380. return true;
  11381. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  11382. !Type->isReferenceType()) {
  11383. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  11384. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  11385. return true;
  11386. }
  11387. Type = Type.getNonReferenceType();
  11388. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  11389. // A variable that is privatized must not have a const-qualified type
  11390. // unless it is of class type with a mutable member. This restriction does
  11391. // not apply to the firstprivate clause.
  11392. if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
  11393. return true;
  11394. // A list item must be of integral or pointer type.
  11395. Type = Type.getUnqualifiedType().getCanonicalType();
  11396. const auto *Ty = Type.getTypePtrOrNull();
  11397. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  11398. !Ty->isPointerType())) {
  11399. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  11400. if (D) {
  11401. bool IsDecl =
  11402. !VD ||
  11403. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11404. Diag(D->getLocation(),
  11405. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11406. << D;
  11407. }
  11408. return true;
  11409. }
  11410. return false;
  11411. }
  11412. OMPClause *Sema::ActOnOpenMPLinearClause(
  11413. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  11414. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  11415. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  11416. SmallVector<Expr *, 8> Vars;
  11417. SmallVector<Expr *, 8> Privates;
  11418. SmallVector<Expr *, 8> Inits;
  11419. SmallVector<Decl *, 4> ExprCaptures;
  11420. SmallVector<Expr *, 4> ExprPostUpdates;
  11421. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  11422. LinKind = OMPC_LINEAR_val;
  11423. for (Expr *RefExpr : VarList) {
  11424. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  11425. SourceLocation ELoc;
  11426. SourceRange ERange;
  11427. Expr *SimpleRefExpr = RefExpr;
  11428. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11429. if (Res.second) {
  11430. // It will be analyzed later.
  11431. Vars.push_back(RefExpr);
  11432. Privates.push_back(nullptr);
  11433. Inits.push_back(nullptr);
  11434. }
  11435. ValueDecl *D = Res.first;
  11436. if (!D)
  11437. continue;
  11438. QualType Type = D->getType();
  11439. auto *VD = dyn_cast<VarDecl>(D);
  11440. // OpenMP [2.14.3.7, linear clause]
  11441. // A list-item cannot appear in more than one linear clause.
  11442. // A list-item that appears in a linear clause cannot appear in any
  11443. // other data-sharing attribute clause.
  11444. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  11445. if (DVar.RefExpr) {
  11446. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  11447. << getOpenMPClauseName(OMPC_linear);
  11448. reportOriginalDsa(*this, DSAStack, D, DVar);
  11449. continue;
  11450. }
  11451. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  11452. continue;
  11453. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  11454. // Build private copy of original var.
  11455. VarDecl *Private =
  11456. buildVarDecl(*this, ELoc, Type, D->getName(),
  11457. D->hasAttrs() ? &D->getAttrs() : nullptr,
  11458. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  11459. DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  11460. // Build var to save initial value.
  11461. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  11462. Expr *InitExpr;
  11463. DeclRefExpr *Ref = nullptr;
  11464. if (!VD && !CurContext->isDependentContext()) {
  11465. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  11466. if (!isOpenMPCapturedDecl(D)) {
  11467. ExprCaptures.push_back(Ref->getDecl());
  11468. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  11469. ExprResult RefRes = DefaultLvalueConversion(Ref);
  11470. if (!RefRes.isUsable())
  11471. continue;
  11472. ExprResult PostUpdateRes =
  11473. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  11474. SimpleRefExpr, RefRes.get());
  11475. if (!PostUpdateRes.isUsable())
  11476. continue;
  11477. ExprPostUpdates.push_back(
  11478. IgnoredValueConversions(PostUpdateRes.get()).get());
  11479. }
  11480. }
  11481. }
  11482. if (LinKind == OMPC_LINEAR_uval)
  11483. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  11484. else
  11485. InitExpr = VD ? SimpleRefExpr : Ref;
  11486. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  11487. /*DirectInit=*/false);
  11488. DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  11489. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  11490. Vars.push_back((VD || CurContext->isDependentContext())
  11491. ? RefExpr->IgnoreParens()
  11492. : Ref);
  11493. Privates.push_back(PrivateRef);
  11494. Inits.push_back(InitRef);
  11495. }
  11496. if (Vars.empty())
  11497. return nullptr;
  11498. Expr *StepExpr = Step;
  11499. Expr *CalcStepExpr = nullptr;
  11500. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  11501. !Step->isInstantiationDependent() &&
  11502. !Step->containsUnexpandedParameterPack()) {
  11503. SourceLocation StepLoc = Step->getBeginLoc();
  11504. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  11505. if (Val.isInvalid())
  11506. return nullptr;
  11507. StepExpr = Val.get();
  11508. // Build var to save the step value.
  11509. VarDecl *SaveVar =
  11510. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  11511. ExprResult SaveRef =
  11512. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  11513. ExprResult CalcStep =
  11514. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  11515. CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
  11516. // Warn about zero linear step (it would be probably better specified as
  11517. // making corresponding variables 'const').
  11518. llvm::APSInt Result;
  11519. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  11520. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  11521. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  11522. << (Vars.size() > 1);
  11523. if (!IsConstant && CalcStep.isUsable()) {
  11524. // Calculate the step beforehand instead of doing this on each iteration.
  11525. // (This is not used if the number of iterations may be kfold-ed).
  11526. CalcStepExpr = CalcStep.get();
  11527. }
  11528. }
  11529. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  11530. ColonLoc, EndLoc, Vars, Privates, Inits,
  11531. StepExpr, CalcStepExpr,
  11532. buildPreInits(Context, ExprCaptures),
  11533. buildPostUpdate(*this, ExprPostUpdates));
  11534. }
  11535. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  11536. Expr *NumIterations, Sema &SemaRef,
  11537. Scope *S, DSAStackTy *Stack) {
  11538. // Walk the vars and build update/final expressions for the CodeGen.
  11539. SmallVector<Expr *, 8> Updates;
  11540. SmallVector<Expr *, 8> Finals;
  11541. Expr *Step = Clause.getStep();
  11542. Expr *CalcStep = Clause.getCalcStep();
  11543. // OpenMP [2.14.3.7, linear clause]
  11544. // If linear-step is not specified it is assumed to be 1.
  11545. if (!Step)
  11546. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  11547. else if (CalcStep)
  11548. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  11549. bool HasErrors = false;
  11550. auto CurInit = Clause.inits().begin();
  11551. auto CurPrivate = Clause.privates().begin();
  11552. OpenMPLinearClauseKind LinKind = Clause.getModifier();
  11553. for (Expr *RefExpr : Clause.varlists()) {
  11554. SourceLocation ELoc;
  11555. SourceRange ERange;
  11556. Expr *SimpleRefExpr = RefExpr;
  11557. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
  11558. ValueDecl *D = Res.first;
  11559. if (Res.second || !D) {
  11560. Updates.push_back(nullptr);
  11561. Finals.push_back(nullptr);
  11562. HasErrors = true;
  11563. continue;
  11564. }
  11565. auto &&Info = Stack->isLoopControlVariable(D);
  11566. // OpenMP [2.15.11, distribute simd Construct]
  11567. // A list item may not appear in a linear clause, unless it is the loop
  11568. // iteration variable.
  11569. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  11570. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  11571. SemaRef.Diag(ELoc,
  11572. diag::err_omp_linear_distribute_var_non_loop_iteration);
  11573. Updates.push_back(nullptr);
  11574. Finals.push_back(nullptr);
  11575. HasErrors = true;
  11576. continue;
  11577. }
  11578. Expr *InitExpr = *CurInit;
  11579. // Build privatized reference to the current linear var.
  11580. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  11581. Expr *CapturedRef;
  11582. if (LinKind == OMPC_LINEAR_uval)
  11583. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  11584. else
  11585. CapturedRef =
  11586. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  11587. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  11588. /*RefersToCapture=*/true);
  11589. // Build update: Var = InitExpr + IV * Step
  11590. ExprResult Update;
  11591. if (!Info.first)
  11592. Update =
  11593. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
  11594. InitExpr, IV, Step, /* Subtract */ false);
  11595. else
  11596. Update = *CurPrivate;
  11597. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
  11598. /*DiscardedValue*/ false);
  11599. // Build final: Var = InitExpr + NumIterations * Step
  11600. ExprResult Final;
  11601. if (!Info.first)
  11602. Final =
  11603. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  11604. InitExpr, NumIterations, Step, /*Subtract=*/false);
  11605. else
  11606. Final = *CurPrivate;
  11607. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
  11608. /*DiscardedValue*/ false);
  11609. if (!Update.isUsable() || !Final.isUsable()) {
  11610. Updates.push_back(nullptr);
  11611. Finals.push_back(nullptr);
  11612. HasErrors = true;
  11613. } else {
  11614. Updates.push_back(Update.get());
  11615. Finals.push_back(Final.get());
  11616. }
  11617. ++CurInit;
  11618. ++CurPrivate;
  11619. }
  11620. Clause.setUpdates(Updates);
  11621. Clause.setFinals(Finals);
  11622. return HasErrors;
  11623. }
  11624. OMPClause *Sema::ActOnOpenMPAlignedClause(
  11625. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  11626. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  11627. SmallVector<Expr *, 8> Vars;
  11628. for (Expr *RefExpr : VarList) {
  11629. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  11630. SourceLocation ELoc;
  11631. SourceRange ERange;
  11632. Expr *SimpleRefExpr = RefExpr;
  11633. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11634. if (Res.second) {
  11635. // It will be analyzed later.
  11636. Vars.push_back(RefExpr);
  11637. }
  11638. ValueDecl *D = Res.first;
  11639. if (!D)
  11640. continue;
  11641. QualType QType = D->getType();
  11642. auto *VD = dyn_cast<VarDecl>(D);
  11643. // OpenMP [2.8.1, simd construct, Restrictions]
  11644. // The type of list items appearing in the aligned clause must be
  11645. // array, pointer, reference to array, or reference to pointer.
  11646. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  11647. const Type *Ty = QType.getTypePtrOrNull();
  11648. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  11649. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  11650. << QType << getLangOpts().CPlusPlus << ERange;
  11651. bool IsDecl =
  11652. !VD ||
  11653. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11654. Diag(D->getLocation(),
  11655. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11656. << D;
  11657. continue;
  11658. }
  11659. // OpenMP [2.8.1, simd construct, Restrictions]
  11660. // A list-item cannot appear in more than one aligned clause.
  11661. if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  11662. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  11663. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  11664. << getOpenMPClauseName(OMPC_aligned);
  11665. continue;
  11666. }
  11667. DeclRefExpr *Ref = nullptr;
  11668. if (!VD && isOpenMPCapturedDecl(D))
  11669. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11670. Vars.push_back(DefaultFunctionArrayConversion(
  11671. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  11672. .get());
  11673. }
  11674. // OpenMP [2.8.1, simd construct, Description]
  11675. // The parameter of the aligned clause, alignment, must be a constant
  11676. // positive integer expression.
  11677. // If no optional parameter is specified, implementation-defined default
  11678. // alignments for SIMD instructions on the target platforms are assumed.
  11679. if (Alignment != nullptr) {
  11680. ExprResult AlignResult =
  11681. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  11682. if (AlignResult.isInvalid())
  11683. return nullptr;
  11684. Alignment = AlignResult.get();
  11685. }
  11686. if (Vars.empty())
  11687. return nullptr;
  11688. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  11689. EndLoc, Vars, Alignment);
  11690. }
  11691. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  11692. SourceLocation StartLoc,
  11693. SourceLocation LParenLoc,
  11694. SourceLocation EndLoc) {
  11695. SmallVector<Expr *, 8> Vars;
  11696. SmallVector<Expr *, 8> SrcExprs;
  11697. SmallVector<Expr *, 8> DstExprs;
  11698. SmallVector<Expr *, 8> AssignmentOps;
  11699. for (Expr *RefExpr : VarList) {
  11700. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  11701. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  11702. // It will be analyzed later.
  11703. Vars.push_back(RefExpr);
  11704. SrcExprs.push_back(nullptr);
  11705. DstExprs.push_back(nullptr);
  11706. AssignmentOps.push_back(nullptr);
  11707. continue;
  11708. }
  11709. SourceLocation ELoc = RefExpr->getExprLoc();
  11710. // OpenMP [2.1, C/C++]
  11711. // A list item is a variable name.
  11712. // OpenMP [2.14.4.1, Restrictions, p.1]
  11713. // A list item that appears in a copyin clause must be threadprivate.
  11714. auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
  11715. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  11716. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  11717. << 0 << RefExpr->getSourceRange();
  11718. continue;
  11719. }
  11720. Decl *D = DE->getDecl();
  11721. auto *VD = cast<VarDecl>(D);
  11722. QualType Type = VD->getType();
  11723. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  11724. // It will be analyzed later.
  11725. Vars.push_back(DE);
  11726. SrcExprs.push_back(nullptr);
  11727. DstExprs.push_back(nullptr);
  11728. AssignmentOps.push_back(nullptr);
  11729. continue;
  11730. }
  11731. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  11732. // A list item that appears in a copyin clause must be threadprivate.
  11733. if (!DSAStack->isThreadPrivate(VD)) {
  11734. Diag(ELoc, diag::err_omp_required_access)
  11735. << getOpenMPClauseName(OMPC_copyin)
  11736. << getOpenMPDirectiveName(OMPD_threadprivate);
  11737. continue;
  11738. }
  11739. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  11740. // A variable of class type (or array thereof) that appears in a
  11741. // copyin clause requires an accessible, unambiguous copy assignment
  11742. // operator for the class type.
  11743. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  11744. VarDecl *SrcVD =
  11745. buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
  11746. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  11747. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
  11748. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  11749. VarDecl *DstVD =
  11750. buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
  11751. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  11752. DeclRefExpr *PseudoDstExpr =
  11753. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  11754. // For arrays generate assignment operation for single element and replace
  11755. // it by the original array element in CodeGen.
  11756. ExprResult AssignmentOp =
  11757. BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
  11758. PseudoSrcExpr);
  11759. if (AssignmentOp.isInvalid())
  11760. continue;
  11761. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  11762. /*DiscardedValue*/ false);
  11763. if (AssignmentOp.isInvalid())
  11764. continue;
  11765. DSAStack->addDSA(VD, DE, OMPC_copyin);
  11766. Vars.push_back(DE);
  11767. SrcExprs.push_back(PseudoSrcExpr);
  11768. DstExprs.push_back(PseudoDstExpr);
  11769. AssignmentOps.push_back(AssignmentOp.get());
  11770. }
  11771. if (Vars.empty())
  11772. return nullptr;
  11773. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  11774. SrcExprs, DstExprs, AssignmentOps);
  11775. }
  11776. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  11777. SourceLocation StartLoc,
  11778. SourceLocation LParenLoc,
  11779. SourceLocation EndLoc) {
  11780. SmallVector<Expr *, 8> Vars;
  11781. SmallVector<Expr *, 8> SrcExprs;
  11782. SmallVector<Expr *, 8> DstExprs;
  11783. SmallVector<Expr *, 8> AssignmentOps;
  11784. for (Expr *RefExpr : VarList) {
  11785. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  11786. SourceLocation ELoc;
  11787. SourceRange ERange;
  11788. Expr *SimpleRefExpr = RefExpr;
  11789. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11790. if (Res.second) {
  11791. // It will be analyzed later.
  11792. Vars.push_back(RefExpr);
  11793. SrcExprs.push_back(nullptr);
  11794. DstExprs.push_back(nullptr);
  11795. AssignmentOps.push_back(nullptr);
  11796. }
  11797. ValueDecl *D = Res.first;
  11798. if (!D)
  11799. continue;
  11800. QualType Type = D->getType();
  11801. auto *VD = dyn_cast<VarDecl>(D);
  11802. // OpenMP [2.14.4.2, Restrictions, p.2]
  11803. // A list item that appears in a copyprivate clause may not appear in a
  11804. // private or firstprivate clause on the single construct.
  11805. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  11806. DSAStackTy::DSAVarData DVar =
  11807. DSAStack->getTopDSA(D, /*FromParent=*/false);
  11808. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  11809. DVar.RefExpr) {
  11810. Diag(ELoc, diag::err_omp_wrong_dsa)
  11811. << getOpenMPClauseName(DVar.CKind)
  11812. << getOpenMPClauseName(OMPC_copyprivate);
  11813. reportOriginalDsa(*this, DSAStack, D, DVar);
  11814. continue;
  11815. }
  11816. // OpenMP [2.11.4.2, Restrictions, p.1]
  11817. // All list items that appear in a copyprivate clause must be either
  11818. // threadprivate or private in the enclosing context.
  11819. if (DVar.CKind == OMPC_unknown) {
  11820. DVar = DSAStack->getImplicitDSA(D, false);
  11821. if (DVar.CKind == OMPC_shared) {
  11822. Diag(ELoc, diag::err_omp_required_access)
  11823. << getOpenMPClauseName(OMPC_copyprivate)
  11824. << "threadprivate or private in the enclosing context";
  11825. reportOriginalDsa(*this, DSAStack, D, DVar);
  11826. continue;
  11827. }
  11828. }
  11829. }
  11830. // Variably modified types are not supported.
  11831. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  11832. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  11833. << getOpenMPClauseName(OMPC_copyprivate) << Type
  11834. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11835. bool IsDecl =
  11836. !VD ||
  11837. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11838. Diag(D->getLocation(),
  11839. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11840. << D;
  11841. continue;
  11842. }
  11843. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  11844. // A variable of class type (or array thereof) that appears in a
  11845. // copyin clause requires an accessible, unambiguous copy assignment
  11846. // operator for the class type.
  11847. Type = Context.getBaseElementType(Type.getNonReferenceType())
  11848. .getUnqualifiedType();
  11849. VarDecl *SrcVD =
  11850. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
  11851. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11852. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  11853. VarDecl *DstVD =
  11854. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
  11855. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11856. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  11857. ExprResult AssignmentOp = BuildBinOp(
  11858. DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
  11859. if (AssignmentOp.isInvalid())
  11860. continue;
  11861. AssignmentOp =
  11862. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  11863. if (AssignmentOp.isInvalid())
  11864. continue;
  11865. // No need to mark vars as copyprivate, they are already threadprivate or
  11866. // implicitly private.
  11867. assert(VD || isOpenMPCapturedDecl(D));
  11868. Vars.push_back(
  11869. VD ? RefExpr->IgnoreParens()
  11870. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  11871. SrcExprs.push_back(PseudoSrcExpr);
  11872. DstExprs.push_back(PseudoDstExpr);
  11873. AssignmentOps.push_back(AssignmentOp.get());
  11874. }
  11875. if (Vars.empty())
  11876. return nullptr;
  11877. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11878. Vars, SrcExprs, DstExprs, AssignmentOps);
  11879. }
  11880. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  11881. SourceLocation StartLoc,
  11882. SourceLocation LParenLoc,
  11883. SourceLocation EndLoc) {
  11884. if (VarList.empty())
  11885. return nullptr;
  11886. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  11887. }
  11888. OMPClause *
  11889. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  11890. SourceLocation DepLoc, SourceLocation ColonLoc,
  11891. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  11892. SourceLocation LParenLoc, SourceLocation EndLoc) {
  11893. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  11894. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  11895. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  11896. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  11897. return nullptr;
  11898. }
  11899. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  11900. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  11901. DepKind == OMPC_DEPEND_sink)) {
  11902. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  11903. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  11904. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  11905. /*Last=*/OMPC_DEPEND_unknown, Except)
  11906. << getOpenMPClauseName(OMPC_depend);
  11907. return nullptr;
  11908. }
  11909. SmallVector<Expr *, 8> Vars;
  11910. DSAStackTy::OperatorOffsetTy OpsOffs;
  11911. llvm::APSInt DepCounter(/*BitWidth=*/32);
  11912. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  11913. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
  11914. if (const Expr *OrderedCountExpr =
  11915. DSAStack->getParentOrderedRegionParam().first) {
  11916. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  11917. TotalDepCount.setIsUnsigned(/*Val=*/true);
  11918. }
  11919. }
  11920. for (Expr *RefExpr : VarList) {
  11921. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  11922. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  11923. // It will be analyzed later.
  11924. Vars.push_back(RefExpr);
  11925. continue;
  11926. }
  11927. SourceLocation ELoc = RefExpr->getExprLoc();
  11928. Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
  11929. if (DepKind == OMPC_DEPEND_sink) {
  11930. if (DSAStack->getParentOrderedRegionParam().first &&
  11931. DepCounter >= TotalDepCount) {
  11932. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  11933. continue;
  11934. }
  11935. ++DepCounter;
  11936. // OpenMP [2.13.9, Summary]
  11937. // depend(dependence-type : vec), where dependence-type is:
  11938. // 'sink' and where vec is the iteration vector, which has the form:
  11939. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  11940. // where n is the value specified by the ordered clause in the loop
  11941. // directive, xi denotes the loop iteration variable of the i-th nested
  11942. // loop associated with the loop directive, and di is a constant
  11943. // non-negative integer.
  11944. if (CurContext->isDependentContext()) {
  11945. // It will be analyzed later.
  11946. Vars.push_back(RefExpr);
  11947. continue;
  11948. }
  11949. SimpleExpr = SimpleExpr->IgnoreImplicit();
  11950. OverloadedOperatorKind OOK = OO_None;
  11951. SourceLocation OOLoc;
  11952. Expr *LHS = SimpleExpr;
  11953. Expr *RHS = nullptr;
  11954. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  11955. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  11956. OOLoc = BO->getOperatorLoc();
  11957. LHS = BO->getLHS()->IgnoreParenImpCasts();
  11958. RHS = BO->getRHS()->IgnoreParenImpCasts();
  11959. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  11960. OOK = OCE->getOperator();
  11961. OOLoc = OCE->getOperatorLoc();
  11962. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  11963. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  11964. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  11965. OOK = MCE->getMethodDecl()
  11966. ->getNameInfo()
  11967. .getName()
  11968. .getCXXOverloadedOperator();
  11969. OOLoc = MCE->getCallee()->getExprLoc();
  11970. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  11971. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  11972. }
  11973. SourceLocation ELoc;
  11974. SourceRange ERange;
  11975. auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
  11976. if (Res.second) {
  11977. // It will be analyzed later.
  11978. Vars.push_back(RefExpr);
  11979. }
  11980. ValueDecl *D = Res.first;
  11981. if (!D)
  11982. continue;
  11983. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  11984. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  11985. continue;
  11986. }
  11987. if (RHS) {
  11988. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  11989. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  11990. if (RHSRes.isInvalid())
  11991. continue;
  11992. }
  11993. if (!CurContext->isDependentContext() &&
  11994. DSAStack->getParentOrderedRegionParam().first &&
  11995. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  11996. const ValueDecl *VD =
  11997. DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
  11998. if (VD)
  11999. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  12000. << 1 << VD;
  12001. else
  12002. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  12003. continue;
  12004. }
  12005. OpsOffs.emplace_back(RHS, OOK);
  12006. } else {
  12007. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  12008. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  12009. (ASE &&
  12010. !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
  12011. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  12012. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  12013. << RefExpr->getSourceRange();
  12014. continue;
  12015. }
  12016. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  12017. getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  12018. ExprResult Res =
  12019. CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
  12020. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  12021. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  12022. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  12023. << RefExpr->getSourceRange();
  12024. continue;
  12025. }
  12026. }
  12027. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  12028. }
  12029. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  12030. TotalDepCount > VarList.size() &&
  12031. DSAStack->getParentOrderedRegionParam().first &&
  12032. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  12033. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
  12034. << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  12035. }
  12036. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  12037. Vars.empty())
  12038. return nullptr;
  12039. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  12040. DepKind, DepLoc, ColonLoc, Vars,
  12041. TotalDepCount.getZExtValue());
  12042. if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
  12043. DSAStack->isParentOrderedRegion())
  12044. DSAStack->addDoacrossDependClause(C, OpsOffs);
  12045. return C;
  12046. }
  12047. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  12048. SourceLocation LParenLoc,
  12049. SourceLocation EndLoc) {
  12050. Expr *ValExpr = Device;
  12051. Stmt *HelperValStmt = nullptr;
  12052. // OpenMP [2.9.1, Restrictions]
  12053. // The device expression must evaluate to a non-negative integer value.
  12054. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  12055. /*StrictlyPositive=*/false))
  12056. return nullptr;
  12057. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  12058. OpenMPDirectiveKind CaptureRegion =
  12059. getOpenMPCaptureRegionForClause(DKind, OMPC_device);
  12060. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  12061. ValExpr = MakeFullExpr(ValExpr).get();
  12062. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  12063. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  12064. HelperValStmt = buildPreInits(Context, Captures);
  12065. }
  12066. return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
  12067. StartLoc, LParenLoc, EndLoc);
  12068. }
  12069. static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  12070. DSAStackTy *Stack, QualType QTy,
  12071. bool FullCheck = true) {
  12072. NamedDecl *ND;
  12073. if (QTy->isIncompleteType(&ND)) {
  12074. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  12075. return false;
  12076. }
  12077. if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
  12078. !QTy.isTrivialType(SemaRef.Context))
  12079. SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
  12080. return true;
  12081. }
  12082. /// Return true if it can be proven that the provided array expression
  12083. /// (array section or array subscript) does NOT specify the whole size of the
  12084. /// array whose base type is \a BaseQTy.
  12085. static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  12086. const Expr *E,
  12087. QualType BaseQTy) {
  12088. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  12089. // If this is an array subscript, it refers to the whole size if the size of
  12090. // the dimension is constant and equals 1. Also, an array section assumes the
  12091. // format of an array subscript if no colon is used.
  12092. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  12093. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  12094. return ATy->getSize().getSExtValue() != 1;
  12095. // Size can't be evaluated statically.
  12096. return false;
  12097. }
  12098. assert(OASE && "Expecting array section if not an array subscript.");
  12099. const Expr *LowerBound = OASE->getLowerBound();
  12100. const Expr *Length = OASE->getLength();
  12101. // If there is a lower bound that does not evaluates to zero, we are not
  12102. // covering the whole dimension.
  12103. if (LowerBound) {
  12104. Expr::EvalResult Result;
  12105. if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
  12106. return false; // Can't get the integer value as a constant.
  12107. llvm::APSInt ConstLowerBound = Result.Val.getInt();
  12108. if (ConstLowerBound.getSExtValue())
  12109. return true;
  12110. }
  12111. // If we don't have a length we covering the whole dimension.
  12112. if (!Length)
  12113. return false;
  12114. // If the base is a pointer, we don't have a way to get the size of the
  12115. // pointee.
  12116. if (BaseQTy->isPointerType())
  12117. return false;
  12118. // We can only check if the length is the same as the size of the dimension
  12119. // if we have a constant array.
  12120. const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  12121. if (!CATy)
  12122. return false;
  12123. Expr::EvalResult Result;
  12124. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  12125. return false; // Can't get the integer value as a constant.
  12126. llvm::APSInt ConstLength = Result.Val.getInt();
  12127. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  12128. }
  12129. // Return true if it can be proven that the provided array expression (array
  12130. // section or array subscript) does NOT specify a single element of the array
  12131. // whose base type is \a BaseQTy.
  12132. static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  12133. const Expr *E,
  12134. QualType BaseQTy) {
  12135. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  12136. // An array subscript always refer to a single element. Also, an array section
  12137. // assumes the format of an array subscript if no colon is used.
  12138. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  12139. return false;
  12140. assert(OASE && "Expecting array section if not an array subscript.");
  12141. const Expr *Length = OASE->getLength();
  12142. // If we don't have a length we have to check if the array has unitary size
  12143. // for this dimension. Also, we should always expect a length if the base type
  12144. // is pointer.
  12145. if (!Length) {
  12146. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  12147. return ATy->getSize().getSExtValue() != 1;
  12148. // We cannot assume anything.
  12149. return false;
  12150. }
  12151. // Check if the length evaluates to 1.
  12152. Expr::EvalResult Result;
  12153. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  12154. return false; // Can't get the integer value as a constant.
  12155. llvm::APSInt ConstLength = Result.Val.getInt();
  12156. return ConstLength.getSExtValue() != 1;
  12157. }
  12158. // Return the expression of the base of the mappable expression or null if it
  12159. // cannot be determined and do all the necessary checks to see if the expression
  12160. // is valid as a standalone mappable expression. In the process, record all the
  12161. // components of the expression.
  12162. static const Expr *checkMapClauseExpressionBase(
  12163. Sema &SemaRef, Expr *E,
  12164. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  12165. OpenMPClauseKind CKind, bool NoDiagnose) {
  12166. SourceLocation ELoc = E->getExprLoc();
  12167. SourceRange ERange = E->getSourceRange();
  12168. // The base of elements of list in a map clause have to be either:
  12169. // - a reference to variable or field.
  12170. // - a member expression.
  12171. // - an array expression.
  12172. //
  12173. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  12174. // reference to 'r'.
  12175. //
  12176. // If we have:
  12177. //
  12178. // struct SS {
  12179. // Bla S;
  12180. // foo() {
  12181. // #pragma omp target map (S.Arr[:12]);
  12182. // }
  12183. // }
  12184. //
  12185. // We want to retrieve the member expression 'this->S';
  12186. const Expr *RelevantExpr = nullptr;
  12187. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  12188. // If a list item is an array section, it must specify contiguous storage.
  12189. //
  12190. // For this restriction it is sufficient that we make sure only references
  12191. // to variables or fields and array expressions, and that no array sections
  12192. // exist except in the rightmost expression (unless they cover the whole
  12193. // dimension of the array). E.g. these would be invalid:
  12194. //
  12195. // r.ArrS[3:5].Arr[6:7]
  12196. //
  12197. // r.ArrS[3:5].x
  12198. //
  12199. // but these would be valid:
  12200. // r.ArrS[3].Arr[6:7]
  12201. //
  12202. // r.ArrS[3].x
  12203. bool AllowUnitySizeArraySection = true;
  12204. bool AllowWholeSizeArraySection = true;
  12205. while (!RelevantExpr) {
  12206. E = E->IgnoreParenImpCasts();
  12207. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  12208. if (!isa<VarDecl>(CurE->getDecl()))
  12209. return nullptr;
  12210. RelevantExpr = CurE;
  12211. // If we got a reference to a declaration, we should not expect any array
  12212. // section before that.
  12213. AllowUnitySizeArraySection = false;
  12214. AllowWholeSizeArraySection = false;
  12215. // Record the component.
  12216. CurComponents.emplace_back(CurE, CurE->getDecl());
  12217. } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  12218. Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  12219. if (isa<CXXThisExpr>(BaseE))
  12220. // We found a base expression: this->Val.
  12221. RelevantExpr = CurE;
  12222. else
  12223. E = BaseE;
  12224. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  12225. if (!NoDiagnose) {
  12226. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  12227. << CurE->getSourceRange();
  12228. return nullptr;
  12229. }
  12230. if (RelevantExpr)
  12231. return nullptr;
  12232. continue;
  12233. }
  12234. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  12235. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  12236. // A bit-field cannot appear in a map clause.
  12237. //
  12238. if (FD->isBitField()) {
  12239. if (!NoDiagnose) {
  12240. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  12241. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  12242. return nullptr;
  12243. }
  12244. if (RelevantExpr)
  12245. return nullptr;
  12246. continue;
  12247. }
  12248. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  12249. // If the type of a list item is a reference to a type T then the type
  12250. // will be considered to be T for all purposes of this clause.
  12251. QualType CurType = BaseE->getType().getNonReferenceType();
  12252. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  12253. // A list item cannot be a variable that is a member of a structure with
  12254. // a union type.
  12255. //
  12256. if (CurType->isUnionType()) {
  12257. if (!NoDiagnose) {
  12258. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  12259. << CurE->getSourceRange();
  12260. return nullptr;
  12261. }
  12262. continue;
  12263. }
  12264. // If we got a member expression, we should not expect any array section
  12265. // before that:
  12266. //
  12267. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  12268. // If a list item is an element of a structure, only the rightmost symbol
  12269. // of the variable reference can be an array section.
  12270. //
  12271. AllowUnitySizeArraySection = false;
  12272. AllowWholeSizeArraySection = false;
  12273. // Record the component.
  12274. CurComponents.emplace_back(CurE, FD);
  12275. } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  12276. E = CurE->getBase()->IgnoreParenImpCasts();
  12277. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  12278. if (!NoDiagnose) {
  12279. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  12280. << 0 << CurE->getSourceRange();
  12281. return nullptr;
  12282. }
  12283. continue;
  12284. }
  12285. // If we got an array subscript that express the whole dimension we
  12286. // can have any array expressions before. If it only expressing part of
  12287. // the dimension, we can only have unitary-size array expressions.
  12288. if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  12289. E->getType()))
  12290. AllowWholeSizeArraySection = false;
  12291. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  12292. Expr::EvalResult Result;
  12293. if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  12294. if (!Result.Val.getInt().isNullValue()) {
  12295. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  12296. diag::err_omp_invalid_map_this_expr);
  12297. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  12298. diag::note_omp_invalid_subscript_on_this_ptr_map);
  12299. }
  12300. }
  12301. RelevantExpr = TE;
  12302. }
  12303. // Record the component - we don't have any declaration associated.
  12304. CurComponents.emplace_back(CurE, nullptr);
  12305. } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  12306. assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
  12307. E = CurE->getBase()->IgnoreParenImpCasts();
  12308. QualType CurType =
  12309. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  12310. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  12311. // If the type of a list item is a reference to a type T then the type
  12312. // will be considered to be T for all purposes of this clause.
  12313. if (CurType->isReferenceType())
  12314. CurType = CurType->getPointeeType();
  12315. bool IsPointer = CurType->isAnyPointerType();
  12316. if (!IsPointer && !CurType->isArrayType()) {
  12317. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  12318. << 0 << CurE->getSourceRange();
  12319. return nullptr;
  12320. }
  12321. bool NotWhole =
  12322. checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  12323. bool NotUnity =
  12324. checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  12325. if (AllowWholeSizeArraySection) {
  12326. // Any array section is currently allowed. Allowing a whole size array
  12327. // section implies allowing a unity array section as well.
  12328. //
  12329. // If this array section refers to the whole dimension we can still
  12330. // accept other array sections before this one, except if the base is a
  12331. // pointer. Otherwise, only unitary sections are accepted.
  12332. if (NotWhole || IsPointer)
  12333. AllowWholeSizeArraySection = false;
  12334. } else if (AllowUnitySizeArraySection && NotUnity) {
  12335. // A unity or whole array section is not allowed and that is not
  12336. // compatible with the properties of the current array section.
  12337. SemaRef.Diag(
  12338. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  12339. << CurE->getSourceRange();
  12340. return nullptr;
  12341. }
  12342. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  12343. Expr::EvalResult ResultR;
  12344. Expr::EvalResult ResultL;
  12345. if (CurE->getLength()->EvaluateAsInt(ResultR,
  12346. SemaRef.getASTContext())) {
  12347. if (!ResultR.Val.getInt().isOneValue()) {
  12348. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  12349. diag::err_omp_invalid_map_this_expr);
  12350. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  12351. diag::note_omp_invalid_length_on_this_ptr_mapping);
  12352. }
  12353. }
  12354. if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
  12355. ResultL, SemaRef.getASTContext())) {
  12356. if (!ResultL.Val.getInt().isNullValue()) {
  12357. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  12358. diag::err_omp_invalid_map_this_expr);
  12359. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  12360. diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
  12361. }
  12362. }
  12363. RelevantExpr = TE;
  12364. }
  12365. // Record the component - we don't have any declaration associated.
  12366. CurComponents.emplace_back(CurE, nullptr);
  12367. } else {
  12368. if (!NoDiagnose) {
  12369. // If nothing else worked, this is not a valid map clause expression.
  12370. SemaRef.Diag(
  12371. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  12372. << ERange;
  12373. }
  12374. return nullptr;
  12375. }
  12376. }
  12377. return RelevantExpr;
  12378. }
  12379. // Return true if expression E associated with value VD has conflicts with other
  12380. // map information.
  12381. static bool checkMapConflicts(
  12382. Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
  12383. bool CurrentRegionOnly,
  12384. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  12385. OpenMPClauseKind CKind) {
  12386. assert(VD && E);
  12387. SourceLocation ELoc = E->getExprLoc();
  12388. SourceRange ERange = E->getSourceRange();
  12389. // In order to easily check the conflicts we need to match each component of
  12390. // the expression under test with the components of the expressions that are
  12391. // already in the stack.
  12392. assert(!CurComponents.empty() && "Map clause expression with no components!");
  12393. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  12394. "Map clause expression with unexpected base!");
  12395. // Variables to help detecting enclosing problems in data environment nests.
  12396. bool IsEnclosedByDataEnvironmentExpr = false;
  12397. const Expr *EnclosingExpr = nullptr;
  12398. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  12399. VD, CurrentRegionOnly,
  12400. [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
  12401. ERange, CKind, &EnclosingExpr,
  12402. CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
  12403. StackComponents,
  12404. OpenMPClauseKind) {
  12405. assert(!StackComponents.empty() &&
  12406. "Map clause expression with no components!");
  12407. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  12408. "Map clause expression with unexpected base!");
  12409. (void)VD;
  12410. // The whole expression in the stack.
  12411. const Expr *RE = StackComponents.front().getAssociatedExpression();
  12412. // Expressions must start from the same base. Here we detect at which
  12413. // point both expressions diverge from each other and see if we can
  12414. // detect if the memory referred to both expressions is contiguous and
  12415. // do not overlap.
  12416. auto CI = CurComponents.rbegin();
  12417. auto CE = CurComponents.rend();
  12418. auto SI = StackComponents.rbegin();
  12419. auto SE = StackComponents.rend();
  12420. for (; CI != CE && SI != SE; ++CI, ++SI) {
  12421. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  12422. // At most one list item can be an array item derived from a given
  12423. // variable in map clauses of the same construct.
  12424. if (CurrentRegionOnly &&
  12425. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  12426. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  12427. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  12428. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  12429. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  12430. diag::err_omp_multiple_array_items_in_map_clause)
  12431. << CI->getAssociatedExpression()->getSourceRange();
  12432. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  12433. diag::note_used_here)
  12434. << SI->getAssociatedExpression()->getSourceRange();
  12435. return true;
  12436. }
  12437. // Do both expressions have the same kind?
  12438. if (CI->getAssociatedExpression()->getStmtClass() !=
  12439. SI->getAssociatedExpression()->getStmtClass())
  12440. break;
  12441. // Are we dealing with different variables/fields?
  12442. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  12443. break;
  12444. }
  12445. // Check if the extra components of the expressions in the enclosing
  12446. // data environment are redundant for the current base declaration.
  12447. // If they are, the maps completely overlap, which is legal.
  12448. for (; SI != SE; ++SI) {
  12449. QualType Type;
  12450. if (const auto *ASE =
  12451. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  12452. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  12453. } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
  12454. SI->getAssociatedExpression())) {
  12455. const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
  12456. Type =
  12457. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  12458. }
  12459. if (Type.isNull() || Type->isAnyPointerType() ||
  12460. checkArrayExpressionDoesNotReferToWholeSize(
  12461. SemaRef, SI->getAssociatedExpression(), Type))
  12462. break;
  12463. }
  12464. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  12465. // List items of map clauses in the same construct must not share
  12466. // original storage.
  12467. //
  12468. // If the expressions are exactly the same or one is a subset of the
  12469. // other, it means they are sharing storage.
  12470. if (CI == CE && SI == SE) {
  12471. if (CurrentRegionOnly) {
  12472. if (CKind == OMPC_map) {
  12473. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  12474. } else {
  12475. assert(CKind == OMPC_to || CKind == OMPC_from);
  12476. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  12477. << ERange;
  12478. }
  12479. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  12480. << RE->getSourceRange();
  12481. return true;
  12482. }
  12483. // If we find the same expression in the enclosing data environment,
  12484. // that is legal.
  12485. IsEnclosedByDataEnvironmentExpr = true;
  12486. return false;
  12487. }
  12488. QualType DerivedType =
  12489. std::prev(CI)->getAssociatedDeclaration()->getType();
  12490. SourceLocation DerivedLoc =
  12491. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  12492. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  12493. // If the type of a list item is a reference to a type T then the type
  12494. // will be considered to be T for all purposes of this clause.
  12495. DerivedType = DerivedType.getNonReferenceType();
  12496. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  12497. // A variable for which the type is pointer and an array section
  12498. // derived from that variable must not appear as list items of map
  12499. // clauses of the same construct.
  12500. //
  12501. // Also, cover one of the cases in:
  12502. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  12503. // If any part of the original storage of a list item has corresponding
  12504. // storage in the device data environment, all of the original storage
  12505. // must have corresponding storage in the device data environment.
  12506. //
  12507. if (DerivedType->isAnyPointerType()) {
  12508. if (CI == CE || SI == SE) {
  12509. SemaRef.Diag(
  12510. DerivedLoc,
  12511. diag::err_omp_pointer_mapped_along_with_derived_section)
  12512. << DerivedLoc;
  12513. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  12514. << RE->getSourceRange();
  12515. return true;
  12516. }
  12517. if (CI->getAssociatedExpression()->getStmtClass() !=
  12518. SI->getAssociatedExpression()->getStmtClass() ||
  12519. CI->getAssociatedDeclaration()->getCanonicalDecl() ==
  12520. SI->getAssociatedDeclaration()->getCanonicalDecl()) {
  12521. assert(CI != CE && SI != SE);
  12522. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
  12523. << DerivedLoc;
  12524. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  12525. << RE->getSourceRange();
  12526. return true;
  12527. }
  12528. }
  12529. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  12530. // List items of map clauses in the same construct must not share
  12531. // original storage.
  12532. //
  12533. // An expression is a subset of the other.
  12534. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  12535. if (CKind == OMPC_map) {
  12536. if (CI != CE || SI != SE) {
  12537. // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
  12538. // a pointer.
  12539. auto Begin =
  12540. CI != CE ? CurComponents.begin() : StackComponents.begin();
  12541. auto End = CI != CE ? CurComponents.end() : StackComponents.end();
  12542. auto It = Begin;
  12543. while (It != End && !It->getAssociatedDeclaration())
  12544. std::advance(It, 1);
  12545. assert(It != End &&
  12546. "Expected at least one component with the declaration.");
  12547. if (It != Begin && It->getAssociatedDeclaration()
  12548. ->getType()
  12549. .getCanonicalType()
  12550. ->isAnyPointerType()) {
  12551. IsEnclosedByDataEnvironmentExpr = false;
  12552. EnclosingExpr = nullptr;
  12553. return false;
  12554. }
  12555. }
  12556. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  12557. } else {
  12558. assert(CKind == OMPC_to || CKind == OMPC_from);
  12559. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  12560. << ERange;
  12561. }
  12562. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  12563. << RE->getSourceRange();
  12564. return true;
  12565. }
  12566. // The current expression uses the same base as other expression in the
  12567. // data environment but does not contain it completely.
  12568. if (!CurrentRegionOnly && SI != SE)
  12569. EnclosingExpr = RE;
  12570. // The current expression is a subset of the expression in the data
  12571. // environment.
  12572. IsEnclosedByDataEnvironmentExpr |=
  12573. (!CurrentRegionOnly && CI != CE && SI == SE);
  12574. return false;
  12575. });
  12576. if (CurrentRegionOnly)
  12577. return FoundError;
  12578. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  12579. // If any part of the original storage of a list item has corresponding
  12580. // storage in the device data environment, all of the original storage must
  12581. // have corresponding storage in the device data environment.
  12582. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  12583. // If a list item is an element of a structure, and a different element of
  12584. // the structure has a corresponding list item in the device data environment
  12585. // prior to a task encountering the construct associated with the map clause,
  12586. // then the list item must also have a corresponding list item in the device
  12587. // data environment prior to the task encountering the construct.
  12588. //
  12589. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  12590. SemaRef.Diag(ELoc,
  12591. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  12592. << ERange;
  12593. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  12594. << EnclosingExpr->getSourceRange();
  12595. return true;
  12596. }
  12597. return FoundError;
  12598. }
  12599. // Look up the user-defined mapper given the mapper name and mapped type, and
  12600. // build a reference to it.
  12601. static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
  12602. CXXScopeSpec &MapperIdScopeSpec,
  12603. const DeclarationNameInfo &MapperId,
  12604. QualType Type,
  12605. Expr *UnresolvedMapper) {
  12606. if (MapperIdScopeSpec.isInvalid())
  12607. return ExprError();
  12608. // Find all user-defined mappers with the given MapperId.
  12609. SmallVector<UnresolvedSet<8>, 4> Lookups;
  12610. LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
  12611. Lookup.suppressDiagnostics();
  12612. if (S) {
  12613. while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
  12614. NamedDecl *D = Lookup.getRepresentativeDecl();
  12615. while (S && !S->isDeclScope(D))
  12616. S = S->getParent();
  12617. if (S)
  12618. S = S->getParent();
  12619. Lookups.emplace_back();
  12620. Lookups.back().append(Lookup.begin(), Lookup.end());
  12621. Lookup.clear();
  12622. }
  12623. } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
  12624. // Extract the user-defined mappers with the given MapperId.
  12625. Lookups.push_back(UnresolvedSet<8>());
  12626. for (NamedDecl *D : ULE->decls()) {
  12627. auto *DMD = cast<OMPDeclareMapperDecl>(D);
  12628. assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
  12629. Lookups.back().addDecl(DMD);
  12630. }
  12631. }
  12632. // Defer the lookup for dependent types. The results will be passed through
  12633. // UnresolvedMapper on instantiation.
  12634. if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
  12635. Type->isInstantiationDependentType() ||
  12636. Type->containsUnexpandedParameterPack() ||
  12637. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  12638. return !D->isInvalidDecl() &&
  12639. (D->getType()->isDependentType() ||
  12640. D->getType()->isInstantiationDependentType() ||
  12641. D->getType()->containsUnexpandedParameterPack());
  12642. })) {
  12643. UnresolvedSet<8> URS;
  12644. for (const UnresolvedSet<8> &Set : Lookups) {
  12645. if (Set.empty())
  12646. continue;
  12647. URS.append(Set.begin(), Set.end());
  12648. }
  12649. return UnresolvedLookupExpr::Create(
  12650. SemaRef.Context, /*NamingClass=*/nullptr,
  12651. MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
  12652. /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
  12653. }
  12654. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  12655. // The type must be of struct, union or class type in C and C++
  12656. if (!Type->isStructureOrClassType() && !Type->isUnionType())
  12657. return ExprEmpty();
  12658. SourceLocation Loc = MapperId.getLoc();
  12659. // Perform argument dependent lookup.
  12660. if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
  12661. argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
  12662. // Return the first user-defined mapper with the desired type.
  12663. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  12664. Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
  12665. if (!D->isInvalidDecl() &&
  12666. SemaRef.Context.hasSameType(D->getType(), Type))
  12667. return D;
  12668. return nullptr;
  12669. }))
  12670. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  12671. // Find the first user-defined mapper with a type derived from the desired
  12672. // type.
  12673. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  12674. Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
  12675. if (!D->isInvalidDecl() &&
  12676. SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
  12677. !Type.isMoreQualifiedThan(D->getType()))
  12678. return D;
  12679. return nullptr;
  12680. })) {
  12681. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  12682. /*DetectVirtual=*/false);
  12683. if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
  12684. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  12685. VD->getType().getUnqualifiedType()))) {
  12686. if (SemaRef.CheckBaseClassAccess(
  12687. Loc, VD->getType(), Type, Paths.front(),
  12688. /*DiagID=*/0) != Sema::AR_inaccessible) {
  12689. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  12690. }
  12691. }
  12692. }
  12693. }
  12694. // Report error if a mapper is specified, but cannot be found.
  12695. if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
  12696. SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
  12697. << Type << MapperId.getName();
  12698. return ExprError();
  12699. }
  12700. return ExprEmpty();
  12701. }
  12702. namespace {
  12703. // Utility struct that gathers all the related lists associated with a mappable
  12704. // expression.
  12705. struct MappableVarListInfo {
  12706. // The list of expressions.
  12707. ArrayRef<Expr *> VarList;
  12708. // The list of processed expressions.
  12709. SmallVector<Expr *, 16> ProcessedVarList;
  12710. // The mappble components for each expression.
  12711. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  12712. // The base declaration of the variable.
  12713. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  12714. // The reference to the user-defined mapper associated with every expression.
  12715. SmallVector<Expr *, 16> UDMapperList;
  12716. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  12717. // We have a list of components and base declarations for each entry in the
  12718. // variable list.
  12719. VarComponents.reserve(VarList.size());
  12720. VarBaseDeclarations.reserve(VarList.size());
  12721. }
  12722. };
  12723. }
  12724. // Check the validity of the provided variable list for the provided clause kind
  12725. // \a CKind. In the check process the valid expressions, mappable expression
  12726. // components, variables, and user-defined mappers are extracted and used to
  12727. // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
  12728. // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
  12729. // and \a MapperId are expected to be valid if the clause kind is 'map'.
  12730. static void checkMappableExpressionList(
  12731. Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
  12732. MappableVarListInfo &MVLI, SourceLocation StartLoc,
  12733. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
  12734. ArrayRef<Expr *> UnresolvedMappers,
  12735. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  12736. bool IsMapTypeImplicit = false) {
  12737. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  12738. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  12739. "Unexpected clause kind with mappable expressions!");
  12740. // If the identifier of user-defined mapper is not specified, it is "default".
  12741. // We do not change the actual name in this clause to distinguish whether a
  12742. // mapper is specified explicitly, i.e., it is not explicitly specified when
  12743. // MapperId.getName() is empty.
  12744. if (!MapperId.getName() || MapperId.getName().isEmpty()) {
  12745. auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
  12746. MapperId.setName(DeclNames.getIdentifier(
  12747. &SemaRef.getASTContext().Idents.get("default")));
  12748. }
  12749. // Iterators to find the current unresolved mapper expression.
  12750. auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
  12751. bool UpdateUMIt = false;
  12752. Expr *UnresolvedMapper = nullptr;
  12753. // Keep track of the mappable components and base declarations in this clause.
  12754. // Each entry in the list is going to have a list of components associated. We
  12755. // record each set of the components so that we can build the clause later on.
  12756. // In the end we should have the same amount of declarations and component
  12757. // lists.
  12758. for (Expr *RE : MVLI.VarList) {
  12759. assert(RE && "Null expr in omp to/from/map clause");
  12760. SourceLocation ELoc = RE->getExprLoc();
  12761. // Find the current unresolved mapper expression.
  12762. if (UpdateUMIt && UMIt != UMEnd) {
  12763. UMIt++;
  12764. assert(
  12765. UMIt != UMEnd &&
  12766. "Expect the size of UnresolvedMappers to match with that of VarList");
  12767. }
  12768. UpdateUMIt = true;
  12769. if (UMIt != UMEnd)
  12770. UnresolvedMapper = *UMIt;
  12771. const Expr *VE = RE->IgnoreParenLValueCasts();
  12772. if (VE->isValueDependent() || VE->isTypeDependent() ||
  12773. VE->isInstantiationDependent() ||
  12774. VE->containsUnexpandedParameterPack()) {
  12775. // Try to find the associated user-defined mapper.
  12776. ExprResult ER = buildUserDefinedMapperRef(
  12777. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  12778. VE->getType().getCanonicalType(), UnresolvedMapper);
  12779. if (ER.isInvalid())
  12780. continue;
  12781. MVLI.UDMapperList.push_back(ER.get());
  12782. // We can only analyze this information once the missing information is
  12783. // resolved.
  12784. MVLI.ProcessedVarList.push_back(RE);
  12785. continue;
  12786. }
  12787. Expr *SimpleExpr = RE->IgnoreParenCasts();
  12788. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  12789. SemaRef.Diag(ELoc,
  12790. diag::err_omp_expected_named_var_member_or_array_expression)
  12791. << RE->getSourceRange();
  12792. continue;
  12793. }
  12794. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  12795. ValueDecl *CurDeclaration = nullptr;
  12796. // Obtain the array or member expression bases if required. Also, fill the
  12797. // components array with all the components identified in the process.
  12798. const Expr *BE = checkMapClauseExpressionBase(
  12799. SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
  12800. if (!BE)
  12801. continue;
  12802. assert(!CurComponents.empty() &&
  12803. "Invalid mappable expression information.");
  12804. if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
  12805. // Add store "this" pointer to class in DSAStackTy for future checking
  12806. DSAS->addMappedClassesQualTypes(TE->getType());
  12807. // Try to find the associated user-defined mapper.
  12808. ExprResult ER = buildUserDefinedMapperRef(
  12809. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  12810. VE->getType().getCanonicalType(), UnresolvedMapper);
  12811. if (ER.isInvalid())
  12812. continue;
  12813. MVLI.UDMapperList.push_back(ER.get());
  12814. // Skip restriction checking for variable or field declarations
  12815. MVLI.ProcessedVarList.push_back(RE);
  12816. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12817. MVLI.VarComponents.back().append(CurComponents.begin(),
  12818. CurComponents.end());
  12819. MVLI.VarBaseDeclarations.push_back(nullptr);
  12820. continue;
  12821. }
  12822. // For the following checks, we rely on the base declaration which is
  12823. // expected to be associated with the last component. The declaration is
  12824. // expected to be a variable or a field (if 'this' is being mapped).
  12825. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  12826. assert(CurDeclaration && "Null decl on map clause.");
  12827. assert(
  12828. CurDeclaration->isCanonicalDecl() &&
  12829. "Expecting components to have associated only canonical declarations.");
  12830. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  12831. const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  12832. assert((VD || FD) && "Only variables or fields are expected here!");
  12833. (void)FD;
  12834. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  12835. // threadprivate variables cannot appear in a map clause.
  12836. // OpenMP 4.5 [2.10.5, target update Construct]
  12837. // threadprivate variables cannot appear in a from clause.
  12838. if (VD && DSAS->isThreadPrivate(VD)) {
  12839. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  12840. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  12841. << getOpenMPClauseName(CKind);
  12842. reportOriginalDsa(SemaRef, DSAS, VD, DVar);
  12843. continue;
  12844. }
  12845. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  12846. // A list item cannot appear in both a map clause and a data-sharing
  12847. // attribute clause on the same construct.
  12848. // Check conflicts with other map clause expressions. We check the conflicts
  12849. // with the current construct separately from the enclosing data
  12850. // environment, because the restrictions are different. We only have to
  12851. // check conflicts across regions for the map clauses.
  12852. if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  12853. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  12854. break;
  12855. if (CKind == OMPC_map &&
  12856. checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  12857. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  12858. break;
  12859. // OpenMP 4.5 [2.10.5, target update Construct]
  12860. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  12861. // If the type of a list item is a reference to a type T then the type will
  12862. // be considered to be T for all purposes of this clause.
  12863. auto I = llvm::find_if(
  12864. CurComponents,
  12865. [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
  12866. return MC.getAssociatedDeclaration();
  12867. });
  12868. assert(I != CurComponents.end() && "Null decl on map clause.");
  12869. QualType Type =
  12870. I->getAssociatedDeclaration()->getType().getNonReferenceType();
  12871. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  12872. // A list item in a to or from clause must have a mappable type.
  12873. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  12874. // A list item must have a mappable type.
  12875. if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  12876. DSAS, Type))
  12877. continue;
  12878. if (CKind == OMPC_map) {
  12879. // target enter data
  12880. // OpenMP [2.10.2, Restrictions, p. 99]
  12881. // A map-type must be specified in all map clauses and must be either
  12882. // to or alloc.
  12883. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  12884. if (DKind == OMPD_target_enter_data &&
  12885. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  12886. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  12887. << (IsMapTypeImplicit ? 1 : 0)
  12888. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  12889. << getOpenMPDirectiveName(DKind);
  12890. continue;
  12891. }
  12892. // target exit_data
  12893. // OpenMP [2.10.3, Restrictions, p. 102]
  12894. // A map-type must be specified in all map clauses and must be either
  12895. // from, release, or delete.
  12896. if (DKind == OMPD_target_exit_data &&
  12897. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  12898. MapType == OMPC_MAP_delete)) {
  12899. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  12900. << (IsMapTypeImplicit ? 1 : 0)
  12901. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  12902. << getOpenMPDirectiveName(DKind);
  12903. continue;
  12904. }
  12905. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  12906. // A list item cannot appear in both a map clause and a data-sharing
  12907. // attribute clause on the same construct
  12908. if (VD && isOpenMPTargetExecutionDirective(DKind)) {
  12909. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  12910. if (isOpenMPPrivate(DVar.CKind)) {
  12911. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  12912. << getOpenMPClauseName(DVar.CKind)
  12913. << getOpenMPClauseName(OMPC_map)
  12914. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  12915. reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
  12916. continue;
  12917. }
  12918. }
  12919. }
  12920. // Try to find the associated user-defined mapper.
  12921. ExprResult ER = buildUserDefinedMapperRef(
  12922. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  12923. Type.getCanonicalType(), UnresolvedMapper);
  12924. if (ER.isInvalid())
  12925. continue;
  12926. MVLI.UDMapperList.push_back(ER.get());
  12927. // Save the current expression.
  12928. MVLI.ProcessedVarList.push_back(RE);
  12929. // Store the components in the stack so that they can be used to check
  12930. // against other clauses later on.
  12931. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  12932. /*WhereFoundClauseKind=*/OMPC_map);
  12933. // Save the components and declaration to create the clause. For purposes of
  12934. // the clause creation, any component list that has has base 'this' uses
  12935. // null as base declaration.
  12936. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12937. MVLI.VarComponents.back().append(CurComponents.begin(),
  12938. CurComponents.end());
  12939. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  12940. : CurDeclaration);
  12941. }
  12942. }
  12943. OMPClause *Sema::ActOnOpenMPMapClause(
  12944. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  12945. ArrayRef<SourceLocation> MapTypeModifiersLoc,
  12946. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
  12947. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
  12948. SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
  12949. const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
  12950. OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
  12951. OMPC_MAP_MODIFIER_unknown,
  12952. OMPC_MAP_MODIFIER_unknown};
  12953. SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
  12954. // Process map-type-modifiers, flag errors for duplicate modifiers.
  12955. unsigned Count = 0;
  12956. for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
  12957. if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
  12958. llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
  12959. Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
  12960. continue;
  12961. }
  12962. assert(Count < OMPMapClause::NumberOfModifiers &&
  12963. "Modifiers exceed the allowed number of map type modifiers");
  12964. Modifiers[Count] = MapTypeModifiers[I];
  12965. ModifiersLoc[Count] = MapTypeModifiersLoc[I];
  12966. ++Count;
  12967. }
  12968. MappableVarListInfo MVLI(VarList);
  12969. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
  12970. MapperIdScopeSpec, MapperId, UnresolvedMappers,
  12971. MapType, IsMapTypeImplicit);
  12972. // We need to produce a map clause even if we don't have variables so that
  12973. // other diagnostics related with non-existing map clauses are accurate.
  12974. return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
  12975. MVLI.VarBaseDeclarations, MVLI.VarComponents,
  12976. MVLI.UDMapperList, Modifiers, ModifiersLoc,
  12977. MapperIdScopeSpec.getWithLocInContext(Context),
  12978. MapperId, MapType, IsMapTypeImplicit, MapLoc);
  12979. }
  12980. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  12981. TypeResult ParsedType) {
  12982. assert(ParsedType.isUsable());
  12983. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  12984. if (ReductionType.isNull())
  12985. return QualType();
  12986. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  12987. // A type name in a declare reduction directive cannot be a function type, an
  12988. // array type, a reference type, or a type qualified with const, volatile or
  12989. // restrict.
  12990. if (ReductionType.hasQualifiers()) {
  12991. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  12992. return QualType();
  12993. }
  12994. if (ReductionType->isFunctionType()) {
  12995. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  12996. return QualType();
  12997. }
  12998. if (ReductionType->isReferenceType()) {
  12999. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  13000. return QualType();
  13001. }
  13002. if (ReductionType->isArrayType()) {
  13003. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  13004. return QualType();
  13005. }
  13006. return ReductionType;
  13007. }
  13008. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  13009. Scope *S, DeclContext *DC, DeclarationName Name,
  13010. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  13011. AccessSpecifier AS, Decl *PrevDeclInScope) {
  13012. SmallVector<Decl *, 8> Decls;
  13013. Decls.reserve(ReductionTypes.size());
  13014. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  13015. forRedeclarationInCurContext());
  13016. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  13017. // A reduction-identifier may not be re-declared in the current scope for the
  13018. // same type or for a type that is compatible according to the base language
  13019. // rules.
  13020. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  13021. OMPDeclareReductionDecl *PrevDRD = nullptr;
  13022. bool InCompoundScope = true;
  13023. if (S != nullptr) {
  13024. // Find previous declaration with the same name not referenced in other
  13025. // declarations.
  13026. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  13027. InCompoundScope =
  13028. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  13029. LookupName(Lookup, S);
  13030. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  13031. /*AllowInlineNamespace=*/false);
  13032. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  13033. LookupResult::Filter Filter = Lookup.makeFilter();
  13034. while (Filter.hasNext()) {
  13035. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  13036. if (InCompoundScope) {
  13037. auto I = UsedAsPrevious.find(PrevDecl);
  13038. if (I == UsedAsPrevious.end())
  13039. UsedAsPrevious[PrevDecl] = false;
  13040. if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
  13041. UsedAsPrevious[D] = true;
  13042. }
  13043. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  13044. PrevDecl->getLocation();
  13045. }
  13046. Filter.done();
  13047. if (InCompoundScope) {
  13048. for (const auto &PrevData : UsedAsPrevious) {
  13049. if (!PrevData.second) {
  13050. PrevDRD = PrevData.first;
  13051. break;
  13052. }
  13053. }
  13054. }
  13055. } else if (PrevDeclInScope != nullptr) {
  13056. auto *PrevDRDInScope = PrevDRD =
  13057. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  13058. do {
  13059. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  13060. PrevDRDInScope->getLocation();
  13061. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  13062. } while (PrevDRDInScope != nullptr);
  13063. }
  13064. for (const auto &TyData : ReductionTypes) {
  13065. const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  13066. bool Invalid = false;
  13067. if (I != PreviousRedeclTypes.end()) {
  13068. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  13069. << TyData.first;
  13070. Diag(I->second, diag::note_previous_definition);
  13071. Invalid = true;
  13072. }
  13073. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  13074. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  13075. Name, TyData.first, PrevDRD);
  13076. DC->addDecl(DRD);
  13077. DRD->setAccess(AS);
  13078. Decls.push_back(DRD);
  13079. if (Invalid)
  13080. DRD->setInvalidDecl();
  13081. else
  13082. PrevDRD = DRD;
  13083. }
  13084. return DeclGroupPtrTy::make(
  13085. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  13086. }
  13087. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  13088. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  13089. // Enter new function scope.
  13090. PushFunctionScope();
  13091. setFunctionHasBranchProtectedScope();
  13092. getCurFunction()->setHasOMPDeclareReductionCombiner();
  13093. if (S != nullptr)
  13094. PushDeclContext(S, DRD);
  13095. else
  13096. CurContext = DRD;
  13097. PushExpressionEvaluationContext(
  13098. ExpressionEvaluationContext::PotentiallyEvaluated);
  13099. QualType ReductionType = DRD->getType();
  13100. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  13101. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  13102. // uses semantics of argument handles by value, but it should be passed by
  13103. // reference. C lang does not support references, so pass all parameters as
  13104. // pointers.
  13105. // Create 'T omp_in;' variable.
  13106. VarDecl *OmpInParm =
  13107. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  13108. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  13109. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  13110. // uses semantics of argument handles by value, but it should be passed by
  13111. // reference. C lang does not support references, so pass all parameters as
  13112. // pointers.
  13113. // Create 'T omp_out;' variable.
  13114. VarDecl *OmpOutParm =
  13115. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  13116. if (S != nullptr) {
  13117. PushOnScopeChains(OmpInParm, S);
  13118. PushOnScopeChains(OmpOutParm, S);
  13119. } else {
  13120. DRD->addDecl(OmpInParm);
  13121. DRD->addDecl(OmpOutParm);
  13122. }
  13123. Expr *InE =
  13124. ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
  13125. Expr *OutE =
  13126. ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
  13127. DRD->setCombinerData(InE, OutE);
  13128. }
  13129. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  13130. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  13131. DiscardCleanupsInEvaluationContext();
  13132. PopExpressionEvaluationContext();
  13133. PopDeclContext();
  13134. PopFunctionScopeInfo();
  13135. if (Combiner != nullptr)
  13136. DRD->setCombiner(Combiner);
  13137. else
  13138. DRD->setInvalidDecl();
  13139. }
  13140. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  13141. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  13142. // Enter new function scope.
  13143. PushFunctionScope();
  13144. setFunctionHasBranchProtectedScope();
  13145. if (S != nullptr)
  13146. PushDeclContext(S, DRD);
  13147. else
  13148. CurContext = DRD;
  13149. PushExpressionEvaluationContext(
  13150. ExpressionEvaluationContext::PotentiallyEvaluated);
  13151. QualType ReductionType = DRD->getType();
  13152. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  13153. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  13154. // uses semantics of argument handles by value, but it should be passed by
  13155. // reference. C lang does not support references, so pass all parameters as
  13156. // pointers.
  13157. // Create 'T omp_priv;' variable.
  13158. VarDecl *OmpPrivParm =
  13159. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  13160. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  13161. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  13162. // uses semantics of argument handles by value, but it should be passed by
  13163. // reference. C lang does not support references, so pass all parameters as
  13164. // pointers.
  13165. // Create 'T omp_orig;' variable.
  13166. VarDecl *OmpOrigParm =
  13167. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  13168. if (S != nullptr) {
  13169. PushOnScopeChains(OmpPrivParm, S);
  13170. PushOnScopeChains(OmpOrigParm, S);
  13171. } else {
  13172. DRD->addDecl(OmpPrivParm);
  13173. DRD->addDecl(OmpOrigParm);
  13174. }
  13175. Expr *OrigE =
  13176. ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
  13177. Expr *PrivE =
  13178. ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
  13179. DRD->setInitializerData(OrigE, PrivE);
  13180. return OmpPrivParm;
  13181. }
  13182. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  13183. VarDecl *OmpPrivParm) {
  13184. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  13185. DiscardCleanupsInEvaluationContext();
  13186. PopExpressionEvaluationContext();
  13187. PopDeclContext();
  13188. PopFunctionScopeInfo();
  13189. if (Initializer != nullptr) {
  13190. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  13191. } else if (OmpPrivParm->hasInit()) {
  13192. DRD->setInitializer(OmpPrivParm->getInit(),
  13193. OmpPrivParm->isDirectInit()
  13194. ? OMPDeclareReductionDecl::DirectInit
  13195. : OMPDeclareReductionDecl::CopyInit);
  13196. } else {
  13197. DRD->setInvalidDecl();
  13198. }
  13199. }
  13200. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  13201. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  13202. for (Decl *D : DeclReductions.get()) {
  13203. if (IsValid) {
  13204. if (S)
  13205. PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
  13206. /*AddToContext=*/false);
  13207. } else {
  13208. D->setInvalidDecl();
  13209. }
  13210. }
  13211. return DeclReductions;
  13212. }
  13213. TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
  13214. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13215. QualType T = TInfo->getType();
  13216. if (D.isInvalidType())
  13217. return true;
  13218. if (getLangOpts().CPlusPlus) {
  13219. // Check that there are no default arguments (C++ only).
  13220. CheckExtraCXXDefaultArguments(D);
  13221. }
  13222. return CreateParsedType(T, TInfo);
  13223. }
  13224. QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
  13225. TypeResult ParsedType) {
  13226. assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
  13227. QualType MapperType = GetTypeFromParser(ParsedType.get());
  13228. assert(!MapperType.isNull() && "Expect valid mapper type");
  13229. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  13230. // The type must be of struct, union or class type in C and C++
  13231. if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
  13232. Diag(TyLoc, diag::err_omp_mapper_wrong_type);
  13233. return QualType();
  13234. }
  13235. return MapperType;
  13236. }
  13237. OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
  13238. Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
  13239. SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
  13240. Decl *PrevDeclInScope) {
  13241. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
  13242. forRedeclarationInCurContext());
  13243. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  13244. // A mapper-identifier may not be redeclared in the current scope for the
  13245. // same type or for a type that is compatible according to the base language
  13246. // rules.
  13247. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  13248. OMPDeclareMapperDecl *PrevDMD = nullptr;
  13249. bool InCompoundScope = true;
  13250. if (S != nullptr) {
  13251. // Find previous declaration with the same name not referenced in other
  13252. // declarations.
  13253. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  13254. InCompoundScope =
  13255. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  13256. LookupName(Lookup, S);
  13257. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  13258. /*AllowInlineNamespace=*/false);
  13259. llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
  13260. LookupResult::Filter Filter = Lookup.makeFilter();
  13261. while (Filter.hasNext()) {
  13262. auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
  13263. if (InCompoundScope) {
  13264. auto I = UsedAsPrevious.find(PrevDecl);
  13265. if (I == UsedAsPrevious.end())
  13266. UsedAsPrevious[PrevDecl] = false;
  13267. if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
  13268. UsedAsPrevious[D] = true;
  13269. }
  13270. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  13271. PrevDecl->getLocation();
  13272. }
  13273. Filter.done();
  13274. if (InCompoundScope) {
  13275. for (const auto &PrevData : UsedAsPrevious) {
  13276. if (!PrevData.second) {
  13277. PrevDMD = PrevData.first;
  13278. break;
  13279. }
  13280. }
  13281. }
  13282. } else if (PrevDeclInScope) {
  13283. auto *PrevDMDInScope = PrevDMD =
  13284. cast<OMPDeclareMapperDecl>(PrevDeclInScope);
  13285. do {
  13286. PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
  13287. PrevDMDInScope->getLocation();
  13288. PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
  13289. } while (PrevDMDInScope != nullptr);
  13290. }
  13291. const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
  13292. bool Invalid = false;
  13293. if (I != PreviousRedeclTypes.end()) {
  13294. Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
  13295. << MapperType << Name;
  13296. Diag(I->second, diag::note_previous_definition);
  13297. Invalid = true;
  13298. }
  13299. auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
  13300. MapperType, VN, PrevDMD);
  13301. DC->addDecl(DMD);
  13302. DMD->setAccess(AS);
  13303. if (Invalid)
  13304. DMD->setInvalidDecl();
  13305. // Enter new function scope.
  13306. PushFunctionScope();
  13307. setFunctionHasBranchProtectedScope();
  13308. CurContext = DMD;
  13309. return DMD;
  13310. }
  13311. void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
  13312. Scope *S,
  13313. QualType MapperType,
  13314. SourceLocation StartLoc,
  13315. DeclarationName VN) {
  13316. VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
  13317. if (S)
  13318. PushOnScopeChains(VD, S);
  13319. else
  13320. DMD->addDecl(VD);
  13321. Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
  13322. DMD->setMapperVarRef(MapperVarRefExpr);
  13323. }
  13324. Sema::DeclGroupPtrTy
  13325. Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
  13326. ArrayRef<OMPClause *> ClauseList) {
  13327. PopDeclContext();
  13328. PopFunctionScopeInfo();
  13329. if (D) {
  13330. if (S)
  13331. PushOnScopeChains(D, S, /*AddToContext=*/false);
  13332. D->CreateClauses(Context, ClauseList);
  13333. }
  13334. return DeclGroupPtrTy::make(DeclGroupRef(D));
  13335. }
  13336. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  13337. SourceLocation StartLoc,
  13338. SourceLocation LParenLoc,
  13339. SourceLocation EndLoc) {
  13340. Expr *ValExpr = NumTeams;
  13341. Stmt *HelperValStmt = nullptr;
  13342. // OpenMP [teams Constrcut, Restrictions]
  13343. // The num_teams expression must evaluate to a positive integer value.
  13344. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  13345. /*StrictlyPositive=*/true))
  13346. return nullptr;
  13347. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  13348. OpenMPDirectiveKind CaptureRegion =
  13349. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  13350. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  13351. ValExpr = MakeFullExpr(ValExpr).get();
  13352. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13353. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13354. HelperValStmt = buildPreInits(Context, Captures);
  13355. }
  13356. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  13357. StartLoc, LParenLoc, EndLoc);
  13358. }
  13359. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  13360. SourceLocation StartLoc,
  13361. SourceLocation LParenLoc,
  13362. SourceLocation EndLoc) {
  13363. Expr *ValExpr = ThreadLimit;
  13364. Stmt *HelperValStmt = nullptr;
  13365. // OpenMP [teams Constrcut, Restrictions]
  13366. // The thread_limit expression must evaluate to a positive integer value.
  13367. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  13368. /*StrictlyPositive=*/true))
  13369. return nullptr;
  13370. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  13371. OpenMPDirectiveKind CaptureRegion =
  13372. getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  13373. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  13374. ValExpr = MakeFullExpr(ValExpr).get();
  13375. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13376. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13377. HelperValStmt = buildPreInits(Context, Captures);
  13378. }
  13379. return new (Context) OMPThreadLimitClause(
  13380. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  13381. }
  13382. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  13383. SourceLocation StartLoc,
  13384. SourceLocation LParenLoc,
  13385. SourceLocation EndLoc) {
  13386. Expr *ValExpr = Priority;
  13387. // OpenMP [2.9.1, task Constrcut]
  13388. // The priority-value is a non-negative numerical scalar expression.
  13389. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  13390. /*StrictlyPositive=*/false))
  13391. return nullptr;
  13392. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  13393. }
  13394. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  13395. SourceLocation StartLoc,
  13396. SourceLocation LParenLoc,
  13397. SourceLocation EndLoc) {
  13398. Expr *ValExpr = Grainsize;
  13399. // OpenMP [2.9.2, taskloop Constrcut]
  13400. // The parameter of the grainsize clause must be a positive integer
  13401. // expression.
  13402. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  13403. /*StrictlyPositive=*/true))
  13404. return nullptr;
  13405. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  13406. }
  13407. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  13408. SourceLocation StartLoc,
  13409. SourceLocation LParenLoc,
  13410. SourceLocation EndLoc) {
  13411. Expr *ValExpr = NumTasks;
  13412. // OpenMP [2.9.2, taskloop Constrcut]
  13413. // The parameter of the num_tasks clause must be a positive integer
  13414. // expression.
  13415. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  13416. /*StrictlyPositive=*/true))
  13417. return nullptr;
  13418. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  13419. }
  13420. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  13421. SourceLocation LParenLoc,
  13422. SourceLocation EndLoc) {
  13423. // OpenMP [2.13.2, critical construct, Description]
  13424. // ... where hint-expression is an integer constant expression that evaluates
  13425. // to a valid lock hint.
  13426. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  13427. if (HintExpr.isInvalid())
  13428. return nullptr;
  13429. return new (Context)
  13430. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  13431. }
  13432. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  13433. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  13434. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  13435. SourceLocation EndLoc) {
  13436. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  13437. std::string Values;
  13438. Values += "'";
  13439. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  13440. Values += "'";
  13441. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  13442. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  13443. return nullptr;
  13444. }
  13445. Expr *ValExpr = ChunkSize;
  13446. Stmt *HelperValStmt = nullptr;
  13447. if (ChunkSize) {
  13448. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  13449. !ChunkSize->isInstantiationDependent() &&
  13450. !ChunkSize->containsUnexpandedParameterPack()) {
  13451. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  13452. ExprResult Val =
  13453. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  13454. if (Val.isInvalid())
  13455. return nullptr;
  13456. ValExpr = Val.get();
  13457. // OpenMP [2.7.1, Restrictions]
  13458. // chunk_size must be a loop invariant integer expression with a positive
  13459. // value.
  13460. llvm::APSInt Result;
  13461. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  13462. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  13463. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  13464. << "dist_schedule" << ChunkSize->getSourceRange();
  13465. return nullptr;
  13466. }
  13467. } else if (getOpenMPCaptureRegionForClause(
  13468. DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
  13469. OMPD_unknown &&
  13470. !CurContext->isDependentContext()) {
  13471. ValExpr = MakeFullExpr(ValExpr).get();
  13472. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13473. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13474. HelperValStmt = buildPreInits(Context, Captures);
  13475. }
  13476. }
  13477. }
  13478. return new (Context)
  13479. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  13480. Kind, ValExpr, HelperValStmt);
  13481. }
  13482. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  13483. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  13484. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  13485. SourceLocation KindLoc, SourceLocation EndLoc) {
  13486. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  13487. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  13488. std::string Value;
  13489. SourceLocation Loc;
  13490. Value += "'";
  13491. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  13492. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  13493. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  13494. Loc = MLoc;
  13495. } else {
  13496. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  13497. OMPC_DEFAULTMAP_scalar);
  13498. Loc = KindLoc;
  13499. }
  13500. Value += "'";
  13501. Diag(Loc, diag::err_omp_unexpected_clause_value)
  13502. << Value << getOpenMPClauseName(OMPC_defaultmap);
  13503. return nullptr;
  13504. }
  13505. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  13506. return new (Context)
  13507. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  13508. }
  13509. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  13510. DeclContext *CurLexicalContext = getCurLexicalContext();
  13511. if (!CurLexicalContext->isFileContext() &&
  13512. !CurLexicalContext->isExternCContext() &&
  13513. !CurLexicalContext->isExternCXXContext() &&
  13514. !isa<CXXRecordDecl>(CurLexicalContext) &&
  13515. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  13516. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  13517. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  13518. Diag(Loc, diag::err_omp_region_not_file_context);
  13519. return false;
  13520. }
  13521. ++DeclareTargetNestingLevel;
  13522. return true;
  13523. }
  13524. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  13525. assert(DeclareTargetNestingLevel > 0 &&
  13526. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  13527. --DeclareTargetNestingLevel;
  13528. }
  13529. void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
  13530. CXXScopeSpec &ScopeSpec,
  13531. const DeclarationNameInfo &Id,
  13532. OMPDeclareTargetDeclAttr::MapTypeTy MT,
  13533. NamedDeclSetType &SameDirectiveDecls) {
  13534. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  13535. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  13536. if (Lookup.isAmbiguous())
  13537. return;
  13538. Lookup.suppressDiagnostics();
  13539. if (!Lookup.isSingleResult()) {
  13540. VarOrFuncDeclFilterCCC CCC(*this);
  13541. if (TypoCorrection Corrected =
  13542. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  13543. CTK_ErrorRecovery)) {
  13544. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  13545. << Id.getName());
  13546. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  13547. return;
  13548. }
  13549. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  13550. return;
  13551. }
  13552. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  13553. if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
  13554. isa<FunctionTemplateDecl>(ND)) {
  13555. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  13556. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  13557. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  13558. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  13559. cast<ValueDecl>(ND));
  13560. if (!Res) {
  13561. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
  13562. ND->addAttr(A);
  13563. if (ASTMutationListener *ML = Context.getASTMutationListener())
  13564. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  13565. checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
  13566. } else if (*Res != MT) {
  13567. Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
  13568. << Id.getName();
  13569. }
  13570. } else {
  13571. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  13572. }
  13573. }
  13574. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  13575. Sema &SemaRef, Decl *D) {
  13576. if (!D || !isa<VarDecl>(D))
  13577. return;
  13578. auto *VD = cast<VarDecl>(D);
  13579. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  13580. return;
  13581. SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
  13582. SemaRef.Diag(SL, diag::note_used_here) << SR;
  13583. }
  13584. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  13585. Sema &SemaRef, DSAStackTy *Stack,
  13586. ValueDecl *VD) {
  13587. return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
  13588. checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
  13589. /*FullCheck=*/false);
  13590. }
  13591. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
  13592. SourceLocation IdLoc) {
  13593. if (!D || D->isInvalidDecl())
  13594. return;
  13595. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  13596. SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
  13597. if (auto *VD = dyn_cast<VarDecl>(D)) {
  13598. // Only global variables can be marked as declare target.
  13599. if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
  13600. !VD->isStaticDataMember())
  13601. return;
  13602. // 2.10.6: threadprivate variable cannot appear in a declare target
  13603. // directive.
  13604. if (DSAStack->isThreadPrivate(VD)) {
  13605. Diag(SL, diag::err_omp_threadprivate_in_target);
  13606. reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  13607. return;
  13608. }
  13609. }
  13610. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  13611. D = FTD->getTemplatedDecl();
  13612. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  13613. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  13614. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
  13615. if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  13616. assert(IdLoc.isValid() && "Source location is expected");
  13617. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  13618. Diag(FD->getLocation(), diag::note_defined_here) << FD;
  13619. return;
  13620. }
  13621. }
  13622. if (auto *VD = dyn_cast<ValueDecl>(D)) {
  13623. // Problem if any with var declared with incomplete type will be reported
  13624. // as normal, so no need to check it here.
  13625. if ((E || !VD->getType()->isIncompleteType()) &&
  13626. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
  13627. return;
  13628. if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  13629. // Checking declaration inside declare target region.
  13630. if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
  13631. isa<FunctionTemplateDecl>(D)) {
  13632. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  13633. Context, OMPDeclareTargetDeclAttr::MT_To);
  13634. D->addAttr(A);
  13635. if (ASTMutationListener *ML = Context.getASTMutationListener())
  13636. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  13637. }
  13638. return;
  13639. }
  13640. }
  13641. if (!E)
  13642. return;
  13643. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  13644. }
  13645. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  13646. CXXScopeSpec &MapperIdScopeSpec,
  13647. DeclarationNameInfo &MapperId,
  13648. const OMPVarListLocTy &Locs,
  13649. ArrayRef<Expr *> UnresolvedMappers) {
  13650. MappableVarListInfo MVLI(VarList);
  13651. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
  13652. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  13653. if (MVLI.ProcessedVarList.empty())
  13654. return nullptr;
  13655. return OMPToClause::Create(
  13656. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  13657. MVLI.VarComponents, MVLI.UDMapperList,
  13658. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  13659. }
  13660. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  13661. CXXScopeSpec &MapperIdScopeSpec,
  13662. DeclarationNameInfo &MapperId,
  13663. const OMPVarListLocTy &Locs,
  13664. ArrayRef<Expr *> UnresolvedMappers) {
  13665. MappableVarListInfo MVLI(VarList);
  13666. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
  13667. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  13668. if (MVLI.ProcessedVarList.empty())
  13669. return nullptr;
  13670. return OMPFromClause::Create(
  13671. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  13672. MVLI.VarComponents, MVLI.UDMapperList,
  13673. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  13674. }
  13675. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  13676. const OMPVarListLocTy &Locs) {
  13677. MappableVarListInfo MVLI(VarList);
  13678. SmallVector<Expr *, 8> PrivateCopies;
  13679. SmallVector<Expr *, 8> Inits;
  13680. for (Expr *RefExpr : VarList) {
  13681. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  13682. SourceLocation ELoc;
  13683. SourceRange ERange;
  13684. Expr *SimpleRefExpr = RefExpr;
  13685. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  13686. if (Res.second) {
  13687. // It will be analyzed later.
  13688. MVLI.ProcessedVarList.push_back(RefExpr);
  13689. PrivateCopies.push_back(nullptr);
  13690. Inits.push_back(nullptr);
  13691. }
  13692. ValueDecl *D = Res.first;
  13693. if (!D)
  13694. continue;
  13695. QualType Type = D->getType();
  13696. Type = Type.getNonReferenceType().getUnqualifiedType();
  13697. auto *VD = dyn_cast<VarDecl>(D);
  13698. // Item should be a pointer or reference to pointer.
  13699. if (!Type->isPointerType()) {
  13700. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  13701. << 0 << RefExpr->getSourceRange();
  13702. continue;
  13703. }
  13704. // Build the private variable and the expression that refers to it.
  13705. auto VDPrivate =
  13706. buildVarDecl(*this, ELoc, Type, D->getName(),
  13707. D->hasAttrs() ? &D->getAttrs() : nullptr,
  13708. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  13709. if (VDPrivate->isInvalidDecl())
  13710. continue;
  13711. CurContext->addDecl(VDPrivate);
  13712. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  13713. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  13714. // Add temporary variable to initialize the private copy of the pointer.
  13715. VarDecl *VDInit =
  13716. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  13717. DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
  13718. *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
  13719. AddInitializerToDecl(VDPrivate,
  13720. DefaultLvalueConversion(VDInitRefExpr).get(),
  13721. /*DirectInit=*/false);
  13722. // If required, build a capture to implement the privatization initialized
  13723. // with the current list item value.
  13724. DeclRefExpr *Ref = nullptr;
  13725. if (!VD)
  13726. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  13727. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  13728. PrivateCopies.push_back(VDPrivateRefExpr);
  13729. Inits.push_back(VDInitRefExpr);
  13730. // We need to add a data sharing attribute for this variable to make sure it
  13731. // is correctly captured. A variable that shows up in a use_device_ptr has
  13732. // similar properties of a first private variable.
  13733. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  13734. // Create a mappable component for the list item. List items in this clause
  13735. // only need a component.
  13736. MVLI.VarBaseDeclarations.push_back(D);
  13737. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  13738. MVLI.VarComponents.back().push_back(
  13739. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  13740. }
  13741. if (MVLI.ProcessedVarList.empty())
  13742. return nullptr;
  13743. return OMPUseDevicePtrClause::Create(
  13744. Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
  13745. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  13746. }
  13747. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  13748. const OMPVarListLocTy &Locs) {
  13749. MappableVarListInfo MVLI(VarList);
  13750. for (Expr *RefExpr : VarList) {
  13751. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  13752. SourceLocation ELoc;
  13753. SourceRange ERange;
  13754. Expr *SimpleRefExpr = RefExpr;
  13755. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  13756. if (Res.second) {
  13757. // It will be analyzed later.
  13758. MVLI.ProcessedVarList.push_back(RefExpr);
  13759. }
  13760. ValueDecl *D = Res.first;
  13761. if (!D)
  13762. continue;
  13763. QualType Type = D->getType();
  13764. // item should be a pointer or array or reference to pointer or array
  13765. if (!Type.getNonReferenceType()->isPointerType() &&
  13766. !Type.getNonReferenceType()->isArrayType()) {
  13767. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  13768. << 0 << RefExpr->getSourceRange();
  13769. continue;
  13770. }
  13771. // Check if the declaration in the clause does not show up in any data
  13772. // sharing attribute.
  13773. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  13774. if (isOpenMPPrivate(DVar.CKind)) {
  13775. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  13776. << getOpenMPClauseName(DVar.CKind)
  13777. << getOpenMPClauseName(OMPC_is_device_ptr)
  13778. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  13779. reportOriginalDsa(*this, DSAStack, D, DVar);
  13780. continue;
  13781. }
  13782. const Expr *ConflictExpr;
  13783. if (DSAStack->checkMappableExprComponentListsForDecl(
  13784. D, /*CurrentRegionOnly=*/true,
  13785. [&ConflictExpr](
  13786. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  13787. OpenMPClauseKind) -> bool {
  13788. ConflictExpr = R.front().getAssociatedExpression();
  13789. return true;
  13790. })) {
  13791. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  13792. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  13793. << ConflictExpr->getSourceRange();
  13794. continue;
  13795. }
  13796. // Store the components in the stack so that they can be used to check
  13797. // against other clauses later on.
  13798. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  13799. DSAStack->addMappableExpressionComponents(
  13800. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  13801. // Record the expression we've just processed.
  13802. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  13803. // Create a mappable component for the list item. List items in this clause
  13804. // only need a component. We use a null declaration to signal fields in
  13805. // 'this'.
  13806. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  13807. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  13808. "Unexpected device pointer expression!");
  13809. MVLI.VarBaseDeclarations.push_back(
  13810. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  13811. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  13812. MVLI.VarComponents.back().push_back(MC);
  13813. }
  13814. if (MVLI.ProcessedVarList.empty())
  13815. return nullptr;
  13816. return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
  13817. MVLI.VarBaseDeclarations,
  13818. MVLI.VarComponents);
  13819. }
  13820. OMPClause *Sema::ActOnOpenMPAllocateClause(
  13821. Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  13822. SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  13823. if (Allocator) {
  13824. // OpenMP [2.11.4 allocate Clause, Description]
  13825. // allocator is an expression of omp_allocator_handle_t type.
  13826. if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
  13827. return nullptr;
  13828. ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
  13829. if (AllocatorRes.isInvalid())
  13830. return nullptr;
  13831. AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
  13832. DSAStack->getOMPAllocatorHandleT(),
  13833. Sema::AA_Initializing,
  13834. /*AllowExplicit=*/true);
  13835. if (AllocatorRes.isInvalid())
  13836. return nullptr;
  13837. Allocator = AllocatorRes.get();
  13838. }
  13839. // Analyze and build list of variables.
  13840. SmallVector<Expr *, 8> Vars;
  13841. for (Expr *RefExpr : VarList) {
  13842. assert(RefExpr && "NULL expr in OpenMP private clause.");
  13843. SourceLocation ELoc;
  13844. SourceRange ERange;
  13845. Expr *SimpleRefExpr = RefExpr;
  13846. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  13847. if (Res.second) {
  13848. // It will be analyzed later.
  13849. Vars.push_back(RefExpr);
  13850. }
  13851. ValueDecl *D = Res.first;
  13852. if (!D)
  13853. continue;
  13854. auto *VD = dyn_cast<VarDecl>(D);
  13855. DeclRefExpr *Ref = nullptr;
  13856. if (!VD && !CurContext->isDependentContext())
  13857. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  13858. Vars.push_back((VD || CurContext->isDependentContext())
  13859. ? RefExpr->IgnoreParens()
  13860. : Ref);
  13861. }
  13862. if (Vars.empty())
  13863. return nullptr;
  13864. return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
  13865. ColonLoc, EndLoc, Vars);
  13866. }