SemaOpenMP.cpp 571 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361
  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. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  143. Scope *CurScope, SourceLocation Loc)
  144. : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
  145. ConstructLoc(Loc) {}
  146. SharingMapTy() = default;
  147. };
  148. using StackTy = SmallVector<SharingMapTy, 4>;
  149. /// Stack of used declaration and their data-sharing attributes.
  150. DeclSAMapTy Threadprivates;
  151. const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
  152. SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
  153. /// true, if check for DSA must be from parent directive, false, if
  154. /// from current directive.
  155. OpenMPClauseKind ClauseKindMode = OMPC_unknown;
  156. Sema &SemaRef;
  157. bool ForceCapturing = false;
  158. /// true if all the vaiables in the target executable directives must be
  159. /// captured by reference.
  160. bool ForceCaptureByReferenceInTargetExecutable = false;
  161. CriticalsWithHintsTy Criticals;
  162. using iterator = StackTy::const_reverse_iterator;
  163. DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
  164. /// Checks if the variable is a local for OpenMP region.
  165. bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
  166. bool isStackEmpty() const {
  167. return Stack.empty() ||
  168. Stack.back().second != CurrentNonCapturingFunctionScope ||
  169. Stack.back().first.empty();
  170. }
  171. /// Vector of previously declared requires directives
  172. SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
  173. public:
  174. explicit DSAStackTy(Sema &S) : SemaRef(S) {}
  175. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  176. OpenMPClauseKind getClauseParsingMode() const {
  177. assert(isClauseParsingMode() && "Must be in clause parsing mode.");
  178. return ClauseKindMode;
  179. }
  180. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  181. bool isForceVarCapturing() const { return ForceCapturing; }
  182. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  183. void setForceCaptureByReferenceInTargetExecutable(bool V) {
  184. ForceCaptureByReferenceInTargetExecutable = V;
  185. }
  186. bool isForceCaptureByReferenceInTargetExecutable() const {
  187. return ForceCaptureByReferenceInTargetExecutable;
  188. }
  189. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  190. Scope *CurScope, SourceLocation Loc) {
  191. if (Stack.empty() ||
  192. Stack.back().second != CurrentNonCapturingFunctionScope)
  193. Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
  194. Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
  195. Stack.back().first.back().DefaultAttrLoc = Loc;
  196. }
  197. void pop() {
  198. assert(!Stack.back().first.empty() &&
  199. "Data-sharing attributes stack is empty!");
  200. Stack.back().first.pop_back();
  201. }
  202. /// Marks that we're started loop parsing.
  203. void loopInit() {
  204. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  205. "Expected loop-based directive.");
  206. Stack.back().first.back().LoopStart = true;
  207. }
  208. /// Start capturing of the variables in the loop context.
  209. void loopStart() {
  210. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  211. "Expected loop-based directive.");
  212. Stack.back().first.back().LoopStart = false;
  213. }
  214. /// true, if variables are captured, false otherwise.
  215. bool isLoopStarted() const {
  216. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  217. "Expected loop-based directive.");
  218. return !Stack.back().first.back().LoopStart;
  219. }
  220. /// Marks (or clears) declaration as possibly loop counter.
  221. void resetPossibleLoopCounter(const Decl *D = nullptr) {
  222. Stack.back().first.back().PossiblyLoopCounter =
  223. D ? D->getCanonicalDecl() : D;
  224. }
  225. /// Gets the possible loop counter decl.
  226. const Decl *getPossiblyLoopCunter() const {
  227. return Stack.back().first.back().PossiblyLoopCounter;
  228. }
  229. /// Start new OpenMP region stack in new non-capturing function.
  230. void pushFunction() {
  231. const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
  232. assert(!isa<CapturingScopeInfo>(CurFnScope));
  233. CurrentNonCapturingFunctionScope = CurFnScope;
  234. }
  235. /// Pop region stack for non-capturing function.
  236. void popFunction(const FunctionScopeInfo *OldFSI) {
  237. if (!Stack.empty() && Stack.back().second == OldFSI) {
  238. assert(Stack.back().first.empty());
  239. Stack.pop_back();
  240. }
  241. CurrentNonCapturingFunctionScope = nullptr;
  242. for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
  243. if (!isa<CapturingScopeInfo>(FSI)) {
  244. CurrentNonCapturingFunctionScope = FSI;
  245. break;
  246. }
  247. }
  248. }
  249. void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
  250. Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
  251. }
  252. const std::pair<const OMPCriticalDirective *, llvm::APSInt>
  253. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  254. auto I = Criticals.find(Name.getAsString());
  255. if (I != Criticals.end())
  256. return I->second;
  257. return std::make_pair(nullptr, llvm::APSInt());
  258. }
  259. /// If 'aligned' declaration for given variable \a D was not seen yet,
  260. /// add it and return NULL; otherwise return previous occurrence's expression
  261. /// for diagnostics.
  262. const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
  263. /// Register specified variable as loop control variable.
  264. void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
  265. /// Check if the specified variable is a loop control variable for
  266. /// current region.
  267. /// \return The index of the loop control variable in the list of associated
  268. /// for-loops (from outer to inner).
  269. const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
  270. /// Check if the specified variable is a loop control variable for
  271. /// parent region.
  272. /// \return The index of the loop control variable in the list of associated
  273. /// for-loops (from outer to inner).
  274. const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
  275. /// Get the loop control variable for the I-th loop (or nullptr) in
  276. /// parent directive.
  277. const ValueDecl *getParentLoopControlVariable(unsigned I) const;
  278. /// Adds explicit data sharing attribute to the specified declaration.
  279. void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  280. DeclRefExpr *PrivateCopy = nullptr);
  281. /// Adds additional information for the reduction items with the reduction id
  282. /// represented as an operator.
  283. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  284. BinaryOperatorKind BOK);
  285. /// Adds additional information for the reduction items with the reduction id
  286. /// represented as reduction identifier.
  287. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  288. const Expr *ReductionRef);
  289. /// Returns the location and reduction operation from the innermost parent
  290. /// region for the given \p D.
  291. const DSAVarData
  292. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  293. BinaryOperatorKind &BOK,
  294. Expr *&TaskgroupDescriptor) const;
  295. /// Returns the location and reduction operation from the innermost parent
  296. /// region for the given \p D.
  297. const DSAVarData
  298. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  299. const Expr *&ReductionRef,
  300. Expr *&TaskgroupDescriptor) const;
  301. /// Return reduction reference expression for the current taskgroup.
  302. Expr *getTaskgroupReductionRef() const {
  303. assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
  304. "taskgroup reference expression requested for non taskgroup "
  305. "directive.");
  306. return Stack.back().first.back().TaskgroupReductionRef;
  307. }
  308. /// Checks if the given \p VD declaration is actually a taskgroup reduction
  309. /// descriptor variable at the \p Level of OpenMP regions.
  310. bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
  311. return Stack.back().first[Level].TaskgroupReductionRef &&
  312. cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
  313. ->getDecl() == VD;
  314. }
  315. /// Returns data sharing attributes from top of the stack for the
  316. /// specified declaration.
  317. const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  318. /// Returns data-sharing attributes for the specified declaration.
  319. const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
  320. /// Checks if the specified variables has data-sharing attributes which
  321. /// match specified \a CPred predicate in any directive which matches \a DPred
  322. /// predicate.
  323. const DSAVarData
  324. hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  325. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  326. bool FromParent) const;
  327. /// Checks if the specified variables has data-sharing attributes which
  328. /// match specified \a CPred predicate in any innermost directive which
  329. /// matches \a DPred predicate.
  330. const DSAVarData
  331. hasInnermostDSA(ValueDecl *D,
  332. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  333. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  334. bool FromParent) const;
  335. /// Checks if the specified variables has explicit data-sharing
  336. /// attributes which match specified \a CPred predicate at the specified
  337. /// OpenMP region.
  338. bool hasExplicitDSA(const ValueDecl *D,
  339. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  340. unsigned Level, bool NotLastprivate = false) const;
  341. /// Returns true if the directive at level \Level matches in the
  342. /// specified \a DPred predicate.
  343. bool hasExplicitDirective(
  344. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  345. unsigned Level) const;
  346. /// Finds a directive which matches specified \a DPred predicate.
  347. bool hasDirective(
  348. const llvm::function_ref<bool(
  349. OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
  350. DPred,
  351. bool FromParent) const;
  352. /// Returns currently analyzed directive.
  353. OpenMPDirectiveKind getCurrentDirective() const {
  354. return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
  355. }
  356. /// Returns directive kind at specified level.
  357. OpenMPDirectiveKind getDirective(unsigned Level) const {
  358. assert(!isStackEmpty() && "No directive at specified level.");
  359. return Stack.back().first[Level].Directive;
  360. }
  361. /// Returns parent directive.
  362. OpenMPDirectiveKind getParentDirective() const {
  363. if (isStackEmpty() || Stack.back().first.size() == 1)
  364. return OMPD_unknown;
  365. return std::next(Stack.back().first.rbegin())->Directive;
  366. }
  367. /// Add requires decl to internal vector
  368. void addRequiresDecl(OMPRequiresDecl *RD) {
  369. RequiresDecls.push_back(RD);
  370. }
  371. /// Checks for a duplicate clause amongst previously declared requires
  372. /// directives
  373. bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
  374. bool IsDuplicate = false;
  375. for (OMPClause *CNew : ClauseList) {
  376. for (const OMPRequiresDecl *D : RequiresDecls) {
  377. for (const OMPClause *CPrev : D->clauselists()) {
  378. if (CNew->getClauseKind() == CPrev->getClauseKind()) {
  379. SemaRef.Diag(CNew->getBeginLoc(),
  380. diag::err_omp_requires_clause_redeclaration)
  381. << getOpenMPClauseName(CNew->getClauseKind());
  382. SemaRef.Diag(CPrev->getBeginLoc(),
  383. diag::note_omp_requires_previous_clause)
  384. << getOpenMPClauseName(CPrev->getClauseKind());
  385. IsDuplicate = true;
  386. }
  387. }
  388. }
  389. }
  390. return IsDuplicate;
  391. }
  392. /// Set default data sharing attribute to none.
  393. void setDefaultDSANone(SourceLocation Loc) {
  394. assert(!isStackEmpty());
  395. Stack.back().first.back().DefaultAttr = DSA_none;
  396. Stack.back().first.back().DefaultAttrLoc = Loc;
  397. }
  398. /// Set default data sharing attribute to shared.
  399. void setDefaultDSAShared(SourceLocation Loc) {
  400. assert(!isStackEmpty());
  401. Stack.back().first.back().DefaultAttr = DSA_shared;
  402. Stack.back().first.back().DefaultAttrLoc = Loc;
  403. }
  404. /// Set default data mapping attribute to 'tofrom:scalar'.
  405. void setDefaultDMAToFromScalar(SourceLocation Loc) {
  406. assert(!isStackEmpty());
  407. Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
  408. Stack.back().first.back().DefaultMapAttrLoc = Loc;
  409. }
  410. DefaultDataSharingAttributes getDefaultDSA() const {
  411. return isStackEmpty() ? DSA_unspecified
  412. : Stack.back().first.back().DefaultAttr;
  413. }
  414. SourceLocation getDefaultDSALocation() const {
  415. return isStackEmpty() ? SourceLocation()
  416. : Stack.back().first.back().DefaultAttrLoc;
  417. }
  418. DefaultMapAttributes getDefaultDMA() const {
  419. return isStackEmpty() ? DMA_unspecified
  420. : Stack.back().first.back().DefaultMapAttr;
  421. }
  422. DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
  423. return Stack.back().first[Level].DefaultMapAttr;
  424. }
  425. SourceLocation getDefaultDMALocation() const {
  426. return isStackEmpty() ? SourceLocation()
  427. : Stack.back().first.back().DefaultMapAttrLoc;
  428. }
  429. /// Checks if the specified variable is a threadprivate.
  430. bool isThreadPrivate(VarDecl *D) {
  431. const DSAVarData DVar = getTopDSA(D, false);
  432. return isOpenMPThreadPrivate(DVar.CKind);
  433. }
  434. /// Marks current region as ordered (it has an 'ordered' clause).
  435. void setOrderedRegion(bool IsOrdered, const Expr *Param,
  436. OMPOrderedClause *Clause) {
  437. assert(!isStackEmpty());
  438. if (IsOrdered)
  439. Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
  440. else
  441. Stack.back().first.back().OrderedRegion.reset();
  442. }
  443. /// Returns true, if region is ordered (has associated 'ordered' clause),
  444. /// false - otherwise.
  445. bool isOrderedRegion() const {
  446. if (isStackEmpty())
  447. return false;
  448. return Stack.back().first.rbegin()->OrderedRegion.hasValue();
  449. }
  450. /// Returns optional parameter for the ordered region.
  451. std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
  452. if (isStackEmpty() ||
  453. !Stack.back().first.rbegin()->OrderedRegion.hasValue())
  454. return std::make_pair(nullptr, nullptr);
  455. return Stack.back().first.rbegin()->OrderedRegion.getValue();
  456. }
  457. /// Returns true, if parent region is ordered (has associated
  458. /// 'ordered' clause), false - otherwise.
  459. bool isParentOrderedRegion() const {
  460. if (isStackEmpty() || Stack.back().first.size() == 1)
  461. return false;
  462. return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
  463. }
  464. /// Returns optional parameter for the ordered region.
  465. std::pair<const Expr *, OMPOrderedClause *>
  466. getParentOrderedRegionParam() const {
  467. if (isStackEmpty() || Stack.back().first.size() == 1 ||
  468. !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
  469. return std::make_pair(nullptr, nullptr);
  470. return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
  471. }
  472. /// Marks current region as nowait (it has a 'nowait' clause).
  473. void setNowaitRegion(bool IsNowait = true) {
  474. assert(!isStackEmpty());
  475. Stack.back().first.back().NowaitRegion = IsNowait;
  476. }
  477. /// Returns true, if parent region is nowait (has associated
  478. /// 'nowait' clause), false - otherwise.
  479. bool isParentNowaitRegion() const {
  480. if (isStackEmpty() || Stack.back().first.size() == 1)
  481. return false;
  482. return std::next(Stack.back().first.rbegin())->NowaitRegion;
  483. }
  484. /// Marks parent region as cancel region.
  485. void setParentCancelRegion(bool Cancel = true) {
  486. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  487. auto &StackElemRef = *std::next(Stack.back().first.rbegin());
  488. StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
  489. }
  490. }
  491. /// Return true if current region has inner cancel construct.
  492. bool isCancelRegion() const {
  493. return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
  494. }
  495. /// Set collapse value for the region.
  496. void setAssociatedLoops(unsigned Val) {
  497. assert(!isStackEmpty());
  498. Stack.back().first.back().AssociatedLoops = Val;
  499. }
  500. /// Return collapse value for region.
  501. unsigned getAssociatedLoops() const {
  502. return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
  503. }
  504. /// Marks current target region as one with closely nested teams
  505. /// region.
  506. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  507. if (!isStackEmpty() && Stack.back().first.size() > 1) {
  508. std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
  509. TeamsRegionLoc;
  510. }
  511. }
  512. /// Returns true, if current region has closely nested teams region.
  513. bool hasInnerTeamsRegion() const {
  514. return getInnerTeamsRegionLoc().isValid();
  515. }
  516. /// Returns location of the nested teams region (if any).
  517. SourceLocation getInnerTeamsRegionLoc() const {
  518. return isStackEmpty() ? SourceLocation()
  519. : Stack.back().first.back().InnerTeamsRegionLoc;
  520. }
  521. Scope *getCurScope() const {
  522. return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
  523. }
  524. SourceLocation getConstructLoc() const {
  525. return isStackEmpty() ? SourceLocation()
  526. : Stack.back().first.back().ConstructLoc;
  527. }
  528. /// Do the check specified in \a Check to all component lists and return true
  529. /// if any issue is found.
  530. bool checkMappableExprComponentListsForDecl(
  531. const ValueDecl *VD, bool CurrentRegionOnly,
  532. const llvm::function_ref<
  533. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  534. OpenMPClauseKind)>
  535. Check) const {
  536. if (isStackEmpty())
  537. return false;
  538. auto SI = Stack.back().first.rbegin();
  539. auto SE = Stack.back().first.rend();
  540. if (SI == SE)
  541. return false;
  542. if (CurrentRegionOnly)
  543. SE = std::next(SI);
  544. else
  545. std::advance(SI, 1);
  546. for (; SI != SE; ++SI) {
  547. auto MI = SI->MappedExprComponents.find(VD);
  548. if (MI != SI->MappedExprComponents.end())
  549. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  550. MI->second.Components)
  551. if (Check(L, MI->second.Kind))
  552. return true;
  553. }
  554. return false;
  555. }
  556. /// Do the check specified in \a Check to all component lists at a given level
  557. /// and return true if any issue is found.
  558. bool checkMappableExprComponentListsForDeclAtLevel(
  559. const ValueDecl *VD, unsigned Level,
  560. const llvm::function_ref<
  561. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  562. OpenMPClauseKind)>
  563. Check) const {
  564. if (isStackEmpty())
  565. return false;
  566. auto StartI = Stack.back().first.begin();
  567. auto EndI = Stack.back().first.end();
  568. if (std::distance(StartI, EndI) <= (int)Level)
  569. return false;
  570. std::advance(StartI, Level);
  571. auto MI = StartI->MappedExprComponents.find(VD);
  572. if (MI != StartI->MappedExprComponents.end())
  573. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  574. MI->second.Components)
  575. if (Check(L, MI->second.Kind))
  576. return true;
  577. return false;
  578. }
  579. /// Create a new mappable expression component list associated with a given
  580. /// declaration and initialize it with the provided list of components.
  581. void addMappableExpressionComponents(
  582. const ValueDecl *VD,
  583. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  584. OpenMPClauseKind WhereFoundClauseKind) {
  585. assert(!isStackEmpty() &&
  586. "Not expecting to retrieve components from a empty stack!");
  587. MappedExprComponentTy &MEC =
  588. Stack.back().first.back().MappedExprComponents[VD];
  589. // Create new entry and append the new components there.
  590. MEC.Components.resize(MEC.Components.size() + 1);
  591. MEC.Components.back().append(Components.begin(), Components.end());
  592. MEC.Kind = WhereFoundClauseKind;
  593. }
  594. unsigned getNestingLevel() const {
  595. assert(!isStackEmpty());
  596. return Stack.back().first.size() - 1;
  597. }
  598. void addDoacrossDependClause(OMPDependClause *C,
  599. const OperatorOffsetTy &OpsOffs) {
  600. assert(!isStackEmpty() && Stack.back().first.size() > 1);
  601. SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  602. assert(isOpenMPWorksharingDirective(StackElem.Directive));
  603. StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
  604. }
  605. llvm::iterator_range<DoacrossDependMapTy::const_iterator>
  606. getDoacrossDependClauses() const {
  607. assert(!isStackEmpty());
  608. const SharingMapTy &StackElem = Stack.back().first.back();
  609. if (isOpenMPWorksharingDirective(StackElem.Directive)) {
  610. const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
  611. return llvm::make_range(Ref.begin(), Ref.end());
  612. }
  613. return llvm::make_range(StackElem.DoacrossDepends.end(),
  614. StackElem.DoacrossDepends.end());
  615. }
  616. // Store types of classes which have been explicitly mapped
  617. void addMappedClassesQualTypes(QualType QT) {
  618. SharingMapTy &StackElem = Stack.back().first.back();
  619. StackElem.MappedClassesQualTypes.insert(QT);
  620. }
  621. // Return set of mapped classes types
  622. bool isClassPreviouslyMapped(QualType QT) const {
  623. const SharingMapTy &StackElem = Stack.back().first.back();
  624. return StackElem.MappedClassesQualTypes.count(QT) != 0;
  625. }
  626. };
  627. bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  628. return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
  629. }
  630. bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  631. return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || DKind == OMPD_unknown;
  632. }
  633. } // namespace
  634. static const Expr *getExprAsWritten(const Expr *E) {
  635. if (const auto *FE = dyn_cast<FullExpr>(E))
  636. E = FE->getSubExpr();
  637. if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  638. E = MTE->GetTemporaryExpr();
  639. while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  640. E = Binder->getSubExpr();
  641. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  642. E = ICE->getSubExprAsWritten();
  643. return E->IgnoreParens();
  644. }
  645. static Expr *getExprAsWritten(Expr *E) {
  646. return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
  647. }
  648. static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
  649. if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
  650. if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  651. D = ME->getMemberDecl();
  652. const auto *VD = dyn_cast<VarDecl>(D);
  653. const auto *FD = dyn_cast<FieldDecl>(D);
  654. if (VD != nullptr) {
  655. VD = VD->getCanonicalDecl();
  656. D = VD;
  657. } else {
  658. assert(FD);
  659. FD = FD->getCanonicalDecl();
  660. D = FD;
  661. }
  662. return D;
  663. }
  664. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  665. return const_cast<ValueDecl *>(
  666. getCanonicalDecl(const_cast<const ValueDecl *>(D)));
  667. }
  668. DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
  669. ValueDecl *D) const {
  670. D = getCanonicalDecl(D);
  671. auto *VD = dyn_cast<VarDecl>(D);
  672. const auto *FD = dyn_cast<FieldDecl>(D);
  673. DSAVarData DVar;
  674. if (isStackEmpty() || Iter == Stack.back().first.rend()) {
  675. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  676. // in a region but not in construct]
  677. // File-scope or namespace-scope variables referenced in called routines
  678. // in the region are shared unless they appear in a threadprivate
  679. // directive.
  680. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
  681. DVar.CKind = OMPC_shared;
  682. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  683. // in a region but not in construct]
  684. // Variables with static storage duration that are declared in called
  685. // routines in the region are shared.
  686. if (VD && VD->hasGlobalStorage())
  687. DVar.CKind = OMPC_shared;
  688. // Non-static data members are shared by default.
  689. if (FD)
  690. DVar.CKind = OMPC_shared;
  691. return DVar;
  692. }
  693. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  694. // in a Construct, C/C++, predetermined, p.1]
  695. // Variables with automatic storage duration that are declared in a scope
  696. // inside the construct are private.
  697. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  698. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  699. DVar.CKind = OMPC_private;
  700. return DVar;
  701. }
  702. DVar.DKind = Iter->Directive;
  703. // Explicitly specified attributes and local variables with predetermined
  704. // attributes.
  705. if (Iter->SharingMap.count(D)) {
  706. const DSAInfo &Data = Iter->SharingMap.lookup(D);
  707. DVar.RefExpr = Data.RefExpr.getPointer();
  708. DVar.PrivateCopy = Data.PrivateCopy;
  709. DVar.CKind = Data.Attributes;
  710. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  711. return DVar;
  712. }
  713. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  714. // in a Construct, C/C++, implicitly determined, p.1]
  715. // In a parallel or task construct, the data-sharing attributes of these
  716. // variables are determined by the default clause, if present.
  717. switch (Iter->DefaultAttr) {
  718. case DSA_shared:
  719. DVar.CKind = OMPC_shared;
  720. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  721. return DVar;
  722. case DSA_none:
  723. return DVar;
  724. case DSA_unspecified:
  725. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  726. // in a Construct, implicitly determined, p.2]
  727. // In a parallel construct, if no default clause is present, these
  728. // variables are shared.
  729. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  730. if (isOpenMPParallelDirective(DVar.DKind) ||
  731. isOpenMPTeamsDirective(DVar.DKind)) {
  732. DVar.CKind = OMPC_shared;
  733. return DVar;
  734. }
  735. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  736. // in a Construct, implicitly determined, p.4]
  737. // In a task construct, if no default clause is present, a variable that in
  738. // the enclosing context is determined to be shared by all implicit tasks
  739. // bound to the current team is shared.
  740. if (isOpenMPTaskingDirective(DVar.DKind)) {
  741. DSAVarData DVarTemp;
  742. iterator I = Iter, E = Stack.back().first.rend();
  743. do {
  744. ++I;
  745. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  746. // Referenced in a Construct, implicitly determined, p.6]
  747. // In a task construct, if no default clause is present, a variable
  748. // whose data-sharing attribute is not determined by the rules above is
  749. // firstprivate.
  750. DVarTemp = getDSA(I, D);
  751. if (DVarTemp.CKind != OMPC_shared) {
  752. DVar.RefExpr = nullptr;
  753. DVar.CKind = OMPC_firstprivate;
  754. return DVar;
  755. }
  756. } while (I != E && !isImplicitTaskingRegion(I->Directive));
  757. DVar.CKind =
  758. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  759. return DVar;
  760. }
  761. }
  762. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  763. // in a Construct, implicitly determined, p.3]
  764. // For constructs other than task, if no default clause is present, these
  765. // variables inherit their data-sharing attributes from the enclosing
  766. // context.
  767. return getDSA(++Iter, D);
  768. }
  769. const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
  770. const Expr *NewDE) {
  771. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  772. D = getCanonicalDecl(D);
  773. SharingMapTy &StackElem = Stack.back().first.back();
  774. auto It = StackElem.AlignedMap.find(D);
  775. if (It == StackElem.AlignedMap.end()) {
  776. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  777. StackElem.AlignedMap[D] = NewDE;
  778. return nullptr;
  779. }
  780. assert(It->second && "Unexpected nullptr expr in the aligned map");
  781. return It->second;
  782. }
  783. void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
  784. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  785. D = getCanonicalDecl(D);
  786. SharingMapTy &StackElem = Stack.back().first.back();
  787. StackElem.LCVMap.try_emplace(
  788. D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
  789. }
  790. const DSAStackTy::LCDeclInfo
  791. DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
  792. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  793. D = getCanonicalDecl(D);
  794. const SharingMapTy &StackElem = Stack.back().first.back();
  795. auto It = StackElem.LCVMap.find(D);
  796. if (It != StackElem.LCVMap.end())
  797. return It->second;
  798. return {0, nullptr};
  799. }
  800. const DSAStackTy::LCDeclInfo
  801. DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
  802. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  803. "Data-sharing attributes stack is empty");
  804. D = getCanonicalDecl(D);
  805. const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  806. auto It = StackElem.LCVMap.find(D);
  807. if (It != StackElem.LCVMap.end())
  808. return It->second;
  809. return {0, nullptr};
  810. }
  811. const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
  812. assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
  813. "Data-sharing attributes stack is empty");
  814. const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
  815. if (StackElem.LCVMap.size() < I)
  816. return nullptr;
  817. for (const auto &Pair : StackElem.LCVMap)
  818. if (Pair.second.first == I)
  819. return Pair.first;
  820. return nullptr;
  821. }
  822. void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  823. DeclRefExpr *PrivateCopy) {
  824. D = getCanonicalDecl(D);
  825. if (A == OMPC_threadprivate) {
  826. DSAInfo &Data = Threadprivates[D];
  827. Data.Attributes = A;
  828. Data.RefExpr.setPointer(E);
  829. Data.PrivateCopy = nullptr;
  830. } else {
  831. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  832. DSAInfo &Data = Stack.back().first.back().SharingMap[D];
  833. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  834. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  835. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  836. (isLoopControlVariable(D).first && A == OMPC_private));
  837. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  838. Data.RefExpr.setInt(/*IntVal=*/true);
  839. return;
  840. }
  841. const bool IsLastprivate =
  842. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  843. Data.Attributes = A;
  844. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  845. Data.PrivateCopy = PrivateCopy;
  846. if (PrivateCopy) {
  847. DSAInfo &Data =
  848. Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
  849. Data.Attributes = A;
  850. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  851. Data.PrivateCopy = nullptr;
  852. }
  853. }
  854. }
  855. /// Build a variable declaration for OpenMP loop iteration variable.
  856. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  857. StringRef Name, const AttrVec *Attrs = nullptr,
  858. DeclRefExpr *OrigRef = nullptr) {
  859. DeclContext *DC = SemaRef.CurContext;
  860. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  861. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  862. auto *Decl =
  863. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  864. if (Attrs) {
  865. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  866. I != E; ++I)
  867. Decl->addAttr(*I);
  868. }
  869. Decl->setImplicit();
  870. if (OrigRef) {
  871. Decl->addAttr(
  872. OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
  873. }
  874. return Decl;
  875. }
  876. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  877. SourceLocation Loc,
  878. bool RefersToCapture = false) {
  879. D->setReferenced();
  880. D->markUsed(S.Context);
  881. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  882. SourceLocation(), D, RefersToCapture, Loc, Ty,
  883. VK_LValue);
  884. }
  885. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  886. BinaryOperatorKind BOK) {
  887. D = getCanonicalDecl(D);
  888. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  889. assert(
  890. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  891. "Additional reduction info may be specified only for reduction items.");
  892. ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
  893. assert(ReductionData.ReductionRange.isInvalid() &&
  894. Stack.back().first.back().Directive == OMPD_taskgroup &&
  895. "Additional reduction info may be specified only once for reduction "
  896. "items.");
  897. ReductionData.set(BOK, SR);
  898. Expr *&TaskgroupReductionRef =
  899. Stack.back().first.back().TaskgroupReductionRef;
  900. if (!TaskgroupReductionRef) {
  901. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  902. SemaRef.Context.VoidPtrTy, ".task_red.");
  903. TaskgroupReductionRef =
  904. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  905. }
  906. }
  907. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  908. const Expr *ReductionRef) {
  909. D = getCanonicalDecl(D);
  910. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  911. assert(
  912. Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
  913. "Additional reduction info may be specified only for reduction items.");
  914. ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
  915. assert(ReductionData.ReductionRange.isInvalid() &&
  916. Stack.back().first.back().Directive == OMPD_taskgroup &&
  917. "Additional reduction info may be specified only once for reduction "
  918. "items.");
  919. ReductionData.set(ReductionRef, SR);
  920. Expr *&TaskgroupReductionRef =
  921. Stack.back().first.back().TaskgroupReductionRef;
  922. if (!TaskgroupReductionRef) {
  923. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  924. SemaRef.Context.VoidPtrTy, ".task_red.");
  925. TaskgroupReductionRef =
  926. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  927. }
  928. }
  929. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  930. const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
  931. Expr *&TaskgroupDescriptor) const {
  932. D = getCanonicalDecl(D);
  933. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  934. if (Stack.back().first.empty())
  935. return DSAVarData();
  936. for (iterator I = std::next(Stack.back().first.rbegin(), 1),
  937. E = Stack.back().first.rend();
  938. I != E; std::advance(I, 1)) {
  939. const DSAInfo &Data = I->SharingMap.lookup(D);
  940. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  941. continue;
  942. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  943. if (!ReductionData.ReductionOp ||
  944. ReductionData.ReductionOp.is<const Expr *>())
  945. return DSAVarData();
  946. SR = ReductionData.ReductionRange;
  947. BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
  948. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  949. "expression for the descriptor is not "
  950. "set.");
  951. TaskgroupDescriptor = I->TaskgroupReductionRef;
  952. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  953. Data.PrivateCopy, I->DefaultAttrLoc);
  954. }
  955. return DSAVarData();
  956. }
  957. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  958. const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
  959. Expr *&TaskgroupDescriptor) const {
  960. D = getCanonicalDecl(D);
  961. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  962. if (Stack.back().first.empty())
  963. return DSAVarData();
  964. for (iterator I = std::next(Stack.back().first.rbegin(), 1),
  965. E = Stack.back().first.rend();
  966. I != E; std::advance(I, 1)) {
  967. const DSAInfo &Data = I->SharingMap.lookup(D);
  968. if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
  969. continue;
  970. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  971. if (!ReductionData.ReductionOp ||
  972. !ReductionData.ReductionOp.is<const Expr *>())
  973. return DSAVarData();
  974. SR = ReductionData.ReductionRange;
  975. ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
  976. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  977. "expression for the descriptor is not "
  978. "set.");
  979. TaskgroupDescriptor = I->TaskgroupReductionRef;
  980. return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
  981. Data.PrivateCopy, I->DefaultAttrLoc);
  982. }
  983. return DSAVarData();
  984. }
  985. bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
  986. D = D->getCanonicalDecl();
  987. if (!isStackEmpty()) {
  988. iterator I = Iter, E = Stack.back().first.rend();
  989. Scope *TopScope = nullptr;
  990. while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) &&
  991. !isOpenMPTargetExecutionDirective(I->Directive))
  992. ++I;
  993. if (I == E)
  994. return false;
  995. TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  996. Scope *CurScope = getCurScope();
  997. while (CurScope != TopScope && !CurScope->isDeclScope(D))
  998. CurScope = CurScope->getParent();
  999. return CurScope != TopScope;
  1000. }
  1001. return false;
  1002. }
  1003. static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
  1004. bool AcceptIfMutable = true,
  1005. bool *IsClassType = nullptr) {
  1006. ASTContext &Context = SemaRef.getASTContext();
  1007. Type = Type.getNonReferenceType().getCanonicalType();
  1008. bool IsConstant = Type.isConstant(Context);
  1009. Type = Context.getBaseElementType(Type);
  1010. const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
  1011. ? Type->getAsCXXRecordDecl()
  1012. : nullptr;
  1013. if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  1014. if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
  1015. RD = CTD->getTemplatedDecl();
  1016. if (IsClassType)
  1017. *IsClassType = RD;
  1018. return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
  1019. RD->hasDefinition() && RD->hasMutableFields());
  1020. }
  1021. static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
  1022. QualType Type, OpenMPClauseKind CKind,
  1023. SourceLocation ELoc,
  1024. bool AcceptIfMutable = true,
  1025. bool ListItemNotVar = false) {
  1026. ASTContext &Context = SemaRef.getASTContext();
  1027. bool IsClassType;
  1028. if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
  1029. unsigned Diag = ListItemNotVar
  1030. ? diag::err_omp_const_list_item
  1031. : IsClassType ? diag::err_omp_const_not_mutable_variable
  1032. : diag::err_omp_const_variable;
  1033. SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
  1034. if (!ListItemNotVar && D) {
  1035. const VarDecl *VD = dyn_cast<VarDecl>(D);
  1036. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  1037. VarDecl::DeclarationOnly;
  1038. SemaRef.Diag(D->getLocation(),
  1039. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1040. << D;
  1041. }
  1042. return true;
  1043. }
  1044. return false;
  1045. }
  1046. const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
  1047. bool FromParent) {
  1048. D = getCanonicalDecl(D);
  1049. DSAVarData DVar;
  1050. auto *VD = dyn_cast<VarDecl>(D);
  1051. auto TI = Threadprivates.find(D);
  1052. if (TI != Threadprivates.end()) {
  1053. DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
  1054. DVar.CKind = OMPC_threadprivate;
  1055. return DVar;
  1056. }
  1057. if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  1058. DVar.RefExpr = buildDeclRefExpr(
  1059. SemaRef, VD, D->getType().getNonReferenceType(),
  1060. VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
  1061. DVar.CKind = OMPC_threadprivate;
  1062. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1063. return DVar;
  1064. }
  1065. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1066. // in a Construct, C/C++, predetermined, p.1]
  1067. // Variables appearing in threadprivate directives are threadprivate.
  1068. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  1069. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1070. SemaRef.getLangOpts().OpenMPUseTLS &&
  1071. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  1072. (VD && VD->getStorageClass() == SC_Register &&
  1073. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  1074. DVar.RefExpr = buildDeclRefExpr(
  1075. SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
  1076. DVar.CKind = OMPC_threadprivate;
  1077. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1078. return DVar;
  1079. }
  1080. if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
  1081. VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
  1082. !isLoopControlVariable(D).first) {
  1083. iterator IterTarget =
  1084. std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
  1085. [](const SharingMapTy &Data) {
  1086. return isOpenMPTargetExecutionDirective(Data.Directive);
  1087. });
  1088. if (IterTarget != Stack.back().first.rend()) {
  1089. iterator ParentIterTarget = std::next(IterTarget, 1);
  1090. for (iterator Iter = Stack.back().first.rbegin();
  1091. Iter != ParentIterTarget; std::advance(Iter, 1)) {
  1092. if (isOpenMPLocal(VD, Iter)) {
  1093. DVar.RefExpr =
  1094. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1095. D->getLocation());
  1096. DVar.CKind = OMPC_threadprivate;
  1097. return DVar;
  1098. }
  1099. }
  1100. if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
  1101. auto DSAIter = IterTarget->SharingMap.find(D);
  1102. if (DSAIter != IterTarget->SharingMap.end() &&
  1103. isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
  1104. DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
  1105. DVar.CKind = OMPC_threadprivate;
  1106. return DVar;
  1107. }
  1108. iterator End = Stack.back().first.rend();
  1109. if (!SemaRef.isOpenMPCapturedByRef(
  1110. D, std::distance(ParentIterTarget, End))) {
  1111. DVar.RefExpr =
  1112. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1113. IterTarget->ConstructLoc);
  1114. DVar.CKind = OMPC_threadprivate;
  1115. return DVar;
  1116. }
  1117. }
  1118. }
  1119. }
  1120. if (isStackEmpty())
  1121. // Not in OpenMP execution region and top scope was already checked.
  1122. return DVar;
  1123. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1124. // in a Construct, C/C++, predetermined, p.4]
  1125. // Static data members are shared.
  1126. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1127. // in a Construct, C/C++, predetermined, p.7]
  1128. // Variables with static storage duration that are declared in a scope
  1129. // inside the construct are shared.
  1130. auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
  1131. if (VD && VD->isStaticDataMember()) {
  1132. DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
  1133. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  1134. return DVar;
  1135. DVar.CKind = OMPC_shared;
  1136. return DVar;
  1137. }
  1138. // The predetermined shared attribute for const-qualified types having no
  1139. // mutable members was removed after OpenMP 3.1.
  1140. if (SemaRef.LangOpts.OpenMP <= 31) {
  1141. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1142. // in a Construct, C/C++, predetermined, p.6]
  1143. // Variables with const qualified type having no mutable member are
  1144. // shared.
  1145. if (isConstNotMutableType(SemaRef, D->getType())) {
  1146. // Variables with const-qualified type having no mutable member may be
  1147. // listed in a firstprivate clause, even if they are static data members.
  1148. DSAVarData DVarTemp = hasInnermostDSA(
  1149. D,
  1150. [](OpenMPClauseKind C) {
  1151. return C == OMPC_firstprivate || C == OMPC_shared;
  1152. },
  1153. MatchesAlways, FromParent);
  1154. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  1155. return DVarTemp;
  1156. DVar.CKind = OMPC_shared;
  1157. return DVar;
  1158. }
  1159. }
  1160. // Explicitly specified attributes and local variables with predetermined
  1161. // attributes.
  1162. iterator I = Stack.back().first.rbegin();
  1163. iterator EndI = Stack.back().first.rend();
  1164. if (FromParent && I != EndI)
  1165. std::advance(I, 1);
  1166. auto It = I->SharingMap.find(D);
  1167. if (It != I->SharingMap.end()) {
  1168. const DSAInfo &Data = It->getSecond();
  1169. DVar.RefExpr = Data.RefExpr.getPointer();
  1170. DVar.PrivateCopy = Data.PrivateCopy;
  1171. DVar.CKind = Data.Attributes;
  1172. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1173. DVar.DKind = I->Directive;
  1174. }
  1175. return DVar;
  1176. }
  1177. const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  1178. bool FromParent) const {
  1179. if (isStackEmpty()) {
  1180. iterator I;
  1181. return getDSA(I, D);
  1182. }
  1183. D = getCanonicalDecl(D);
  1184. iterator StartI = Stack.back().first.rbegin();
  1185. iterator EndI = Stack.back().first.rend();
  1186. if (FromParent && StartI != EndI)
  1187. std::advance(StartI, 1);
  1188. return getDSA(StartI, D);
  1189. }
  1190. const DSAStackTy::DSAVarData
  1191. DSAStackTy::hasDSA(ValueDecl *D,
  1192. const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1193. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1194. bool FromParent) const {
  1195. if (isStackEmpty())
  1196. return {};
  1197. D = getCanonicalDecl(D);
  1198. iterator I = Stack.back().first.rbegin();
  1199. iterator EndI = Stack.back().first.rend();
  1200. if (FromParent && I != EndI)
  1201. std::advance(I, 1);
  1202. for (; I != EndI; std::advance(I, 1)) {
  1203. if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive))
  1204. continue;
  1205. iterator NewI = I;
  1206. DSAVarData DVar = getDSA(NewI, D);
  1207. if (I == NewI && CPred(DVar.CKind))
  1208. return DVar;
  1209. }
  1210. return {};
  1211. }
  1212. const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  1213. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1214. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1215. bool FromParent) const {
  1216. if (isStackEmpty())
  1217. return {};
  1218. D = getCanonicalDecl(D);
  1219. iterator StartI = Stack.back().first.rbegin();
  1220. iterator EndI = Stack.back().first.rend();
  1221. if (FromParent && StartI != EndI)
  1222. std::advance(StartI, 1);
  1223. if (StartI == EndI || !DPred(StartI->Directive))
  1224. return {};
  1225. iterator NewI = StartI;
  1226. DSAVarData DVar = getDSA(NewI, D);
  1227. return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
  1228. }
  1229. bool DSAStackTy::hasExplicitDSA(
  1230. const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
  1231. unsigned Level, bool NotLastprivate) const {
  1232. if (isStackEmpty())
  1233. return false;
  1234. D = getCanonicalDecl(D);
  1235. auto StartI = Stack.back().first.begin();
  1236. auto EndI = Stack.back().first.end();
  1237. if (std::distance(StartI, EndI) <= (int)Level)
  1238. return false;
  1239. std::advance(StartI, Level);
  1240. auto I = StartI->SharingMap.find(D);
  1241. if ((I != StartI->SharingMap.end()) &&
  1242. I->getSecond().RefExpr.getPointer() &&
  1243. CPred(I->getSecond().Attributes) &&
  1244. (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
  1245. return true;
  1246. // Check predetermined rules for the loop control variables.
  1247. auto LI = StartI->LCVMap.find(D);
  1248. if (LI != StartI->LCVMap.end())
  1249. return CPred(OMPC_private);
  1250. return false;
  1251. }
  1252. bool DSAStackTy::hasExplicitDirective(
  1253. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1254. unsigned Level) const {
  1255. if (isStackEmpty())
  1256. return false;
  1257. auto StartI = Stack.back().first.begin();
  1258. auto EndI = Stack.back().first.end();
  1259. if (std::distance(StartI, EndI) <= (int)Level)
  1260. return false;
  1261. std::advance(StartI, Level);
  1262. return DPred(StartI->Directive);
  1263. }
  1264. bool DSAStackTy::hasDirective(
  1265. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1266. const DeclarationNameInfo &, SourceLocation)>
  1267. DPred,
  1268. bool FromParent) const {
  1269. // We look only in the enclosing region.
  1270. if (isStackEmpty())
  1271. return false;
  1272. auto StartI = std::next(Stack.back().first.rbegin());
  1273. auto EndI = Stack.back().first.rend();
  1274. if (FromParent && StartI != EndI)
  1275. StartI = std::next(StartI);
  1276. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  1277. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1278. return true;
  1279. }
  1280. return false;
  1281. }
  1282. void Sema::InitDataSharingAttributesStack() {
  1283. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1284. }
  1285. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1286. void Sema::pushOpenMPFunctionRegion() {
  1287. DSAStack->pushFunction();
  1288. }
  1289. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1290. DSAStack->popFunction(OldFSI);
  1291. }
  1292. static bool isOpenMPDeviceDelayedContext(Sema &S) {
  1293. assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  1294. "Expected OpenMP device compilation.");
  1295. return !S.isInOpenMPTargetExecutionDirective() &&
  1296. !S.isInOpenMPDeclareTargetContext();
  1297. }
  1298. /// Do we know that we will eventually codegen the given function?
  1299. static bool isKnownEmitted(Sema &S, FunctionDecl *FD) {
  1300. assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  1301. "Expected OpenMP device compilation.");
  1302. // Templates are emitted when they're instantiated.
  1303. if (FD->isDependentContext())
  1304. return false;
  1305. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  1306. FD->getCanonicalDecl()))
  1307. return true;
  1308. // Otherwise, the function is known-emitted if it's in our set of
  1309. // known-emitted functions.
  1310. return S.DeviceKnownEmittedFns.count(FD) > 0;
  1311. }
  1312. Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
  1313. unsigned DiagID) {
  1314. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1315. "Expected OpenMP device compilation.");
  1316. return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) &&
  1317. !isKnownEmitted(*this, getCurFunctionDecl()))
  1318. ? DeviceDiagBuilder::K_Deferred
  1319. : DeviceDiagBuilder::K_Immediate,
  1320. Loc, DiagID, getCurFunctionDecl(), *this);
  1321. }
  1322. void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) {
  1323. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1324. "Expected OpenMP device compilation.");
  1325. assert(Callee && "Callee may not be null.");
  1326. FunctionDecl *Caller = getCurFunctionDecl();
  1327. // If the caller is known-emitted, mark the callee as known-emitted.
  1328. // Otherwise, mark the call in our call graph so we can traverse it later.
  1329. if (!isOpenMPDeviceDelayedContext(*this) ||
  1330. (Caller && isKnownEmitted(*this, Caller)))
  1331. markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted);
  1332. else if (Caller)
  1333. DeviceCallGraph[Caller].insert({Callee, Loc});
  1334. }
  1335. bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
  1336. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1337. ASTContext &Ctx = getASTContext();
  1338. bool IsByRef = true;
  1339. // Find the directive that is associated with the provided scope.
  1340. D = cast<ValueDecl>(D->getCanonicalDecl());
  1341. QualType Ty = D->getType();
  1342. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1343. // This table summarizes how a given variable should be passed to the device
  1344. // given its type and the clauses where it appears. This table is based on
  1345. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1346. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1347. //
  1348. // =========================================================================
  1349. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1350. // | |(tofrom:scalar)| | pvt | | | |
  1351. // =========================================================================
  1352. // | scl | | | | - | | bycopy|
  1353. // | scl | | - | x | - | - | bycopy|
  1354. // | scl | | x | - | - | - | null |
  1355. // | scl | x | | | - | | byref |
  1356. // | scl | x | - | x | - | - | bycopy|
  1357. // | scl | x | x | - | - | - | null |
  1358. // | scl | | - | - | - | x | byref |
  1359. // | scl | x | - | - | - | x | byref |
  1360. //
  1361. // | agg | n.a. | | | - | | byref |
  1362. // | agg | n.a. | - | x | - | - | byref |
  1363. // | agg | n.a. | x | - | - | - | null |
  1364. // | agg | n.a. | - | - | - | x | byref |
  1365. // | agg | n.a. | - | - | - | x[] | byref |
  1366. //
  1367. // | ptr | n.a. | | | - | | bycopy|
  1368. // | ptr | n.a. | - | x | - | - | bycopy|
  1369. // | ptr | n.a. | x | - | - | - | null |
  1370. // | ptr | n.a. | - | - | - | x | byref |
  1371. // | ptr | n.a. | - | - | - | x[] | bycopy|
  1372. // | ptr | n.a. | - | - | x | | bycopy|
  1373. // | ptr | n.a. | - | - | x | x | bycopy|
  1374. // | ptr | n.a. | - | - | x | x[] | bycopy|
  1375. // =========================================================================
  1376. // Legend:
  1377. // scl - scalar
  1378. // ptr - pointer
  1379. // agg - aggregate
  1380. // x - applies
  1381. // - - invalid in this combination
  1382. // [] - mapped with an array section
  1383. // byref - should be mapped by reference
  1384. // byval - should be mapped by value
  1385. // null - initialize a local variable to null on the device
  1386. //
  1387. // Observations:
  1388. // - All scalar declarations that show up in a map clause have to be passed
  1389. // by reference, because they may have been mapped in the enclosing data
  1390. // environment.
  1391. // - If the scalar value does not fit the size of uintptr, it has to be
  1392. // passed by reference, regardless the result in the table above.
  1393. // - For pointers mapped by value that have either an implicit map or an
  1394. // array section, the runtime library may pass the NULL value to the
  1395. // device instead of the value passed to it by the compiler.
  1396. if (Ty->isReferenceType())
  1397. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  1398. // Locate map clauses and see if the variable being captured is referred to
  1399. // in any of those clauses. Here we only care about variables, not fields,
  1400. // because fields are part of aggregates.
  1401. bool IsVariableUsedInMapClause = false;
  1402. bool IsVariableAssociatedWithSection = false;
  1403. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1404. D, Level,
  1405. [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
  1406. OMPClauseMappableExprCommon::MappableExprComponentListRef
  1407. MapExprComponents,
  1408. OpenMPClauseKind WhereFoundClauseKind) {
  1409. // Only the map clause information influences how a variable is
  1410. // captured. E.g. is_device_ptr does not require changing the default
  1411. // behavior.
  1412. if (WhereFoundClauseKind != OMPC_map)
  1413. return false;
  1414. auto EI = MapExprComponents.rbegin();
  1415. auto EE = MapExprComponents.rend();
  1416. assert(EI != EE && "Invalid map expression!");
  1417. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  1418. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  1419. ++EI;
  1420. if (EI == EE)
  1421. return false;
  1422. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  1423. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  1424. isa<MemberExpr>(EI->getAssociatedExpression())) {
  1425. IsVariableAssociatedWithSection = true;
  1426. // There is nothing more we need to know about this variable.
  1427. return true;
  1428. }
  1429. // Keep looking for more map info.
  1430. return false;
  1431. });
  1432. if (IsVariableUsedInMapClause) {
  1433. // If variable is identified in a map clause it is always captured by
  1434. // reference except if it is a pointer that is dereferenced somehow.
  1435. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  1436. } else {
  1437. // By default, all the data that has a scalar type is mapped by copy
  1438. // (except for reduction variables).
  1439. IsByRef =
  1440. (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1441. !Ty->isAnyPointerType()) ||
  1442. !Ty->isScalarType() ||
  1443. DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
  1444. DSAStack->hasExplicitDSA(
  1445. D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
  1446. }
  1447. }
  1448. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  1449. IsByRef =
  1450. ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  1451. !Ty->isAnyPointerType()) ||
  1452. !DSAStack->hasExplicitDSA(
  1453. D,
  1454. [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
  1455. Level, /*NotLastprivate=*/true)) &&
  1456. // If the variable is artificial and must be captured by value - try to
  1457. // capture by value.
  1458. !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
  1459. !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
  1460. }
  1461. // When passing data by copy, we need to make sure it fits the uintptr size
  1462. // and alignment, because the runtime library only deals with uintptr types.
  1463. // If it does not fit the uintptr size, we need to pass the data by reference
  1464. // instead.
  1465. if (!IsByRef &&
  1466. (Ctx.getTypeSizeInChars(Ty) >
  1467. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  1468. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  1469. IsByRef = true;
  1470. }
  1471. return IsByRef;
  1472. }
  1473. unsigned Sema::getOpenMPNestingLevel() const {
  1474. assert(getLangOpts().OpenMP);
  1475. return DSAStack->getNestingLevel();
  1476. }
  1477. bool Sema::isInOpenMPTargetExecutionDirective() const {
  1478. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  1479. !DSAStack->isClauseParsingMode()) ||
  1480. DSAStack->hasDirective(
  1481. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  1482. SourceLocation) -> bool {
  1483. return isOpenMPTargetExecutionDirective(K);
  1484. },
  1485. false);
  1486. }
  1487. VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
  1488. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1489. D = getCanonicalDecl(D);
  1490. // If we are attempting to capture a global variable in a directive with
  1491. // 'target' we return true so that this global is also mapped to the device.
  1492. //
  1493. auto *VD = dyn_cast<VarDecl>(D);
  1494. if (VD && !VD->hasLocalStorage()) {
  1495. if (isInOpenMPDeclareTargetContext() &&
  1496. (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
  1497. // Try to mark variable as declare target if it is used in capturing
  1498. // regions.
  1499. if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1500. checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
  1501. return nullptr;
  1502. } else if (isInOpenMPTargetExecutionDirective()) {
  1503. // If the declaration is enclosed in a 'declare target' directive,
  1504. // then it should not be captured.
  1505. //
  1506. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  1507. return nullptr;
  1508. return VD;
  1509. }
  1510. }
  1511. // Capture variables captured by reference in lambdas for target-based
  1512. // directives.
  1513. if (VD && !DSAStack->isClauseParsingMode()) {
  1514. if (const auto *RD = VD->getType()
  1515. .getCanonicalType()
  1516. .getNonReferenceType()
  1517. ->getAsCXXRecordDecl()) {
  1518. bool SavedForceCaptureByReferenceInTargetExecutable =
  1519. DSAStack->isForceCaptureByReferenceInTargetExecutable();
  1520. DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
  1521. if (RD->isLambda()) {
  1522. llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
  1523. FieldDecl *ThisCapture;
  1524. RD->getCaptureFields(Captures, ThisCapture);
  1525. for (const LambdaCapture &LC : RD->captures()) {
  1526. if (LC.getCaptureKind() == LCK_ByRef) {
  1527. VarDecl *VD = LC.getCapturedVar();
  1528. DeclContext *VDC = VD->getDeclContext();
  1529. if (!VDC->Encloses(CurContext))
  1530. continue;
  1531. DSAStackTy::DSAVarData DVarPrivate =
  1532. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  1533. // Do not capture already captured variables.
  1534. if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
  1535. DVarPrivate.CKind == OMPC_unknown &&
  1536. !DSAStack->checkMappableExprComponentListsForDecl(
  1537. D, /*CurrentRegionOnly=*/true,
  1538. [](OMPClauseMappableExprCommon::
  1539. MappableExprComponentListRef,
  1540. OpenMPClauseKind) { return true; }))
  1541. MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
  1542. } else if (LC.getCaptureKind() == LCK_This) {
  1543. QualType ThisTy = getCurrentThisType();
  1544. if (!ThisTy.isNull() &&
  1545. Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
  1546. CheckCXXThisCapture(LC.getLocation());
  1547. }
  1548. }
  1549. }
  1550. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  1551. SavedForceCaptureByReferenceInTargetExecutable);
  1552. }
  1553. }
  1554. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  1555. (!DSAStack->isClauseParsingMode() ||
  1556. DSAStack->getParentDirective() != OMPD_unknown)) {
  1557. auto &&Info = DSAStack->isLoopControlVariable(D);
  1558. if (Info.first ||
  1559. (VD && VD->hasLocalStorage() &&
  1560. isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
  1561. (VD && DSAStack->isForceVarCapturing()))
  1562. return VD ? VD : Info.second;
  1563. DSAStackTy::DSAVarData DVarPrivate =
  1564. DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  1565. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  1566. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1567. DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
  1568. [](OpenMPDirectiveKind) { return true; },
  1569. DSAStack->isClauseParsingMode());
  1570. if (DVarPrivate.CKind != OMPC_unknown)
  1571. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  1572. }
  1573. return nullptr;
  1574. }
  1575. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  1576. unsigned Level) const {
  1577. SmallVector<OpenMPDirectiveKind, 4> Regions;
  1578. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  1579. FunctionScopesIndex -= Regions.size();
  1580. }
  1581. void Sema::startOpenMPLoop() {
  1582. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  1583. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
  1584. DSAStack->loopInit();
  1585. }
  1586. bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
  1587. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1588. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  1589. if (DSAStack->getAssociatedLoops() > 0 &&
  1590. !DSAStack->isLoopStarted()) {
  1591. DSAStack->resetPossibleLoopCounter(D);
  1592. DSAStack->loopStart();
  1593. return true;
  1594. }
  1595. if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
  1596. DSAStack->isLoopControlVariable(D).first) &&
  1597. !DSAStack->hasExplicitDSA(
  1598. D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
  1599. !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
  1600. return true;
  1601. }
  1602. return DSAStack->hasExplicitDSA(
  1603. D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
  1604. (DSAStack->isClauseParsingMode() &&
  1605. DSAStack->getClauseParsingMode() == OMPC_private) ||
  1606. // Consider taskgroup reduction descriptor variable a private to avoid
  1607. // possible capture in the region.
  1608. (DSAStack->hasExplicitDirective(
  1609. [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
  1610. Level) &&
  1611. DSAStack->isTaskgroupReductionRef(D, Level));
  1612. }
  1613. void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
  1614. unsigned Level) {
  1615. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1616. D = getCanonicalDecl(D);
  1617. OpenMPClauseKind OMPC = OMPC_unknown;
  1618. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  1619. const unsigned NewLevel = I - 1;
  1620. if (DSAStack->hasExplicitDSA(D,
  1621. [&OMPC](const OpenMPClauseKind K) {
  1622. if (isOpenMPPrivate(K)) {
  1623. OMPC = K;
  1624. return true;
  1625. }
  1626. return false;
  1627. },
  1628. NewLevel))
  1629. break;
  1630. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  1631. D, NewLevel,
  1632. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  1633. OpenMPClauseKind) { return true; })) {
  1634. OMPC = OMPC_map;
  1635. break;
  1636. }
  1637. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1638. NewLevel)) {
  1639. OMPC = OMPC_map;
  1640. if (D->getType()->isScalarType() &&
  1641. DSAStack->getDefaultDMAAtLevel(NewLevel) !=
  1642. DefaultMapAttributes::DMA_tofrom_scalar)
  1643. OMPC = OMPC_firstprivate;
  1644. break;
  1645. }
  1646. }
  1647. if (OMPC != OMPC_unknown)
  1648. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
  1649. }
  1650. bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
  1651. unsigned Level) const {
  1652. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1653. // Return true if the current level is no longer enclosed in a target region.
  1654. const auto *VD = dyn_cast<VarDecl>(D);
  1655. return VD && !VD->hasLocalStorage() &&
  1656. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  1657. Level);
  1658. }
  1659. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  1660. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  1661. const DeclarationNameInfo &DirName,
  1662. Scope *CurScope, SourceLocation Loc) {
  1663. DSAStack->push(DKind, DirName, CurScope, Loc);
  1664. PushExpressionEvaluationContext(
  1665. ExpressionEvaluationContext::PotentiallyEvaluated);
  1666. }
  1667. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  1668. DSAStack->setClauseParsingMode(K);
  1669. }
  1670. void Sema::EndOpenMPClause() {
  1671. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  1672. }
  1673. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  1674. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  1675. // A variable of class type (or array thereof) that appears in a lastprivate
  1676. // clause requires an accessible, unambiguous default constructor for the
  1677. // class type, unless the list item is also specified in a firstprivate
  1678. // clause.
  1679. if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  1680. for (OMPClause *C : D->clauses()) {
  1681. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  1682. SmallVector<Expr *, 8> PrivateCopies;
  1683. for (Expr *DE : Clause->varlists()) {
  1684. if (DE->isValueDependent() || DE->isTypeDependent()) {
  1685. PrivateCopies.push_back(nullptr);
  1686. continue;
  1687. }
  1688. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  1689. auto *VD = cast<VarDecl>(DRE->getDecl());
  1690. QualType Type = VD->getType().getNonReferenceType();
  1691. const DSAStackTy::DSAVarData DVar =
  1692. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  1693. if (DVar.CKind == OMPC_lastprivate) {
  1694. // Generate helper private variable and initialize it with the
  1695. // default value. The address of the original variable is replaced
  1696. // by the address of the new private variable in CodeGen. This new
  1697. // variable is not added to IdResolver, so the code in the OpenMP
  1698. // region uses original variable for proper diagnostics.
  1699. VarDecl *VDPrivate = buildVarDecl(
  1700. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  1701. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
  1702. ActOnUninitializedDecl(VDPrivate);
  1703. if (VDPrivate->isInvalidDecl())
  1704. continue;
  1705. PrivateCopies.push_back(buildDeclRefExpr(
  1706. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  1707. } else {
  1708. // The variable is also a firstprivate, so initialization sequence
  1709. // for private copy is generated already.
  1710. PrivateCopies.push_back(nullptr);
  1711. }
  1712. }
  1713. // Set initializers to private copies if no errors were found.
  1714. if (PrivateCopies.size() == Clause->varlist_size())
  1715. Clause->setPrivateCopies(PrivateCopies);
  1716. }
  1717. }
  1718. }
  1719. DSAStack->pop();
  1720. DiscardCleanupsInEvaluationContext();
  1721. PopExpressionEvaluationContext();
  1722. }
  1723. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  1724. Expr *NumIterations, Sema &SemaRef,
  1725. Scope *S, DSAStackTy *Stack);
  1726. namespace {
  1727. class VarDeclFilterCCC final : public CorrectionCandidateCallback {
  1728. private:
  1729. Sema &SemaRef;
  1730. public:
  1731. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1732. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1733. NamedDecl *ND = Candidate.getCorrectionDecl();
  1734. if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  1735. return VD->hasGlobalStorage() &&
  1736. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1737. SemaRef.getCurScope());
  1738. }
  1739. return false;
  1740. }
  1741. };
  1742. class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
  1743. private:
  1744. Sema &SemaRef;
  1745. public:
  1746. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  1747. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  1748. NamedDecl *ND = Candidate.getCorrectionDecl();
  1749. if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
  1750. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  1751. SemaRef.getCurScope());
  1752. }
  1753. return false;
  1754. }
  1755. };
  1756. } // namespace
  1757. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  1758. CXXScopeSpec &ScopeSpec,
  1759. const DeclarationNameInfo &Id) {
  1760. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  1761. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  1762. if (Lookup.isAmbiguous())
  1763. return ExprError();
  1764. VarDecl *VD;
  1765. if (!Lookup.isSingleResult()) {
  1766. if (TypoCorrection Corrected = CorrectTypo(
  1767. Id, LookupOrdinaryName, CurScope, nullptr,
  1768. llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
  1769. diagnoseTypo(Corrected,
  1770. PDiag(Lookup.empty()
  1771. ? diag::err_undeclared_var_use_suggest
  1772. : diag::err_omp_expected_var_arg_suggest)
  1773. << Id.getName());
  1774. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  1775. } else {
  1776. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  1777. : diag::err_omp_expected_var_arg)
  1778. << Id.getName();
  1779. return ExprError();
  1780. }
  1781. } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  1782. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  1783. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  1784. return ExprError();
  1785. }
  1786. Lookup.suppressDiagnostics();
  1787. // OpenMP [2.9.2, Syntax, C/C++]
  1788. // Variables must be file-scope, namespace-scope, or static block-scope.
  1789. if (!VD->hasGlobalStorage()) {
  1790. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  1791. << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
  1792. bool IsDecl =
  1793. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1794. Diag(VD->getLocation(),
  1795. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1796. << VD;
  1797. return ExprError();
  1798. }
  1799. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  1800. NamedDecl *ND = CanonicalVD;
  1801. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  1802. // A threadprivate directive for file-scope variables must appear outside
  1803. // any definition or declaration.
  1804. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  1805. !getCurLexicalContext()->isTranslationUnit()) {
  1806. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1807. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1808. bool IsDecl =
  1809. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1810. Diag(VD->getLocation(),
  1811. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1812. << VD;
  1813. return ExprError();
  1814. }
  1815. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  1816. // A threadprivate directive for static class member variables must appear
  1817. // in the class definition, in the same scope in which the member
  1818. // variables are declared.
  1819. if (CanonicalVD->isStaticDataMember() &&
  1820. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  1821. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1822. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1823. bool IsDecl =
  1824. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1825. Diag(VD->getLocation(),
  1826. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1827. << VD;
  1828. return ExprError();
  1829. }
  1830. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  1831. // A threadprivate directive for namespace-scope variables must appear
  1832. // outside any definition or declaration other than the namespace
  1833. // definition itself.
  1834. if (CanonicalVD->getDeclContext()->isNamespace() &&
  1835. (!getCurLexicalContext()->isFileContext() ||
  1836. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  1837. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1838. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1839. bool IsDecl =
  1840. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1841. Diag(VD->getLocation(),
  1842. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1843. << VD;
  1844. return ExprError();
  1845. }
  1846. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  1847. // A threadprivate directive for static block-scope variables must appear
  1848. // in the scope of the variable and not in a nested scope.
  1849. if (CanonicalVD->isStaticLocal() && CurScope &&
  1850. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  1851. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1852. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1853. bool IsDecl =
  1854. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1855. Diag(VD->getLocation(),
  1856. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1857. << VD;
  1858. return ExprError();
  1859. }
  1860. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  1861. // A threadprivate directive must lexically precede all references to any
  1862. // of the variables in its list.
  1863. if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
  1864. Diag(Id.getLoc(), diag::err_omp_var_used)
  1865. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1866. return ExprError();
  1867. }
  1868. QualType ExprType = VD->getType().getNonReferenceType();
  1869. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  1870. SourceLocation(), VD,
  1871. /*RefersToEnclosingVariableOrCapture=*/false,
  1872. Id.getLoc(), ExprType, VK_LValue);
  1873. }
  1874. Sema::DeclGroupPtrTy
  1875. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  1876. ArrayRef<Expr *> VarList) {
  1877. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  1878. CurContext->addDecl(D);
  1879. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1880. }
  1881. return nullptr;
  1882. }
  1883. namespace {
  1884. class LocalVarRefChecker final
  1885. : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  1886. Sema &SemaRef;
  1887. public:
  1888. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  1889. if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1890. if (VD->hasLocalStorage()) {
  1891. SemaRef.Diag(E->getBeginLoc(),
  1892. diag::err_omp_local_var_in_threadprivate_init)
  1893. << E->getSourceRange();
  1894. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  1895. << VD << VD->getSourceRange();
  1896. return true;
  1897. }
  1898. }
  1899. return false;
  1900. }
  1901. bool VisitStmt(const Stmt *S) {
  1902. for (const Stmt *Child : S->children()) {
  1903. if (Child && Visit(Child))
  1904. return true;
  1905. }
  1906. return false;
  1907. }
  1908. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  1909. };
  1910. } // namespace
  1911. OMPThreadPrivateDecl *
  1912. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  1913. SmallVector<Expr *, 8> Vars;
  1914. for (Expr *RefExpr : VarList) {
  1915. auto *DE = cast<DeclRefExpr>(RefExpr);
  1916. auto *VD = cast<VarDecl>(DE->getDecl());
  1917. SourceLocation ILoc = DE->getExprLoc();
  1918. // Mark variable as used.
  1919. VD->setReferenced();
  1920. VD->markUsed(Context);
  1921. QualType QType = VD->getType();
  1922. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  1923. // It will be analyzed later.
  1924. Vars.push_back(DE);
  1925. continue;
  1926. }
  1927. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1928. // A threadprivate variable must not have an incomplete type.
  1929. if (RequireCompleteType(ILoc, VD->getType(),
  1930. diag::err_omp_threadprivate_incomplete_type)) {
  1931. continue;
  1932. }
  1933. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1934. // A threadprivate variable must not have a reference type.
  1935. if (VD->getType()->isReferenceType()) {
  1936. Diag(ILoc, diag::err_omp_ref_type_arg)
  1937. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  1938. bool IsDecl =
  1939. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1940. Diag(VD->getLocation(),
  1941. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1942. << VD;
  1943. continue;
  1944. }
  1945. // Check if this is a TLS variable. If TLS is not being supported, produce
  1946. // the corresponding diagnostic.
  1947. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  1948. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1949. getLangOpts().OpenMPUseTLS &&
  1950. getASTContext().getTargetInfo().isTLSSupported())) ||
  1951. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  1952. !VD->isLocalVarDecl())) {
  1953. Diag(ILoc, diag::err_omp_var_thread_local)
  1954. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  1955. bool IsDecl =
  1956. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1957. Diag(VD->getLocation(),
  1958. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1959. << VD;
  1960. continue;
  1961. }
  1962. // Check if initial value of threadprivate variable reference variable with
  1963. // local storage (it is not supported by runtime).
  1964. if (const Expr *Init = VD->getAnyInitializer()) {
  1965. LocalVarRefChecker Checker(*this);
  1966. if (Checker.Visit(Init))
  1967. continue;
  1968. }
  1969. Vars.push_back(RefExpr);
  1970. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  1971. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  1972. Context, SourceRange(Loc, Loc)));
  1973. if (ASTMutationListener *ML = Context.getASTMutationListener())
  1974. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  1975. }
  1976. OMPThreadPrivateDecl *D = nullptr;
  1977. if (!Vars.empty()) {
  1978. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  1979. Vars);
  1980. D->setAccess(AS_public);
  1981. }
  1982. return D;
  1983. }
  1984. Sema::DeclGroupPtrTy
  1985. Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
  1986. ArrayRef<OMPClause *> ClauseList) {
  1987. OMPRequiresDecl *D = nullptr;
  1988. if (!CurContext->isFileContext()) {
  1989. Diag(Loc, diag::err_omp_invalid_scope) << "requires";
  1990. } else {
  1991. D = CheckOMPRequiresDecl(Loc, ClauseList);
  1992. if (D) {
  1993. CurContext->addDecl(D);
  1994. DSAStack->addRequiresDecl(D);
  1995. }
  1996. }
  1997. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1998. }
  1999. OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
  2000. ArrayRef<OMPClause *> ClauseList) {
  2001. if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
  2002. return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
  2003. ClauseList);
  2004. return nullptr;
  2005. }
  2006. static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
  2007. const ValueDecl *D,
  2008. const DSAStackTy::DSAVarData &DVar,
  2009. bool IsLoopIterVar = false) {
  2010. if (DVar.RefExpr) {
  2011. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  2012. << getOpenMPClauseName(DVar.CKind);
  2013. return;
  2014. }
  2015. enum {
  2016. PDSA_StaticMemberShared,
  2017. PDSA_StaticLocalVarShared,
  2018. PDSA_LoopIterVarPrivate,
  2019. PDSA_LoopIterVarLinear,
  2020. PDSA_LoopIterVarLastprivate,
  2021. PDSA_ConstVarShared,
  2022. PDSA_GlobalVarShared,
  2023. PDSA_TaskVarFirstprivate,
  2024. PDSA_LocalVarPrivate,
  2025. PDSA_Implicit
  2026. } Reason = PDSA_Implicit;
  2027. bool ReportHint = false;
  2028. auto ReportLoc = D->getLocation();
  2029. auto *VD = dyn_cast<VarDecl>(D);
  2030. if (IsLoopIterVar) {
  2031. if (DVar.CKind == OMPC_private)
  2032. Reason = PDSA_LoopIterVarPrivate;
  2033. else if (DVar.CKind == OMPC_lastprivate)
  2034. Reason = PDSA_LoopIterVarLastprivate;
  2035. else
  2036. Reason = PDSA_LoopIterVarLinear;
  2037. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  2038. DVar.CKind == OMPC_firstprivate) {
  2039. Reason = PDSA_TaskVarFirstprivate;
  2040. ReportLoc = DVar.ImplicitDSALoc;
  2041. } else if (VD && VD->isStaticLocal())
  2042. Reason = PDSA_StaticLocalVarShared;
  2043. else if (VD && VD->isStaticDataMember())
  2044. Reason = PDSA_StaticMemberShared;
  2045. else if (VD && VD->isFileVarDecl())
  2046. Reason = PDSA_GlobalVarShared;
  2047. else if (D->getType().isConstant(SemaRef.getASTContext()))
  2048. Reason = PDSA_ConstVarShared;
  2049. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  2050. ReportHint = true;
  2051. Reason = PDSA_LocalVarPrivate;
  2052. }
  2053. if (Reason != PDSA_Implicit) {
  2054. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  2055. << Reason << ReportHint
  2056. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  2057. } else if (DVar.ImplicitDSALoc.isValid()) {
  2058. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  2059. << getOpenMPClauseName(DVar.CKind);
  2060. }
  2061. }
  2062. namespace {
  2063. class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
  2064. DSAStackTy *Stack;
  2065. Sema &SemaRef;
  2066. bool ErrorFound = false;
  2067. CapturedStmt *CS = nullptr;
  2068. llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
  2069. llvm::SmallVector<Expr *, 4> ImplicitMap;
  2070. Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
  2071. llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
  2072. void VisitSubCaptures(OMPExecutableDirective *S) {
  2073. // Check implicitly captured variables.
  2074. if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
  2075. return;
  2076. for (const CapturedStmt::Capture &Cap :
  2077. S->getInnermostCapturedStmt()->captures()) {
  2078. if (!Cap.capturesVariable())
  2079. continue;
  2080. VarDecl *VD = Cap.getCapturedVar();
  2081. // Do not try to map the variable if it or its sub-component was mapped
  2082. // already.
  2083. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  2084. Stack->checkMappableExprComponentListsForDecl(
  2085. VD, /*CurrentRegionOnly=*/true,
  2086. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  2087. OpenMPClauseKind) { return true; }))
  2088. continue;
  2089. DeclRefExpr *DRE = buildDeclRefExpr(
  2090. SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
  2091. Cap.getLocation(), /*RefersToCapture=*/true);
  2092. Visit(DRE);
  2093. }
  2094. }
  2095. public:
  2096. void VisitDeclRefExpr(DeclRefExpr *E) {
  2097. if (E->isTypeDependent() || E->isValueDependent() ||
  2098. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2099. return;
  2100. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2101. VD = VD->getCanonicalDecl();
  2102. // Skip internally declared variables.
  2103. if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
  2104. return;
  2105. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  2106. // Check if the variable has explicit DSA set and stop analysis if it so.
  2107. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  2108. return;
  2109. // Skip internally declared static variables.
  2110. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2111. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2112. if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
  2113. (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
  2114. return;
  2115. SourceLocation ELoc = E->getExprLoc();
  2116. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2117. // The default(none) clause requires that each variable that is referenced
  2118. // in the construct, and does not have a predetermined data-sharing
  2119. // attribute, must have its data-sharing attribute explicitly determined
  2120. // by being listed in a data-sharing attribute clause.
  2121. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  2122. isImplicitOrExplicitTaskingRegion(DKind) &&
  2123. VarsWithInheritedDSA.count(VD) == 0) {
  2124. VarsWithInheritedDSA[VD] = E;
  2125. return;
  2126. }
  2127. if (isOpenMPTargetExecutionDirective(DKind) &&
  2128. !Stack->isLoopControlVariable(VD).first) {
  2129. if (!Stack->checkMappableExprComponentListsForDecl(
  2130. VD, /*CurrentRegionOnly=*/true,
  2131. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2132. StackComponents,
  2133. OpenMPClauseKind) {
  2134. // Variable is used if it has been marked as an array, array
  2135. // section or the variable iself.
  2136. return StackComponents.size() == 1 ||
  2137. std::all_of(
  2138. std::next(StackComponents.rbegin()),
  2139. StackComponents.rend(),
  2140. [](const OMPClauseMappableExprCommon::
  2141. MappableComponent &MC) {
  2142. return MC.getAssociatedDeclaration() ==
  2143. nullptr &&
  2144. (isa<OMPArraySectionExpr>(
  2145. MC.getAssociatedExpression()) ||
  2146. isa<ArraySubscriptExpr>(
  2147. MC.getAssociatedExpression()));
  2148. });
  2149. })) {
  2150. bool IsFirstprivate = false;
  2151. // By default lambdas are captured as firstprivates.
  2152. if (const auto *RD =
  2153. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  2154. IsFirstprivate = RD->isLambda();
  2155. IsFirstprivate =
  2156. IsFirstprivate ||
  2157. (VD->getType().getNonReferenceType()->isScalarType() &&
  2158. Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
  2159. if (IsFirstprivate)
  2160. ImplicitFirstprivate.emplace_back(E);
  2161. else
  2162. ImplicitMap.emplace_back(E);
  2163. return;
  2164. }
  2165. }
  2166. // OpenMP [2.9.3.6, Restrictions, p.2]
  2167. // A list item that appears in a reduction clause of the innermost
  2168. // enclosing worksharing or parallel construct may not be accessed in an
  2169. // explicit task.
  2170. DVar = Stack->hasInnermostDSA(
  2171. VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2172. [](OpenMPDirectiveKind K) {
  2173. return isOpenMPParallelDirective(K) ||
  2174. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2175. },
  2176. /*FromParent=*/true);
  2177. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2178. ErrorFound = true;
  2179. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2180. reportOriginalDsa(SemaRef, Stack, VD, DVar);
  2181. return;
  2182. }
  2183. // Define implicit data-sharing attributes for task.
  2184. DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
  2185. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2186. !Stack->isLoopControlVariable(VD).first)
  2187. ImplicitFirstprivate.push_back(E);
  2188. }
  2189. }
  2190. void VisitMemberExpr(MemberExpr *E) {
  2191. if (E->isTypeDependent() || E->isValueDependent() ||
  2192. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  2193. return;
  2194. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  2195. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  2196. if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  2197. if (!FD)
  2198. return;
  2199. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
  2200. // Check if the variable has explicit DSA set and stop analysis if it
  2201. // so.
  2202. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  2203. return;
  2204. if (isOpenMPTargetExecutionDirective(DKind) &&
  2205. !Stack->isLoopControlVariable(FD).first &&
  2206. !Stack->checkMappableExprComponentListsForDecl(
  2207. FD, /*CurrentRegionOnly=*/true,
  2208. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2209. StackComponents,
  2210. OpenMPClauseKind) {
  2211. return isa<CXXThisExpr>(
  2212. cast<MemberExpr>(
  2213. StackComponents.back().getAssociatedExpression())
  2214. ->getBase()
  2215. ->IgnoreParens());
  2216. })) {
  2217. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  2218. // A bit-field cannot appear in a map clause.
  2219. //
  2220. if (FD->isBitField())
  2221. return;
  2222. // Check to see if the member expression is referencing a class that
  2223. // has already been explicitly mapped
  2224. if (Stack->isClassPreviouslyMapped(TE->getType()))
  2225. return;
  2226. ImplicitMap.emplace_back(E);
  2227. return;
  2228. }
  2229. SourceLocation ELoc = E->getExprLoc();
  2230. // OpenMP [2.9.3.6, Restrictions, p.2]
  2231. // A list item that appears in a reduction clause of the innermost
  2232. // enclosing worksharing or parallel construct may not be accessed in
  2233. // an explicit task.
  2234. DVar = Stack->hasInnermostDSA(
  2235. FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  2236. [](OpenMPDirectiveKind K) {
  2237. return isOpenMPParallelDirective(K) ||
  2238. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  2239. },
  2240. /*FromParent=*/true);
  2241. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  2242. ErrorFound = true;
  2243. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  2244. reportOriginalDsa(SemaRef, Stack, FD, DVar);
  2245. return;
  2246. }
  2247. // Define implicit data-sharing attributes for task.
  2248. DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
  2249. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  2250. !Stack->isLoopControlVariable(FD).first) {
  2251. // Check if there is a captured expression for the current field in the
  2252. // region. Do not mark it as firstprivate unless there is no captured
  2253. // expression.
  2254. // TODO: try to make it firstprivate.
  2255. if (DVar.CKind != OMPC_unknown)
  2256. ImplicitFirstprivate.push_back(E);
  2257. }
  2258. return;
  2259. }
  2260. if (isOpenMPTargetExecutionDirective(DKind)) {
  2261. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  2262. if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  2263. /*NoDiagnose=*/true))
  2264. return;
  2265. const auto *VD = cast<ValueDecl>(
  2266. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  2267. if (!Stack->checkMappableExprComponentListsForDecl(
  2268. VD, /*CurrentRegionOnly=*/true,
  2269. [&CurComponents](
  2270. OMPClauseMappableExprCommon::MappableExprComponentListRef
  2271. StackComponents,
  2272. OpenMPClauseKind) {
  2273. auto CCI = CurComponents.rbegin();
  2274. auto CCE = CurComponents.rend();
  2275. for (const auto &SC : llvm::reverse(StackComponents)) {
  2276. // Do both expressions have the same kind?
  2277. if (CCI->getAssociatedExpression()->getStmtClass() !=
  2278. SC.getAssociatedExpression()->getStmtClass())
  2279. if (!(isa<OMPArraySectionExpr>(
  2280. SC.getAssociatedExpression()) &&
  2281. isa<ArraySubscriptExpr>(
  2282. CCI->getAssociatedExpression())))
  2283. return false;
  2284. const Decl *CCD = CCI->getAssociatedDeclaration();
  2285. const Decl *SCD = SC.getAssociatedDeclaration();
  2286. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  2287. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  2288. if (SCD != CCD)
  2289. return false;
  2290. std::advance(CCI, 1);
  2291. if (CCI == CCE)
  2292. break;
  2293. }
  2294. return true;
  2295. })) {
  2296. Visit(E->getBase());
  2297. }
  2298. } else {
  2299. Visit(E->getBase());
  2300. }
  2301. }
  2302. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  2303. for (OMPClause *C : S->clauses()) {
  2304. // Skip analysis of arguments of implicitly defined firstprivate clause
  2305. // for task|target directives.
  2306. // Skip analysis of arguments of implicitly defined map clause for target
  2307. // directives.
  2308. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  2309. C->isImplicit())) {
  2310. for (Stmt *CC : C->children()) {
  2311. if (CC)
  2312. Visit(CC);
  2313. }
  2314. }
  2315. }
  2316. // Check implicitly captured variables.
  2317. VisitSubCaptures(S);
  2318. }
  2319. void VisitStmt(Stmt *S) {
  2320. for (Stmt *C : S->children()) {
  2321. if (C) {
  2322. // Check implicitly captured variables in the task-based directives to
  2323. // check if they must be firstprivatized.
  2324. Visit(C);
  2325. }
  2326. }
  2327. }
  2328. bool isErrorFound() const { return ErrorFound; }
  2329. ArrayRef<Expr *> getImplicitFirstprivate() const {
  2330. return ImplicitFirstprivate;
  2331. }
  2332. ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
  2333. const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
  2334. return VarsWithInheritedDSA;
  2335. }
  2336. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  2337. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
  2338. };
  2339. } // namespace
  2340. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  2341. switch (DKind) {
  2342. case OMPD_parallel:
  2343. case OMPD_parallel_for:
  2344. case OMPD_parallel_for_simd:
  2345. case OMPD_parallel_sections:
  2346. case OMPD_teams:
  2347. case OMPD_teams_distribute:
  2348. case OMPD_teams_distribute_simd: {
  2349. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2350. QualType KmpInt32PtrTy =
  2351. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2352. Sema::CapturedParamNameType Params[] = {
  2353. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2354. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2355. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2356. };
  2357. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2358. Params);
  2359. break;
  2360. }
  2361. case OMPD_target_teams:
  2362. case OMPD_target_parallel:
  2363. case OMPD_target_parallel_for:
  2364. case OMPD_target_parallel_for_simd:
  2365. case OMPD_target_teams_distribute:
  2366. case OMPD_target_teams_distribute_simd: {
  2367. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2368. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2369. QualType KmpInt32PtrTy =
  2370. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2371. QualType Args[] = {VoidPtrTy};
  2372. FunctionProtoType::ExtProtoInfo EPI;
  2373. EPI.Variadic = true;
  2374. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2375. Sema::CapturedParamNameType Params[] = {
  2376. std::make_pair(".global_tid.", KmpInt32Ty),
  2377. std::make_pair(".part_id.", KmpInt32PtrTy),
  2378. std::make_pair(".privates.", VoidPtrTy),
  2379. std::make_pair(
  2380. ".copy_fn.",
  2381. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2382. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2383. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2384. };
  2385. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2386. Params);
  2387. // Mark this captured region as inlined, because we don't use outlined
  2388. // function directly.
  2389. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2390. AlwaysInlineAttr::CreateImplicit(
  2391. Context, AlwaysInlineAttr::Keyword_forceinline));
  2392. Sema::CapturedParamNameType ParamsTarget[] = {
  2393. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2394. };
  2395. // Start a captured region for 'target' with no implicit parameters.
  2396. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2397. ParamsTarget);
  2398. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  2399. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2400. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2401. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2402. };
  2403. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2404. // the same implicit parameters.
  2405. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2406. ParamsTeamsOrParallel);
  2407. break;
  2408. }
  2409. case OMPD_target:
  2410. case OMPD_target_simd: {
  2411. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2412. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2413. QualType KmpInt32PtrTy =
  2414. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2415. QualType Args[] = {VoidPtrTy};
  2416. FunctionProtoType::ExtProtoInfo EPI;
  2417. EPI.Variadic = true;
  2418. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2419. Sema::CapturedParamNameType Params[] = {
  2420. std::make_pair(".global_tid.", KmpInt32Ty),
  2421. std::make_pair(".part_id.", KmpInt32PtrTy),
  2422. std::make_pair(".privates.", VoidPtrTy),
  2423. std::make_pair(
  2424. ".copy_fn.",
  2425. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2426. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2427. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2428. };
  2429. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2430. Params);
  2431. // Mark this captured region as inlined, because we don't use outlined
  2432. // function directly.
  2433. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2434. AlwaysInlineAttr::CreateImplicit(
  2435. Context, AlwaysInlineAttr::Keyword_forceinline));
  2436. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2437. std::make_pair(StringRef(), QualType()));
  2438. break;
  2439. }
  2440. case OMPD_simd:
  2441. case OMPD_for:
  2442. case OMPD_for_simd:
  2443. case OMPD_sections:
  2444. case OMPD_section:
  2445. case OMPD_single:
  2446. case OMPD_master:
  2447. case OMPD_critical:
  2448. case OMPD_taskgroup:
  2449. case OMPD_distribute:
  2450. case OMPD_distribute_simd:
  2451. case OMPD_ordered:
  2452. case OMPD_atomic:
  2453. case OMPD_target_data: {
  2454. Sema::CapturedParamNameType Params[] = {
  2455. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2456. };
  2457. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2458. Params);
  2459. break;
  2460. }
  2461. case OMPD_task: {
  2462. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2463. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2464. QualType KmpInt32PtrTy =
  2465. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2466. QualType Args[] = {VoidPtrTy};
  2467. FunctionProtoType::ExtProtoInfo EPI;
  2468. EPI.Variadic = true;
  2469. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2470. Sema::CapturedParamNameType Params[] = {
  2471. std::make_pair(".global_tid.", KmpInt32Ty),
  2472. std::make_pair(".part_id.", KmpInt32PtrTy),
  2473. std::make_pair(".privates.", VoidPtrTy),
  2474. std::make_pair(
  2475. ".copy_fn.",
  2476. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2477. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2478. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2479. };
  2480. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2481. Params);
  2482. // Mark this captured region as inlined, because we don't use outlined
  2483. // function directly.
  2484. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2485. AlwaysInlineAttr::CreateImplicit(
  2486. Context, AlwaysInlineAttr::Keyword_forceinline));
  2487. break;
  2488. }
  2489. case OMPD_taskloop:
  2490. case OMPD_taskloop_simd: {
  2491. QualType KmpInt32Ty =
  2492. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  2493. .withConst();
  2494. QualType KmpUInt64Ty =
  2495. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  2496. .withConst();
  2497. QualType KmpInt64Ty =
  2498. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  2499. .withConst();
  2500. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2501. QualType KmpInt32PtrTy =
  2502. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2503. QualType Args[] = {VoidPtrTy};
  2504. FunctionProtoType::ExtProtoInfo EPI;
  2505. EPI.Variadic = true;
  2506. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2507. Sema::CapturedParamNameType Params[] = {
  2508. std::make_pair(".global_tid.", KmpInt32Ty),
  2509. std::make_pair(".part_id.", KmpInt32PtrTy),
  2510. std::make_pair(".privates.", VoidPtrTy),
  2511. std::make_pair(
  2512. ".copy_fn.",
  2513. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2514. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2515. std::make_pair(".lb.", KmpUInt64Ty),
  2516. std::make_pair(".ub.", KmpUInt64Ty),
  2517. std::make_pair(".st.", KmpInt64Ty),
  2518. std::make_pair(".liter.", KmpInt32Ty),
  2519. std::make_pair(".reductions.", VoidPtrTy),
  2520. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2521. };
  2522. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2523. Params);
  2524. // Mark this captured region as inlined, because we don't use outlined
  2525. // function directly.
  2526. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2527. AlwaysInlineAttr::CreateImplicit(
  2528. Context, AlwaysInlineAttr::Keyword_forceinline));
  2529. break;
  2530. }
  2531. case OMPD_distribute_parallel_for_simd:
  2532. case OMPD_distribute_parallel_for: {
  2533. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2534. QualType KmpInt32PtrTy =
  2535. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2536. Sema::CapturedParamNameType Params[] = {
  2537. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2538. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2539. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2540. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2541. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2542. };
  2543. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2544. Params);
  2545. break;
  2546. }
  2547. case OMPD_target_teams_distribute_parallel_for:
  2548. case OMPD_target_teams_distribute_parallel_for_simd: {
  2549. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2550. QualType KmpInt32PtrTy =
  2551. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2552. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2553. QualType Args[] = {VoidPtrTy};
  2554. FunctionProtoType::ExtProtoInfo EPI;
  2555. EPI.Variadic = true;
  2556. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2557. Sema::CapturedParamNameType Params[] = {
  2558. std::make_pair(".global_tid.", KmpInt32Ty),
  2559. std::make_pair(".part_id.", KmpInt32PtrTy),
  2560. std::make_pair(".privates.", VoidPtrTy),
  2561. std::make_pair(
  2562. ".copy_fn.",
  2563. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2564. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2565. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2566. };
  2567. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2568. Params);
  2569. // Mark this captured region as inlined, because we don't use outlined
  2570. // function directly.
  2571. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2572. AlwaysInlineAttr::CreateImplicit(
  2573. Context, AlwaysInlineAttr::Keyword_forceinline));
  2574. Sema::CapturedParamNameType ParamsTarget[] = {
  2575. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2576. };
  2577. // Start a captured region for 'target' with no implicit parameters.
  2578. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2579. ParamsTarget);
  2580. Sema::CapturedParamNameType ParamsTeams[] = {
  2581. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2582. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2583. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2584. };
  2585. // Start a captured region for 'target' with no implicit parameters.
  2586. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2587. ParamsTeams);
  2588. Sema::CapturedParamNameType ParamsParallel[] = {
  2589. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2590. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2591. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2592. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2593. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2594. };
  2595. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2596. // the same implicit parameters.
  2597. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2598. ParamsParallel);
  2599. break;
  2600. }
  2601. case OMPD_teams_distribute_parallel_for:
  2602. case OMPD_teams_distribute_parallel_for_simd: {
  2603. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2604. QualType KmpInt32PtrTy =
  2605. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2606. Sema::CapturedParamNameType ParamsTeams[] = {
  2607. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2608. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2609. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2610. };
  2611. // Start a captured region for 'target' with no implicit parameters.
  2612. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2613. ParamsTeams);
  2614. Sema::CapturedParamNameType ParamsParallel[] = {
  2615. std::make_pair(".global_tid.", KmpInt32PtrTy),
  2616. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  2617. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  2618. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  2619. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2620. };
  2621. // Start a captured region for 'teams' or 'parallel'. Both regions have
  2622. // the same implicit parameters.
  2623. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2624. ParamsParallel);
  2625. break;
  2626. }
  2627. case OMPD_target_update:
  2628. case OMPD_target_enter_data:
  2629. case OMPD_target_exit_data: {
  2630. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  2631. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  2632. QualType KmpInt32PtrTy =
  2633. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  2634. QualType Args[] = {VoidPtrTy};
  2635. FunctionProtoType::ExtProtoInfo EPI;
  2636. EPI.Variadic = true;
  2637. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  2638. Sema::CapturedParamNameType Params[] = {
  2639. std::make_pair(".global_tid.", KmpInt32Ty),
  2640. std::make_pair(".part_id.", KmpInt32PtrTy),
  2641. std::make_pair(".privates.", VoidPtrTy),
  2642. std::make_pair(
  2643. ".copy_fn.",
  2644. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  2645. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  2646. std::make_pair(StringRef(), QualType()) // __context with shared vars
  2647. };
  2648. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  2649. Params);
  2650. // Mark this captured region as inlined, because we don't use outlined
  2651. // function directly.
  2652. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  2653. AlwaysInlineAttr::CreateImplicit(
  2654. Context, AlwaysInlineAttr::Keyword_forceinline));
  2655. break;
  2656. }
  2657. case OMPD_threadprivate:
  2658. case OMPD_taskyield:
  2659. case OMPD_barrier:
  2660. case OMPD_taskwait:
  2661. case OMPD_cancellation_point:
  2662. case OMPD_cancel:
  2663. case OMPD_flush:
  2664. case OMPD_declare_reduction:
  2665. case OMPD_declare_mapper:
  2666. case OMPD_declare_simd:
  2667. case OMPD_declare_target:
  2668. case OMPD_end_declare_target:
  2669. case OMPD_requires:
  2670. llvm_unreachable("OpenMP Directive is not allowed");
  2671. case OMPD_unknown:
  2672. llvm_unreachable("Unknown OpenMP directive");
  2673. }
  2674. }
  2675. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  2676. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2677. getOpenMPCaptureRegions(CaptureRegions, DKind);
  2678. return CaptureRegions.size();
  2679. }
  2680. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  2681. Expr *CaptureExpr, bool WithInit,
  2682. bool AsExpression) {
  2683. assert(CaptureExpr);
  2684. ASTContext &C = S.getASTContext();
  2685. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  2686. QualType Ty = Init->getType();
  2687. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  2688. if (S.getLangOpts().CPlusPlus) {
  2689. Ty = C.getLValueReferenceType(Ty);
  2690. } else {
  2691. Ty = C.getPointerType(Ty);
  2692. ExprResult Res =
  2693. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  2694. if (!Res.isUsable())
  2695. return nullptr;
  2696. Init = Res.get();
  2697. }
  2698. WithInit = true;
  2699. }
  2700. auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
  2701. CaptureExpr->getBeginLoc());
  2702. if (!WithInit)
  2703. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
  2704. S.CurContext->addHiddenDecl(CED);
  2705. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  2706. return CED;
  2707. }
  2708. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  2709. bool WithInit) {
  2710. OMPCapturedExprDecl *CD;
  2711. if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
  2712. CD = cast<OMPCapturedExprDecl>(VD);
  2713. else
  2714. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  2715. /*AsExpression=*/false);
  2716. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2717. CaptureExpr->getExprLoc());
  2718. }
  2719. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  2720. CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
  2721. if (!Ref) {
  2722. OMPCapturedExprDecl *CD = buildCaptureDecl(
  2723. S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
  2724. /*WithInit=*/true, /*AsExpression=*/true);
  2725. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  2726. CaptureExpr->getExprLoc());
  2727. }
  2728. ExprResult Res = Ref;
  2729. if (!S.getLangOpts().CPlusPlus &&
  2730. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  2731. Ref->getType()->isPointerType()) {
  2732. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  2733. if (!Res.isUsable())
  2734. return ExprError();
  2735. }
  2736. return S.DefaultLvalueConversion(Res.get());
  2737. }
  2738. namespace {
  2739. // OpenMP directives parsed in this section are represented as a
  2740. // CapturedStatement with an associated statement. If a syntax error
  2741. // is detected during the parsing of the associated statement, the
  2742. // compiler must abort processing and close the CapturedStatement.
  2743. //
  2744. // Combined directives such as 'target parallel' have more than one
  2745. // nested CapturedStatements. This RAII ensures that we unwind out
  2746. // of all the nested CapturedStatements when an error is found.
  2747. class CaptureRegionUnwinderRAII {
  2748. private:
  2749. Sema &S;
  2750. bool &ErrorFound;
  2751. OpenMPDirectiveKind DKind = OMPD_unknown;
  2752. public:
  2753. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  2754. OpenMPDirectiveKind DKind)
  2755. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  2756. ~CaptureRegionUnwinderRAII() {
  2757. if (ErrorFound) {
  2758. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  2759. while (--ThisCaptureLevel >= 0)
  2760. S.ActOnCapturedRegionError();
  2761. }
  2762. }
  2763. };
  2764. } // namespace
  2765. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  2766. ArrayRef<OMPClause *> Clauses) {
  2767. bool ErrorFound = false;
  2768. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  2769. *this, ErrorFound, DSAStack->getCurrentDirective());
  2770. if (!S.isUsable()) {
  2771. ErrorFound = true;
  2772. return StmtError();
  2773. }
  2774. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2775. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  2776. OMPOrderedClause *OC = nullptr;
  2777. OMPScheduleClause *SC = nullptr;
  2778. SmallVector<const OMPLinearClause *, 4> LCs;
  2779. SmallVector<const OMPClauseWithPreInit *, 4> PICs;
  2780. // This is required for proper codegen.
  2781. for (OMPClause *Clause : Clauses) {
  2782. if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  2783. Clause->getClauseKind() == OMPC_in_reduction) {
  2784. // Capture taskgroup task_reduction descriptors inside the tasking regions
  2785. // with the corresponding in_reduction items.
  2786. auto *IRC = cast<OMPInReductionClause>(Clause);
  2787. for (Expr *E : IRC->taskgroup_descriptors())
  2788. if (E)
  2789. MarkDeclarationsReferencedInExpr(E);
  2790. }
  2791. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  2792. Clause->getClauseKind() == OMPC_copyprivate ||
  2793. (getLangOpts().OpenMPUseTLS &&
  2794. getASTContext().getTargetInfo().isTLSSupported() &&
  2795. Clause->getClauseKind() == OMPC_copyin)) {
  2796. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  2797. // Mark all variables in private list clauses as used in inner region.
  2798. for (Stmt *VarRef : Clause->children()) {
  2799. if (auto *E = cast_or_null<Expr>(VarRef)) {
  2800. MarkDeclarationsReferencedInExpr(E);
  2801. }
  2802. }
  2803. DSAStack->setForceVarCapturing(/*V=*/false);
  2804. } else if (CaptureRegions.size() > 1 ||
  2805. CaptureRegions.back() != OMPD_unknown) {
  2806. if (auto *C = OMPClauseWithPreInit::get(Clause))
  2807. PICs.push_back(C);
  2808. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  2809. if (Expr *E = C->getPostUpdateExpr())
  2810. MarkDeclarationsReferencedInExpr(E);
  2811. }
  2812. }
  2813. if (Clause->getClauseKind() == OMPC_schedule)
  2814. SC = cast<OMPScheduleClause>(Clause);
  2815. else if (Clause->getClauseKind() == OMPC_ordered)
  2816. OC = cast<OMPOrderedClause>(Clause);
  2817. else if (Clause->getClauseKind() == OMPC_linear)
  2818. LCs.push_back(cast<OMPLinearClause>(Clause));
  2819. }
  2820. // OpenMP, 2.7.1 Loop Construct, Restrictions
  2821. // The nonmonotonic modifier cannot be specified if an ordered clause is
  2822. // specified.
  2823. if (SC &&
  2824. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  2825. SC->getSecondScheduleModifier() ==
  2826. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  2827. OC) {
  2828. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  2829. ? SC->getFirstScheduleModifierLoc()
  2830. : SC->getSecondScheduleModifierLoc(),
  2831. diag::err_omp_schedule_nonmonotonic_ordered)
  2832. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  2833. ErrorFound = true;
  2834. }
  2835. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  2836. for (const OMPLinearClause *C : LCs) {
  2837. Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
  2838. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  2839. }
  2840. ErrorFound = true;
  2841. }
  2842. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  2843. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  2844. OC->getNumForLoops()) {
  2845. Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
  2846. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  2847. ErrorFound = true;
  2848. }
  2849. if (ErrorFound) {
  2850. return StmtError();
  2851. }
  2852. StmtResult SR = S;
  2853. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  2854. // Mark all variables in private list clauses as used in inner region.
  2855. // Required for proper codegen of combined directives.
  2856. // TODO: add processing for other clauses.
  2857. if (ThisCaptureRegion != OMPD_unknown) {
  2858. for (const clang::OMPClauseWithPreInit *C : PICs) {
  2859. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  2860. // Find the particular capture region for the clause if the
  2861. // directive is a combined one with multiple capture regions.
  2862. // If the directive is not a combined one, the capture region
  2863. // associated with the clause is OMPD_unknown and is generated
  2864. // only once.
  2865. if (CaptureRegion == ThisCaptureRegion ||
  2866. CaptureRegion == OMPD_unknown) {
  2867. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  2868. for (Decl *D : DS->decls())
  2869. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  2870. }
  2871. }
  2872. }
  2873. }
  2874. SR = ActOnCapturedRegionEnd(SR.get());
  2875. }
  2876. return SR;
  2877. }
  2878. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  2879. OpenMPDirectiveKind CancelRegion,
  2880. SourceLocation StartLoc) {
  2881. // CancelRegion is only needed for cancel and cancellation_point.
  2882. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  2883. return false;
  2884. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  2885. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  2886. return false;
  2887. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  2888. << getOpenMPDirectiveName(CancelRegion);
  2889. return true;
  2890. }
  2891. static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
  2892. OpenMPDirectiveKind CurrentRegion,
  2893. const DeclarationNameInfo &CurrentName,
  2894. OpenMPDirectiveKind CancelRegion,
  2895. SourceLocation StartLoc) {
  2896. if (Stack->getCurScope()) {
  2897. OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
  2898. OpenMPDirectiveKind OffendingRegion = ParentRegion;
  2899. bool NestingProhibited = false;
  2900. bool CloseNesting = true;
  2901. bool OrphanSeen = false;
  2902. enum {
  2903. NoRecommend,
  2904. ShouldBeInParallelRegion,
  2905. ShouldBeInOrderedRegion,
  2906. ShouldBeInTargetRegion,
  2907. ShouldBeInTeamsRegion
  2908. } Recommend = NoRecommend;
  2909. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
  2910. // OpenMP [2.16, Nesting of Regions]
  2911. // OpenMP constructs may not be nested inside a simd region.
  2912. // OpenMP [2.8.1,simd Construct, Restrictions]
  2913. // An ordered construct with the simd clause is the only OpenMP
  2914. // construct that can appear in the simd region.
  2915. // Allowing a SIMD construct nested in another SIMD construct is an
  2916. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  2917. // message.
  2918. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  2919. ? diag::err_omp_prohibited_region_simd
  2920. : diag::warn_omp_nesting_simd);
  2921. return CurrentRegion != OMPD_simd;
  2922. }
  2923. if (ParentRegion == OMPD_atomic) {
  2924. // OpenMP [2.16, Nesting of Regions]
  2925. // OpenMP constructs may not be nested inside an atomic region.
  2926. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  2927. return true;
  2928. }
  2929. if (CurrentRegion == OMPD_section) {
  2930. // OpenMP [2.7.2, sections Construct, Restrictions]
  2931. // Orphaned section directives are prohibited. That is, the section
  2932. // directives must appear within the sections construct and must not be
  2933. // encountered elsewhere in the sections region.
  2934. if (ParentRegion != OMPD_sections &&
  2935. ParentRegion != OMPD_parallel_sections) {
  2936. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  2937. << (ParentRegion != OMPD_unknown)
  2938. << getOpenMPDirectiveName(ParentRegion);
  2939. return true;
  2940. }
  2941. return false;
  2942. }
  2943. // Allow some constructs (except teams and cancellation constructs) to be
  2944. // orphaned (they could be used in functions, called from OpenMP regions
  2945. // with the required preconditions).
  2946. if (ParentRegion == OMPD_unknown &&
  2947. !isOpenMPNestingTeamsDirective(CurrentRegion) &&
  2948. CurrentRegion != OMPD_cancellation_point &&
  2949. CurrentRegion != OMPD_cancel)
  2950. return false;
  2951. if (CurrentRegion == OMPD_cancellation_point ||
  2952. CurrentRegion == OMPD_cancel) {
  2953. // OpenMP [2.16, Nesting of Regions]
  2954. // A cancellation point construct for which construct-type-clause is
  2955. // taskgroup must be nested inside a task construct. A cancellation
  2956. // point construct for which construct-type-clause is not taskgroup must
  2957. // be closely nested inside an OpenMP construct that matches the type
  2958. // specified in construct-type-clause.
  2959. // A cancel construct for which construct-type-clause is taskgroup must be
  2960. // nested inside a task construct. A cancel construct for which
  2961. // construct-type-clause is not taskgroup must be closely nested inside an
  2962. // OpenMP construct that matches the type specified in
  2963. // construct-type-clause.
  2964. NestingProhibited =
  2965. !((CancelRegion == OMPD_parallel &&
  2966. (ParentRegion == OMPD_parallel ||
  2967. ParentRegion == OMPD_target_parallel)) ||
  2968. (CancelRegion == OMPD_for &&
  2969. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  2970. ParentRegion == OMPD_target_parallel_for ||
  2971. ParentRegion == OMPD_distribute_parallel_for ||
  2972. ParentRegion == OMPD_teams_distribute_parallel_for ||
  2973. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  2974. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  2975. (CancelRegion == OMPD_sections &&
  2976. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  2977. ParentRegion == OMPD_parallel_sections)));
  2978. OrphanSeen = ParentRegion == OMPD_unknown;
  2979. } else if (CurrentRegion == OMPD_master) {
  2980. // OpenMP [2.16, Nesting of Regions]
  2981. // A master region may not be closely nested inside a worksharing,
  2982. // atomic, or explicit task region.
  2983. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2984. isOpenMPTaskingDirective(ParentRegion);
  2985. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  2986. // OpenMP [2.16, Nesting of Regions]
  2987. // A critical region may not be nested (closely or otherwise) inside a
  2988. // critical region with the same name. Note that this restriction is not
  2989. // sufficient to prevent deadlock.
  2990. SourceLocation PreviousCriticalLoc;
  2991. bool DeadLock = Stack->hasDirective(
  2992. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  2993. const DeclarationNameInfo &DNI,
  2994. SourceLocation Loc) {
  2995. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  2996. PreviousCriticalLoc = Loc;
  2997. return true;
  2998. }
  2999. return false;
  3000. },
  3001. false /* skip top directive */);
  3002. if (DeadLock) {
  3003. SemaRef.Diag(StartLoc,
  3004. diag::err_omp_prohibited_region_critical_same_name)
  3005. << CurrentName.getName();
  3006. if (PreviousCriticalLoc.isValid())
  3007. SemaRef.Diag(PreviousCriticalLoc,
  3008. diag::note_omp_previous_critical_region);
  3009. return true;
  3010. }
  3011. } else if (CurrentRegion == OMPD_barrier) {
  3012. // OpenMP [2.16, Nesting of Regions]
  3013. // A barrier region may not be closely nested inside a worksharing,
  3014. // explicit task, critical, ordered, atomic, or master region.
  3015. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3016. isOpenMPTaskingDirective(ParentRegion) ||
  3017. ParentRegion == OMPD_master ||
  3018. ParentRegion == OMPD_critical ||
  3019. ParentRegion == OMPD_ordered;
  3020. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  3021. !isOpenMPParallelDirective(CurrentRegion) &&
  3022. !isOpenMPTeamsDirective(CurrentRegion)) {
  3023. // OpenMP [2.16, Nesting of Regions]
  3024. // A worksharing region may not be closely nested inside a worksharing,
  3025. // explicit task, critical, ordered, atomic, or master region.
  3026. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  3027. isOpenMPTaskingDirective(ParentRegion) ||
  3028. ParentRegion == OMPD_master ||
  3029. ParentRegion == OMPD_critical ||
  3030. ParentRegion == OMPD_ordered;
  3031. Recommend = ShouldBeInParallelRegion;
  3032. } else if (CurrentRegion == OMPD_ordered) {
  3033. // OpenMP [2.16, Nesting of Regions]
  3034. // An ordered region may not be closely nested inside a critical,
  3035. // atomic, or explicit task region.
  3036. // An ordered region must be closely nested inside a loop region (or
  3037. // parallel loop region) with an ordered clause.
  3038. // OpenMP [2.8.1,simd Construct, Restrictions]
  3039. // An ordered construct with the simd clause is the only OpenMP construct
  3040. // that can appear in the simd region.
  3041. NestingProhibited = ParentRegion == OMPD_critical ||
  3042. isOpenMPTaskingDirective(ParentRegion) ||
  3043. !(isOpenMPSimdDirective(ParentRegion) ||
  3044. Stack->isParentOrderedRegion());
  3045. Recommend = ShouldBeInOrderedRegion;
  3046. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  3047. // OpenMP [2.16, Nesting of Regions]
  3048. // If specified, a teams construct must be contained within a target
  3049. // construct.
  3050. NestingProhibited = ParentRegion != OMPD_target;
  3051. OrphanSeen = ParentRegion == OMPD_unknown;
  3052. Recommend = ShouldBeInTargetRegion;
  3053. }
  3054. if (!NestingProhibited &&
  3055. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  3056. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  3057. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  3058. // OpenMP [2.16, Nesting of Regions]
  3059. // distribute, parallel, parallel sections, parallel workshare, and the
  3060. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  3061. // constructs that can be closely nested in the teams region.
  3062. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  3063. !isOpenMPDistributeDirective(CurrentRegion);
  3064. Recommend = ShouldBeInParallelRegion;
  3065. }
  3066. if (!NestingProhibited &&
  3067. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  3068. // OpenMP 4.5 [2.17 Nesting of Regions]
  3069. // The region associated with the distribute construct must be strictly
  3070. // nested inside a teams region
  3071. NestingProhibited =
  3072. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  3073. Recommend = ShouldBeInTeamsRegion;
  3074. }
  3075. if (!NestingProhibited &&
  3076. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  3077. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  3078. // OpenMP 4.5 [2.17 Nesting of Regions]
  3079. // If a target, target update, target data, target enter data, or
  3080. // target exit data construct is encountered during execution of a
  3081. // target region, the behavior is unspecified.
  3082. NestingProhibited = Stack->hasDirective(
  3083. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  3084. SourceLocation) {
  3085. if (isOpenMPTargetExecutionDirective(K)) {
  3086. OffendingRegion = K;
  3087. return true;
  3088. }
  3089. return false;
  3090. },
  3091. false /* don't skip top directive */);
  3092. CloseNesting = false;
  3093. }
  3094. if (NestingProhibited) {
  3095. if (OrphanSeen) {
  3096. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  3097. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  3098. } else {
  3099. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  3100. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  3101. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  3102. }
  3103. return true;
  3104. }
  3105. }
  3106. return false;
  3107. }
  3108. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  3109. ArrayRef<OMPClause *> Clauses,
  3110. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  3111. bool ErrorFound = false;
  3112. unsigned NamedModifiersNumber = 0;
  3113. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  3114. OMPD_unknown + 1);
  3115. SmallVector<SourceLocation, 4> NameModifierLoc;
  3116. for (const OMPClause *C : Clauses) {
  3117. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  3118. // At most one if clause without a directive-name-modifier can appear on
  3119. // the directive.
  3120. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  3121. if (FoundNameModifiers[CurNM]) {
  3122. S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  3123. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  3124. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  3125. ErrorFound = true;
  3126. } else if (CurNM != OMPD_unknown) {
  3127. NameModifierLoc.push_back(IC->getNameModifierLoc());
  3128. ++NamedModifiersNumber;
  3129. }
  3130. FoundNameModifiers[CurNM] = IC;
  3131. if (CurNM == OMPD_unknown)
  3132. continue;
  3133. // Check if the specified name modifier is allowed for the current
  3134. // directive.
  3135. // At most one if clause with the particular directive-name-modifier can
  3136. // appear on the directive.
  3137. bool MatchFound = false;
  3138. for (auto NM : AllowedNameModifiers) {
  3139. if (CurNM == NM) {
  3140. MatchFound = true;
  3141. break;
  3142. }
  3143. }
  3144. if (!MatchFound) {
  3145. S.Diag(IC->getNameModifierLoc(),
  3146. diag::err_omp_wrong_if_directive_name_modifier)
  3147. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  3148. ErrorFound = true;
  3149. }
  3150. }
  3151. }
  3152. // If any if clause on the directive includes a directive-name-modifier then
  3153. // all if clauses on the directive must include a directive-name-modifier.
  3154. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  3155. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  3156. S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
  3157. diag::err_omp_no_more_if_clause);
  3158. } else {
  3159. std::string Values;
  3160. std::string Sep(", ");
  3161. unsigned AllowedCnt = 0;
  3162. unsigned TotalAllowedNum =
  3163. AllowedNameModifiers.size() - NamedModifiersNumber;
  3164. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  3165. ++Cnt) {
  3166. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  3167. if (!FoundNameModifiers[NM]) {
  3168. Values += "'";
  3169. Values += getOpenMPDirectiveName(NM);
  3170. Values += "'";
  3171. if (AllowedCnt + 2 == TotalAllowedNum)
  3172. Values += " or ";
  3173. else if (AllowedCnt + 1 != TotalAllowedNum)
  3174. Values += Sep;
  3175. ++AllowedCnt;
  3176. }
  3177. }
  3178. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
  3179. diag::err_omp_unnamed_if_clause)
  3180. << (TotalAllowedNum > 1) << Values;
  3181. }
  3182. for (SourceLocation Loc : NameModifierLoc) {
  3183. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  3184. }
  3185. ErrorFound = true;
  3186. }
  3187. return ErrorFound;
  3188. }
  3189. StmtResult Sema::ActOnOpenMPExecutableDirective(
  3190. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  3191. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  3192. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  3193. StmtResult Res = StmtError();
  3194. // First check CancelRegion which is then used in checkNestingOfRegions.
  3195. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  3196. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  3197. StartLoc))
  3198. return StmtError();
  3199. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  3200. VarsWithInheritedDSAType VarsWithInheritedDSA;
  3201. bool ErrorFound = false;
  3202. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  3203. if (AStmt && !CurContext->isDependentContext()) {
  3204. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  3205. // Check default data sharing attributes for referenced variables.
  3206. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  3207. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  3208. Stmt *S = AStmt;
  3209. while (--ThisCaptureLevel >= 0)
  3210. S = cast<CapturedStmt>(S)->getCapturedStmt();
  3211. DSAChecker.Visit(S);
  3212. if (DSAChecker.isErrorFound())
  3213. return StmtError();
  3214. // Generate list of implicitly defined firstprivate variables.
  3215. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  3216. SmallVector<Expr *, 4> ImplicitFirstprivates(
  3217. DSAChecker.getImplicitFirstprivate().begin(),
  3218. DSAChecker.getImplicitFirstprivate().end());
  3219. SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
  3220. DSAChecker.getImplicitMap().end());
  3221. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  3222. for (OMPClause *C : Clauses) {
  3223. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  3224. for (Expr *E : IRC->taskgroup_descriptors())
  3225. if (E)
  3226. ImplicitFirstprivates.emplace_back(E);
  3227. }
  3228. }
  3229. if (!ImplicitFirstprivates.empty()) {
  3230. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  3231. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  3232. SourceLocation())) {
  3233. ClausesWithImplicit.push_back(Implicit);
  3234. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  3235. ImplicitFirstprivates.size();
  3236. } else {
  3237. ErrorFound = true;
  3238. }
  3239. }
  3240. if (!ImplicitMaps.empty()) {
  3241. CXXScopeSpec MapperIdScopeSpec;
  3242. DeclarationNameInfo MapperId;
  3243. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  3244. llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
  3245. OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
  3246. SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
  3247. ClausesWithImplicit.emplace_back(Implicit);
  3248. ErrorFound |=
  3249. cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
  3250. } else {
  3251. ErrorFound = true;
  3252. }
  3253. }
  3254. }
  3255. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  3256. switch (Kind) {
  3257. case OMPD_parallel:
  3258. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  3259. EndLoc);
  3260. AllowedNameModifiers.push_back(OMPD_parallel);
  3261. break;
  3262. case OMPD_simd:
  3263. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  3264. VarsWithInheritedDSA);
  3265. break;
  3266. case OMPD_for:
  3267. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  3268. VarsWithInheritedDSA);
  3269. break;
  3270. case OMPD_for_simd:
  3271. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3272. EndLoc, VarsWithInheritedDSA);
  3273. break;
  3274. case OMPD_sections:
  3275. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  3276. EndLoc);
  3277. break;
  3278. case OMPD_section:
  3279. assert(ClausesWithImplicit.empty() &&
  3280. "No clauses are allowed for 'omp section' directive");
  3281. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  3282. break;
  3283. case OMPD_single:
  3284. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  3285. EndLoc);
  3286. break;
  3287. case OMPD_master:
  3288. assert(ClausesWithImplicit.empty() &&
  3289. "No clauses are allowed for 'omp master' directive");
  3290. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  3291. break;
  3292. case OMPD_critical:
  3293. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  3294. StartLoc, EndLoc);
  3295. break;
  3296. case OMPD_parallel_for:
  3297. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  3298. EndLoc, VarsWithInheritedDSA);
  3299. AllowedNameModifiers.push_back(OMPD_parallel);
  3300. break;
  3301. case OMPD_parallel_for_simd:
  3302. Res = ActOnOpenMPParallelForSimdDirective(
  3303. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3304. AllowedNameModifiers.push_back(OMPD_parallel);
  3305. break;
  3306. case OMPD_parallel_sections:
  3307. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  3308. StartLoc, EndLoc);
  3309. AllowedNameModifiers.push_back(OMPD_parallel);
  3310. break;
  3311. case OMPD_task:
  3312. Res =
  3313. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  3314. AllowedNameModifiers.push_back(OMPD_task);
  3315. break;
  3316. case OMPD_taskyield:
  3317. assert(ClausesWithImplicit.empty() &&
  3318. "No clauses are allowed for 'omp taskyield' directive");
  3319. assert(AStmt == nullptr &&
  3320. "No associated statement allowed for 'omp taskyield' directive");
  3321. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  3322. break;
  3323. case OMPD_barrier:
  3324. assert(ClausesWithImplicit.empty() &&
  3325. "No clauses are allowed for 'omp barrier' directive");
  3326. assert(AStmt == nullptr &&
  3327. "No associated statement allowed for 'omp barrier' directive");
  3328. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  3329. break;
  3330. case OMPD_taskwait:
  3331. assert(ClausesWithImplicit.empty() &&
  3332. "No clauses are allowed for 'omp taskwait' directive");
  3333. assert(AStmt == nullptr &&
  3334. "No associated statement allowed for 'omp taskwait' directive");
  3335. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  3336. break;
  3337. case OMPD_taskgroup:
  3338. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  3339. EndLoc);
  3340. break;
  3341. case OMPD_flush:
  3342. assert(AStmt == nullptr &&
  3343. "No associated statement allowed for 'omp flush' directive");
  3344. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  3345. break;
  3346. case OMPD_ordered:
  3347. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  3348. EndLoc);
  3349. break;
  3350. case OMPD_atomic:
  3351. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  3352. EndLoc);
  3353. break;
  3354. case OMPD_teams:
  3355. Res =
  3356. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  3357. break;
  3358. case OMPD_target:
  3359. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  3360. EndLoc);
  3361. AllowedNameModifiers.push_back(OMPD_target);
  3362. break;
  3363. case OMPD_target_parallel:
  3364. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  3365. StartLoc, EndLoc);
  3366. AllowedNameModifiers.push_back(OMPD_target);
  3367. AllowedNameModifiers.push_back(OMPD_parallel);
  3368. break;
  3369. case OMPD_target_parallel_for:
  3370. Res = ActOnOpenMPTargetParallelForDirective(
  3371. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3372. AllowedNameModifiers.push_back(OMPD_target);
  3373. AllowedNameModifiers.push_back(OMPD_parallel);
  3374. break;
  3375. case OMPD_cancellation_point:
  3376. assert(ClausesWithImplicit.empty() &&
  3377. "No clauses are allowed for 'omp cancellation point' directive");
  3378. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  3379. "cancellation point' directive");
  3380. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  3381. break;
  3382. case OMPD_cancel:
  3383. assert(AStmt == nullptr &&
  3384. "No associated statement allowed for 'omp cancel' directive");
  3385. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  3386. CancelRegion);
  3387. AllowedNameModifiers.push_back(OMPD_cancel);
  3388. break;
  3389. case OMPD_target_data:
  3390. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  3391. EndLoc);
  3392. AllowedNameModifiers.push_back(OMPD_target_data);
  3393. break;
  3394. case OMPD_target_enter_data:
  3395. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  3396. EndLoc, AStmt);
  3397. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  3398. break;
  3399. case OMPD_target_exit_data:
  3400. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  3401. EndLoc, AStmt);
  3402. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  3403. break;
  3404. case OMPD_taskloop:
  3405. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  3406. EndLoc, VarsWithInheritedDSA);
  3407. AllowedNameModifiers.push_back(OMPD_taskloop);
  3408. break;
  3409. case OMPD_taskloop_simd:
  3410. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3411. EndLoc, VarsWithInheritedDSA);
  3412. AllowedNameModifiers.push_back(OMPD_taskloop);
  3413. break;
  3414. case OMPD_distribute:
  3415. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  3416. EndLoc, VarsWithInheritedDSA);
  3417. break;
  3418. case OMPD_target_update:
  3419. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  3420. EndLoc, AStmt);
  3421. AllowedNameModifiers.push_back(OMPD_target_update);
  3422. break;
  3423. case OMPD_distribute_parallel_for:
  3424. Res = ActOnOpenMPDistributeParallelForDirective(
  3425. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3426. AllowedNameModifiers.push_back(OMPD_parallel);
  3427. break;
  3428. case OMPD_distribute_parallel_for_simd:
  3429. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  3430. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3431. AllowedNameModifiers.push_back(OMPD_parallel);
  3432. break;
  3433. case OMPD_distribute_simd:
  3434. Res = ActOnOpenMPDistributeSimdDirective(
  3435. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3436. break;
  3437. case OMPD_target_parallel_for_simd:
  3438. Res = ActOnOpenMPTargetParallelForSimdDirective(
  3439. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3440. AllowedNameModifiers.push_back(OMPD_target);
  3441. AllowedNameModifiers.push_back(OMPD_parallel);
  3442. break;
  3443. case OMPD_target_simd:
  3444. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  3445. EndLoc, VarsWithInheritedDSA);
  3446. AllowedNameModifiers.push_back(OMPD_target);
  3447. break;
  3448. case OMPD_teams_distribute:
  3449. Res = ActOnOpenMPTeamsDistributeDirective(
  3450. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3451. break;
  3452. case OMPD_teams_distribute_simd:
  3453. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  3454. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3455. break;
  3456. case OMPD_teams_distribute_parallel_for_simd:
  3457. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  3458. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3459. AllowedNameModifiers.push_back(OMPD_parallel);
  3460. break;
  3461. case OMPD_teams_distribute_parallel_for:
  3462. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  3463. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3464. AllowedNameModifiers.push_back(OMPD_parallel);
  3465. break;
  3466. case OMPD_target_teams:
  3467. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  3468. EndLoc);
  3469. AllowedNameModifiers.push_back(OMPD_target);
  3470. break;
  3471. case OMPD_target_teams_distribute:
  3472. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  3473. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3474. AllowedNameModifiers.push_back(OMPD_target);
  3475. break;
  3476. case OMPD_target_teams_distribute_parallel_for:
  3477. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  3478. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3479. AllowedNameModifiers.push_back(OMPD_target);
  3480. AllowedNameModifiers.push_back(OMPD_parallel);
  3481. break;
  3482. case OMPD_target_teams_distribute_parallel_for_simd:
  3483. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  3484. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3485. AllowedNameModifiers.push_back(OMPD_target);
  3486. AllowedNameModifiers.push_back(OMPD_parallel);
  3487. break;
  3488. case OMPD_target_teams_distribute_simd:
  3489. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  3490. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  3491. AllowedNameModifiers.push_back(OMPD_target);
  3492. break;
  3493. case OMPD_declare_target:
  3494. case OMPD_end_declare_target:
  3495. case OMPD_threadprivate:
  3496. case OMPD_declare_reduction:
  3497. case OMPD_declare_mapper:
  3498. case OMPD_declare_simd:
  3499. case OMPD_requires:
  3500. llvm_unreachable("OpenMP Directive is not allowed");
  3501. case OMPD_unknown:
  3502. llvm_unreachable("Unknown OpenMP directive");
  3503. }
  3504. for (const auto &P : VarsWithInheritedDSA) {
  3505. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  3506. << P.first << P.second->getSourceRange();
  3507. }
  3508. ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
  3509. if (!AllowedNameModifiers.empty())
  3510. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  3511. ErrorFound;
  3512. if (ErrorFound)
  3513. return StmtError();
  3514. return Res;
  3515. }
  3516. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  3517. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  3518. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  3519. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  3520. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  3521. assert(Aligneds.size() == Alignments.size());
  3522. assert(Linears.size() == LinModifiers.size());
  3523. assert(Linears.size() == Steps.size());
  3524. if (!DG || DG.get().isNull())
  3525. return DeclGroupPtrTy();
  3526. if (!DG.get().isSingleDecl()) {
  3527. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
  3528. return DG;
  3529. }
  3530. Decl *ADecl = DG.get().getSingleDecl();
  3531. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  3532. ADecl = FTD->getTemplatedDecl();
  3533. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  3534. if (!FD) {
  3535. Diag(ADecl->getLocation(), diag::err_omp_function_expected);
  3536. return DeclGroupPtrTy();
  3537. }
  3538. // OpenMP [2.8.2, declare simd construct, Description]
  3539. // The parameter of the simdlen clause must be a constant positive integer
  3540. // expression.
  3541. ExprResult SL;
  3542. if (Simdlen)
  3543. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  3544. // OpenMP [2.8.2, declare simd construct, Description]
  3545. // The special this pointer can be used as if was one of the arguments to the
  3546. // function in any of the linear, aligned, or uniform clauses.
  3547. // The uniform clause declares one or more arguments to have an invariant
  3548. // value for all concurrent invocations of the function in the execution of a
  3549. // single SIMD loop.
  3550. llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
  3551. const Expr *UniformedLinearThis = nullptr;
  3552. for (const Expr *E : Uniforms) {
  3553. E = E->IgnoreParenImpCasts();
  3554. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3555. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  3556. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3557. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3558. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  3559. UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
  3560. continue;
  3561. }
  3562. if (isa<CXXThisExpr>(E)) {
  3563. UniformedLinearThis = E;
  3564. continue;
  3565. }
  3566. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3567. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3568. }
  3569. // OpenMP [2.8.2, declare simd construct, Description]
  3570. // The aligned clause declares that the object to which each list item points
  3571. // is aligned to the number of bytes expressed in the optional parameter of
  3572. // the aligned clause.
  3573. // The special this pointer can be used as if was one of the arguments to the
  3574. // function in any of the linear, aligned, or uniform clauses.
  3575. // The type of list items appearing in the aligned clause must be array,
  3576. // pointer, reference to array, or reference to pointer.
  3577. llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
  3578. const Expr *AlignedThis = nullptr;
  3579. for (const Expr *E : Aligneds) {
  3580. E = E->IgnoreParenImpCasts();
  3581. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3582. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3583. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3584. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3585. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3586. ->getCanonicalDecl() == CanonPVD) {
  3587. // OpenMP [2.8.1, simd construct, Restrictions]
  3588. // A list-item cannot appear in more than one aligned clause.
  3589. if (AlignedArgs.count(CanonPVD) > 0) {
  3590. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3591. << 1 << E->getSourceRange();
  3592. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  3593. diag::note_omp_explicit_dsa)
  3594. << getOpenMPClauseName(OMPC_aligned);
  3595. continue;
  3596. }
  3597. AlignedArgs[CanonPVD] = E;
  3598. QualType QTy = PVD->getType()
  3599. .getNonReferenceType()
  3600. .getUnqualifiedType()
  3601. .getCanonicalType();
  3602. const Type *Ty = QTy.getTypePtrOrNull();
  3603. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  3604. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  3605. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  3606. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  3607. }
  3608. continue;
  3609. }
  3610. }
  3611. if (isa<CXXThisExpr>(E)) {
  3612. if (AlignedThis) {
  3613. Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
  3614. << 2 << E->getSourceRange();
  3615. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3616. << getOpenMPClauseName(OMPC_aligned);
  3617. }
  3618. AlignedThis = E;
  3619. continue;
  3620. }
  3621. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3622. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3623. }
  3624. // The optional parameter of the aligned clause, alignment, must be a constant
  3625. // positive integer expression. If no optional parameter is specified,
  3626. // implementation-defined default alignments for SIMD instructions on the
  3627. // target platforms are assumed.
  3628. SmallVector<const Expr *, 4> NewAligns;
  3629. for (Expr *E : Alignments) {
  3630. ExprResult Align;
  3631. if (E)
  3632. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  3633. NewAligns.push_back(Align.get());
  3634. }
  3635. // OpenMP [2.8.2, declare simd construct, Description]
  3636. // The linear clause declares one or more list items to be private to a SIMD
  3637. // lane and to have a linear relationship with respect to the iteration space
  3638. // of a loop.
  3639. // The special this pointer can be used as if was one of the arguments to the
  3640. // function in any of the linear, aligned, or uniform clauses.
  3641. // When a linear-step expression is specified in a linear clause it must be
  3642. // either a constant integer expression or an integer-typed parameter that is
  3643. // specified in a uniform clause on the directive.
  3644. llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
  3645. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  3646. auto MI = LinModifiers.begin();
  3647. for (const Expr *E : Linears) {
  3648. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  3649. ++MI;
  3650. E = E->IgnoreParenImpCasts();
  3651. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  3652. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3653. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3654. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  3655. FD->getParamDecl(PVD->getFunctionScopeIndex())
  3656. ->getCanonicalDecl() == CanonPVD) {
  3657. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  3658. // A list-item cannot appear in more than one linear clause.
  3659. if (LinearArgs.count(CanonPVD) > 0) {
  3660. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3661. << getOpenMPClauseName(OMPC_linear)
  3662. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  3663. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  3664. diag::note_omp_explicit_dsa)
  3665. << getOpenMPClauseName(OMPC_linear);
  3666. continue;
  3667. }
  3668. // Each argument can appear in at most one uniform or linear clause.
  3669. if (UniformedArgs.count(CanonPVD) > 0) {
  3670. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3671. << getOpenMPClauseName(OMPC_linear)
  3672. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  3673. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  3674. diag::note_omp_explicit_dsa)
  3675. << getOpenMPClauseName(OMPC_uniform);
  3676. continue;
  3677. }
  3678. LinearArgs[CanonPVD] = E;
  3679. if (E->isValueDependent() || E->isTypeDependent() ||
  3680. E->isInstantiationDependent() ||
  3681. E->containsUnexpandedParameterPack())
  3682. continue;
  3683. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  3684. PVD->getOriginalType());
  3685. continue;
  3686. }
  3687. }
  3688. if (isa<CXXThisExpr>(E)) {
  3689. if (UniformedLinearThis) {
  3690. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  3691. << getOpenMPClauseName(OMPC_linear)
  3692. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  3693. << E->getSourceRange();
  3694. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  3695. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  3696. : OMPC_linear);
  3697. continue;
  3698. }
  3699. UniformedLinearThis = E;
  3700. if (E->isValueDependent() || E->isTypeDependent() ||
  3701. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  3702. continue;
  3703. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  3704. E->getType());
  3705. continue;
  3706. }
  3707. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  3708. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  3709. }
  3710. Expr *Step = nullptr;
  3711. Expr *NewStep = nullptr;
  3712. SmallVector<Expr *, 4> NewSteps;
  3713. for (Expr *E : Steps) {
  3714. // Skip the same step expression, it was checked already.
  3715. if (Step == E || !E) {
  3716. NewSteps.push_back(E ? NewStep : nullptr);
  3717. continue;
  3718. }
  3719. Step = E;
  3720. if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
  3721. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  3722. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  3723. if (UniformedArgs.count(CanonPVD) == 0) {
  3724. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  3725. << Step->getSourceRange();
  3726. } else if (E->isValueDependent() || E->isTypeDependent() ||
  3727. E->isInstantiationDependent() ||
  3728. E->containsUnexpandedParameterPack() ||
  3729. CanonPVD->getType()->hasIntegerRepresentation()) {
  3730. NewSteps.push_back(Step);
  3731. } else {
  3732. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  3733. << Step->getSourceRange();
  3734. }
  3735. continue;
  3736. }
  3737. NewStep = Step;
  3738. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  3739. !Step->isInstantiationDependent() &&
  3740. !Step->containsUnexpandedParameterPack()) {
  3741. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  3742. .get();
  3743. if (NewStep)
  3744. NewStep = VerifyIntegerConstantExpression(NewStep).get();
  3745. }
  3746. NewSteps.push_back(NewStep);
  3747. }
  3748. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  3749. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  3750. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  3751. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  3752. const_cast<Expr **>(Linears.data()), Linears.size(),
  3753. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  3754. NewSteps.data(), NewSteps.size(), SR);
  3755. ADecl->addAttr(NewAttr);
  3756. return ConvertDeclToDeclGroup(ADecl);
  3757. }
  3758. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  3759. Stmt *AStmt,
  3760. SourceLocation StartLoc,
  3761. SourceLocation EndLoc) {
  3762. if (!AStmt)
  3763. return StmtError();
  3764. auto *CS = cast<CapturedStmt>(AStmt);
  3765. // 1.2.2 OpenMP Language Terminology
  3766. // Structured block - An executable statement with a single entry at the
  3767. // top and a single exit at the bottom.
  3768. // The point of exit cannot be a branch out of the structured block.
  3769. // longjmp() and throw() must not violate the entry/exit criteria.
  3770. CS->getCapturedDecl()->setNothrow();
  3771. setFunctionHasBranchProtectedScope();
  3772. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  3773. DSAStack->isCancelRegion());
  3774. }
  3775. namespace {
  3776. /// Helper class for checking canonical form of the OpenMP loops and
  3777. /// extracting iteration space of each loop in the loop nest, that will be used
  3778. /// for IR generation.
  3779. class OpenMPIterationSpaceChecker {
  3780. /// Reference to Sema.
  3781. Sema &SemaRef;
  3782. /// A location for diagnostics (when there is no some better location).
  3783. SourceLocation DefaultLoc;
  3784. /// A location for diagnostics (when increment is not compatible).
  3785. SourceLocation ConditionLoc;
  3786. /// A source location for referring to loop init later.
  3787. SourceRange InitSrcRange;
  3788. /// A source location for referring to condition later.
  3789. SourceRange ConditionSrcRange;
  3790. /// A source location for referring to increment later.
  3791. SourceRange IncrementSrcRange;
  3792. /// Loop variable.
  3793. ValueDecl *LCDecl = nullptr;
  3794. /// Reference to loop variable.
  3795. Expr *LCRef = nullptr;
  3796. /// Lower bound (initializer for the var).
  3797. Expr *LB = nullptr;
  3798. /// Upper bound.
  3799. Expr *UB = nullptr;
  3800. /// Loop step (increment).
  3801. Expr *Step = nullptr;
  3802. /// This flag is true when condition is one of:
  3803. /// Var < UB
  3804. /// Var <= UB
  3805. /// UB > Var
  3806. /// UB >= Var
  3807. /// This will have no value when the condition is !=
  3808. llvm::Optional<bool> TestIsLessOp;
  3809. /// This flag is true when condition is strict ( < or > ).
  3810. bool TestIsStrictOp = false;
  3811. /// This flag is true when step is subtracted on each iteration.
  3812. bool SubtractStep = false;
  3813. public:
  3814. OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
  3815. : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
  3816. /// Check init-expr for canonical loop form and save loop counter
  3817. /// variable - #Var and its initialization value - #LB.
  3818. bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
  3819. /// Check test-expr for canonical form, save upper-bound (#UB), flags
  3820. /// for less/greater and for strict/non-strict comparison.
  3821. bool checkAndSetCond(Expr *S);
  3822. /// Check incr-expr for canonical loop form and return true if it
  3823. /// does not conform, otherwise save loop step (#Step).
  3824. bool checkAndSetInc(Expr *S);
  3825. /// Return the loop counter variable.
  3826. ValueDecl *getLoopDecl() const { return LCDecl; }
  3827. /// Return the reference expression to loop counter variable.
  3828. Expr *getLoopDeclRefExpr() const { return LCRef; }
  3829. /// Source range of the loop init.
  3830. SourceRange getInitSrcRange() const { return InitSrcRange; }
  3831. /// Source range of the loop condition.
  3832. SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
  3833. /// Source range of the loop increment.
  3834. SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
  3835. /// True if the step should be subtracted.
  3836. bool shouldSubtractStep() const { return SubtractStep; }
  3837. /// True, if the compare operator is strict (<, > or !=).
  3838. bool isStrictTestOp() const { return TestIsStrictOp; }
  3839. /// Build the expression to calculate the number of iterations.
  3840. Expr *buildNumIterations(
  3841. Scope *S, const bool LimitedType,
  3842. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  3843. /// Build the precondition expression for the loops.
  3844. Expr *
  3845. buildPreCond(Scope *S, Expr *Cond,
  3846. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  3847. /// Build reference expression to the counter be used for codegen.
  3848. DeclRefExpr *
  3849. buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  3850. DSAStackTy &DSA) const;
  3851. /// Build reference expression to the private counter be used for
  3852. /// codegen.
  3853. Expr *buildPrivateCounterVar() const;
  3854. /// Build initialization of the counter be used for codegen.
  3855. Expr *buildCounterInit() const;
  3856. /// Build step of the counter be used for codegen.
  3857. Expr *buildCounterStep() const;
  3858. /// Build loop data with counter value for depend clauses in ordered
  3859. /// directives.
  3860. Expr *
  3861. buildOrderedLoopData(Scope *S, Expr *Counter,
  3862. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  3863. SourceLocation Loc, Expr *Inc = nullptr,
  3864. OverloadedOperatorKind OOK = OO_Amp);
  3865. /// Return true if any expression is dependent.
  3866. bool dependent() const;
  3867. private:
  3868. /// Check the right-hand side of an assignment in the increment
  3869. /// expression.
  3870. bool checkAndSetIncRHS(Expr *RHS);
  3871. /// Helper to set loop counter variable and its initializer.
  3872. bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
  3873. /// Helper to set upper bound.
  3874. bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
  3875. SourceRange SR, SourceLocation SL);
  3876. /// Helper to set loop increment.
  3877. bool setStep(Expr *NewStep, bool Subtract);
  3878. };
  3879. bool OpenMPIterationSpaceChecker::dependent() const {
  3880. if (!LCDecl) {
  3881. assert(!LB && !UB && !Step);
  3882. return false;
  3883. }
  3884. return LCDecl->getType()->isDependentType() ||
  3885. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  3886. (Step && Step->isValueDependent());
  3887. }
  3888. bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
  3889. Expr *NewLCRefExpr,
  3890. Expr *NewLB) {
  3891. // State consistency checking to ensure correct usage.
  3892. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  3893. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3894. if (!NewLCDecl || !NewLB)
  3895. return true;
  3896. LCDecl = getCanonicalDecl(NewLCDecl);
  3897. LCRef = NewLCRefExpr;
  3898. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  3899. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3900. if ((Ctor->isCopyOrMoveConstructor() ||
  3901. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3902. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3903. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  3904. LB = NewLB;
  3905. return false;
  3906. }
  3907. bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
  3908. llvm::Optional<bool> LessOp,
  3909. bool StrictOp, SourceRange SR,
  3910. SourceLocation SL) {
  3911. // State consistency checking to ensure correct usage.
  3912. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  3913. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  3914. if (!NewUB)
  3915. return true;
  3916. UB = NewUB;
  3917. if (LessOp)
  3918. TestIsLessOp = LessOp;
  3919. TestIsStrictOp = StrictOp;
  3920. ConditionSrcRange = SR;
  3921. ConditionLoc = SL;
  3922. return false;
  3923. }
  3924. bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
  3925. // State consistency checking to ensure correct usage.
  3926. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  3927. if (!NewStep)
  3928. return true;
  3929. if (!NewStep->isValueDependent()) {
  3930. // Check that the step is integer expression.
  3931. SourceLocation StepLoc = NewStep->getBeginLoc();
  3932. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  3933. StepLoc, getExprAsWritten(NewStep));
  3934. if (Val.isInvalid())
  3935. return true;
  3936. NewStep = Val.get();
  3937. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  3938. // If test-expr is of form var relational-op b and relational-op is < or
  3939. // <= then incr-expr must cause var to increase on each iteration of the
  3940. // loop. If test-expr is of form var relational-op b and relational-op is
  3941. // > or >= then incr-expr must cause var to decrease on each iteration of
  3942. // the loop.
  3943. // If test-expr is of form b relational-op var and relational-op is < or
  3944. // <= then incr-expr must cause var to decrease on each iteration of the
  3945. // loop. If test-expr is of form b relational-op var and relational-op is
  3946. // > or >= then incr-expr must cause var to increase on each iteration of
  3947. // the loop.
  3948. llvm::APSInt Result;
  3949. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  3950. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  3951. bool IsConstNeg =
  3952. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  3953. bool IsConstPos =
  3954. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  3955. bool IsConstZero = IsConstant && !Result.getBoolValue();
  3956. // != with increment is treated as <; != with decrement is treated as >
  3957. if (!TestIsLessOp.hasValue())
  3958. TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
  3959. if (UB && (IsConstZero ||
  3960. (TestIsLessOp.getValue() ?
  3961. (IsConstNeg || (IsUnsigned && Subtract)) :
  3962. (IsConstPos || (IsUnsigned && !Subtract))))) {
  3963. SemaRef.Diag(NewStep->getExprLoc(),
  3964. diag::err_omp_loop_incr_not_compatible)
  3965. << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
  3966. SemaRef.Diag(ConditionLoc,
  3967. diag::note_omp_loop_cond_requres_compatible_incr)
  3968. << TestIsLessOp.getValue() << ConditionSrcRange;
  3969. return true;
  3970. }
  3971. if (TestIsLessOp.getValue() == Subtract) {
  3972. NewStep =
  3973. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  3974. .get();
  3975. Subtract = !Subtract;
  3976. }
  3977. }
  3978. Step = NewStep;
  3979. SubtractStep = Subtract;
  3980. return false;
  3981. }
  3982. bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
  3983. // Check init-expr for canonical loop form and save loop counter
  3984. // variable - #Var and its initialization value - #LB.
  3985. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  3986. // var = lb
  3987. // integer-type var = lb
  3988. // random-access-iterator-type var = lb
  3989. // pointer-type var = lb
  3990. //
  3991. if (!S) {
  3992. if (EmitDiags) {
  3993. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  3994. }
  3995. return true;
  3996. }
  3997. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  3998. if (!ExprTemp->cleanupsHaveSideEffects())
  3999. S = ExprTemp->getSubExpr();
  4000. InitSrcRange = S->getSourceRange();
  4001. if (Expr *E = dyn_cast<Expr>(S))
  4002. S = E->IgnoreParens();
  4003. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  4004. if (BO->getOpcode() == BO_Assign) {
  4005. Expr *LHS = BO->getLHS()->IgnoreParens();
  4006. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  4007. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  4008. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  4009. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  4010. return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
  4011. }
  4012. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  4013. if (ME->isArrow() &&
  4014. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  4015. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  4016. }
  4017. }
  4018. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  4019. if (DS->isSingleDecl()) {
  4020. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  4021. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  4022. // Accept non-canonical init form here but emit ext. warning.
  4023. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  4024. SemaRef.Diag(S->getBeginLoc(),
  4025. diag::ext_omp_loop_not_canonical_init)
  4026. << S->getSourceRange();
  4027. return setLCDeclAndLB(
  4028. Var,
  4029. buildDeclRefExpr(SemaRef, Var,
  4030. Var->getType().getNonReferenceType(),
  4031. DS->getBeginLoc()),
  4032. Var->getInit());
  4033. }
  4034. }
  4035. }
  4036. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  4037. if (CE->getOperator() == OO_Equal) {
  4038. Expr *LHS = CE->getArg(0);
  4039. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  4040. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  4041. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  4042. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  4043. return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
  4044. }
  4045. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  4046. if (ME->isArrow() &&
  4047. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  4048. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
  4049. }
  4050. }
  4051. }
  4052. if (dependent() || SemaRef.CurContext->isDependentContext())
  4053. return false;
  4054. if (EmitDiags) {
  4055. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
  4056. << S->getSourceRange();
  4057. }
  4058. return true;
  4059. }
  4060. /// Ignore parenthesizes, implicit casts, copy constructor and return the
  4061. /// variable (which may be the loop variable) if possible.
  4062. static const ValueDecl *getInitLCDecl(const Expr *E) {
  4063. if (!E)
  4064. return nullptr;
  4065. E = getExprAsWritten(E);
  4066. if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  4067. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  4068. if ((Ctor->isCopyOrMoveConstructor() ||
  4069. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  4070. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  4071. E = CE->getArg(0)->IgnoreParenImpCasts();
  4072. if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  4073. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  4074. return getCanonicalDecl(VD);
  4075. }
  4076. if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
  4077. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  4078. return getCanonicalDecl(ME->getMemberDecl());
  4079. return nullptr;
  4080. }
  4081. bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
  4082. // Check test-expr for canonical form, save upper-bound UB, flags for
  4083. // less/greater and for strict/non-strict comparison.
  4084. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  4085. // var relational-op b
  4086. // b relational-op var
  4087. //
  4088. if (!S) {
  4089. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
  4090. return true;
  4091. }
  4092. S = getExprAsWritten(S);
  4093. SourceLocation CondLoc = S->getBeginLoc();
  4094. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  4095. if (BO->isRelationalOp()) {
  4096. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4097. return setUB(BO->getRHS(),
  4098. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  4099. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  4100. BO->getSourceRange(), BO->getOperatorLoc());
  4101. if (getInitLCDecl(BO->getRHS()) == LCDecl)
  4102. return setUB(BO->getLHS(),
  4103. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  4104. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  4105. BO->getSourceRange(), BO->getOperatorLoc());
  4106. } else if (BO->getOpcode() == BO_NE)
  4107. return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
  4108. BO->getRHS() : BO->getLHS(),
  4109. /*LessOp=*/llvm::None,
  4110. /*StrictOp=*/true,
  4111. BO->getSourceRange(), BO->getOperatorLoc());
  4112. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  4113. if (CE->getNumArgs() == 2) {
  4114. auto Op = CE->getOperator();
  4115. switch (Op) {
  4116. case OO_Greater:
  4117. case OO_GreaterEqual:
  4118. case OO_Less:
  4119. case OO_LessEqual:
  4120. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4121. return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  4122. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  4123. CE->getOperatorLoc());
  4124. if (getInitLCDecl(CE->getArg(1)) == LCDecl)
  4125. return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  4126. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  4127. CE->getOperatorLoc());
  4128. break;
  4129. case OO_ExclaimEqual:
  4130. return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
  4131. CE->getArg(1) : CE->getArg(0),
  4132. /*LessOp=*/llvm::None,
  4133. /*StrictOp=*/true,
  4134. CE->getSourceRange(),
  4135. CE->getOperatorLoc());
  4136. break;
  4137. default:
  4138. break;
  4139. }
  4140. }
  4141. }
  4142. if (dependent() || SemaRef.CurContext->isDependentContext())
  4143. return false;
  4144. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  4145. << S->getSourceRange() << LCDecl;
  4146. return true;
  4147. }
  4148. bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
  4149. // RHS of canonical loop form increment can be:
  4150. // var + incr
  4151. // incr + var
  4152. // var - incr
  4153. //
  4154. RHS = RHS->IgnoreParenImpCasts();
  4155. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  4156. if (BO->isAdditiveOp()) {
  4157. bool IsAdd = BO->getOpcode() == BO_Add;
  4158. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4159. return setStep(BO->getRHS(), !IsAdd);
  4160. if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
  4161. return setStep(BO->getLHS(), /*Subtract=*/false);
  4162. }
  4163. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  4164. bool IsAdd = CE->getOperator() == OO_Plus;
  4165. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  4166. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4167. return setStep(CE->getArg(1), !IsAdd);
  4168. if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
  4169. return setStep(CE->getArg(0), /*Subtract=*/false);
  4170. }
  4171. }
  4172. if (dependent() || SemaRef.CurContext->isDependentContext())
  4173. return false;
  4174. SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  4175. << RHS->getSourceRange() << LCDecl;
  4176. return true;
  4177. }
  4178. bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
  4179. // Check incr-expr for canonical loop form and return true if it
  4180. // does not conform.
  4181. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  4182. // ++var
  4183. // var++
  4184. // --var
  4185. // var--
  4186. // var += incr
  4187. // var -= incr
  4188. // var = var + incr
  4189. // var = incr + var
  4190. // var = var - incr
  4191. //
  4192. if (!S) {
  4193. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  4194. return true;
  4195. }
  4196. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  4197. if (!ExprTemp->cleanupsHaveSideEffects())
  4198. S = ExprTemp->getSubExpr();
  4199. IncrementSrcRange = S->getSourceRange();
  4200. S = S->IgnoreParens();
  4201. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  4202. if (UO->isIncrementDecrementOp() &&
  4203. getInitLCDecl(UO->getSubExpr()) == LCDecl)
  4204. return setStep(SemaRef
  4205. .ActOnIntegerConstant(UO->getBeginLoc(),
  4206. (UO->isDecrementOp() ? -1 : 1))
  4207. .get(),
  4208. /*Subtract=*/false);
  4209. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  4210. switch (BO->getOpcode()) {
  4211. case BO_AddAssign:
  4212. case BO_SubAssign:
  4213. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4214. return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  4215. break;
  4216. case BO_Assign:
  4217. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  4218. return checkAndSetIncRHS(BO->getRHS());
  4219. break;
  4220. default:
  4221. break;
  4222. }
  4223. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  4224. switch (CE->getOperator()) {
  4225. case OO_PlusPlus:
  4226. case OO_MinusMinus:
  4227. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4228. return setStep(SemaRef
  4229. .ActOnIntegerConstant(
  4230. CE->getBeginLoc(),
  4231. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  4232. .get(),
  4233. /*Subtract=*/false);
  4234. break;
  4235. case OO_PlusEqual:
  4236. case OO_MinusEqual:
  4237. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4238. return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  4239. break;
  4240. case OO_Equal:
  4241. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  4242. return checkAndSetIncRHS(CE->getArg(1));
  4243. break;
  4244. default:
  4245. break;
  4246. }
  4247. }
  4248. if (dependent() || SemaRef.CurContext->isDependentContext())
  4249. return false;
  4250. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  4251. << S->getSourceRange() << LCDecl;
  4252. return true;
  4253. }
  4254. static ExprResult
  4255. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  4256. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4257. if (SemaRef.CurContext->isDependentContext())
  4258. return ExprResult(Capture);
  4259. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  4260. return SemaRef.PerformImplicitConversion(
  4261. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  4262. /*AllowExplicit=*/true);
  4263. auto I = Captures.find(Capture);
  4264. if (I != Captures.end())
  4265. return buildCapture(SemaRef, Capture, I->second);
  4266. DeclRefExpr *Ref = nullptr;
  4267. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  4268. Captures[Capture] = Ref;
  4269. return Res;
  4270. }
  4271. /// Build the expression to calculate the number of iterations.
  4272. Expr *OpenMPIterationSpaceChecker::buildNumIterations(
  4273. Scope *S, const bool LimitedType,
  4274. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  4275. ExprResult Diff;
  4276. QualType VarType = LCDecl->getType().getNonReferenceType();
  4277. if (VarType->isIntegerType() || VarType->isPointerType() ||
  4278. SemaRef.getLangOpts().CPlusPlus) {
  4279. // Upper - Lower
  4280. Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
  4281. Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
  4282. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  4283. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  4284. if (!Upper || !Lower)
  4285. return nullptr;
  4286. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  4287. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  4288. // BuildBinOp already emitted error, this one is to point user to upper
  4289. // and lower bound, and to tell what is passed to 'operator-'.
  4290. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  4291. << Upper->getSourceRange() << Lower->getSourceRange();
  4292. return nullptr;
  4293. }
  4294. }
  4295. if (!Diff.isUsable())
  4296. return nullptr;
  4297. // Upper - Lower [- 1]
  4298. if (TestIsStrictOp)
  4299. Diff = SemaRef.BuildBinOp(
  4300. S, DefaultLoc, BO_Sub, Diff.get(),
  4301. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  4302. if (!Diff.isUsable())
  4303. return nullptr;
  4304. // Upper - Lower [- 1] + Step
  4305. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  4306. if (!NewStep.isUsable())
  4307. return nullptr;
  4308. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  4309. if (!Diff.isUsable())
  4310. return nullptr;
  4311. // Parentheses (for dumping/debugging purposes only).
  4312. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  4313. if (!Diff.isUsable())
  4314. return nullptr;
  4315. // (Upper - Lower [- 1] + Step) / Step
  4316. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  4317. if (!Diff.isUsable())
  4318. return nullptr;
  4319. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  4320. QualType Type = Diff.get()->getType();
  4321. ASTContext &C = SemaRef.Context;
  4322. bool UseVarType = VarType->hasIntegerRepresentation() &&
  4323. C.getTypeSize(Type) > C.getTypeSize(VarType);
  4324. if (!Type->isIntegerType() || UseVarType) {
  4325. unsigned NewSize =
  4326. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  4327. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  4328. : Type->hasSignedIntegerRepresentation();
  4329. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  4330. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  4331. Diff = SemaRef.PerformImplicitConversion(
  4332. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  4333. if (!Diff.isUsable())
  4334. return nullptr;
  4335. }
  4336. }
  4337. if (LimitedType) {
  4338. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  4339. if (NewSize != C.getTypeSize(Type)) {
  4340. if (NewSize < C.getTypeSize(Type)) {
  4341. assert(NewSize == 64 && "incorrect loop var size");
  4342. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  4343. << InitSrcRange << ConditionSrcRange;
  4344. }
  4345. QualType NewType = C.getIntTypeForBitwidth(
  4346. NewSize, Type->hasSignedIntegerRepresentation() ||
  4347. C.getTypeSize(Type) < NewSize);
  4348. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  4349. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  4350. Sema::AA_Converting, true);
  4351. if (!Diff.isUsable())
  4352. return nullptr;
  4353. }
  4354. }
  4355. }
  4356. return Diff.get();
  4357. }
  4358. Expr *OpenMPIterationSpaceChecker::buildPreCond(
  4359. Scope *S, Expr *Cond,
  4360. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  4361. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  4362. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4363. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4364. ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
  4365. ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
  4366. if (!NewLB.isUsable() || !NewUB.isUsable())
  4367. return nullptr;
  4368. ExprResult CondExpr =
  4369. SemaRef.BuildBinOp(S, DefaultLoc,
  4370. TestIsLessOp.getValue() ?
  4371. (TestIsStrictOp ? BO_LT : BO_LE) :
  4372. (TestIsStrictOp ? BO_GT : BO_GE),
  4373. NewLB.get(), NewUB.get());
  4374. if (CondExpr.isUsable()) {
  4375. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  4376. SemaRef.Context.BoolTy))
  4377. CondExpr = SemaRef.PerformImplicitConversion(
  4378. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  4379. /*AllowExplicit=*/true);
  4380. }
  4381. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4382. // Otherwise use original loop condition and evaluate it in runtime.
  4383. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  4384. }
  4385. /// Build reference expression to the counter be used for codegen.
  4386. DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
  4387. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  4388. DSAStackTy &DSA) const {
  4389. auto *VD = dyn_cast<VarDecl>(LCDecl);
  4390. if (!VD) {
  4391. VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
  4392. DeclRefExpr *Ref = buildDeclRefExpr(
  4393. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  4394. const DSAStackTy::DSAVarData Data =
  4395. DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  4396. // If the loop control decl is explicitly marked as private, do not mark it
  4397. // as captured again.
  4398. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  4399. Captures.insert(std::make_pair(LCRef, Ref));
  4400. return Ref;
  4401. }
  4402. return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
  4403. DefaultLoc);
  4404. }
  4405. Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
  4406. if (LCDecl && !LCDecl->isInvalidDecl()) {
  4407. QualType Type = LCDecl->getType().getNonReferenceType();
  4408. VarDecl *PrivateVar = buildVarDecl(
  4409. SemaRef, DefaultLoc, Type, LCDecl->getName(),
  4410. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
  4411. isa<VarDecl>(LCDecl)
  4412. ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
  4413. : nullptr);
  4414. if (PrivateVar->isInvalidDecl())
  4415. return nullptr;
  4416. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  4417. }
  4418. return nullptr;
  4419. }
  4420. /// Build initialization of the counter to be used for codegen.
  4421. Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
  4422. /// Build step of the counter be used for codegen.
  4423. Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
  4424. Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
  4425. Scope *S, Expr *Counter,
  4426. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
  4427. Expr *Inc, OverloadedOperatorKind OOK) {
  4428. Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
  4429. if (!Cnt)
  4430. return nullptr;
  4431. if (Inc) {
  4432. assert((OOK == OO_Plus || OOK == OO_Minus) &&
  4433. "Expected only + or - operations for depend clauses.");
  4434. BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
  4435. Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
  4436. if (!Cnt)
  4437. return nullptr;
  4438. }
  4439. ExprResult Diff;
  4440. QualType VarType = LCDecl->getType().getNonReferenceType();
  4441. if (VarType->isIntegerType() || VarType->isPointerType() ||
  4442. SemaRef.getLangOpts().CPlusPlus) {
  4443. // Upper - Lower
  4444. Expr *Upper = TestIsLessOp.getValue()
  4445. ? Cnt
  4446. : tryBuildCapture(SemaRef, UB, Captures).get();
  4447. Expr *Lower = TestIsLessOp.getValue()
  4448. ? tryBuildCapture(SemaRef, LB, Captures).get()
  4449. : Cnt;
  4450. if (!Upper || !Lower)
  4451. return nullptr;
  4452. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  4453. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  4454. // BuildBinOp already emitted error, this one is to point user to upper
  4455. // and lower bound, and to tell what is passed to 'operator-'.
  4456. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  4457. << Upper->getSourceRange() << Lower->getSourceRange();
  4458. return nullptr;
  4459. }
  4460. }
  4461. if (!Diff.isUsable())
  4462. return nullptr;
  4463. // Parentheses (for dumping/debugging purposes only).
  4464. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  4465. if (!Diff.isUsable())
  4466. return nullptr;
  4467. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  4468. if (!NewStep.isUsable())
  4469. return nullptr;
  4470. // (Upper - Lower) / Step
  4471. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  4472. if (!Diff.isUsable())
  4473. return nullptr;
  4474. return Diff.get();
  4475. }
  4476. /// Iteration space of a single for loop.
  4477. struct LoopIterationSpace final {
  4478. /// True if the condition operator is the strict compare operator (<, > or
  4479. /// !=).
  4480. bool IsStrictCompare = false;
  4481. /// Condition of the loop.
  4482. Expr *PreCond = nullptr;
  4483. /// This expression calculates the number of iterations in the loop.
  4484. /// It is always possible to calculate it before starting the loop.
  4485. Expr *NumIterations = nullptr;
  4486. /// The loop counter variable.
  4487. Expr *CounterVar = nullptr;
  4488. /// Private loop counter variable.
  4489. Expr *PrivateCounterVar = nullptr;
  4490. /// This is initializer for the initial value of #CounterVar.
  4491. Expr *CounterInit = nullptr;
  4492. /// This is step for the #CounterVar used to generate its update:
  4493. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  4494. Expr *CounterStep = nullptr;
  4495. /// Should step be subtracted?
  4496. bool Subtract = false;
  4497. /// Source range of the loop init.
  4498. SourceRange InitSrcRange;
  4499. /// Source range of the loop condition.
  4500. SourceRange CondSrcRange;
  4501. /// Source range of the loop increment.
  4502. SourceRange IncSrcRange;
  4503. };
  4504. } // namespace
  4505. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  4506. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  4507. assert(Init && "Expected loop in canonical form.");
  4508. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  4509. if (AssociatedLoops > 0 &&
  4510. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  4511. DSAStack->loopStart();
  4512. OpenMPIterationSpaceChecker ISC(*this, ForLoc);
  4513. if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
  4514. if (ValueDecl *D = ISC.getLoopDecl()) {
  4515. auto *VD = dyn_cast<VarDecl>(D);
  4516. if (!VD) {
  4517. if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
  4518. VD = Private;
  4519. } else {
  4520. DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
  4521. /*WithInit=*/false);
  4522. VD = cast<VarDecl>(Ref->getDecl());
  4523. }
  4524. }
  4525. DSAStack->addLoopControlVariable(D, VD);
  4526. const Decl *LD = DSAStack->getPossiblyLoopCunter();
  4527. if (LD != D->getCanonicalDecl()) {
  4528. DSAStack->resetPossibleLoopCounter();
  4529. if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
  4530. MarkDeclarationsReferencedInExpr(
  4531. buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
  4532. Var->getType().getNonLValueExprType(Context),
  4533. ForLoc, /*RefersToCapture=*/true));
  4534. }
  4535. }
  4536. }
  4537. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  4538. }
  4539. }
  4540. /// Called on a for stmt to check and extract its iteration space
  4541. /// for further processing (such as collapsing).
  4542. static bool checkOpenMPIterationSpace(
  4543. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  4544. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  4545. unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
  4546. Expr *OrderedLoopCountExpr,
  4547. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  4548. LoopIterationSpace &ResultIterSpace,
  4549. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4550. // OpenMP [2.6, Canonical Loop Form]
  4551. // for (init-expr; test-expr; incr-expr) structured-block
  4552. auto *For = dyn_cast_or_null<ForStmt>(S);
  4553. if (!For) {
  4554. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
  4555. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  4556. << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
  4557. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  4558. if (TotalNestedLoopCount > 1) {
  4559. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  4560. SemaRef.Diag(DSA.getConstructLoc(),
  4561. diag::note_omp_collapse_ordered_expr)
  4562. << 2 << CollapseLoopCountExpr->getSourceRange()
  4563. << OrderedLoopCountExpr->getSourceRange();
  4564. else if (CollapseLoopCountExpr)
  4565. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4566. diag::note_omp_collapse_ordered_expr)
  4567. << 0 << CollapseLoopCountExpr->getSourceRange();
  4568. else
  4569. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4570. diag::note_omp_collapse_ordered_expr)
  4571. << 1 << OrderedLoopCountExpr->getSourceRange();
  4572. }
  4573. return true;
  4574. }
  4575. assert(For->getBody());
  4576. OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
  4577. // Check init.
  4578. Stmt *Init = For->getInit();
  4579. if (ISC.checkAndSetInit(Init))
  4580. return true;
  4581. bool HasErrors = false;
  4582. // Check loop variable's type.
  4583. if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
  4584. Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
  4585. // OpenMP [2.6, Canonical Loop Form]
  4586. // Var is one of the following:
  4587. // A variable of signed or unsigned integer type.
  4588. // For C++, a variable of a random access iterator type.
  4589. // For C, a variable of a pointer type.
  4590. QualType VarType = LCDecl->getType().getNonReferenceType();
  4591. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  4592. !VarType->isPointerType() &&
  4593. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  4594. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
  4595. << SemaRef.getLangOpts().CPlusPlus;
  4596. HasErrors = true;
  4597. }
  4598. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  4599. // a Construct
  4600. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  4601. // parallel for construct is (are) private.
  4602. // The loop iteration variable in the associated for-loop of a simd
  4603. // construct with just one associated for-loop is linear with a
  4604. // constant-linear-step that is the increment of the associated for-loop.
  4605. // Exclude loop var from the list of variables with implicitly defined data
  4606. // sharing attributes.
  4607. VarsWithImplicitDSA.erase(LCDecl);
  4608. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  4609. // in a Construct, C/C++].
  4610. // The loop iteration variable in the associated for-loop of a simd
  4611. // construct with just one associated for-loop may be listed in a linear
  4612. // clause with a constant-linear-step that is the increment of the
  4613. // associated for-loop.
  4614. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  4615. // parallel for construct may be listed in a private or lastprivate clause.
  4616. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
  4617. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  4618. // declared in the loop and it is predetermined as a private.
  4619. OpenMPClauseKind PredeterminedCKind =
  4620. isOpenMPSimdDirective(DKind)
  4621. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  4622. : OMPC_private;
  4623. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  4624. DVar.CKind != PredeterminedCKind) ||
  4625. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  4626. isOpenMPDistributeDirective(DKind)) &&
  4627. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  4628. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  4629. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  4630. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
  4631. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  4632. << getOpenMPClauseName(PredeterminedCKind);
  4633. if (DVar.RefExpr == nullptr)
  4634. DVar.CKind = PredeterminedCKind;
  4635. reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
  4636. HasErrors = true;
  4637. } else if (LoopDeclRefExpr != nullptr) {
  4638. // Make the loop iteration variable private (for worksharing constructs),
  4639. // linear (for simd directives with the only one associated loop) or
  4640. // lastprivate (for simd directives with several collapsed or ordered
  4641. // loops).
  4642. if (DVar.CKind == OMPC_unknown)
  4643. DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
  4644. }
  4645. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  4646. // Check test-expr.
  4647. HasErrors |= ISC.checkAndSetCond(For->getCond());
  4648. // Check incr-expr.
  4649. HasErrors |= ISC.checkAndSetInc(For->getInc());
  4650. }
  4651. if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  4652. return HasErrors;
  4653. // Build the loop's iteration space representation.
  4654. ResultIterSpace.PreCond =
  4655. ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
  4656. ResultIterSpace.NumIterations = ISC.buildNumIterations(
  4657. DSA.getCurScope(),
  4658. (isOpenMPWorksharingDirective(DKind) ||
  4659. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
  4660. Captures);
  4661. ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
  4662. ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
  4663. ResultIterSpace.CounterInit = ISC.buildCounterInit();
  4664. ResultIterSpace.CounterStep = ISC.buildCounterStep();
  4665. ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
  4666. ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
  4667. ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
  4668. ResultIterSpace.Subtract = ISC.shouldSubtractStep();
  4669. ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
  4670. HasErrors |= (ResultIterSpace.PreCond == nullptr ||
  4671. ResultIterSpace.NumIterations == nullptr ||
  4672. ResultIterSpace.CounterVar == nullptr ||
  4673. ResultIterSpace.PrivateCounterVar == nullptr ||
  4674. ResultIterSpace.CounterInit == nullptr ||
  4675. ResultIterSpace.CounterStep == nullptr);
  4676. if (!HasErrors && DSA.isOrderedRegion()) {
  4677. if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
  4678. if (CurrentNestedLoopCount <
  4679. DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
  4680. DSA.getOrderedRegionParam().second->setLoopNumIterations(
  4681. CurrentNestedLoopCount, ResultIterSpace.NumIterations);
  4682. DSA.getOrderedRegionParam().second->setLoopCounter(
  4683. CurrentNestedLoopCount, ResultIterSpace.CounterVar);
  4684. }
  4685. }
  4686. for (auto &Pair : DSA.getDoacrossDependClauses()) {
  4687. if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
  4688. // Erroneous case - clause has some problems.
  4689. continue;
  4690. }
  4691. if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
  4692. Pair.second.size() <= CurrentNestedLoopCount) {
  4693. // Erroneous case - clause has some problems.
  4694. Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
  4695. continue;
  4696. }
  4697. Expr *CntValue;
  4698. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  4699. CntValue = ISC.buildOrderedLoopData(
  4700. DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
  4701. Pair.first->getDependencyLoc());
  4702. else
  4703. CntValue = ISC.buildOrderedLoopData(
  4704. DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
  4705. Pair.first->getDependencyLoc(),
  4706. Pair.second[CurrentNestedLoopCount].first,
  4707. Pair.second[CurrentNestedLoopCount].second);
  4708. Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
  4709. }
  4710. }
  4711. return HasErrors;
  4712. }
  4713. /// Build 'VarRef = Start.
  4714. static ExprResult
  4715. buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  4716. ExprResult Start,
  4717. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4718. // Build 'VarRef = Start.
  4719. ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
  4720. if (!NewStart.isUsable())
  4721. return ExprError();
  4722. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  4723. VarRef.get()->getType())) {
  4724. NewStart = SemaRef.PerformImplicitConversion(
  4725. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  4726. /*AllowExplicit=*/true);
  4727. if (!NewStart.isUsable())
  4728. return ExprError();
  4729. }
  4730. ExprResult Init =
  4731. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4732. return Init;
  4733. }
  4734. /// Build 'VarRef = Start + Iter * Step'.
  4735. static ExprResult buildCounterUpdate(
  4736. Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  4737. ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
  4738. llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
  4739. // Add parentheses (for debugging purposes only).
  4740. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  4741. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  4742. !Step.isUsable())
  4743. return ExprError();
  4744. ExprResult NewStep = Step;
  4745. if (Captures)
  4746. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  4747. if (NewStep.isInvalid())
  4748. return ExprError();
  4749. ExprResult Update =
  4750. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  4751. if (!Update.isUsable())
  4752. return ExprError();
  4753. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  4754. // 'VarRef = Start (+|-) Iter * Step'.
  4755. ExprResult NewStart = Start;
  4756. if (Captures)
  4757. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  4758. if (NewStart.isInvalid())
  4759. return ExprError();
  4760. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  4761. ExprResult SavedUpdate = Update;
  4762. ExprResult UpdateVal;
  4763. if (VarRef.get()->getType()->isOverloadableType() ||
  4764. NewStart.get()->getType()->isOverloadableType() ||
  4765. Update.get()->getType()->isOverloadableType()) {
  4766. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  4767. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  4768. Update =
  4769. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  4770. if (Update.isUsable()) {
  4771. UpdateVal =
  4772. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  4773. VarRef.get(), SavedUpdate.get());
  4774. if (UpdateVal.isUsable()) {
  4775. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  4776. UpdateVal.get());
  4777. }
  4778. }
  4779. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  4780. }
  4781. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  4782. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  4783. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  4784. NewStart.get(), SavedUpdate.get());
  4785. if (!Update.isUsable())
  4786. return ExprError();
  4787. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  4788. VarRef.get()->getType())) {
  4789. Update = SemaRef.PerformImplicitConversion(
  4790. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  4791. if (!Update.isUsable())
  4792. return ExprError();
  4793. }
  4794. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  4795. }
  4796. return Update;
  4797. }
  4798. /// Convert integer expression \a E to make it have at least \a Bits
  4799. /// bits.
  4800. static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  4801. if (E == nullptr)
  4802. return ExprError();
  4803. ASTContext &C = SemaRef.Context;
  4804. QualType OldType = E->getType();
  4805. unsigned HasBits = C.getTypeSize(OldType);
  4806. if (HasBits >= Bits)
  4807. return ExprResult(E);
  4808. // OK to convert to signed, because new type has more bits than old.
  4809. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  4810. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  4811. true);
  4812. }
  4813. /// Check if the given expression \a E is a constant integer that fits
  4814. /// into \a Bits bits.
  4815. static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
  4816. if (E == nullptr)
  4817. return false;
  4818. llvm::APSInt Result;
  4819. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  4820. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  4821. return false;
  4822. }
  4823. /// Build preinits statement for the given declarations.
  4824. static Stmt *buildPreInits(ASTContext &Context,
  4825. MutableArrayRef<Decl *> PreInits) {
  4826. if (!PreInits.empty()) {
  4827. return new (Context) DeclStmt(
  4828. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  4829. SourceLocation(), SourceLocation());
  4830. }
  4831. return nullptr;
  4832. }
  4833. /// Build preinits statement for the given declarations.
  4834. static Stmt *
  4835. buildPreInits(ASTContext &Context,
  4836. const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  4837. if (!Captures.empty()) {
  4838. SmallVector<Decl *, 16> PreInits;
  4839. for (const auto &Pair : Captures)
  4840. PreInits.push_back(Pair.second->getDecl());
  4841. return buildPreInits(Context, PreInits);
  4842. }
  4843. return nullptr;
  4844. }
  4845. /// Build postupdate expression for the given list of postupdates expressions.
  4846. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  4847. Expr *PostUpdate = nullptr;
  4848. if (!PostUpdates.empty()) {
  4849. for (Expr *E : PostUpdates) {
  4850. Expr *ConvE = S.BuildCStyleCastExpr(
  4851. E->getExprLoc(),
  4852. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  4853. E->getExprLoc(), E)
  4854. .get();
  4855. PostUpdate = PostUpdate
  4856. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  4857. PostUpdate, ConvE)
  4858. .get()
  4859. : ConvE;
  4860. }
  4861. }
  4862. return PostUpdate;
  4863. }
  4864. /// Called on a for stmt to check itself and nested loops (if any).
  4865. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  4866. /// number of collapsed loops otherwise.
  4867. static unsigned
  4868. checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  4869. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  4870. DSAStackTy &DSA,
  4871. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  4872. OMPLoopDirective::HelperExprs &Built) {
  4873. unsigned NestedLoopCount = 1;
  4874. if (CollapseLoopCountExpr) {
  4875. // Found 'collapse' clause - calculate collapse number.
  4876. Expr::EvalResult Result;
  4877. if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
  4878. NestedLoopCount = Result.Val.getInt().getLimitedValue();
  4879. }
  4880. unsigned OrderedLoopCount = 1;
  4881. if (OrderedLoopCountExpr) {
  4882. // Found 'ordered' clause - calculate collapse number.
  4883. Expr::EvalResult EVResult;
  4884. if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
  4885. llvm::APSInt Result = EVResult.Val.getInt();
  4886. if (Result.getLimitedValue() < NestedLoopCount) {
  4887. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  4888. diag::err_omp_wrong_ordered_loop_count)
  4889. << OrderedLoopCountExpr->getSourceRange();
  4890. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  4891. diag::note_collapse_loop_count)
  4892. << CollapseLoopCountExpr->getSourceRange();
  4893. }
  4894. OrderedLoopCount = Result.getLimitedValue();
  4895. }
  4896. }
  4897. // This is helper routine for loop directives (e.g., 'for', 'simd',
  4898. // 'for simd', etc.).
  4899. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  4900. SmallVector<LoopIterationSpace, 4> IterSpaces(
  4901. std::max(OrderedLoopCount, NestedLoopCount));
  4902. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  4903. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  4904. if (checkOpenMPIterationSpace(
  4905. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  4906. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  4907. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
  4908. Captures))
  4909. return 0;
  4910. // Move on to the next nested for loop, or to the loop body.
  4911. // OpenMP [2.8.1, simd construct, Restrictions]
  4912. // All loops associated with the construct must be perfectly nested; that
  4913. // is, there must be no intervening code nor any OpenMP directive between
  4914. // any two loops.
  4915. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  4916. }
  4917. for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
  4918. if (checkOpenMPIterationSpace(
  4919. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  4920. std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
  4921. OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
  4922. Captures))
  4923. return 0;
  4924. if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
  4925. // Handle initialization of captured loop iterator variables.
  4926. auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
  4927. if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
  4928. Captures[DRE] = DRE;
  4929. }
  4930. }
  4931. // Move on to the next nested for loop, or to the loop body.
  4932. // OpenMP [2.8.1, simd construct, Restrictions]
  4933. // All loops associated with the construct must be perfectly nested; that
  4934. // is, there must be no intervening code nor any OpenMP directive between
  4935. // any two loops.
  4936. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  4937. }
  4938. Built.clear(/* size */ NestedLoopCount);
  4939. if (SemaRef.CurContext->isDependentContext())
  4940. return NestedLoopCount;
  4941. // An example of what is generated for the following code:
  4942. //
  4943. // #pragma omp simd collapse(2) ordered(2)
  4944. // for (i = 0; i < NI; ++i)
  4945. // for (k = 0; k < NK; ++k)
  4946. // for (j = J0; j < NJ; j+=2) {
  4947. // <loop body>
  4948. // }
  4949. //
  4950. // We generate the code below.
  4951. // Note: the loop body may be outlined in CodeGen.
  4952. // Note: some counters may be C++ classes, operator- is used to find number of
  4953. // iterations and operator+= to calculate counter value.
  4954. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  4955. // or i64 is currently supported).
  4956. //
  4957. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  4958. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  4959. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  4960. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  4961. // // similar updates for vars in clauses (e.g. 'linear')
  4962. // <loop body (using local i and j)>
  4963. // }
  4964. // i = NI; // assign final values of counters
  4965. // j = NJ;
  4966. //
  4967. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  4968. // the iteration counts of the collapsed for loops.
  4969. // Precondition tests if there is at least one iteration (all conditions are
  4970. // true).
  4971. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  4972. Expr *N0 = IterSpaces[0].NumIterations;
  4973. ExprResult LastIteration32 =
  4974. widenIterationCount(/*Bits=*/32,
  4975. SemaRef
  4976. .PerformImplicitConversion(
  4977. N0->IgnoreImpCasts(), N0->getType(),
  4978. Sema::AA_Converting, /*AllowExplicit=*/true)
  4979. .get(),
  4980. SemaRef);
  4981. ExprResult LastIteration64 = widenIterationCount(
  4982. /*Bits=*/64,
  4983. SemaRef
  4984. .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
  4985. Sema::AA_Converting,
  4986. /*AllowExplicit=*/true)
  4987. .get(),
  4988. SemaRef);
  4989. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  4990. return NestedLoopCount;
  4991. ASTContext &C = SemaRef.Context;
  4992. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  4993. Scope *CurScope = DSA.getCurScope();
  4994. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  4995. if (PreCond.isUsable()) {
  4996. PreCond =
  4997. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  4998. PreCond.get(), IterSpaces[Cnt].PreCond);
  4999. }
  5000. Expr *N = IterSpaces[Cnt].NumIterations;
  5001. SourceLocation Loc = N->getExprLoc();
  5002. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  5003. if (LastIteration32.isUsable())
  5004. LastIteration32 = SemaRef.BuildBinOp(
  5005. CurScope, Loc, BO_Mul, LastIteration32.get(),
  5006. SemaRef
  5007. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  5008. Sema::AA_Converting,
  5009. /*AllowExplicit=*/true)
  5010. .get());
  5011. if (LastIteration64.isUsable())
  5012. LastIteration64 = SemaRef.BuildBinOp(
  5013. CurScope, Loc, BO_Mul, LastIteration64.get(),
  5014. SemaRef
  5015. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  5016. Sema::AA_Converting,
  5017. /*AllowExplicit=*/true)
  5018. .get());
  5019. }
  5020. // Choose either the 32-bit or 64-bit version.
  5021. ExprResult LastIteration = LastIteration64;
  5022. if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
  5023. (LastIteration32.isUsable() &&
  5024. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  5025. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  5026. fitsInto(
  5027. /*Bits=*/32,
  5028. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  5029. LastIteration64.get(), SemaRef))))
  5030. LastIteration = LastIteration32;
  5031. QualType VType = LastIteration.get()->getType();
  5032. QualType RealVType = VType;
  5033. QualType StrideVType = VType;
  5034. if (isOpenMPTaskLoopDirective(DKind)) {
  5035. VType =
  5036. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  5037. StrideVType =
  5038. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  5039. }
  5040. if (!LastIteration.isUsable())
  5041. return 0;
  5042. // Save the number of iterations.
  5043. ExprResult NumIterations = LastIteration;
  5044. {
  5045. LastIteration = SemaRef.BuildBinOp(
  5046. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  5047. LastIteration.get(),
  5048. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5049. if (!LastIteration.isUsable())
  5050. return 0;
  5051. }
  5052. // Calculate the last iteration number beforehand instead of doing this on
  5053. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  5054. llvm::APSInt Result;
  5055. bool IsConstant =
  5056. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  5057. ExprResult CalcLastIteration;
  5058. if (!IsConstant) {
  5059. ExprResult SaveRef =
  5060. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  5061. LastIteration = SaveRef;
  5062. // Prepare SaveRef + 1.
  5063. NumIterations = SemaRef.BuildBinOp(
  5064. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  5065. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  5066. if (!NumIterations.isUsable())
  5067. return 0;
  5068. }
  5069. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  5070. // Build variables passed into runtime, necessary for worksharing directives.
  5071. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  5072. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  5073. isOpenMPDistributeDirective(DKind)) {
  5074. // Lower bound variable, initialized with zero.
  5075. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  5076. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  5077. SemaRef.AddInitializerToDecl(LBDecl,
  5078. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  5079. /*DirectInit*/ false);
  5080. // Upper bound variable, initialized with last iteration number.
  5081. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  5082. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  5083. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  5084. /*DirectInit*/ false);
  5085. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  5086. // This will be used to implement clause 'lastprivate'.
  5087. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  5088. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  5089. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  5090. SemaRef.AddInitializerToDecl(ILDecl,
  5091. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  5092. /*DirectInit*/ false);
  5093. // Stride variable returned by runtime (we initialize it to 1 by default).
  5094. VarDecl *STDecl =
  5095. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  5096. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  5097. SemaRef.AddInitializerToDecl(STDecl,
  5098. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  5099. /*DirectInit*/ false);
  5100. // Build expression: UB = min(UB, LastIteration)
  5101. // It is necessary for CodeGen of directives with static scheduling.
  5102. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  5103. UB.get(), LastIteration.get());
  5104. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  5105. LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
  5106. LastIteration.get(), UB.get());
  5107. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  5108. CondOp.get());
  5109. EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
  5110. // If we have a combined directive that combines 'distribute', 'for' or
  5111. // 'simd' we need to be able to access the bounds of the schedule of the
  5112. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  5113. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  5114. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5115. // Lower bound variable, initialized with zero.
  5116. VarDecl *CombLBDecl =
  5117. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  5118. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  5119. SemaRef.AddInitializerToDecl(
  5120. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  5121. /*DirectInit*/ false);
  5122. // Upper bound variable, initialized with last iteration number.
  5123. VarDecl *CombUBDecl =
  5124. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  5125. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  5126. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  5127. /*DirectInit*/ false);
  5128. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  5129. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  5130. ExprResult CombCondOp =
  5131. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  5132. LastIteration.get(), CombUB.get());
  5133. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  5134. CombCondOp.get());
  5135. CombEUB =
  5136. SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
  5137. const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  5138. // We expect to have at least 2 more parameters than the 'parallel'
  5139. // directive does - the lower and upper bounds of the previous schedule.
  5140. assert(CD->getNumParams() >= 4 &&
  5141. "Unexpected number of parameters in loop combined directive");
  5142. // Set the proper type for the bounds given what we learned from the
  5143. // enclosed loops.
  5144. ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  5145. ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  5146. // Previous lower and upper bounds are obtained from the region
  5147. // parameters.
  5148. PrevLB =
  5149. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  5150. PrevUB =
  5151. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  5152. }
  5153. }
  5154. // Build the iteration variable and its initialization before loop.
  5155. ExprResult IV;
  5156. ExprResult Init, CombInit;
  5157. {
  5158. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  5159. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  5160. Expr *RHS =
  5161. (isOpenMPWorksharingDirective(DKind) ||
  5162. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  5163. ? LB.get()
  5164. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  5165. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  5166. Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
  5167. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5168. Expr *CombRHS =
  5169. (isOpenMPWorksharingDirective(DKind) ||
  5170. isOpenMPTaskLoopDirective(DKind) ||
  5171. isOpenMPDistributeDirective(DKind))
  5172. ? CombLB.get()
  5173. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  5174. CombInit =
  5175. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  5176. CombInit =
  5177. SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
  5178. }
  5179. }
  5180. bool UseStrictCompare =
  5181. RealVType->hasUnsignedIntegerRepresentation() &&
  5182. llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
  5183. return LIS.IsStrictCompare;
  5184. });
  5185. // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
  5186. // unsigned IV)) for worksharing loops.
  5187. SourceLocation CondLoc = AStmt->getBeginLoc();
  5188. Expr *BoundUB = UB.get();
  5189. if (UseStrictCompare) {
  5190. BoundUB =
  5191. SemaRef
  5192. .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
  5193. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  5194. .get();
  5195. BoundUB =
  5196. SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
  5197. }
  5198. ExprResult Cond =
  5199. (isOpenMPWorksharingDirective(DKind) ||
  5200. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  5201. ? SemaRef.BuildBinOp(CurScope, CondLoc,
  5202. UseStrictCompare ? BO_LT : BO_LE, IV.get(),
  5203. BoundUB)
  5204. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  5205. NumIterations.get());
  5206. ExprResult CombDistCond;
  5207. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5208. CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  5209. NumIterations.get());
  5210. }
  5211. ExprResult CombCond;
  5212. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5213. Expr *BoundCombUB = CombUB.get();
  5214. if (UseStrictCompare) {
  5215. BoundCombUB =
  5216. SemaRef
  5217. .BuildBinOp(
  5218. CurScope, CondLoc, BO_Add, BoundCombUB,
  5219. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  5220. .get();
  5221. BoundCombUB =
  5222. SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
  5223. .get();
  5224. }
  5225. CombCond =
  5226. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  5227. IV.get(), BoundCombUB);
  5228. }
  5229. // Loop increment (IV = IV + 1)
  5230. SourceLocation IncLoc = AStmt->getBeginLoc();
  5231. ExprResult Inc =
  5232. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  5233. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  5234. if (!Inc.isUsable())
  5235. return 0;
  5236. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  5237. Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
  5238. if (!Inc.isUsable())
  5239. return 0;
  5240. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  5241. // Used for directives with static scheduling.
  5242. // In combined construct, add combined version that use CombLB and CombUB
  5243. // base variables for the update
  5244. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  5245. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  5246. isOpenMPDistributeDirective(DKind)) {
  5247. // LB + ST
  5248. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  5249. if (!NextLB.isUsable())
  5250. return 0;
  5251. // LB = LB + ST
  5252. NextLB =
  5253. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  5254. NextLB =
  5255. SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
  5256. if (!NextLB.isUsable())
  5257. return 0;
  5258. // UB + ST
  5259. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  5260. if (!NextUB.isUsable())
  5261. return 0;
  5262. // UB = UB + ST
  5263. NextUB =
  5264. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  5265. NextUB =
  5266. SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
  5267. if (!NextUB.isUsable())
  5268. return 0;
  5269. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5270. CombNextLB =
  5271. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  5272. if (!NextLB.isUsable())
  5273. return 0;
  5274. // LB = LB + ST
  5275. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  5276. CombNextLB.get());
  5277. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
  5278. /*DiscardedValue*/ false);
  5279. if (!CombNextLB.isUsable())
  5280. return 0;
  5281. // UB + ST
  5282. CombNextUB =
  5283. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  5284. if (!CombNextUB.isUsable())
  5285. return 0;
  5286. // UB = UB + ST
  5287. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  5288. CombNextUB.get());
  5289. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
  5290. /*DiscardedValue*/ false);
  5291. if (!CombNextUB.isUsable())
  5292. return 0;
  5293. }
  5294. }
  5295. // Create increment expression for distribute loop when combined in a same
  5296. // directive with for as IV = IV + ST; ensure upper bound expression based
  5297. // on PrevUB instead of NumIterations - used to implement 'for' when found
  5298. // in combination with 'distribute', like in 'distribute parallel for'
  5299. SourceLocation DistIncLoc = AStmt->getBeginLoc();
  5300. ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
  5301. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  5302. DistCond = SemaRef.BuildBinOp(
  5303. CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
  5304. assert(DistCond.isUsable() && "distribute cond expr was not built");
  5305. DistInc =
  5306. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  5307. assert(DistInc.isUsable() && "distribute inc expr was not built");
  5308. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  5309. DistInc.get());
  5310. DistInc =
  5311. SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
  5312. assert(DistInc.isUsable() && "distribute inc expr was not built");
  5313. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  5314. // construct
  5315. SourceLocation DistEUBLoc = AStmt->getBeginLoc();
  5316. ExprResult IsUBGreater =
  5317. SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
  5318. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  5319. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
  5320. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  5321. CondOp.get());
  5322. PrevEUB =
  5323. SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
  5324. // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
  5325. // parallel for is in combination with a distribute directive with
  5326. // schedule(static, 1)
  5327. Expr *BoundPrevUB = PrevUB.get();
  5328. if (UseStrictCompare) {
  5329. BoundPrevUB =
  5330. SemaRef
  5331. .BuildBinOp(
  5332. CurScope, CondLoc, BO_Add, BoundPrevUB,
  5333. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  5334. .get();
  5335. BoundPrevUB =
  5336. SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
  5337. .get();
  5338. }
  5339. ParForInDistCond =
  5340. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  5341. IV.get(), BoundPrevUB);
  5342. }
  5343. // Build updates and final values of the loop counters.
  5344. bool HasErrors = false;
  5345. Built.Counters.resize(NestedLoopCount);
  5346. Built.Inits.resize(NestedLoopCount);
  5347. Built.Updates.resize(NestedLoopCount);
  5348. Built.Finals.resize(NestedLoopCount);
  5349. {
  5350. // We implement the following algorithm for obtaining the
  5351. // original loop iteration variable values based on the
  5352. // value of the collapsed loop iteration variable IV.
  5353. //
  5354. // Let n+1 be the number of collapsed loops in the nest.
  5355. // Iteration variables (I0, I1, .... In)
  5356. // Iteration counts (N0, N1, ... Nn)
  5357. //
  5358. // Acc = IV;
  5359. //
  5360. // To compute Ik for loop k, 0 <= k <= n, generate:
  5361. // Prod = N(k+1) * N(k+2) * ... * Nn;
  5362. // Ik = Acc / Prod;
  5363. // Acc -= Ik * Prod;
  5364. //
  5365. ExprResult Acc = IV;
  5366. for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  5367. LoopIterationSpace &IS = IterSpaces[Cnt];
  5368. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  5369. ExprResult Iter;
  5370. // Compute prod
  5371. ExprResult Prod =
  5372. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  5373. for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
  5374. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
  5375. IterSpaces[K].NumIterations);
  5376. // Iter = Acc / Prod
  5377. // If there is at least one more inner loop to avoid
  5378. // multiplication by 1.
  5379. if (Cnt + 1 < NestedLoopCount)
  5380. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
  5381. Acc.get(), Prod.get());
  5382. else
  5383. Iter = Acc;
  5384. if (!Iter.isUsable()) {
  5385. HasErrors = true;
  5386. break;
  5387. }
  5388. // Update Acc:
  5389. // Acc -= Iter * Prod
  5390. // Check if there is at least one more inner loop to avoid
  5391. // multiplication by 1.
  5392. if (Cnt + 1 < NestedLoopCount)
  5393. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
  5394. Iter.get(), Prod.get());
  5395. else
  5396. Prod = Iter;
  5397. Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
  5398. Acc.get(), Prod.get());
  5399. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  5400. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  5401. DeclRefExpr *CounterVar = buildDeclRefExpr(
  5402. SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  5403. /*RefersToCapture=*/true);
  5404. ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  5405. IS.CounterInit, Captures);
  5406. if (!Init.isUsable()) {
  5407. HasErrors = true;
  5408. break;
  5409. }
  5410. ExprResult Update = buildCounterUpdate(
  5411. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  5412. IS.CounterStep, IS.Subtract, &Captures);
  5413. if (!Update.isUsable()) {
  5414. HasErrors = true;
  5415. break;
  5416. }
  5417. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  5418. ExprResult Final = buildCounterUpdate(
  5419. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
  5420. IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
  5421. if (!Final.isUsable()) {
  5422. HasErrors = true;
  5423. break;
  5424. }
  5425. if (!Update.isUsable() || !Final.isUsable()) {
  5426. HasErrors = true;
  5427. break;
  5428. }
  5429. // Save results
  5430. Built.Counters[Cnt] = IS.CounterVar;
  5431. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  5432. Built.Inits[Cnt] = Init.get();
  5433. Built.Updates[Cnt] = Update.get();
  5434. Built.Finals[Cnt] = Final.get();
  5435. }
  5436. }
  5437. if (HasErrors)
  5438. return 0;
  5439. // Save results
  5440. Built.IterationVarRef = IV.get();
  5441. Built.LastIteration = LastIteration.get();
  5442. Built.NumIterations = NumIterations.get();
  5443. Built.CalcLastIteration = SemaRef
  5444. .ActOnFinishFullExpr(CalcLastIteration.get(),
  5445. /*DiscardedValue*/ false)
  5446. .get();
  5447. Built.PreCond = PreCond.get();
  5448. Built.PreInits = buildPreInits(C, Captures);
  5449. Built.Cond = Cond.get();
  5450. Built.Init = Init.get();
  5451. Built.Inc = Inc.get();
  5452. Built.LB = LB.get();
  5453. Built.UB = UB.get();
  5454. Built.IL = IL.get();
  5455. Built.ST = ST.get();
  5456. Built.EUB = EUB.get();
  5457. Built.NLB = NextLB.get();
  5458. Built.NUB = NextUB.get();
  5459. Built.PrevLB = PrevLB.get();
  5460. Built.PrevUB = PrevUB.get();
  5461. Built.DistInc = DistInc.get();
  5462. Built.PrevEUB = PrevEUB.get();
  5463. Built.DistCombinedFields.LB = CombLB.get();
  5464. Built.DistCombinedFields.UB = CombUB.get();
  5465. Built.DistCombinedFields.EUB = CombEUB.get();
  5466. Built.DistCombinedFields.Init = CombInit.get();
  5467. Built.DistCombinedFields.Cond = CombCond.get();
  5468. Built.DistCombinedFields.NLB = CombNextLB.get();
  5469. Built.DistCombinedFields.NUB = CombNextUB.get();
  5470. Built.DistCombinedFields.DistCond = CombDistCond.get();
  5471. Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
  5472. return NestedLoopCount;
  5473. }
  5474. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  5475. auto CollapseClauses =
  5476. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  5477. if (CollapseClauses.begin() != CollapseClauses.end())
  5478. return (*CollapseClauses.begin())->getNumForLoops();
  5479. return nullptr;
  5480. }
  5481. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  5482. auto OrderedClauses =
  5483. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  5484. if (OrderedClauses.begin() != OrderedClauses.end())
  5485. return (*OrderedClauses.begin())->getNumForLoops();
  5486. return nullptr;
  5487. }
  5488. static bool checkSimdlenSafelenSpecified(Sema &S,
  5489. const ArrayRef<OMPClause *> Clauses) {
  5490. const OMPSafelenClause *Safelen = nullptr;
  5491. const OMPSimdlenClause *Simdlen = nullptr;
  5492. for (const OMPClause *Clause : Clauses) {
  5493. if (Clause->getClauseKind() == OMPC_safelen)
  5494. Safelen = cast<OMPSafelenClause>(Clause);
  5495. else if (Clause->getClauseKind() == OMPC_simdlen)
  5496. Simdlen = cast<OMPSimdlenClause>(Clause);
  5497. if (Safelen && Simdlen)
  5498. break;
  5499. }
  5500. if (Simdlen && Safelen) {
  5501. const Expr *SimdlenLength = Simdlen->getSimdlen();
  5502. const Expr *SafelenLength = Safelen->getSafelen();
  5503. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  5504. SimdlenLength->isInstantiationDependent() ||
  5505. SimdlenLength->containsUnexpandedParameterPack())
  5506. return false;
  5507. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  5508. SafelenLength->isInstantiationDependent() ||
  5509. SafelenLength->containsUnexpandedParameterPack())
  5510. return false;
  5511. Expr::EvalResult SimdlenResult, SafelenResult;
  5512. SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
  5513. SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
  5514. llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
  5515. llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
  5516. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  5517. // If both simdlen and safelen clauses are specified, the value of the
  5518. // simdlen parameter must be less than or equal to the value of the safelen
  5519. // parameter.
  5520. if (SimdlenRes > SafelenRes) {
  5521. S.Diag(SimdlenLength->getExprLoc(),
  5522. diag::err_omp_wrong_simdlen_safelen_values)
  5523. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  5524. return true;
  5525. }
  5526. }
  5527. return false;
  5528. }
  5529. StmtResult
  5530. Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  5531. SourceLocation StartLoc, SourceLocation EndLoc,
  5532. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5533. if (!AStmt)
  5534. return StmtError();
  5535. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5536. OMPLoopDirective::HelperExprs B;
  5537. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5538. // define the nested loops number.
  5539. unsigned NestedLoopCount = checkOpenMPLoop(
  5540. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  5541. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  5542. if (NestedLoopCount == 0)
  5543. return StmtError();
  5544. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5545. "omp simd loop exprs were not built");
  5546. if (!CurContext->isDependentContext()) {
  5547. // Finalize the clauses that need pre-built expressions for CodeGen.
  5548. for (OMPClause *C : Clauses) {
  5549. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5550. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5551. B.NumIterations, *this, CurScope,
  5552. DSAStack))
  5553. return StmtError();
  5554. }
  5555. }
  5556. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5557. return StmtError();
  5558. setFunctionHasBranchProtectedScope();
  5559. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5560. Clauses, AStmt, B);
  5561. }
  5562. StmtResult
  5563. Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  5564. SourceLocation StartLoc, SourceLocation EndLoc,
  5565. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5566. if (!AStmt)
  5567. return StmtError();
  5568. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5569. OMPLoopDirective::HelperExprs B;
  5570. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5571. // define the nested loops number.
  5572. unsigned NestedLoopCount = checkOpenMPLoop(
  5573. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  5574. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  5575. if (NestedLoopCount == 0)
  5576. return StmtError();
  5577. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5578. "omp for loop exprs were not built");
  5579. if (!CurContext->isDependentContext()) {
  5580. // Finalize the clauses that need pre-built expressions for CodeGen.
  5581. for (OMPClause *C : Clauses) {
  5582. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5583. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5584. B.NumIterations, *this, CurScope,
  5585. DSAStack))
  5586. return StmtError();
  5587. }
  5588. }
  5589. setFunctionHasBranchProtectedScope();
  5590. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5591. Clauses, AStmt, B, DSAStack->isCancelRegion());
  5592. }
  5593. StmtResult Sema::ActOnOpenMPForSimdDirective(
  5594. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5595. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5596. if (!AStmt)
  5597. return StmtError();
  5598. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5599. OMPLoopDirective::HelperExprs B;
  5600. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5601. // define the nested loops number.
  5602. unsigned NestedLoopCount =
  5603. checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  5604. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5605. VarsWithImplicitDSA, B);
  5606. if (NestedLoopCount == 0)
  5607. return StmtError();
  5608. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5609. "omp for simd loop exprs were not built");
  5610. if (!CurContext->isDependentContext()) {
  5611. // Finalize the clauses that need pre-built expressions for CodeGen.
  5612. for (OMPClause *C : Clauses) {
  5613. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5614. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5615. B.NumIterations, *this, CurScope,
  5616. DSAStack))
  5617. return StmtError();
  5618. }
  5619. }
  5620. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5621. return StmtError();
  5622. setFunctionHasBranchProtectedScope();
  5623. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  5624. Clauses, AStmt, B);
  5625. }
  5626. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  5627. Stmt *AStmt,
  5628. SourceLocation StartLoc,
  5629. SourceLocation EndLoc) {
  5630. if (!AStmt)
  5631. return StmtError();
  5632. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5633. auto BaseStmt = AStmt;
  5634. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  5635. BaseStmt = CS->getCapturedStmt();
  5636. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  5637. auto S = C->children();
  5638. if (S.begin() == S.end())
  5639. return StmtError();
  5640. // All associated statements must be '#pragma omp section' except for
  5641. // the first one.
  5642. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  5643. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  5644. if (SectionStmt)
  5645. Diag(SectionStmt->getBeginLoc(),
  5646. diag::err_omp_sections_substmt_not_section);
  5647. return StmtError();
  5648. }
  5649. cast<OMPSectionDirective>(SectionStmt)
  5650. ->setHasCancel(DSAStack->isCancelRegion());
  5651. }
  5652. } else {
  5653. Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
  5654. return StmtError();
  5655. }
  5656. setFunctionHasBranchProtectedScope();
  5657. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5658. DSAStack->isCancelRegion());
  5659. }
  5660. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  5661. SourceLocation StartLoc,
  5662. SourceLocation EndLoc) {
  5663. if (!AStmt)
  5664. return StmtError();
  5665. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5666. setFunctionHasBranchProtectedScope();
  5667. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  5668. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  5669. DSAStack->isCancelRegion());
  5670. }
  5671. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  5672. Stmt *AStmt,
  5673. SourceLocation StartLoc,
  5674. SourceLocation EndLoc) {
  5675. if (!AStmt)
  5676. return StmtError();
  5677. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5678. setFunctionHasBranchProtectedScope();
  5679. // OpenMP [2.7.3, single Construct, Restrictions]
  5680. // The copyprivate clause must not be used with the nowait clause.
  5681. const OMPClause *Nowait = nullptr;
  5682. const OMPClause *Copyprivate = nullptr;
  5683. for (const OMPClause *Clause : Clauses) {
  5684. if (Clause->getClauseKind() == OMPC_nowait)
  5685. Nowait = Clause;
  5686. else if (Clause->getClauseKind() == OMPC_copyprivate)
  5687. Copyprivate = Clause;
  5688. if (Copyprivate && Nowait) {
  5689. Diag(Copyprivate->getBeginLoc(),
  5690. diag::err_omp_single_copyprivate_with_nowait);
  5691. Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
  5692. return StmtError();
  5693. }
  5694. }
  5695. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5696. }
  5697. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  5698. SourceLocation StartLoc,
  5699. SourceLocation EndLoc) {
  5700. if (!AStmt)
  5701. return StmtError();
  5702. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5703. setFunctionHasBranchProtectedScope();
  5704. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  5705. }
  5706. StmtResult Sema::ActOnOpenMPCriticalDirective(
  5707. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  5708. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  5709. if (!AStmt)
  5710. return StmtError();
  5711. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5712. bool ErrorFound = false;
  5713. llvm::APSInt Hint;
  5714. SourceLocation HintLoc;
  5715. bool DependentHint = false;
  5716. for (const OMPClause *C : Clauses) {
  5717. if (C->getClauseKind() == OMPC_hint) {
  5718. if (!DirName.getName()) {
  5719. Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
  5720. ErrorFound = true;
  5721. }
  5722. Expr *E = cast<OMPHintClause>(C)->getHint();
  5723. if (E->isTypeDependent() || E->isValueDependent() ||
  5724. E->isInstantiationDependent()) {
  5725. DependentHint = true;
  5726. } else {
  5727. Hint = E->EvaluateKnownConstInt(Context);
  5728. HintLoc = C->getBeginLoc();
  5729. }
  5730. }
  5731. }
  5732. if (ErrorFound)
  5733. return StmtError();
  5734. const auto Pair = DSAStack->getCriticalWithHint(DirName);
  5735. if (Pair.first && DirName.getName() && !DependentHint) {
  5736. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  5737. Diag(StartLoc, diag::err_omp_critical_with_hint);
  5738. if (HintLoc.isValid())
  5739. Diag(HintLoc, diag::note_omp_critical_hint_here)
  5740. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  5741. else
  5742. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  5743. if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  5744. Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
  5745. << 1
  5746. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  5747. /*Radix=*/10, /*Signed=*/false);
  5748. } else {
  5749. Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
  5750. }
  5751. }
  5752. }
  5753. setFunctionHasBranchProtectedScope();
  5754. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  5755. Clauses, AStmt);
  5756. if (!Pair.first && DirName.getName() && !DependentHint)
  5757. DSAStack->addCriticalWithHint(Dir, Hint);
  5758. return Dir;
  5759. }
  5760. StmtResult Sema::ActOnOpenMPParallelForDirective(
  5761. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5762. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5763. if (!AStmt)
  5764. return StmtError();
  5765. auto *CS = cast<CapturedStmt>(AStmt);
  5766. // 1.2.2 OpenMP Language Terminology
  5767. // Structured block - An executable statement with a single entry at the
  5768. // top and a single exit at the bottom.
  5769. // The point of exit cannot be a branch out of the structured block.
  5770. // longjmp() and throw() must not violate the entry/exit criteria.
  5771. CS->getCapturedDecl()->setNothrow();
  5772. OMPLoopDirective::HelperExprs B;
  5773. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5774. // define the nested loops number.
  5775. unsigned NestedLoopCount =
  5776. checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  5777. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5778. VarsWithImplicitDSA, B);
  5779. if (NestedLoopCount == 0)
  5780. return StmtError();
  5781. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5782. "omp parallel for loop exprs were not built");
  5783. if (!CurContext->isDependentContext()) {
  5784. // Finalize the clauses that need pre-built expressions for CodeGen.
  5785. for (OMPClause *C : Clauses) {
  5786. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5787. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5788. B.NumIterations, *this, CurScope,
  5789. DSAStack))
  5790. return StmtError();
  5791. }
  5792. }
  5793. setFunctionHasBranchProtectedScope();
  5794. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  5795. NestedLoopCount, Clauses, AStmt, B,
  5796. DSAStack->isCancelRegion());
  5797. }
  5798. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  5799. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5800. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  5801. if (!AStmt)
  5802. return StmtError();
  5803. auto *CS = cast<CapturedStmt>(AStmt);
  5804. // 1.2.2 OpenMP Language Terminology
  5805. // Structured block - An executable statement with a single entry at the
  5806. // top and a single exit at the bottom.
  5807. // The point of exit cannot be a branch out of the structured block.
  5808. // longjmp() and throw() must not violate the entry/exit criteria.
  5809. CS->getCapturedDecl()->setNothrow();
  5810. OMPLoopDirective::HelperExprs B;
  5811. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5812. // define the nested loops number.
  5813. unsigned NestedLoopCount =
  5814. checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  5815. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  5816. VarsWithImplicitDSA, B);
  5817. if (NestedLoopCount == 0)
  5818. return StmtError();
  5819. if (!CurContext->isDependentContext()) {
  5820. // Finalize the clauses that need pre-built expressions for CodeGen.
  5821. for (OMPClause *C : Clauses) {
  5822. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  5823. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  5824. B.NumIterations, *this, CurScope,
  5825. DSAStack))
  5826. return StmtError();
  5827. }
  5828. }
  5829. if (checkSimdlenSafelenSpecified(*this, Clauses))
  5830. return StmtError();
  5831. setFunctionHasBranchProtectedScope();
  5832. return OMPParallelForSimdDirective::Create(
  5833. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  5834. }
  5835. StmtResult
  5836. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  5837. Stmt *AStmt, SourceLocation StartLoc,
  5838. SourceLocation EndLoc) {
  5839. if (!AStmt)
  5840. return StmtError();
  5841. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5842. auto BaseStmt = AStmt;
  5843. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  5844. BaseStmt = CS->getCapturedStmt();
  5845. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  5846. auto S = C->children();
  5847. if (S.begin() == S.end())
  5848. return StmtError();
  5849. // All associated statements must be '#pragma omp section' except for
  5850. // the first one.
  5851. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  5852. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  5853. if (SectionStmt)
  5854. Diag(SectionStmt->getBeginLoc(),
  5855. diag::err_omp_parallel_sections_substmt_not_section);
  5856. return StmtError();
  5857. }
  5858. cast<OMPSectionDirective>(SectionStmt)
  5859. ->setHasCancel(DSAStack->isCancelRegion());
  5860. }
  5861. } else {
  5862. Diag(AStmt->getBeginLoc(),
  5863. diag::err_omp_parallel_sections_not_compound_stmt);
  5864. return StmtError();
  5865. }
  5866. setFunctionHasBranchProtectedScope();
  5867. return OMPParallelSectionsDirective::Create(
  5868. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  5869. }
  5870. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  5871. Stmt *AStmt, SourceLocation StartLoc,
  5872. SourceLocation EndLoc) {
  5873. if (!AStmt)
  5874. return StmtError();
  5875. auto *CS = cast<CapturedStmt>(AStmt);
  5876. // 1.2.2 OpenMP Language Terminology
  5877. // Structured block - An executable statement with a single entry at the
  5878. // top and a single exit at the bottom.
  5879. // The point of exit cannot be a branch out of the structured block.
  5880. // longjmp() and throw() must not violate the entry/exit criteria.
  5881. CS->getCapturedDecl()->setNothrow();
  5882. setFunctionHasBranchProtectedScope();
  5883. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5884. DSAStack->isCancelRegion());
  5885. }
  5886. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  5887. SourceLocation EndLoc) {
  5888. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  5889. }
  5890. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  5891. SourceLocation EndLoc) {
  5892. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  5893. }
  5894. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  5895. SourceLocation EndLoc) {
  5896. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  5897. }
  5898. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  5899. Stmt *AStmt,
  5900. SourceLocation StartLoc,
  5901. SourceLocation EndLoc) {
  5902. if (!AStmt)
  5903. return StmtError();
  5904. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5905. setFunctionHasBranchProtectedScope();
  5906. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5907. AStmt,
  5908. DSAStack->getTaskgroupReductionRef());
  5909. }
  5910. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  5911. SourceLocation StartLoc,
  5912. SourceLocation EndLoc) {
  5913. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  5914. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  5915. }
  5916. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  5917. Stmt *AStmt,
  5918. SourceLocation StartLoc,
  5919. SourceLocation EndLoc) {
  5920. const OMPClause *DependFound = nullptr;
  5921. const OMPClause *DependSourceClause = nullptr;
  5922. const OMPClause *DependSinkClause = nullptr;
  5923. bool ErrorFound = false;
  5924. const OMPThreadsClause *TC = nullptr;
  5925. const OMPSIMDClause *SC = nullptr;
  5926. for (const OMPClause *C : Clauses) {
  5927. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  5928. DependFound = C;
  5929. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  5930. if (DependSourceClause) {
  5931. Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  5932. << getOpenMPDirectiveName(OMPD_ordered)
  5933. << getOpenMPClauseName(OMPC_depend) << 2;
  5934. ErrorFound = true;
  5935. } else {
  5936. DependSourceClause = C;
  5937. }
  5938. if (DependSinkClause) {
  5939. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  5940. << 0;
  5941. ErrorFound = true;
  5942. }
  5943. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  5944. if (DependSourceClause) {
  5945. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  5946. << 1;
  5947. ErrorFound = true;
  5948. }
  5949. DependSinkClause = C;
  5950. }
  5951. } else if (C->getClauseKind() == OMPC_threads) {
  5952. TC = cast<OMPThreadsClause>(C);
  5953. } else if (C->getClauseKind() == OMPC_simd) {
  5954. SC = cast<OMPSIMDClause>(C);
  5955. }
  5956. }
  5957. if (!ErrorFound && !SC &&
  5958. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  5959. // OpenMP [2.8.1,simd Construct, Restrictions]
  5960. // An ordered construct with the simd clause is the only OpenMP construct
  5961. // that can appear in the simd region.
  5962. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  5963. ErrorFound = true;
  5964. } else if (DependFound && (TC || SC)) {
  5965. Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
  5966. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  5967. ErrorFound = true;
  5968. } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
  5969. Diag(DependFound->getBeginLoc(),
  5970. diag::err_omp_ordered_directive_without_param);
  5971. ErrorFound = true;
  5972. } else if (TC || Clauses.empty()) {
  5973. if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
  5974. SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
  5975. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  5976. << (TC != nullptr);
  5977. Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
  5978. ErrorFound = true;
  5979. }
  5980. }
  5981. if ((!AStmt && !DependFound) || ErrorFound)
  5982. return StmtError();
  5983. if (AStmt) {
  5984. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5985. setFunctionHasBranchProtectedScope();
  5986. }
  5987. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5988. }
  5989. namespace {
  5990. /// Helper class for checking expression in 'omp atomic [update]'
  5991. /// construct.
  5992. class OpenMPAtomicUpdateChecker {
  5993. /// Error results for atomic update expressions.
  5994. enum ExprAnalysisErrorCode {
  5995. /// A statement is not an expression statement.
  5996. NotAnExpression,
  5997. /// Expression is not builtin binary or unary operation.
  5998. NotABinaryOrUnaryExpression,
  5999. /// Unary operation is not post-/pre- increment/decrement operation.
  6000. NotAnUnaryIncDecExpression,
  6001. /// An expression is not of scalar type.
  6002. NotAScalarType,
  6003. /// A binary operation is not an assignment operation.
  6004. NotAnAssignmentOp,
  6005. /// RHS part of the binary operation is not a binary expression.
  6006. NotABinaryExpression,
  6007. /// RHS part is not additive/multiplicative/shift/biwise binary
  6008. /// expression.
  6009. NotABinaryOperator,
  6010. /// RHS binary operation does not have reference to the updated LHS
  6011. /// part.
  6012. NotAnUpdateExpression,
  6013. /// No errors is found.
  6014. NoError
  6015. };
  6016. /// Reference to Sema.
  6017. Sema &SemaRef;
  6018. /// A location for note diagnostics (when error is found).
  6019. SourceLocation NoteLoc;
  6020. /// 'x' lvalue part of the source atomic expression.
  6021. Expr *X;
  6022. /// 'expr' rvalue part of the source atomic expression.
  6023. Expr *E;
  6024. /// Helper expression of the form
  6025. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  6026. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  6027. Expr *UpdateExpr;
  6028. /// Is 'x' a LHS in a RHS part of full update expression. It is
  6029. /// important for non-associative operations.
  6030. bool IsXLHSInRHSPart;
  6031. BinaryOperatorKind Op;
  6032. SourceLocation OpLoc;
  6033. /// true if the source expression is a postfix unary operation, false
  6034. /// if it is a prefix unary operation.
  6035. bool IsPostfixUpdate;
  6036. public:
  6037. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  6038. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  6039. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  6040. /// Check specified statement that it is suitable for 'atomic update'
  6041. /// constructs and extract 'x', 'expr' and Operation from the original
  6042. /// expression. If DiagId and NoteId == 0, then only check is performed
  6043. /// without error notification.
  6044. /// \param DiagId Diagnostic which should be emitted if error is found.
  6045. /// \param NoteId Diagnostic note for the main error message.
  6046. /// \return true if statement is not an update expression, false otherwise.
  6047. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  6048. /// Return the 'x' lvalue part of the source atomic expression.
  6049. Expr *getX() const { return X; }
  6050. /// Return the 'expr' rvalue part of the source atomic expression.
  6051. Expr *getExpr() const { return E; }
  6052. /// Return the update expression used in calculation of the updated
  6053. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  6054. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  6055. Expr *getUpdateExpr() const { return UpdateExpr; }
  6056. /// Return true if 'x' is LHS in RHS part of full update expression,
  6057. /// false otherwise.
  6058. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  6059. /// true if the source expression is a postfix unary operation, false
  6060. /// if it is a prefix unary operation.
  6061. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  6062. private:
  6063. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  6064. unsigned NoteId = 0);
  6065. };
  6066. } // namespace
  6067. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  6068. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  6069. ExprAnalysisErrorCode ErrorFound = NoError;
  6070. SourceLocation ErrorLoc, NoteLoc;
  6071. SourceRange ErrorRange, NoteRange;
  6072. // Allowed constructs are:
  6073. // x = x binop expr;
  6074. // x = expr binop x;
  6075. if (AtomicBinOp->getOpcode() == BO_Assign) {
  6076. X = AtomicBinOp->getLHS();
  6077. if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  6078. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  6079. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  6080. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  6081. AtomicInnerBinOp->isBitwiseOp()) {
  6082. Op = AtomicInnerBinOp->getOpcode();
  6083. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  6084. Expr *LHS = AtomicInnerBinOp->getLHS();
  6085. Expr *RHS = AtomicInnerBinOp->getRHS();
  6086. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  6087. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  6088. /*Canonical=*/true);
  6089. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  6090. /*Canonical=*/true);
  6091. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  6092. /*Canonical=*/true);
  6093. if (XId == LHSId) {
  6094. E = RHS;
  6095. IsXLHSInRHSPart = true;
  6096. } else if (XId == RHSId) {
  6097. E = LHS;
  6098. IsXLHSInRHSPart = false;
  6099. } else {
  6100. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  6101. ErrorRange = AtomicInnerBinOp->getSourceRange();
  6102. NoteLoc = X->getExprLoc();
  6103. NoteRange = X->getSourceRange();
  6104. ErrorFound = NotAnUpdateExpression;
  6105. }
  6106. } else {
  6107. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  6108. ErrorRange = AtomicInnerBinOp->getSourceRange();
  6109. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  6110. NoteRange = SourceRange(NoteLoc, NoteLoc);
  6111. ErrorFound = NotABinaryOperator;
  6112. }
  6113. } else {
  6114. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  6115. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  6116. ErrorFound = NotABinaryExpression;
  6117. }
  6118. } else {
  6119. ErrorLoc = AtomicBinOp->getExprLoc();
  6120. ErrorRange = AtomicBinOp->getSourceRange();
  6121. NoteLoc = AtomicBinOp->getOperatorLoc();
  6122. NoteRange = SourceRange(NoteLoc, NoteLoc);
  6123. ErrorFound = NotAnAssignmentOp;
  6124. }
  6125. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  6126. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  6127. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  6128. return true;
  6129. }
  6130. if (SemaRef.CurContext->isDependentContext())
  6131. E = X = UpdateExpr = nullptr;
  6132. return ErrorFound != NoError;
  6133. }
  6134. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  6135. unsigned NoteId) {
  6136. ExprAnalysisErrorCode ErrorFound = NoError;
  6137. SourceLocation ErrorLoc, NoteLoc;
  6138. SourceRange ErrorRange, NoteRange;
  6139. // Allowed constructs are:
  6140. // x++;
  6141. // x--;
  6142. // ++x;
  6143. // --x;
  6144. // x binop= expr;
  6145. // x = x binop expr;
  6146. // x = expr binop x;
  6147. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  6148. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  6149. if (AtomicBody->getType()->isScalarType() ||
  6150. AtomicBody->isInstantiationDependent()) {
  6151. if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  6152. AtomicBody->IgnoreParenImpCasts())) {
  6153. // Check for Compound Assignment Operation
  6154. Op = BinaryOperator::getOpForCompoundAssignment(
  6155. AtomicCompAssignOp->getOpcode());
  6156. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  6157. E = AtomicCompAssignOp->getRHS();
  6158. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  6159. IsXLHSInRHSPart = true;
  6160. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  6161. AtomicBody->IgnoreParenImpCasts())) {
  6162. // Check for Binary Operation
  6163. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  6164. return true;
  6165. } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  6166. AtomicBody->IgnoreParenImpCasts())) {
  6167. // Check for Unary Operation
  6168. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  6169. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  6170. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  6171. OpLoc = AtomicUnaryOp->getOperatorLoc();
  6172. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  6173. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  6174. IsXLHSInRHSPart = true;
  6175. } else {
  6176. ErrorFound = NotAnUnaryIncDecExpression;
  6177. ErrorLoc = AtomicUnaryOp->getExprLoc();
  6178. ErrorRange = AtomicUnaryOp->getSourceRange();
  6179. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  6180. NoteRange = SourceRange(NoteLoc, NoteLoc);
  6181. }
  6182. } else if (!AtomicBody->isInstantiationDependent()) {
  6183. ErrorFound = NotABinaryOrUnaryExpression;
  6184. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  6185. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  6186. }
  6187. } else {
  6188. ErrorFound = NotAScalarType;
  6189. NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
  6190. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6191. }
  6192. } else {
  6193. ErrorFound = NotAnExpression;
  6194. NoteLoc = ErrorLoc = S->getBeginLoc();
  6195. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6196. }
  6197. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  6198. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  6199. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  6200. return true;
  6201. }
  6202. if (SemaRef.CurContext->isDependentContext())
  6203. E = X = UpdateExpr = nullptr;
  6204. if (ErrorFound == NoError && E && X) {
  6205. // Build an update expression of form 'OpaqueValueExpr(x) binop
  6206. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  6207. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  6208. auto *OVEX = new (SemaRef.getASTContext())
  6209. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  6210. auto *OVEExpr = new (SemaRef.getASTContext())
  6211. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  6212. ExprResult Update =
  6213. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  6214. IsXLHSInRHSPart ? OVEExpr : OVEX);
  6215. if (Update.isInvalid())
  6216. return true;
  6217. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  6218. Sema::AA_Casting);
  6219. if (Update.isInvalid())
  6220. return true;
  6221. UpdateExpr = Update.get();
  6222. }
  6223. return ErrorFound != NoError;
  6224. }
  6225. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  6226. Stmt *AStmt,
  6227. SourceLocation StartLoc,
  6228. SourceLocation EndLoc) {
  6229. if (!AStmt)
  6230. return StmtError();
  6231. auto *CS = cast<CapturedStmt>(AStmt);
  6232. // 1.2.2 OpenMP Language Terminology
  6233. // Structured block - An executable statement with a single entry at the
  6234. // top and a single exit at the bottom.
  6235. // The point of exit cannot be a branch out of the structured block.
  6236. // longjmp() and throw() must not violate the entry/exit criteria.
  6237. OpenMPClauseKind AtomicKind = OMPC_unknown;
  6238. SourceLocation AtomicKindLoc;
  6239. for (const OMPClause *C : Clauses) {
  6240. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  6241. C->getClauseKind() == OMPC_update ||
  6242. C->getClauseKind() == OMPC_capture) {
  6243. if (AtomicKind != OMPC_unknown) {
  6244. Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
  6245. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  6246. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  6247. << getOpenMPClauseName(AtomicKind);
  6248. } else {
  6249. AtomicKind = C->getClauseKind();
  6250. AtomicKindLoc = C->getBeginLoc();
  6251. }
  6252. }
  6253. }
  6254. Stmt *Body = CS->getCapturedStmt();
  6255. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  6256. Body = EWC->getSubExpr();
  6257. Expr *X = nullptr;
  6258. Expr *V = nullptr;
  6259. Expr *E = nullptr;
  6260. Expr *UE = nullptr;
  6261. bool IsXLHSInRHSPart = false;
  6262. bool IsPostfixUpdate = false;
  6263. // OpenMP [2.12.6, atomic Construct]
  6264. // In the next expressions:
  6265. // * x and v (as applicable) are both l-value expressions with scalar type.
  6266. // * During the execution of an atomic region, multiple syntactic
  6267. // occurrences of x must designate the same storage location.
  6268. // * Neither of v and expr (as applicable) may access the storage location
  6269. // designated by x.
  6270. // * Neither of x and expr (as applicable) may access the storage location
  6271. // designated by v.
  6272. // * expr is an expression with scalar type.
  6273. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  6274. // * binop, binop=, ++, and -- are not overloaded operators.
  6275. // * The expression x binop expr must be numerically equivalent to x binop
  6276. // (expr). This requirement is satisfied if the operators in expr have
  6277. // precedence greater than binop, or by using parentheses around expr or
  6278. // subexpressions of expr.
  6279. // * The expression expr binop x must be numerically equivalent to (expr)
  6280. // binop x. This requirement is satisfied if the operators in expr have
  6281. // precedence equal to or greater than binop, or by using parentheses around
  6282. // expr or subexpressions of expr.
  6283. // * For forms that allow multiple occurrences of x, the number of times
  6284. // that x is evaluated is unspecified.
  6285. if (AtomicKind == OMPC_read) {
  6286. enum {
  6287. NotAnExpression,
  6288. NotAnAssignmentOp,
  6289. NotAScalarType,
  6290. NotAnLValue,
  6291. NoError
  6292. } ErrorFound = NoError;
  6293. SourceLocation ErrorLoc, NoteLoc;
  6294. SourceRange ErrorRange, NoteRange;
  6295. // If clause is read:
  6296. // v = x;
  6297. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6298. const auto *AtomicBinOp =
  6299. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6300. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6301. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  6302. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  6303. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  6304. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  6305. if (!X->isLValue() || !V->isLValue()) {
  6306. const Expr *NotLValueExpr = X->isLValue() ? V : X;
  6307. ErrorFound = NotAnLValue;
  6308. ErrorLoc = AtomicBinOp->getExprLoc();
  6309. ErrorRange = AtomicBinOp->getSourceRange();
  6310. NoteLoc = NotLValueExpr->getExprLoc();
  6311. NoteRange = NotLValueExpr->getSourceRange();
  6312. }
  6313. } else if (!X->isInstantiationDependent() ||
  6314. !V->isInstantiationDependent()) {
  6315. const Expr *NotScalarExpr =
  6316. (X->isInstantiationDependent() || X->getType()->isScalarType())
  6317. ? V
  6318. : X;
  6319. ErrorFound = NotAScalarType;
  6320. ErrorLoc = AtomicBinOp->getExprLoc();
  6321. ErrorRange = AtomicBinOp->getSourceRange();
  6322. NoteLoc = NotScalarExpr->getExprLoc();
  6323. NoteRange = NotScalarExpr->getSourceRange();
  6324. }
  6325. } else if (!AtomicBody->isInstantiationDependent()) {
  6326. ErrorFound = NotAnAssignmentOp;
  6327. ErrorLoc = AtomicBody->getExprLoc();
  6328. ErrorRange = AtomicBody->getSourceRange();
  6329. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6330. : AtomicBody->getExprLoc();
  6331. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6332. : AtomicBody->getSourceRange();
  6333. }
  6334. } else {
  6335. ErrorFound = NotAnExpression;
  6336. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6337. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6338. }
  6339. if (ErrorFound != NoError) {
  6340. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  6341. << ErrorRange;
  6342. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  6343. << NoteRange;
  6344. return StmtError();
  6345. }
  6346. if (CurContext->isDependentContext())
  6347. V = X = nullptr;
  6348. } else if (AtomicKind == OMPC_write) {
  6349. enum {
  6350. NotAnExpression,
  6351. NotAnAssignmentOp,
  6352. NotAScalarType,
  6353. NotAnLValue,
  6354. NoError
  6355. } ErrorFound = NoError;
  6356. SourceLocation ErrorLoc, NoteLoc;
  6357. SourceRange ErrorRange, NoteRange;
  6358. // If clause is write:
  6359. // x = expr;
  6360. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6361. const auto *AtomicBinOp =
  6362. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6363. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6364. X = AtomicBinOp->getLHS();
  6365. E = AtomicBinOp->getRHS();
  6366. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  6367. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  6368. if (!X->isLValue()) {
  6369. ErrorFound = NotAnLValue;
  6370. ErrorLoc = AtomicBinOp->getExprLoc();
  6371. ErrorRange = AtomicBinOp->getSourceRange();
  6372. NoteLoc = X->getExprLoc();
  6373. NoteRange = X->getSourceRange();
  6374. }
  6375. } else if (!X->isInstantiationDependent() ||
  6376. !E->isInstantiationDependent()) {
  6377. const Expr *NotScalarExpr =
  6378. (X->isInstantiationDependent() || X->getType()->isScalarType())
  6379. ? E
  6380. : X;
  6381. ErrorFound = NotAScalarType;
  6382. ErrorLoc = AtomicBinOp->getExprLoc();
  6383. ErrorRange = AtomicBinOp->getSourceRange();
  6384. NoteLoc = NotScalarExpr->getExprLoc();
  6385. NoteRange = NotScalarExpr->getSourceRange();
  6386. }
  6387. } else if (!AtomicBody->isInstantiationDependent()) {
  6388. ErrorFound = NotAnAssignmentOp;
  6389. ErrorLoc = AtomicBody->getExprLoc();
  6390. ErrorRange = AtomicBody->getSourceRange();
  6391. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6392. : AtomicBody->getExprLoc();
  6393. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6394. : AtomicBody->getSourceRange();
  6395. }
  6396. } else {
  6397. ErrorFound = NotAnExpression;
  6398. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6399. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  6400. }
  6401. if (ErrorFound != NoError) {
  6402. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  6403. << ErrorRange;
  6404. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  6405. << NoteRange;
  6406. return StmtError();
  6407. }
  6408. if (CurContext->isDependentContext())
  6409. E = X = nullptr;
  6410. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  6411. // If clause is update:
  6412. // x++;
  6413. // x--;
  6414. // ++x;
  6415. // --x;
  6416. // x binop= expr;
  6417. // x = x binop expr;
  6418. // x = expr binop x;
  6419. OpenMPAtomicUpdateChecker Checker(*this);
  6420. if (Checker.checkStatement(
  6421. Body, (AtomicKind == OMPC_update)
  6422. ? diag::err_omp_atomic_update_not_expression_statement
  6423. : diag::err_omp_atomic_not_expression_statement,
  6424. diag::note_omp_atomic_update))
  6425. return StmtError();
  6426. if (!CurContext->isDependentContext()) {
  6427. E = Checker.getExpr();
  6428. X = Checker.getX();
  6429. UE = Checker.getUpdateExpr();
  6430. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6431. }
  6432. } else if (AtomicKind == OMPC_capture) {
  6433. enum {
  6434. NotAnAssignmentOp,
  6435. NotACompoundStatement,
  6436. NotTwoSubstatements,
  6437. NotASpecificExpression,
  6438. NoError
  6439. } ErrorFound = NoError;
  6440. SourceLocation ErrorLoc, NoteLoc;
  6441. SourceRange ErrorRange, NoteRange;
  6442. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  6443. // If clause is a capture:
  6444. // v = x++;
  6445. // v = x--;
  6446. // v = ++x;
  6447. // v = --x;
  6448. // v = x binop= expr;
  6449. // v = x = x binop expr;
  6450. // v = x = expr binop x;
  6451. const auto *AtomicBinOp =
  6452. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  6453. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  6454. V = AtomicBinOp->getLHS();
  6455. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  6456. OpenMPAtomicUpdateChecker Checker(*this);
  6457. if (Checker.checkStatement(
  6458. Body, diag::err_omp_atomic_capture_not_expression_statement,
  6459. diag::note_omp_atomic_update))
  6460. return StmtError();
  6461. E = Checker.getExpr();
  6462. X = Checker.getX();
  6463. UE = Checker.getUpdateExpr();
  6464. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6465. IsPostfixUpdate = Checker.isPostfixUpdate();
  6466. } else if (!AtomicBody->isInstantiationDependent()) {
  6467. ErrorLoc = AtomicBody->getExprLoc();
  6468. ErrorRange = AtomicBody->getSourceRange();
  6469. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  6470. : AtomicBody->getExprLoc();
  6471. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  6472. : AtomicBody->getSourceRange();
  6473. ErrorFound = NotAnAssignmentOp;
  6474. }
  6475. if (ErrorFound != NoError) {
  6476. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  6477. << ErrorRange;
  6478. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  6479. return StmtError();
  6480. }
  6481. if (CurContext->isDependentContext())
  6482. UE = V = E = X = nullptr;
  6483. } else {
  6484. // If clause is a capture:
  6485. // { v = x; x = expr; }
  6486. // { v = x; x++; }
  6487. // { v = x; x--; }
  6488. // { v = x; ++x; }
  6489. // { v = x; --x; }
  6490. // { v = x; x binop= expr; }
  6491. // { v = x; x = x binop expr; }
  6492. // { v = x; x = expr binop x; }
  6493. // { x++; v = x; }
  6494. // { x--; v = x; }
  6495. // { ++x; v = x; }
  6496. // { --x; v = x; }
  6497. // { x binop= expr; v = x; }
  6498. // { x = x binop expr; v = x; }
  6499. // { x = expr binop x; v = x; }
  6500. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  6501. // Check that this is { expr1; expr2; }
  6502. if (CS->size() == 2) {
  6503. Stmt *First = CS->body_front();
  6504. Stmt *Second = CS->body_back();
  6505. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  6506. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  6507. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  6508. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  6509. // Need to find what subexpression is 'v' and what is 'x'.
  6510. OpenMPAtomicUpdateChecker Checker(*this);
  6511. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  6512. BinaryOperator *BinOp = nullptr;
  6513. if (IsUpdateExprFound) {
  6514. BinOp = dyn_cast<BinaryOperator>(First);
  6515. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  6516. }
  6517. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  6518. // { v = x; x++; }
  6519. // { v = x; x--; }
  6520. // { v = x; ++x; }
  6521. // { v = x; --x; }
  6522. // { v = x; x binop= expr; }
  6523. // { v = x; x = x binop expr; }
  6524. // { v = x; x = expr binop x; }
  6525. // Check that the first expression has form v = x.
  6526. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  6527. llvm::FoldingSetNodeID XId, PossibleXId;
  6528. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  6529. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  6530. IsUpdateExprFound = XId == PossibleXId;
  6531. if (IsUpdateExprFound) {
  6532. V = BinOp->getLHS();
  6533. X = Checker.getX();
  6534. E = Checker.getExpr();
  6535. UE = Checker.getUpdateExpr();
  6536. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6537. IsPostfixUpdate = true;
  6538. }
  6539. }
  6540. if (!IsUpdateExprFound) {
  6541. IsUpdateExprFound = !Checker.checkStatement(First);
  6542. BinOp = nullptr;
  6543. if (IsUpdateExprFound) {
  6544. BinOp = dyn_cast<BinaryOperator>(Second);
  6545. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  6546. }
  6547. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  6548. // { x++; v = x; }
  6549. // { x--; v = x; }
  6550. // { ++x; v = x; }
  6551. // { --x; v = x; }
  6552. // { x binop= expr; v = x; }
  6553. // { x = x binop expr; v = x; }
  6554. // { x = expr binop x; v = x; }
  6555. // Check that the second expression has form v = x.
  6556. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  6557. llvm::FoldingSetNodeID XId, PossibleXId;
  6558. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  6559. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  6560. IsUpdateExprFound = XId == PossibleXId;
  6561. if (IsUpdateExprFound) {
  6562. V = BinOp->getLHS();
  6563. X = Checker.getX();
  6564. E = Checker.getExpr();
  6565. UE = Checker.getUpdateExpr();
  6566. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  6567. IsPostfixUpdate = false;
  6568. }
  6569. }
  6570. }
  6571. if (!IsUpdateExprFound) {
  6572. // { v = x; x = expr; }
  6573. auto *FirstExpr = dyn_cast<Expr>(First);
  6574. auto *SecondExpr = dyn_cast<Expr>(Second);
  6575. if (!FirstExpr || !SecondExpr ||
  6576. !(FirstExpr->isInstantiationDependent() ||
  6577. SecondExpr->isInstantiationDependent())) {
  6578. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  6579. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  6580. ErrorFound = NotAnAssignmentOp;
  6581. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  6582. : First->getBeginLoc();
  6583. NoteRange = ErrorRange = FirstBinOp
  6584. ? FirstBinOp->getSourceRange()
  6585. : SourceRange(ErrorLoc, ErrorLoc);
  6586. } else {
  6587. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  6588. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  6589. ErrorFound = NotAnAssignmentOp;
  6590. NoteLoc = ErrorLoc = SecondBinOp
  6591. ? SecondBinOp->getOperatorLoc()
  6592. : Second->getBeginLoc();
  6593. NoteRange = ErrorRange =
  6594. SecondBinOp ? SecondBinOp->getSourceRange()
  6595. : SourceRange(ErrorLoc, ErrorLoc);
  6596. } else {
  6597. Expr *PossibleXRHSInFirst =
  6598. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  6599. Expr *PossibleXLHSInSecond =
  6600. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  6601. llvm::FoldingSetNodeID X1Id, X2Id;
  6602. PossibleXRHSInFirst->Profile(X1Id, Context,
  6603. /*Canonical=*/true);
  6604. PossibleXLHSInSecond->Profile(X2Id, Context,
  6605. /*Canonical=*/true);
  6606. IsUpdateExprFound = X1Id == X2Id;
  6607. if (IsUpdateExprFound) {
  6608. V = FirstBinOp->getLHS();
  6609. X = SecondBinOp->getLHS();
  6610. E = SecondBinOp->getRHS();
  6611. UE = nullptr;
  6612. IsXLHSInRHSPart = false;
  6613. IsPostfixUpdate = true;
  6614. } else {
  6615. ErrorFound = NotASpecificExpression;
  6616. ErrorLoc = FirstBinOp->getExprLoc();
  6617. ErrorRange = FirstBinOp->getSourceRange();
  6618. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  6619. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  6620. }
  6621. }
  6622. }
  6623. }
  6624. }
  6625. } else {
  6626. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6627. NoteRange = ErrorRange =
  6628. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  6629. ErrorFound = NotTwoSubstatements;
  6630. }
  6631. } else {
  6632. NoteLoc = ErrorLoc = Body->getBeginLoc();
  6633. NoteRange = ErrorRange =
  6634. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  6635. ErrorFound = NotACompoundStatement;
  6636. }
  6637. if (ErrorFound != NoError) {
  6638. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  6639. << ErrorRange;
  6640. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  6641. return StmtError();
  6642. }
  6643. if (CurContext->isDependentContext())
  6644. UE = V = E = X = nullptr;
  6645. }
  6646. }
  6647. setFunctionHasBranchProtectedScope();
  6648. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  6649. X, V, E, UE, IsXLHSInRHSPart,
  6650. IsPostfixUpdate);
  6651. }
  6652. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  6653. Stmt *AStmt,
  6654. SourceLocation StartLoc,
  6655. SourceLocation EndLoc) {
  6656. if (!AStmt)
  6657. return StmtError();
  6658. auto *CS = cast<CapturedStmt>(AStmt);
  6659. // 1.2.2 OpenMP Language Terminology
  6660. // Structured block - An executable statement with a single entry at the
  6661. // top and a single exit at the bottom.
  6662. // The point of exit cannot be a branch out of the structured block.
  6663. // longjmp() and throw() must not violate the entry/exit criteria.
  6664. CS->getCapturedDecl()->setNothrow();
  6665. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
  6666. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6667. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6668. // 1.2.2 OpenMP Language Terminology
  6669. // Structured block - An executable statement with a single entry at the
  6670. // top and a single exit at the bottom.
  6671. // The point of exit cannot be a branch out of the structured block.
  6672. // longjmp() and throw() must not violate the entry/exit criteria.
  6673. CS->getCapturedDecl()->setNothrow();
  6674. }
  6675. // OpenMP [2.16, Nesting of Regions]
  6676. // If specified, a teams construct must be contained within a target
  6677. // construct. That target construct must contain no statements or directives
  6678. // outside of the teams construct.
  6679. if (DSAStack->hasInnerTeamsRegion()) {
  6680. const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
  6681. bool OMPTeamsFound = true;
  6682. if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
  6683. auto I = CS->body_begin();
  6684. while (I != CS->body_end()) {
  6685. const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  6686. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
  6687. OMPTeamsFound) {
  6688. OMPTeamsFound = false;
  6689. break;
  6690. }
  6691. ++I;
  6692. }
  6693. assert(I != CS->body_end() && "Not found statement");
  6694. S = *I;
  6695. } else {
  6696. const auto *OED = dyn_cast<OMPExecutableDirective>(S);
  6697. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  6698. }
  6699. if (!OMPTeamsFound) {
  6700. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  6701. Diag(DSAStack->getInnerTeamsRegionLoc(),
  6702. diag::note_omp_nested_teams_construct_here);
  6703. Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
  6704. << isa<OMPExecutableDirective>(S);
  6705. return StmtError();
  6706. }
  6707. }
  6708. setFunctionHasBranchProtectedScope();
  6709. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6710. }
  6711. StmtResult
  6712. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  6713. Stmt *AStmt, SourceLocation StartLoc,
  6714. SourceLocation EndLoc) {
  6715. if (!AStmt)
  6716. return StmtError();
  6717. auto *CS = cast<CapturedStmt>(AStmt);
  6718. // 1.2.2 OpenMP Language Terminology
  6719. // Structured block - An executable statement with a single entry at the
  6720. // top and a single exit at the bottom.
  6721. // The point of exit cannot be a branch out of the structured block.
  6722. // longjmp() and throw() must not violate the entry/exit criteria.
  6723. CS->getCapturedDecl()->setNothrow();
  6724. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
  6725. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6726. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6727. // 1.2.2 OpenMP Language Terminology
  6728. // Structured block - An executable statement with a single entry at the
  6729. // top and a single exit at the bottom.
  6730. // The point of exit cannot be a branch out of the structured block.
  6731. // longjmp() and throw() must not violate the entry/exit criteria.
  6732. CS->getCapturedDecl()->setNothrow();
  6733. }
  6734. setFunctionHasBranchProtectedScope();
  6735. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6736. AStmt);
  6737. }
  6738. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  6739. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  6740. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  6741. if (!AStmt)
  6742. return StmtError();
  6743. auto *CS = cast<CapturedStmt>(AStmt);
  6744. // 1.2.2 OpenMP Language Terminology
  6745. // Structured block - An executable statement with a single entry at the
  6746. // top and a single exit at the bottom.
  6747. // The point of exit cannot be a branch out of the structured block.
  6748. // longjmp() and throw() must not violate the entry/exit criteria.
  6749. CS->getCapturedDecl()->setNothrow();
  6750. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  6751. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6752. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6753. // 1.2.2 OpenMP Language Terminology
  6754. // Structured block - An executable statement with a single entry at the
  6755. // top and a single exit at the bottom.
  6756. // The point of exit cannot be a branch out of the structured block.
  6757. // longjmp() and throw() must not violate the entry/exit criteria.
  6758. CS->getCapturedDecl()->setNothrow();
  6759. }
  6760. OMPLoopDirective::HelperExprs B;
  6761. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  6762. // define the nested loops number.
  6763. unsigned NestedLoopCount =
  6764. checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  6765. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  6766. VarsWithImplicitDSA, B);
  6767. if (NestedLoopCount == 0)
  6768. return StmtError();
  6769. assert((CurContext->isDependentContext() || B.builtAll()) &&
  6770. "omp target parallel for loop exprs were not built");
  6771. if (!CurContext->isDependentContext()) {
  6772. // Finalize the clauses that need pre-built expressions for CodeGen.
  6773. for (OMPClause *C : Clauses) {
  6774. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  6775. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  6776. B.NumIterations, *this, CurScope,
  6777. DSAStack))
  6778. return StmtError();
  6779. }
  6780. }
  6781. setFunctionHasBranchProtectedScope();
  6782. return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
  6783. NestedLoopCount, Clauses, AStmt,
  6784. B, DSAStack->isCancelRegion());
  6785. }
  6786. /// Check for existence of a map clause in the list of clauses.
  6787. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  6788. const OpenMPClauseKind K) {
  6789. return llvm::any_of(
  6790. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  6791. }
  6792. template <typename... Params>
  6793. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  6794. const Params... ClauseTypes) {
  6795. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  6796. }
  6797. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  6798. Stmt *AStmt,
  6799. SourceLocation StartLoc,
  6800. SourceLocation EndLoc) {
  6801. if (!AStmt)
  6802. return StmtError();
  6803. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  6804. // OpenMP [2.10.1, Restrictions, p. 97]
  6805. // At least one map clause must appear on the directive.
  6806. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
  6807. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6808. << "'map' or 'use_device_ptr'"
  6809. << getOpenMPDirectiveName(OMPD_target_data);
  6810. return StmtError();
  6811. }
  6812. setFunctionHasBranchProtectedScope();
  6813. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6814. AStmt);
  6815. }
  6816. StmtResult
  6817. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  6818. SourceLocation StartLoc,
  6819. SourceLocation EndLoc, Stmt *AStmt) {
  6820. if (!AStmt)
  6821. return StmtError();
  6822. auto *CS = cast<CapturedStmt>(AStmt);
  6823. // 1.2.2 OpenMP Language Terminology
  6824. // Structured block - An executable statement with a single entry at the
  6825. // top and a single exit at the bottom.
  6826. // The point of exit cannot be a branch out of the structured block.
  6827. // longjmp() and throw() must not violate the entry/exit criteria.
  6828. CS->getCapturedDecl()->setNothrow();
  6829. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  6830. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6831. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6832. // 1.2.2 OpenMP Language Terminology
  6833. // Structured block - An executable statement with a single entry at the
  6834. // top and a single exit at the bottom.
  6835. // The point of exit cannot be a branch out of the structured block.
  6836. // longjmp() and throw() must not violate the entry/exit criteria.
  6837. CS->getCapturedDecl()->setNothrow();
  6838. }
  6839. // OpenMP [2.10.2, Restrictions, p. 99]
  6840. // At least one map clause must appear on the directive.
  6841. if (!hasClauses(Clauses, OMPC_map)) {
  6842. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6843. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  6844. return StmtError();
  6845. }
  6846. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6847. AStmt);
  6848. }
  6849. StmtResult
  6850. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  6851. SourceLocation StartLoc,
  6852. SourceLocation EndLoc, Stmt *AStmt) {
  6853. if (!AStmt)
  6854. return StmtError();
  6855. auto *CS = cast<CapturedStmt>(AStmt);
  6856. // 1.2.2 OpenMP Language Terminology
  6857. // Structured block - An executable statement with a single entry at the
  6858. // top and a single exit at the bottom.
  6859. // The point of exit cannot be a branch out of the structured block.
  6860. // longjmp() and throw() must not violate the entry/exit criteria.
  6861. CS->getCapturedDecl()->setNothrow();
  6862. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  6863. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6864. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6865. // 1.2.2 OpenMP Language Terminology
  6866. // Structured block - An executable statement with a single entry at the
  6867. // top and a single exit at the bottom.
  6868. // The point of exit cannot be a branch out of the structured block.
  6869. // longjmp() and throw() must not violate the entry/exit criteria.
  6870. CS->getCapturedDecl()->setNothrow();
  6871. }
  6872. // OpenMP [2.10.3, Restrictions, p. 102]
  6873. // At least one map clause must appear on the directive.
  6874. if (!hasClauses(Clauses, OMPC_map)) {
  6875. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  6876. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  6877. return StmtError();
  6878. }
  6879. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6880. AStmt);
  6881. }
  6882. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  6883. SourceLocation StartLoc,
  6884. SourceLocation EndLoc,
  6885. Stmt *AStmt) {
  6886. if (!AStmt)
  6887. return StmtError();
  6888. auto *CS = cast<CapturedStmt>(AStmt);
  6889. // 1.2.2 OpenMP Language Terminology
  6890. // Structured block - An executable statement with a single entry at the
  6891. // top and a single exit at the bottom.
  6892. // The point of exit cannot be a branch out of the structured block.
  6893. // longjmp() and throw() must not violate the entry/exit criteria.
  6894. CS->getCapturedDecl()->setNothrow();
  6895. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  6896. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  6897. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  6898. // 1.2.2 OpenMP Language Terminology
  6899. // Structured block - An executable statement with a single entry at the
  6900. // top and a single exit at the bottom.
  6901. // The point of exit cannot be a branch out of the structured block.
  6902. // longjmp() and throw() must not violate the entry/exit criteria.
  6903. CS->getCapturedDecl()->setNothrow();
  6904. }
  6905. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  6906. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  6907. return StmtError();
  6908. }
  6909. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6910. AStmt);
  6911. }
  6912. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  6913. Stmt *AStmt, SourceLocation StartLoc,
  6914. SourceLocation EndLoc) {
  6915. if (!AStmt)
  6916. return StmtError();
  6917. auto *CS = cast<CapturedStmt>(AStmt);
  6918. // 1.2.2 OpenMP Language Terminology
  6919. // Structured block - An executable statement with a single entry at the
  6920. // top and a single exit at the bottom.
  6921. // The point of exit cannot be a branch out of the structured block.
  6922. // longjmp() and throw() must not violate the entry/exit criteria.
  6923. CS->getCapturedDecl()->setNothrow();
  6924. setFunctionHasBranchProtectedScope();
  6925. DSAStack->setParentTeamsRegionLoc(StartLoc);
  6926. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  6927. }
  6928. StmtResult
  6929. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  6930. SourceLocation EndLoc,
  6931. OpenMPDirectiveKind CancelRegion) {
  6932. if (DSAStack->isParentNowaitRegion()) {
  6933. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  6934. return StmtError();
  6935. }
  6936. if (DSAStack->isParentOrderedRegion()) {
  6937. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  6938. return StmtError();
  6939. }
  6940. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  6941. CancelRegion);
  6942. }
  6943. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  6944. SourceLocation StartLoc,
  6945. SourceLocation EndLoc,
  6946. OpenMPDirectiveKind CancelRegion) {
  6947. if (DSAStack->isParentNowaitRegion()) {
  6948. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  6949. return StmtError();
  6950. }
  6951. if (DSAStack->isParentOrderedRegion()) {
  6952. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  6953. return StmtError();
  6954. }
  6955. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  6956. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  6957. CancelRegion);
  6958. }
  6959. static bool checkGrainsizeNumTasksClauses(Sema &S,
  6960. ArrayRef<OMPClause *> Clauses) {
  6961. const OMPClause *PrevClause = nullptr;
  6962. bool ErrorFound = false;
  6963. for (const OMPClause *C : Clauses) {
  6964. if (C->getClauseKind() == OMPC_grainsize ||
  6965. C->getClauseKind() == OMPC_num_tasks) {
  6966. if (!PrevClause)
  6967. PrevClause = C;
  6968. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  6969. S.Diag(C->getBeginLoc(),
  6970. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  6971. << getOpenMPClauseName(C->getClauseKind())
  6972. << getOpenMPClauseName(PrevClause->getClauseKind());
  6973. S.Diag(PrevClause->getBeginLoc(),
  6974. diag::note_omp_previous_grainsize_num_tasks)
  6975. << getOpenMPClauseName(PrevClause->getClauseKind());
  6976. ErrorFound = true;
  6977. }
  6978. }
  6979. }
  6980. return ErrorFound;
  6981. }
  6982. static bool checkReductionClauseWithNogroup(Sema &S,
  6983. ArrayRef<OMPClause *> Clauses) {
  6984. const OMPClause *ReductionClause = nullptr;
  6985. const OMPClause *NogroupClause = nullptr;
  6986. for (const OMPClause *C : Clauses) {
  6987. if (C->getClauseKind() == OMPC_reduction) {
  6988. ReductionClause = C;
  6989. if (NogroupClause)
  6990. break;
  6991. continue;
  6992. }
  6993. if (C->getClauseKind() == OMPC_nogroup) {
  6994. NogroupClause = C;
  6995. if (ReductionClause)
  6996. break;
  6997. continue;
  6998. }
  6999. }
  7000. if (ReductionClause && NogroupClause) {
  7001. S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
  7002. << SourceRange(NogroupClause->getBeginLoc(),
  7003. NogroupClause->getEndLoc());
  7004. return true;
  7005. }
  7006. return false;
  7007. }
  7008. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  7009. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7010. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7011. if (!AStmt)
  7012. return StmtError();
  7013. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7014. OMPLoopDirective::HelperExprs B;
  7015. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7016. // define the nested loops number.
  7017. unsigned NestedLoopCount =
  7018. checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  7019. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  7020. VarsWithImplicitDSA, B);
  7021. if (NestedLoopCount == 0)
  7022. return StmtError();
  7023. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7024. "omp for loop exprs were not built");
  7025. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  7026. // The grainsize clause and num_tasks clause are mutually exclusive and may
  7027. // not appear on the same taskloop directive.
  7028. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  7029. return StmtError();
  7030. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  7031. // If a reduction clause is present on the taskloop directive, the nogroup
  7032. // clause must not be specified.
  7033. if (checkReductionClauseWithNogroup(*this, Clauses))
  7034. return StmtError();
  7035. setFunctionHasBranchProtectedScope();
  7036. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  7037. NestedLoopCount, Clauses, AStmt, B);
  7038. }
  7039. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  7040. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7041. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7042. if (!AStmt)
  7043. return StmtError();
  7044. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7045. OMPLoopDirective::HelperExprs B;
  7046. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7047. // define the nested loops number.
  7048. unsigned NestedLoopCount =
  7049. checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  7050. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  7051. VarsWithImplicitDSA, B);
  7052. if (NestedLoopCount == 0)
  7053. return StmtError();
  7054. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7055. "omp for loop exprs were not built");
  7056. if (!CurContext->isDependentContext()) {
  7057. // Finalize the clauses that need pre-built expressions for CodeGen.
  7058. for (OMPClause *C : Clauses) {
  7059. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7060. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7061. B.NumIterations, *this, CurScope,
  7062. DSAStack))
  7063. return StmtError();
  7064. }
  7065. }
  7066. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  7067. // The grainsize clause and num_tasks clause are mutually exclusive and may
  7068. // not appear on the same taskloop directive.
  7069. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  7070. return StmtError();
  7071. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  7072. // If a reduction clause is present on the taskloop directive, the nogroup
  7073. // clause must not be specified.
  7074. if (checkReductionClauseWithNogroup(*this, Clauses))
  7075. return StmtError();
  7076. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7077. return StmtError();
  7078. setFunctionHasBranchProtectedScope();
  7079. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  7080. NestedLoopCount, Clauses, AStmt, B);
  7081. }
  7082. StmtResult Sema::ActOnOpenMPDistributeDirective(
  7083. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7084. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7085. if (!AStmt)
  7086. return StmtError();
  7087. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  7088. OMPLoopDirective::HelperExprs B;
  7089. // In presence of clause 'collapse' with number of loops, it will
  7090. // define the nested loops number.
  7091. unsigned NestedLoopCount =
  7092. checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  7093. nullptr /*ordered not a clause on distribute*/, AStmt,
  7094. *this, *DSAStack, VarsWithImplicitDSA, B);
  7095. if (NestedLoopCount == 0)
  7096. return StmtError();
  7097. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7098. "omp for loop exprs were not built");
  7099. setFunctionHasBranchProtectedScope();
  7100. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  7101. NestedLoopCount, Clauses, AStmt, B);
  7102. }
  7103. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  7104. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7105. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7106. if (!AStmt)
  7107. return StmtError();
  7108. auto *CS = cast<CapturedStmt>(AStmt);
  7109. // 1.2.2 OpenMP Language Terminology
  7110. // Structured block - An executable statement with a single entry at the
  7111. // top and a single exit at the bottom.
  7112. // The point of exit cannot be a branch out of the structured block.
  7113. // longjmp() and throw() must not violate the entry/exit criteria.
  7114. CS->getCapturedDecl()->setNothrow();
  7115. for (int ThisCaptureLevel =
  7116. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  7117. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7118. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7119. // 1.2.2 OpenMP Language Terminology
  7120. // Structured block - An executable statement with a single entry at the
  7121. // top and a single exit at the bottom.
  7122. // The point of exit cannot be a branch out of the structured block.
  7123. // longjmp() and throw() must not violate the entry/exit criteria.
  7124. CS->getCapturedDecl()->setNothrow();
  7125. }
  7126. OMPLoopDirective::HelperExprs B;
  7127. // In presence of clause 'collapse' with number of loops, it will
  7128. // define the nested loops number.
  7129. unsigned NestedLoopCount = checkOpenMPLoop(
  7130. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  7131. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7132. VarsWithImplicitDSA, B);
  7133. if (NestedLoopCount == 0)
  7134. return StmtError();
  7135. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7136. "omp for loop exprs were not built");
  7137. setFunctionHasBranchProtectedScope();
  7138. return OMPDistributeParallelForDirective::Create(
  7139. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  7140. DSAStack->isCancelRegion());
  7141. }
  7142. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  7143. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7144. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7145. if (!AStmt)
  7146. return StmtError();
  7147. auto *CS = cast<CapturedStmt>(AStmt);
  7148. // 1.2.2 OpenMP Language Terminology
  7149. // Structured block - An executable statement with a single entry at the
  7150. // top and a single exit at the bottom.
  7151. // The point of exit cannot be a branch out of the structured block.
  7152. // longjmp() and throw() must not violate the entry/exit criteria.
  7153. CS->getCapturedDecl()->setNothrow();
  7154. for (int ThisCaptureLevel =
  7155. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  7156. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7157. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7158. // 1.2.2 OpenMP Language Terminology
  7159. // Structured block - An executable statement with a single entry at the
  7160. // top and a single exit at the bottom.
  7161. // The point of exit cannot be a branch out of the structured block.
  7162. // longjmp() and throw() must not violate the entry/exit criteria.
  7163. CS->getCapturedDecl()->setNothrow();
  7164. }
  7165. OMPLoopDirective::HelperExprs B;
  7166. // In presence of clause 'collapse' with number of loops, it will
  7167. // define the nested loops number.
  7168. unsigned NestedLoopCount = checkOpenMPLoop(
  7169. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7170. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7171. VarsWithImplicitDSA, B);
  7172. if (NestedLoopCount == 0)
  7173. return StmtError();
  7174. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7175. "omp for loop exprs were not built");
  7176. if (!CurContext->isDependentContext()) {
  7177. // Finalize the clauses that need pre-built expressions for CodeGen.
  7178. for (OMPClause *C : Clauses) {
  7179. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7180. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7181. B.NumIterations, *this, CurScope,
  7182. DSAStack))
  7183. return StmtError();
  7184. }
  7185. }
  7186. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7187. return StmtError();
  7188. setFunctionHasBranchProtectedScope();
  7189. return OMPDistributeParallelForSimdDirective::Create(
  7190. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7191. }
  7192. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  7193. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7194. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7195. if (!AStmt)
  7196. return StmtError();
  7197. auto *CS = cast<CapturedStmt>(AStmt);
  7198. // 1.2.2 OpenMP Language Terminology
  7199. // Structured block - An executable statement with a single entry at the
  7200. // top and a single exit at the bottom.
  7201. // The point of exit cannot be a branch out of the structured block.
  7202. // longjmp() and throw() must not violate the entry/exit criteria.
  7203. CS->getCapturedDecl()->setNothrow();
  7204. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  7205. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7206. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7207. // 1.2.2 OpenMP Language Terminology
  7208. // Structured block - An executable statement with a single entry at the
  7209. // top and a single exit at the bottom.
  7210. // The point of exit cannot be a branch out of the structured block.
  7211. // longjmp() and throw() must not violate the entry/exit criteria.
  7212. CS->getCapturedDecl()->setNothrow();
  7213. }
  7214. OMPLoopDirective::HelperExprs B;
  7215. // In presence of clause 'collapse' with number of loops, it will
  7216. // define the nested loops number.
  7217. unsigned NestedLoopCount =
  7218. checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  7219. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7220. *DSAStack, VarsWithImplicitDSA, B);
  7221. if (NestedLoopCount == 0)
  7222. return StmtError();
  7223. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7224. "omp for loop exprs were not built");
  7225. if (!CurContext->isDependentContext()) {
  7226. // Finalize the clauses that need pre-built expressions for CodeGen.
  7227. for (OMPClause *C : Clauses) {
  7228. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7229. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7230. B.NumIterations, *this, CurScope,
  7231. DSAStack))
  7232. return StmtError();
  7233. }
  7234. }
  7235. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7236. return StmtError();
  7237. setFunctionHasBranchProtectedScope();
  7238. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  7239. NestedLoopCount, Clauses, AStmt, B);
  7240. }
  7241. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  7242. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7243. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7244. if (!AStmt)
  7245. return StmtError();
  7246. auto *CS = cast<CapturedStmt>(AStmt);
  7247. // 1.2.2 OpenMP Language Terminology
  7248. // Structured block - An executable statement with a single entry at the
  7249. // top and a single exit at the bottom.
  7250. // The point of exit cannot be a branch out of the structured block.
  7251. // longjmp() and throw() must not violate the entry/exit criteria.
  7252. CS->getCapturedDecl()->setNothrow();
  7253. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  7254. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7255. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7256. // 1.2.2 OpenMP Language Terminology
  7257. // Structured block - An executable statement with a single entry at the
  7258. // top and a single exit at the bottom.
  7259. // The point of exit cannot be a branch out of the structured block.
  7260. // longjmp() and throw() must not violate the entry/exit criteria.
  7261. CS->getCapturedDecl()->setNothrow();
  7262. }
  7263. OMPLoopDirective::HelperExprs B;
  7264. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  7265. // define the nested loops number.
  7266. unsigned NestedLoopCount = checkOpenMPLoop(
  7267. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7268. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  7269. VarsWithImplicitDSA, B);
  7270. if (NestedLoopCount == 0)
  7271. return StmtError();
  7272. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7273. "omp target parallel for simd loop exprs were not built");
  7274. if (!CurContext->isDependentContext()) {
  7275. // Finalize the clauses that need pre-built expressions for CodeGen.
  7276. for (OMPClause *C : Clauses) {
  7277. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7278. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7279. B.NumIterations, *this, CurScope,
  7280. DSAStack))
  7281. return StmtError();
  7282. }
  7283. }
  7284. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7285. return StmtError();
  7286. setFunctionHasBranchProtectedScope();
  7287. return OMPTargetParallelForSimdDirective::Create(
  7288. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7289. }
  7290. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  7291. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7292. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7293. if (!AStmt)
  7294. return StmtError();
  7295. auto *CS = cast<CapturedStmt>(AStmt);
  7296. // 1.2.2 OpenMP Language Terminology
  7297. // Structured block - An executable statement with a single entry at the
  7298. // top and a single exit at the bottom.
  7299. // The point of exit cannot be a branch out of the structured block.
  7300. // longjmp() and throw() must not violate the entry/exit criteria.
  7301. CS->getCapturedDecl()->setNothrow();
  7302. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  7303. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7304. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7305. // 1.2.2 OpenMP Language Terminology
  7306. // Structured block - An executable statement with a single entry at the
  7307. // top and a single exit at the bottom.
  7308. // The point of exit cannot be a branch out of the structured block.
  7309. // longjmp() and throw() must not violate the entry/exit criteria.
  7310. CS->getCapturedDecl()->setNothrow();
  7311. }
  7312. OMPLoopDirective::HelperExprs B;
  7313. // In presence of clause 'collapse' with number of loops, it will define the
  7314. // nested loops number.
  7315. unsigned NestedLoopCount =
  7316. checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  7317. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  7318. VarsWithImplicitDSA, B);
  7319. if (NestedLoopCount == 0)
  7320. return StmtError();
  7321. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7322. "omp target simd loop exprs were not built");
  7323. if (!CurContext->isDependentContext()) {
  7324. // Finalize the clauses that need pre-built expressions for CodeGen.
  7325. for (OMPClause *C : Clauses) {
  7326. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7327. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7328. B.NumIterations, *this, CurScope,
  7329. DSAStack))
  7330. return StmtError();
  7331. }
  7332. }
  7333. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7334. return StmtError();
  7335. setFunctionHasBranchProtectedScope();
  7336. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  7337. NestedLoopCount, Clauses, AStmt, B);
  7338. }
  7339. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  7340. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7341. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7342. if (!AStmt)
  7343. return StmtError();
  7344. auto *CS = cast<CapturedStmt>(AStmt);
  7345. // 1.2.2 OpenMP Language Terminology
  7346. // Structured block - An executable statement with a single entry at the
  7347. // top and a single exit at the bottom.
  7348. // The point of exit cannot be a branch out of the structured block.
  7349. // longjmp() and throw() must not violate the entry/exit criteria.
  7350. CS->getCapturedDecl()->setNothrow();
  7351. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  7352. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7353. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7354. // 1.2.2 OpenMP Language Terminology
  7355. // Structured block - An executable statement with a single entry at the
  7356. // top and a single exit at the bottom.
  7357. // The point of exit cannot be a branch out of the structured block.
  7358. // longjmp() and throw() must not violate the entry/exit criteria.
  7359. CS->getCapturedDecl()->setNothrow();
  7360. }
  7361. OMPLoopDirective::HelperExprs B;
  7362. // In presence of clause 'collapse' with number of loops, it will
  7363. // define the nested loops number.
  7364. unsigned NestedLoopCount =
  7365. checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  7366. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7367. *DSAStack, VarsWithImplicitDSA, B);
  7368. if (NestedLoopCount == 0)
  7369. return StmtError();
  7370. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7371. "omp teams distribute loop exprs were not built");
  7372. setFunctionHasBranchProtectedScope();
  7373. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7374. return OMPTeamsDistributeDirective::Create(
  7375. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7376. }
  7377. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  7378. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7379. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7380. if (!AStmt)
  7381. return StmtError();
  7382. auto *CS = cast<CapturedStmt>(AStmt);
  7383. // 1.2.2 OpenMP Language Terminology
  7384. // Structured block - An executable statement with a single entry at the
  7385. // top and a single exit at the bottom.
  7386. // The point of exit cannot be a branch out of the structured block.
  7387. // longjmp() and throw() must not violate the entry/exit criteria.
  7388. CS->getCapturedDecl()->setNothrow();
  7389. for (int ThisCaptureLevel =
  7390. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  7391. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7392. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7393. // 1.2.2 OpenMP Language Terminology
  7394. // Structured block - An executable statement with a single entry at the
  7395. // top and a single exit at the bottom.
  7396. // The point of exit cannot be a branch out of the structured block.
  7397. // longjmp() and throw() must not violate the entry/exit criteria.
  7398. CS->getCapturedDecl()->setNothrow();
  7399. }
  7400. OMPLoopDirective::HelperExprs B;
  7401. // In presence of clause 'collapse' with number of loops, it will
  7402. // define the nested loops number.
  7403. unsigned NestedLoopCount = checkOpenMPLoop(
  7404. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  7405. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7406. VarsWithImplicitDSA, B);
  7407. if (NestedLoopCount == 0)
  7408. return StmtError();
  7409. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7410. "omp teams distribute simd loop exprs were not built");
  7411. if (!CurContext->isDependentContext()) {
  7412. // Finalize the clauses that need pre-built expressions for CodeGen.
  7413. for (OMPClause *C : Clauses) {
  7414. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7415. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7416. B.NumIterations, *this, CurScope,
  7417. DSAStack))
  7418. return StmtError();
  7419. }
  7420. }
  7421. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7422. return StmtError();
  7423. setFunctionHasBranchProtectedScope();
  7424. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7425. return OMPTeamsDistributeSimdDirective::Create(
  7426. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7427. }
  7428. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  7429. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7430. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7431. if (!AStmt)
  7432. return StmtError();
  7433. auto *CS = cast<CapturedStmt>(AStmt);
  7434. // 1.2.2 OpenMP Language Terminology
  7435. // Structured block - An executable statement with a single entry at the
  7436. // top and a single exit at the bottom.
  7437. // The point of exit cannot be a branch out of the structured block.
  7438. // longjmp() and throw() must not violate the entry/exit criteria.
  7439. CS->getCapturedDecl()->setNothrow();
  7440. for (int ThisCaptureLevel =
  7441. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  7442. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7443. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7444. // 1.2.2 OpenMP Language Terminology
  7445. // Structured block - An executable statement with a single entry at the
  7446. // top and a single exit at the bottom.
  7447. // The point of exit cannot be a branch out of the structured block.
  7448. // longjmp() and throw() must not violate the entry/exit criteria.
  7449. CS->getCapturedDecl()->setNothrow();
  7450. }
  7451. OMPLoopDirective::HelperExprs B;
  7452. // In presence of clause 'collapse' with number of loops, it will
  7453. // define the nested loops number.
  7454. unsigned NestedLoopCount = checkOpenMPLoop(
  7455. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  7456. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7457. VarsWithImplicitDSA, B);
  7458. if (NestedLoopCount == 0)
  7459. return StmtError();
  7460. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7461. "omp for loop exprs were not built");
  7462. if (!CurContext->isDependentContext()) {
  7463. // Finalize the clauses that need pre-built expressions for CodeGen.
  7464. for (OMPClause *C : Clauses) {
  7465. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7466. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7467. B.NumIterations, *this, CurScope,
  7468. DSAStack))
  7469. return StmtError();
  7470. }
  7471. }
  7472. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7473. return StmtError();
  7474. setFunctionHasBranchProtectedScope();
  7475. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7476. return OMPTeamsDistributeParallelForSimdDirective::Create(
  7477. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7478. }
  7479. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  7480. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7481. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7482. if (!AStmt)
  7483. return StmtError();
  7484. auto *CS = cast<CapturedStmt>(AStmt);
  7485. // 1.2.2 OpenMP Language Terminology
  7486. // Structured block - An executable statement with a single entry at the
  7487. // top and a single exit at the bottom.
  7488. // The point of exit cannot be a branch out of the structured block.
  7489. // longjmp() and throw() must not violate the entry/exit criteria.
  7490. CS->getCapturedDecl()->setNothrow();
  7491. for (int ThisCaptureLevel =
  7492. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  7493. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7494. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7495. // 1.2.2 OpenMP Language Terminology
  7496. // Structured block - An executable statement with a single entry at the
  7497. // top and a single exit at the bottom.
  7498. // The point of exit cannot be a branch out of the structured block.
  7499. // longjmp() and throw() must not violate the entry/exit criteria.
  7500. CS->getCapturedDecl()->setNothrow();
  7501. }
  7502. OMPLoopDirective::HelperExprs B;
  7503. // In presence of clause 'collapse' with number of loops, it will
  7504. // define the nested loops number.
  7505. unsigned NestedLoopCount = checkOpenMPLoop(
  7506. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  7507. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7508. VarsWithImplicitDSA, B);
  7509. if (NestedLoopCount == 0)
  7510. return StmtError();
  7511. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7512. "omp for loop exprs were not built");
  7513. setFunctionHasBranchProtectedScope();
  7514. DSAStack->setParentTeamsRegionLoc(StartLoc);
  7515. return OMPTeamsDistributeParallelForDirective::Create(
  7516. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  7517. DSAStack->isCancelRegion());
  7518. }
  7519. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  7520. Stmt *AStmt,
  7521. SourceLocation StartLoc,
  7522. SourceLocation EndLoc) {
  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 = getOpenMPCaptureLevels(OMPD_target_teams);
  7533. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7534. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7535. // 1.2.2 OpenMP Language Terminology
  7536. // Structured block - An executable statement with a single entry at the
  7537. // top and a single exit at the bottom.
  7538. // The point of exit cannot be a branch out of the structured block.
  7539. // longjmp() and throw() must not violate the entry/exit criteria.
  7540. CS->getCapturedDecl()->setNothrow();
  7541. }
  7542. setFunctionHasBranchProtectedScope();
  7543. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  7544. AStmt);
  7545. }
  7546. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  7547. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7548. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7549. if (!AStmt)
  7550. return StmtError();
  7551. auto *CS = cast<CapturedStmt>(AStmt);
  7552. // 1.2.2 OpenMP Language Terminology
  7553. // Structured block - An executable statement with a single entry at the
  7554. // top and a single exit at the bottom.
  7555. // The point of exit cannot be a branch out of the structured block.
  7556. // longjmp() and throw() must not violate the entry/exit criteria.
  7557. CS->getCapturedDecl()->setNothrow();
  7558. for (int ThisCaptureLevel =
  7559. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  7560. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7561. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7562. // 1.2.2 OpenMP Language Terminology
  7563. // Structured block - An executable statement with a single entry at the
  7564. // top and a single exit at the bottom.
  7565. // The point of exit cannot be a branch out of the structured block.
  7566. // longjmp() and throw() must not violate the entry/exit criteria.
  7567. CS->getCapturedDecl()->setNothrow();
  7568. }
  7569. OMPLoopDirective::HelperExprs B;
  7570. // In presence of clause 'collapse' with number of loops, it will
  7571. // define the nested loops number.
  7572. unsigned NestedLoopCount = checkOpenMPLoop(
  7573. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  7574. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7575. VarsWithImplicitDSA, B);
  7576. if (NestedLoopCount == 0)
  7577. return StmtError();
  7578. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7579. "omp target teams distribute loop exprs were not built");
  7580. setFunctionHasBranchProtectedScope();
  7581. return OMPTargetTeamsDistributeDirective::Create(
  7582. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7583. }
  7584. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  7585. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7586. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7587. if (!AStmt)
  7588. return StmtError();
  7589. auto *CS = cast<CapturedStmt>(AStmt);
  7590. // 1.2.2 OpenMP Language Terminology
  7591. // Structured block - An executable statement with a single entry at the
  7592. // top and a single exit at the bottom.
  7593. // The point of exit cannot be a branch out of the structured block.
  7594. // longjmp() and throw() must not violate the entry/exit criteria.
  7595. CS->getCapturedDecl()->setNothrow();
  7596. for (int ThisCaptureLevel =
  7597. getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
  7598. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7599. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7600. // 1.2.2 OpenMP Language Terminology
  7601. // Structured block - An executable statement with a single entry at the
  7602. // top and a single exit at the bottom.
  7603. // The point of exit cannot be a branch out of the structured block.
  7604. // longjmp() and throw() must not violate the entry/exit criteria.
  7605. CS->getCapturedDecl()->setNothrow();
  7606. }
  7607. OMPLoopDirective::HelperExprs B;
  7608. // In presence of clause 'collapse' with number of loops, it will
  7609. // define the nested loops number.
  7610. unsigned NestedLoopCount = checkOpenMPLoop(
  7611. OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  7612. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7613. VarsWithImplicitDSA, B);
  7614. if (NestedLoopCount == 0)
  7615. return StmtError();
  7616. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7617. "omp target teams distribute parallel for loop exprs were not built");
  7618. if (!CurContext->isDependentContext()) {
  7619. // Finalize the clauses that need pre-built expressions for CodeGen.
  7620. for (OMPClause *C : Clauses) {
  7621. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7622. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7623. B.NumIterations, *this, CurScope,
  7624. DSAStack))
  7625. return StmtError();
  7626. }
  7627. }
  7628. setFunctionHasBranchProtectedScope();
  7629. return OMPTargetTeamsDistributeParallelForDirective::Create(
  7630. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  7631. DSAStack->isCancelRegion());
  7632. }
  7633. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  7634. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7635. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7636. if (!AStmt)
  7637. return StmtError();
  7638. auto *CS = cast<CapturedStmt>(AStmt);
  7639. // 1.2.2 OpenMP Language Terminology
  7640. // Structured block - An executable statement with a single entry at the
  7641. // top and a single exit at the bottom.
  7642. // The point of exit cannot be a branch out of the structured block.
  7643. // longjmp() and throw() must not violate the entry/exit criteria.
  7644. CS->getCapturedDecl()->setNothrow();
  7645. for (int ThisCaptureLevel = getOpenMPCaptureLevels(
  7646. OMPD_target_teams_distribute_parallel_for_simd);
  7647. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7648. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7649. // 1.2.2 OpenMP Language Terminology
  7650. // Structured block - An executable statement with a single entry at the
  7651. // top and a single exit at the bottom.
  7652. // The point of exit cannot be a branch out of the structured block.
  7653. // longjmp() and throw() must not violate the entry/exit criteria.
  7654. CS->getCapturedDecl()->setNothrow();
  7655. }
  7656. OMPLoopDirective::HelperExprs B;
  7657. // In presence of clause 'collapse' with number of loops, it will
  7658. // define the nested loops number.
  7659. unsigned NestedLoopCount =
  7660. checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
  7661. getCollapseNumberExpr(Clauses),
  7662. nullptr /*ordered not a clause on distribute*/, CS, *this,
  7663. *DSAStack, VarsWithImplicitDSA, B);
  7664. if (NestedLoopCount == 0)
  7665. return StmtError();
  7666. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7667. "omp target teams distribute parallel for simd loop exprs were not "
  7668. "built");
  7669. if (!CurContext->isDependentContext()) {
  7670. // Finalize the clauses that need pre-built expressions for CodeGen.
  7671. for (OMPClause *C : Clauses) {
  7672. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7673. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7674. B.NumIterations, *this, CurScope,
  7675. DSAStack))
  7676. return StmtError();
  7677. }
  7678. }
  7679. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7680. return StmtError();
  7681. setFunctionHasBranchProtectedScope();
  7682. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  7683. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7684. }
  7685. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  7686. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  7687. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  7688. if (!AStmt)
  7689. return StmtError();
  7690. auto *CS = cast<CapturedStmt>(AStmt);
  7691. // 1.2.2 OpenMP Language Terminology
  7692. // Structured block - An executable statement with a single entry at the
  7693. // top and a single exit at the bottom.
  7694. // The point of exit cannot be a branch out of the structured block.
  7695. // longjmp() and throw() must not violate the entry/exit criteria.
  7696. CS->getCapturedDecl()->setNothrow();
  7697. for (int ThisCaptureLevel =
  7698. getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
  7699. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  7700. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  7701. // 1.2.2 OpenMP Language Terminology
  7702. // Structured block - An executable statement with a single entry at the
  7703. // top and a single exit at the bottom.
  7704. // The point of exit cannot be a branch out of the structured block.
  7705. // longjmp() and throw() must not violate the entry/exit criteria.
  7706. CS->getCapturedDecl()->setNothrow();
  7707. }
  7708. OMPLoopDirective::HelperExprs B;
  7709. // In presence of clause 'collapse' with number of loops, it will
  7710. // define the nested loops number.
  7711. unsigned NestedLoopCount = checkOpenMPLoop(
  7712. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  7713. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  7714. VarsWithImplicitDSA, B);
  7715. if (NestedLoopCount == 0)
  7716. return StmtError();
  7717. assert((CurContext->isDependentContext() || B.builtAll()) &&
  7718. "omp target teams distribute simd loop exprs were not built");
  7719. if (!CurContext->isDependentContext()) {
  7720. // Finalize the clauses that need pre-built expressions for CodeGen.
  7721. for (OMPClause *C : Clauses) {
  7722. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  7723. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  7724. B.NumIterations, *this, CurScope,
  7725. DSAStack))
  7726. return StmtError();
  7727. }
  7728. }
  7729. if (checkSimdlenSafelenSpecified(*this, Clauses))
  7730. return StmtError();
  7731. setFunctionHasBranchProtectedScope();
  7732. return OMPTargetTeamsDistributeSimdDirective::Create(
  7733. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  7734. }
  7735. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  7736. SourceLocation StartLoc,
  7737. SourceLocation LParenLoc,
  7738. SourceLocation EndLoc) {
  7739. OMPClause *Res = nullptr;
  7740. switch (Kind) {
  7741. case OMPC_final:
  7742. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  7743. break;
  7744. case OMPC_num_threads:
  7745. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  7746. break;
  7747. case OMPC_safelen:
  7748. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  7749. break;
  7750. case OMPC_simdlen:
  7751. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  7752. break;
  7753. case OMPC_collapse:
  7754. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  7755. break;
  7756. case OMPC_ordered:
  7757. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  7758. break;
  7759. case OMPC_device:
  7760. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  7761. break;
  7762. case OMPC_num_teams:
  7763. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  7764. break;
  7765. case OMPC_thread_limit:
  7766. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  7767. break;
  7768. case OMPC_priority:
  7769. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  7770. break;
  7771. case OMPC_grainsize:
  7772. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  7773. break;
  7774. case OMPC_num_tasks:
  7775. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  7776. break;
  7777. case OMPC_hint:
  7778. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  7779. break;
  7780. case OMPC_if:
  7781. case OMPC_default:
  7782. case OMPC_proc_bind:
  7783. case OMPC_schedule:
  7784. case OMPC_private:
  7785. case OMPC_firstprivate:
  7786. case OMPC_lastprivate:
  7787. case OMPC_shared:
  7788. case OMPC_reduction:
  7789. case OMPC_task_reduction:
  7790. case OMPC_in_reduction:
  7791. case OMPC_linear:
  7792. case OMPC_aligned:
  7793. case OMPC_copyin:
  7794. case OMPC_copyprivate:
  7795. case OMPC_nowait:
  7796. case OMPC_untied:
  7797. case OMPC_mergeable:
  7798. case OMPC_threadprivate:
  7799. case OMPC_flush:
  7800. case OMPC_read:
  7801. case OMPC_write:
  7802. case OMPC_update:
  7803. case OMPC_capture:
  7804. case OMPC_seq_cst:
  7805. case OMPC_depend:
  7806. case OMPC_threads:
  7807. case OMPC_simd:
  7808. case OMPC_map:
  7809. case OMPC_nogroup:
  7810. case OMPC_dist_schedule:
  7811. case OMPC_defaultmap:
  7812. case OMPC_unknown:
  7813. case OMPC_uniform:
  7814. case OMPC_to:
  7815. case OMPC_from:
  7816. case OMPC_use_device_ptr:
  7817. case OMPC_is_device_ptr:
  7818. case OMPC_unified_address:
  7819. case OMPC_unified_shared_memory:
  7820. case OMPC_reverse_offload:
  7821. case OMPC_dynamic_allocators:
  7822. case OMPC_atomic_default_mem_order:
  7823. llvm_unreachable("Clause is not allowed.");
  7824. }
  7825. return Res;
  7826. }
  7827. // An OpenMP directive such as 'target parallel' has two captured regions:
  7828. // for the 'target' and 'parallel' respectively. This function returns
  7829. // the region in which to capture expressions associated with a clause.
  7830. // A return value of OMPD_unknown signifies that the expression should not
  7831. // be captured.
  7832. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  7833. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  7834. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  7835. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  7836. switch (CKind) {
  7837. case OMPC_if:
  7838. switch (DKind) {
  7839. case OMPD_target_parallel:
  7840. case OMPD_target_parallel_for:
  7841. case OMPD_target_parallel_for_simd:
  7842. // If this clause applies to the nested 'parallel' region, capture within
  7843. // the 'target' region, otherwise do not capture.
  7844. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  7845. CaptureRegion = OMPD_target;
  7846. break;
  7847. case OMPD_target_teams_distribute_parallel_for:
  7848. case OMPD_target_teams_distribute_parallel_for_simd:
  7849. // If this clause applies to the nested 'parallel' region, capture within
  7850. // the 'teams' region, otherwise do not capture.
  7851. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  7852. CaptureRegion = OMPD_teams;
  7853. break;
  7854. case OMPD_teams_distribute_parallel_for:
  7855. case OMPD_teams_distribute_parallel_for_simd:
  7856. CaptureRegion = OMPD_teams;
  7857. break;
  7858. case OMPD_target_update:
  7859. case OMPD_target_enter_data:
  7860. case OMPD_target_exit_data:
  7861. CaptureRegion = OMPD_task;
  7862. break;
  7863. case OMPD_cancel:
  7864. case OMPD_parallel:
  7865. case OMPD_parallel_sections:
  7866. case OMPD_parallel_for:
  7867. case OMPD_parallel_for_simd:
  7868. case OMPD_target:
  7869. case OMPD_target_simd:
  7870. case OMPD_target_teams:
  7871. case OMPD_target_teams_distribute:
  7872. case OMPD_target_teams_distribute_simd:
  7873. case OMPD_distribute_parallel_for:
  7874. case OMPD_distribute_parallel_for_simd:
  7875. case OMPD_task:
  7876. case OMPD_taskloop:
  7877. case OMPD_taskloop_simd:
  7878. case OMPD_target_data:
  7879. // Do not capture if-clause expressions.
  7880. break;
  7881. case OMPD_threadprivate:
  7882. case OMPD_taskyield:
  7883. case OMPD_barrier:
  7884. case OMPD_taskwait:
  7885. case OMPD_cancellation_point:
  7886. case OMPD_flush:
  7887. case OMPD_declare_reduction:
  7888. case OMPD_declare_mapper:
  7889. case OMPD_declare_simd:
  7890. case OMPD_declare_target:
  7891. case OMPD_end_declare_target:
  7892. case OMPD_teams:
  7893. case OMPD_simd:
  7894. case OMPD_for:
  7895. case OMPD_for_simd:
  7896. case OMPD_sections:
  7897. case OMPD_section:
  7898. case OMPD_single:
  7899. case OMPD_master:
  7900. case OMPD_critical:
  7901. case OMPD_taskgroup:
  7902. case OMPD_distribute:
  7903. case OMPD_ordered:
  7904. case OMPD_atomic:
  7905. case OMPD_distribute_simd:
  7906. case OMPD_teams_distribute:
  7907. case OMPD_teams_distribute_simd:
  7908. case OMPD_requires:
  7909. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  7910. case OMPD_unknown:
  7911. llvm_unreachable("Unknown OpenMP directive");
  7912. }
  7913. break;
  7914. case OMPC_num_threads:
  7915. switch (DKind) {
  7916. case OMPD_target_parallel:
  7917. case OMPD_target_parallel_for:
  7918. case OMPD_target_parallel_for_simd:
  7919. CaptureRegion = OMPD_target;
  7920. break;
  7921. case OMPD_teams_distribute_parallel_for:
  7922. case OMPD_teams_distribute_parallel_for_simd:
  7923. case OMPD_target_teams_distribute_parallel_for:
  7924. case OMPD_target_teams_distribute_parallel_for_simd:
  7925. CaptureRegion = OMPD_teams;
  7926. break;
  7927. case OMPD_parallel:
  7928. case OMPD_parallel_sections:
  7929. case OMPD_parallel_for:
  7930. case OMPD_parallel_for_simd:
  7931. case OMPD_distribute_parallel_for:
  7932. case OMPD_distribute_parallel_for_simd:
  7933. // Do not capture num_threads-clause expressions.
  7934. break;
  7935. case OMPD_target_data:
  7936. case OMPD_target_enter_data:
  7937. case OMPD_target_exit_data:
  7938. case OMPD_target_update:
  7939. case OMPD_target:
  7940. case OMPD_target_simd:
  7941. case OMPD_target_teams:
  7942. case OMPD_target_teams_distribute:
  7943. case OMPD_target_teams_distribute_simd:
  7944. case OMPD_cancel:
  7945. case OMPD_task:
  7946. case OMPD_taskloop:
  7947. case OMPD_taskloop_simd:
  7948. case OMPD_threadprivate:
  7949. case OMPD_taskyield:
  7950. case OMPD_barrier:
  7951. case OMPD_taskwait:
  7952. case OMPD_cancellation_point:
  7953. case OMPD_flush:
  7954. case OMPD_declare_reduction:
  7955. case OMPD_declare_mapper:
  7956. case OMPD_declare_simd:
  7957. case OMPD_declare_target:
  7958. case OMPD_end_declare_target:
  7959. case OMPD_teams:
  7960. case OMPD_simd:
  7961. case OMPD_for:
  7962. case OMPD_for_simd:
  7963. case OMPD_sections:
  7964. case OMPD_section:
  7965. case OMPD_single:
  7966. case OMPD_master:
  7967. case OMPD_critical:
  7968. case OMPD_taskgroup:
  7969. case OMPD_distribute:
  7970. case OMPD_ordered:
  7971. case OMPD_atomic:
  7972. case OMPD_distribute_simd:
  7973. case OMPD_teams_distribute:
  7974. case OMPD_teams_distribute_simd:
  7975. case OMPD_requires:
  7976. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  7977. case OMPD_unknown:
  7978. llvm_unreachable("Unknown OpenMP directive");
  7979. }
  7980. break;
  7981. case OMPC_num_teams:
  7982. switch (DKind) {
  7983. case OMPD_target_teams:
  7984. case OMPD_target_teams_distribute:
  7985. case OMPD_target_teams_distribute_simd:
  7986. case OMPD_target_teams_distribute_parallel_for:
  7987. case OMPD_target_teams_distribute_parallel_for_simd:
  7988. CaptureRegion = OMPD_target;
  7989. break;
  7990. case OMPD_teams_distribute_parallel_for:
  7991. case OMPD_teams_distribute_parallel_for_simd:
  7992. case OMPD_teams:
  7993. case OMPD_teams_distribute:
  7994. case OMPD_teams_distribute_simd:
  7995. // Do not capture num_teams-clause expressions.
  7996. break;
  7997. case OMPD_distribute_parallel_for:
  7998. case OMPD_distribute_parallel_for_simd:
  7999. case OMPD_task:
  8000. case OMPD_taskloop:
  8001. case OMPD_taskloop_simd:
  8002. case OMPD_target_data:
  8003. case OMPD_target_enter_data:
  8004. case OMPD_target_exit_data:
  8005. case OMPD_target_update:
  8006. case OMPD_cancel:
  8007. case OMPD_parallel:
  8008. case OMPD_parallel_sections:
  8009. case OMPD_parallel_for:
  8010. case OMPD_parallel_for_simd:
  8011. case OMPD_target:
  8012. case OMPD_target_simd:
  8013. case OMPD_target_parallel:
  8014. case OMPD_target_parallel_for:
  8015. case OMPD_target_parallel_for_simd:
  8016. case OMPD_threadprivate:
  8017. case OMPD_taskyield:
  8018. case OMPD_barrier:
  8019. case OMPD_taskwait:
  8020. case OMPD_cancellation_point:
  8021. case OMPD_flush:
  8022. case OMPD_declare_reduction:
  8023. case OMPD_declare_mapper:
  8024. case OMPD_declare_simd:
  8025. case OMPD_declare_target:
  8026. case OMPD_end_declare_target:
  8027. case OMPD_simd:
  8028. case OMPD_for:
  8029. case OMPD_for_simd:
  8030. case OMPD_sections:
  8031. case OMPD_section:
  8032. case OMPD_single:
  8033. case OMPD_master:
  8034. case OMPD_critical:
  8035. case OMPD_taskgroup:
  8036. case OMPD_distribute:
  8037. case OMPD_ordered:
  8038. case OMPD_atomic:
  8039. case OMPD_distribute_simd:
  8040. case OMPD_requires:
  8041. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  8042. case OMPD_unknown:
  8043. llvm_unreachable("Unknown OpenMP directive");
  8044. }
  8045. break;
  8046. case OMPC_thread_limit:
  8047. switch (DKind) {
  8048. case OMPD_target_teams:
  8049. case OMPD_target_teams_distribute:
  8050. case OMPD_target_teams_distribute_simd:
  8051. case OMPD_target_teams_distribute_parallel_for:
  8052. case OMPD_target_teams_distribute_parallel_for_simd:
  8053. CaptureRegion = OMPD_target;
  8054. break;
  8055. case OMPD_teams_distribute_parallel_for:
  8056. case OMPD_teams_distribute_parallel_for_simd:
  8057. case OMPD_teams:
  8058. case OMPD_teams_distribute:
  8059. case OMPD_teams_distribute_simd:
  8060. // Do not capture thread_limit-clause expressions.
  8061. break;
  8062. case OMPD_distribute_parallel_for:
  8063. case OMPD_distribute_parallel_for_simd:
  8064. case OMPD_task:
  8065. case OMPD_taskloop:
  8066. case OMPD_taskloop_simd:
  8067. case OMPD_target_data:
  8068. case OMPD_target_enter_data:
  8069. case OMPD_target_exit_data:
  8070. case OMPD_target_update:
  8071. case OMPD_cancel:
  8072. case OMPD_parallel:
  8073. case OMPD_parallel_sections:
  8074. case OMPD_parallel_for:
  8075. case OMPD_parallel_for_simd:
  8076. case OMPD_target:
  8077. case OMPD_target_simd:
  8078. case OMPD_target_parallel:
  8079. case OMPD_target_parallel_for:
  8080. case OMPD_target_parallel_for_simd:
  8081. case OMPD_threadprivate:
  8082. case OMPD_taskyield:
  8083. case OMPD_barrier:
  8084. case OMPD_taskwait:
  8085. case OMPD_cancellation_point:
  8086. case OMPD_flush:
  8087. case OMPD_declare_reduction:
  8088. case OMPD_declare_mapper:
  8089. case OMPD_declare_simd:
  8090. case OMPD_declare_target:
  8091. case OMPD_end_declare_target:
  8092. case OMPD_simd:
  8093. case OMPD_for:
  8094. case OMPD_for_simd:
  8095. case OMPD_sections:
  8096. case OMPD_section:
  8097. case OMPD_single:
  8098. case OMPD_master:
  8099. case OMPD_critical:
  8100. case OMPD_taskgroup:
  8101. case OMPD_distribute:
  8102. case OMPD_ordered:
  8103. case OMPD_atomic:
  8104. case OMPD_distribute_simd:
  8105. case OMPD_requires:
  8106. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  8107. case OMPD_unknown:
  8108. llvm_unreachable("Unknown OpenMP directive");
  8109. }
  8110. break;
  8111. case OMPC_schedule:
  8112. switch (DKind) {
  8113. case OMPD_parallel_for:
  8114. case OMPD_parallel_for_simd:
  8115. case OMPD_distribute_parallel_for:
  8116. case OMPD_distribute_parallel_for_simd:
  8117. case OMPD_teams_distribute_parallel_for:
  8118. case OMPD_teams_distribute_parallel_for_simd:
  8119. case OMPD_target_parallel_for:
  8120. case OMPD_target_parallel_for_simd:
  8121. case OMPD_target_teams_distribute_parallel_for:
  8122. case OMPD_target_teams_distribute_parallel_for_simd:
  8123. CaptureRegion = OMPD_parallel;
  8124. break;
  8125. case OMPD_for:
  8126. case OMPD_for_simd:
  8127. // Do not capture schedule-clause expressions.
  8128. break;
  8129. case OMPD_task:
  8130. case OMPD_taskloop:
  8131. case OMPD_taskloop_simd:
  8132. case OMPD_target_data:
  8133. case OMPD_target_enter_data:
  8134. case OMPD_target_exit_data:
  8135. case OMPD_target_update:
  8136. case OMPD_teams:
  8137. case OMPD_teams_distribute:
  8138. case OMPD_teams_distribute_simd:
  8139. case OMPD_target_teams_distribute:
  8140. case OMPD_target_teams_distribute_simd:
  8141. case OMPD_target:
  8142. case OMPD_target_simd:
  8143. case OMPD_target_parallel:
  8144. case OMPD_cancel:
  8145. case OMPD_parallel:
  8146. case OMPD_parallel_sections:
  8147. case OMPD_threadprivate:
  8148. case OMPD_taskyield:
  8149. case OMPD_barrier:
  8150. case OMPD_taskwait:
  8151. case OMPD_cancellation_point:
  8152. case OMPD_flush:
  8153. case OMPD_declare_reduction:
  8154. case OMPD_declare_mapper:
  8155. case OMPD_declare_simd:
  8156. case OMPD_declare_target:
  8157. case OMPD_end_declare_target:
  8158. case OMPD_simd:
  8159. case OMPD_sections:
  8160. case OMPD_section:
  8161. case OMPD_single:
  8162. case OMPD_master:
  8163. case OMPD_critical:
  8164. case OMPD_taskgroup:
  8165. case OMPD_distribute:
  8166. case OMPD_ordered:
  8167. case OMPD_atomic:
  8168. case OMPD_distribute_simd:
  8169. case OMPD_target_teams:
  8170. case OMPD_requires:
  8171. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  8172. case OMPD_unknown:
  8173. llvm_unreachable("Unknown OpenMP directive");
  8174. }
  8175. break;
  8176. case OMPC_dist_schedule:
  8177. switch (DKind) {
  8178. case OMPD_teams_distribute_parallel_for:
  8179. case OMPD_teams_distribute_parallel_for_simd:
  8180. case OMPD_teams_distribute:
  8181. case OMPD_teams_distribute_simd:
  8182. case OMPD_target_teams_distribute_parallel_for:
  8183. case OMPD_target_teams_distribute_parallel_for_simd:
  8184. case OMPD_target_teams_distribute:
  8185. case OMPD_target_teams_distribute_simd:
  8186. CaptureRegion = OMPD_teams;
  8187. break;
  8188. case OMPD_distribute_parallel_for:
  8189. case OMPD_distribute_parallel_for_simd:
  8190. case OMPD_distribute:
  8191. case OMPD_distribute_simd:
  8192. // Do not capture thread_limit-clause expressions.
  8193. break;
  8194. case OMPD_parallel_for:
  8195. case OMPD_parallel_for_simd:
  8196. case OMPD_target_parallel_for_simd:
  8197. case OMPD_target_parallel_for:
  8198. case OMPD_task:
  8199. case OMPD_taskloop:
  8200. case OMPD_taskloop_simd:
  8201. case OMPD_target_data:
  8202. case OMPD_target_enter_data:
  8203. case OMPD_target_exit_data:
  8204. case OMPD_target_update:
  8205. case OMPD_teams:
  8206. case OMPD_target:
  8207. case OMPD_target_simd:
  8208. case OMPD_target_parallel:
  8209. case OMPD_cancel:
  8210. case OMPD_parallel:
  8211. case OMPD_parallel_sections:
  8212. case OMPD_threadprivate:
  8213. case OMPD_taskyield:
  8214. case OMPD_barrier:
  8215. case OMPD_taskwait:
  8216. case OMPD_cancellation_point:
  8217. case OMPD_flush:
  8218. case OMPD_declare_reduction:
  8219. case OMPD_declare_mapper:
  8220. case OMPD_declare_simd:
  8221. case OMPD_declare_target:
  8222. case OMPD_end_declare_target:
  8223. case OMPD_simd:
  8224. case OMPD_for:
  8225. case OMPD_for_simd:
  8226. case OMPD_sections:
  8227. case OMPD_section:
  8228. case OMPD_single:
  8229. case OMPD_master:
  8230. case OMPD_critical:
  8231. case OMPD_taskgroup:
  8232. case OMPD_ordered:
  8233. case OMPD_atomic:
  8234. case OMPD_target_teams:
  8235. case OMPD_requires:
  8236. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  8237. case OMPD_unknown:
  8238. llvm_unreachable("Unknown OpenMP directive");
  8239. }
  8240. break;
  8241. case OMPC_device:
  8242. switch (DKind) {
  8243. case OMPD_target_update:
  8244. case OMPD_target_enter_data:
  8245. case OMPD_target_exit_data:
  8246. case OMPD_target:
  8247. case OMPD_target_simd:
  8248. case OMPD_target_teams:
  8249. case OMPD_target_parallel:
  8250. case OMPD_target_teams_distribute:
  8251. case OMPD_target_teams_distribute_simd:
  8252. case OMPD_target_parallel_for:
  8253. case OMPD_target_parallel_for_simd:
  8254. case OMPD_target_teams_distribute_parallel_for:
  8255. case OMPD_target_teams_distribute_parallel_for_simd:
  8256. CaptureRegion = OMPD_task;
  8257. break;
  8258. case OMPD_target_data:
  8259. // Do not capture device-clause expressions.
  8260. break;
  8261. case OMPD_teams_distribute_parallel_for:
  8262. case OMPD_teams_distribute_parallel_for_simd:
  8263. case OMPD_teams:
  8264. case OMPD_teams_distribute:
  8265. case OMPD_teams_distribute_simd:
  8266. case OMPD_distribute_parallel_for:
  8267. case OMPD_distribute_parallel_for_simd:
  8268. case OMPD_task:
  8269. case OMPD_taskloop:
  8270. case OMPD_taskloop_simd:
  8271. case OMPD_cancel:
  8272. case OMPD_parallel:
  8273. case OMPD_parallel_sections:
  8274. case OMPD_parallel_for:
  8275. case OMPD_parallel_for_simd:
  8276. case OMPD_threadprivate:
  8277. case OMPD_taskyield:
  8278. case OMPD_barrier:
  8279. case OMPD_taskwait:
  8280. case OMPD_cancellation_point:
  8281. case OMPD_flush:
  8282. case OMPD_declare_reduction:
  8283. case OMPD_declare_mapper:
  8284. case OMPD_declare_simd:
  8285. case OMPD_declare_target:
  8286. case OMPD_end_declare_target:
  8287. case OMPD_simd:
  8288. case OMPD_for:
  8289. case OMPD_for_simd:
  8290. case OMPD_sections:
  8291. case OMPD_section:
  8292. case OMPD_single:
  8293. case OMPD_master:
  8294. case OMPD_critical:
  8295. case OMPD_taskgroup:
  8296. case OMPD_distribute:
  8297. case OMPD_ordered:
  8298. case OMPD_atomic:
  8299. case OMPD_distribute_simd:
  8300. case OMPD_requires:
  8301. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  8302. case OMPD_unknown:
  8303. llvm_unreachable("Unknown OpenMP directive");
  8304. }
  8305. break;
  8306. case OMPC_firstprivate:
  8307. case OMPC_lastprivate:
  8308. case OMPC_reduction:
  8309. case OMPC_task_reduction:
  8310. case OMPC_in_reduction:
  8311. case OMPC_linear:
  8312. case OMPC_default:
  8313. case OMPC_proc_bind:
  8314. case OMPC_final:
  8315. case OMPC_safelen:
  8316. case OMPC_simdlen:
  8317. case OMPC_collapse:
  8318. case OMPC_private:
  8319. case OMPC_shared:
  8320. case OMPC_aligned:
  8321. case OMPC_copyin:
  8322. case OMPC_copyprivate:
  8323. case OMPC_ordered:
  8324. case OMPC_nowait:
  8325. case OMPC_untied:
  8326. case OMPC_mergeable:
  8327. case OMPC_threadprivate:
  8328. case OMPC_flush:
  8329. case OMPC_read:
  8330. case OMPC_write:
  8331. case OMPC_update:
  8332. case OMPC_capture:
  8333. case OMPC_seq_cst:
  8334. case OMPC_depend:
  8335. case OMPC_threads:
  8336. case OMPC_simd:
  8337. case OMPC_map:
  8338. case OMPC_priority:
  8339. case OMPC_grainsize:
  8340. case OMPC_nogroup:
  8341. case OMPC_num_tasks:
  8342. case OMPC_hint:
  8343. case OMPC_defaultmap:
  8344. case OMPC_unknown:
  8345. case OMPC_uniform:
  8346. case OMPC_to:
  8347. case OMPC_from:
  8348. case OMPC_use_device_ptr:
  8349. case OMPC_is_device_ptr:
  8350. case OMPC_unified_address:
  8351. case OMPC_unified_shared_memory:
  8352. case OMPC_reverse_offload:
  8353. case OMPC_dynamic_allocators:
  8354. case OMPC_atomic_default_mem_order:
  8355. llvm_unreachable("Unexpected OpenMP clause.");
  8356. }
  8357. return CaptureRegion;
  8358. }
  8359. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  8360. Expr *Condition, SourceLocation StartLoc,
  8361. SourceLocation LParenLoc,
  8362. SourceLocation NameModifierLoc,
  8363. SourceLocation ColonLoc,
  8364. SourceLocation EndLoc) {
  8365. Expr *ValExpr = Condition;
  8366. Stmt *HelperValStmt = nullptr;
  8367. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  8368. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  8369. !Condition->isInstantiationDependent() &&
  8370. !Condition->containsUnexpandedParameterPack()) {
  8371. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  8372. if (Val.isInvalid())
  8373. return nullptr;
  8374. ValExpr = Val.get();
  8375. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  8376. CaptureRegion =
  8377. getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
  8378. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  8379. ValExpr = MakeFullExpr(ValExpr).get();
  8380. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8381. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8382. HelperValStmt = buildPreInits(Context, Captures);
  8383. }
  8384. }
  8385. return new (Context)
  8386. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  8387. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  8388. }
  8389. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  8390. SourceLocation StartLoc,
  8391. SourceLocation LParenLoc,
  8392. SourceLocation EndLoc) {
  8393. Expr *ValExpr = Condition;
  8394. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  8395. !Condition->isInstantiationDependent() &&
  8396. !Condition->containsUnexpandedParameterPack()) {
  8397. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  8398. if (Val.isInvalid())
  8399. return nullptr;
  8400. ValExpr = MakeFullExpr(Val.get()).get();
  8401. }
  8402. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  8403. }
  8404. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  8405. Expr *Op) {
  8406. if (!Op)
  8407. return ExprError();
  8408. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  8409. public:
  8410. IntConvertDiagnoser()
  8411. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  8412. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  8413. QualType T) override {
  8414. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  8415. }
  8416. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  8417. QualType T) override {
  8418. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  8419. }
  8420. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  8421. QualType T,
  8422. QualType ConvTy) override {
  8423. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  8424. }
  8425. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  8426. QualType ConvTy) override {
  8427. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  8428. << ConvTy->isEnumeralType() << ConvTy;
  8429. }
  8430. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  8431. QualType T) override {
  8432. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  8433. }
  8434. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  8435. QualType ConvTy) override {
  8436. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  8437. << ConvTy->isEnumeralType() << ConvTy;
  8438. }
  8439. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  8440. QualType) override {
  8441. llvm_unreachable("conversion functions are permitted");
  8442. }
  8443. } ConvertDiagnoser;
  8444. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  8445. }
  8446. static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  8447. OpenMPClauseKind CKind,
  8448. bool StrictlyPositive) {
  8449. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  8450. !ValExpr->isInstantiationDependent()) {
  8451. SourceLocation Loc = ValExpr->getExprLoc();
  8452. ExprResult Value =
  8453. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  8454. if (Value.isInvalid())
  8455. return false;
  8456. ValExpr = Value.get();
  8457. // The expression must evaluate to a non-negative integer value.
  8458. llvm::APSInt Result;
  8459. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  8460. Result.isSigned() &&
  8461. !((!StrictlyPositive && Result.isNonNegative()) ||
  8462. (StrictlyPositive && Result.isStrictlyPositive()))) {
  8463. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  8464. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  8465. << ValExpr->getSourceRange();
  8466. return false;
  8467. }
  8468. }
  8469. return true;
  8470. }
  8471. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  8472. SourceLocation StartLoc,
  8473. SourceLocation LParenLoc,
  8474. SourceLocation EndLoc) {
  8475. Expr *ValExpr = NumThreads;
  8476. Stmt *HelperValStmt = nullptr;
  8477. // OpenMP [2.5, Restrictions]
  8478. // The num_threads expression must evaluate to a positive integer value.
  8479. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  8480. /*StrictlyPositive=*/true))
  8481. return nullptr;
  8482. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  8483. OpenMPDirectiveKind CaptureRegion =
  8484. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
  8485. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  8486. ValExpr = MakeFullExpr(ValExpr).get();
  8487. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8488. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8489. HelperValStmt = buildPreInits(Context, Captures);
  8490. }
  8491. return new (Context) OMPNumThreadsClause(
  8492. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  8493. }
  8494. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  8495. OpenMPClauseKind CKind,
  8496. bool StrictlyPositive) {
  8497. if (!E)
  8498. return ExprError();
  8499. if (E->isValueDependent() || E->isTypeDependent() ||
  8500. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  8501. return E;
  8502. llvm::APSInt Result;
  8503. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  8504. if (ICE.isInvalid())
  8505. return ExprError();
  8506. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  8507. (!StrictlyPositive && !Result.isNonNegative())) {
  8508. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  8509. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  8510. << E->getSourceRange();
  8511. return ExprError();
  8512. }
  8513. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  8514. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  8515. << E->getSourceRange();
  8516. return ExprError();
  8517. }
  8518. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  8519. DSAStack->setAssociatedLoops(Result.getExtValue());
  8520. else if (CKind == OMPC_ordered)
  8521. DSAStack->setAssociatedLoops(Result.getExtValue());
  8522. return ICE;
  8523. }
  8524. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  8525. SourceLocation LParenLoc,
  8526. SourceLocation EndLoc) {
  8527. // OpenMP [2.8.1, simd construct, Description]
  8528. // The parameter of the safelen clause must be a constant
  8529. // positive integer expression.
  8530. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  8531. if (Safelen.isInvalid())
  8532. return nullptr;
  8533. return new (Context)
  8534. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  8535. }
  8536. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  8537. SourceLocation LParenLoc,
  8538. SourceLocation EndLoc) {
  8539. // OpenMP [2.8.1, simd construct, Description]
  8540. // The parameter of the simdlen clause must be a constant
  8541. // positive integer expression.
  8542. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  8543. if (Simdlen.isInvalid())
  8544. return nullptr;
  8545. return new (Context)
  8546. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  8547. }
  8548. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  8549. SourceLocation StartLoc,
  8550. SourceLocation LParenLoc,
  8551. SourceLocation EndLoc) {
  8552. // OpenMP [2.7.1, loop construct, Description]
  8553. // OpenMP [2.8.1, simd construct, Description]
  8554. // OpenMP [2.9.6, distribute construct, Description]
  8555. // The parameter of the collapse clause must be a constant
  8556. // positive integer expression.
  8557. ExprResult NumForLoopsResult =
  8558. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  8559. if (NumForLoopsResult.isInvalid())
  8560. return nullptr;
  8561. return new (Context)
  8562. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  8563. }
  8564. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  8565. SourceLocation EndLoc,
  8566. SourceLocation LParenLoc,
  8567. Expr *NumForLoops) {
  8568. // OpenMP [2.7.1, loop construct, Description]
  8569. // OpenMP [2.8.1, simd construct, Description]
  8570. // OpenMP [2.9.6, distribute construct, Description]
  8571. // The parameter of the ordered clause must be a constant
  8572. // positive integer expression if any.
  8573. if (NumForLoops && LParenLoc.isValid()) {
  8574. ExprResult NumForLoopsResult =
  8575. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  8576. if (NumForLoopsResult.isInvalid())
  8577. return nullptr;
  8578. NumForLoops = NumForLoopsResult.get();
  8579. } else {
  8580. NumForLoops = nullptr;
  8581. }
  8582. auto *Clause = OMPOrderedClause::Create(
  8583. Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
  8584. StartLoc, LParenLoc, EndLoc);
  8585. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
  8586. return Clause;
  8587. }
  8588. OMPClause *Sema::ActOnOpenMPSimpleClause(
  8589. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  8590. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  8591. OMPClause *Res = nullptr;
  8592. switch (Kind) {
  8593. case OMPC_default:
  8594. Res =
  8595. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  8596. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  8597. break;
  8598. case OMPC_proc_bind:
  8599. Res = ActOnOpenMPProcBindClause(
  8600. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  8601. LParenLoc, EndLoc);
  8602. break;
  8603. case OMPC_atomic_default_mem_order:
  8604. Res = ActOnOpenMPAtomicDefaultMemOrderClause(
  8605. static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
  8606. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  8607. break;
  8608. case OMPC_if:
  8609. case OMPC_final:
  8610. case OMPC_num_threads:
  8611. case OMPC_safelen:
  8612. case OMPC_simdlen:
  8613. case OMPC_collapse:
  8614. case OMPC_schedule:
  8615. case OMPC_private:
  8616. case OMPC_firstprivate:
  8617. case OMPC_lastprivate:
  8618. case OMPC_shared:
  8619. case OMPC_reduction:
  8620. case OMPC_task_reduction:
  8621. case OMPC_in_reduction:
  8622. case OMPC_linear:
  8623. case OMPC_aligned:
  8624. case OMPC_copyin:
  8625. case OMPC_copyprivate:
  8626. case OMPC_ordered:
  8627. case OMPC_nowait:
  8628. case OMPC_untied:
  8629. case OMPC_mergeable:
  8630. case OMPC_threadprivate:
  8631. case OMPC_flush:
  8632. case OMPC_read:
  8633. case OMPC_write:
  8634. case OMPC_update:
  8635. case OMPC_capture:
  8636. case OMPC_seq_cst:
  8637. case OMPC_depend:
  8638. case OMPC_device:
  8639. case OMPC_threads:
  8640. case OMPC_simd:
  8641. case OMPC_map:
  8642. case OMPC_num_teams:
  8643. case OMPC_thread_limit:
  8644. case OMPC_priority:
  8645. case OMPC_grainsize:
  8646. case OMPC_nogroup:
  8647. case OMPC_num_tasks:
  8648. case OMPC_hint:
  8649. case OMPC_dist_schedule:
  8650. case OMPC_defaultmap:
  8651. case OMPC_unknown:
  8652. case OMPC_uniform:
  8653. case OMPC_to:
  8654. case OMPC_from:
  8655. case OMPC_use_device_ptr:
  8656. case OMPC_is_device_ptr:
  8657. case OMPC_unified_address:
  8658. case OMPC_unified_shared_memory:
  8659. case OMPC_reverse_offload:
  8660. case OMPC_dynamic_allocators:
  8661. llvm_unreachable("Clause is not allowed.");
  8662. }
  8663. return Res;
  8664. }
  8665. static std::string
  8666. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  8667. ArrayRef<unsigned> Exclude = llvm::None) {
  8668. SmallString<256> Buffer;
  8669. llvm::raw_svector_ostream Out(Buffer);
  8670. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  8671. unsigned Skipped = Exclude.size();
  8672. auto S = Exclude.begin(), E = Exclude.end();
  8673. for (unsigned I = First; I < Last; ++I) {
  8674. if (std::find(S, E, I) != E) {
  8675. --Skipped;
  8676. continue;
  8677. }
  8678. Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
  8679. if (I == Bound - Skipped)
  8680. Out << " or ";
  8681. else if (I != Bound + 1 - Skipped)
  8682. Out << ", ";
  8683. }
  8684. return Out.str();
  8685. }
  8686. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  8687. SourceLocation KindKwLoc,
  8688. SourceLocation StartLoc,
  8689. SourceLocation LParenLoc,
  8690. SourceLocation EndLoc) {
  8691. if (Kind == OMPC_DEFAULT_unknown) {
  8692. static_assert(OMPC_DEFAULT_unknown > 0,
  8693. "OMPC_DEFAULT_unknown not greater than 0");
  8694. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  8695. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  8696. /*Last=*/OMPC_DEFAULT_unknown)
  8697. << getOpenMPClauseName(OMPC_default);
  8698. return nullptr;
  8699. }
  8700. switch (Kind) {
  8701. case OMPC_DEFAULT_none:
  8702. DSAStack->setDefaultDSANone(KindKwLoc);
  8703. break;
  8704. case OMPC_DEFAULT_shared:
  8705. DSAStack->setDefaultDSAShared(KindKwLoc);
  8706. break;
  8707. case OMPC_DEFAULT_unknown:
  8708. llvm_unreachable("Clause kind is not allowed.");
  8709. break;
  8710. }
  8711. return new (Context)
  8712. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  8713. }
  8714. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  8715. SourceLocation KindKwLoc,
  8716. SourceLocation StartLoc,
  8717. SourceLocation LParenLoc,
  8718. SourceLocation EndLoc) {
  8719. if (Kind == OMPC_PROC_BIND_unknown) {
  8720. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  8721. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  8722. /*Last=*/OMPC_PROC_BIND_unknown)
  8723. << getOpenMPClauseName(OMPC_proc_bind);
  8724. return nullptr;
  8725. }
  8726. return new (Context)
  8727. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  8728. }
  8729. OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
  8730. OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
  8731. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  8732. if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
  8733. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  8734. << getListOfPossibleValues(
  8735. OMPC_atomic_default_mem_order, /*First=*/0,
  8736. /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
  8737. << getOpenMPClauseName(OMPC_atomic_default_mem_order);
  8738. return nullptr;
  8739. }
  8740. return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
  8741. LParenLoc, EndLoc);
  8742. }
  8743. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  8744. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  8745. SourceLocation StartLoc, SourceLocation LParenLoc,
  8746. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  8747. SourceLocation EndLoc) {
  8748. OMPClause *Res = nullptr;
  8749. switch (Kind) {
  8750. case OMPC_schedule:
  8751. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  8752. assert(Argument.size() == NumberOfElements &&
  8753. ArgumentLoc.size() == NumberOfElements);
  8754. Res = ActOnOpenMPScheduleClause(
  8755. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  8756. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  8757. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  8758. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  8759. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  8760. break;
  8761. case OMPC_if:
  8762. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  8763. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  8764. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  8765. DelimLoc, EndLoc);
  8766. break;
  8767. case OMPC_dist_schedule:
  8768. Res = ActOnOpenMPDistScheduleClause(
  8769. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  8770. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  8771. break;
  8772. case OMPC_defaultmap:
  8773. enum { Modifier, DefaultmapKind };
  8774. Res = ActOnOpenMPDefaultmapClause(
  8775. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  8776. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  8777. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  8778. EndLoc);
  8779. break;
  8780. case OMPC_final:
  8781. case OMPC_num_threads:
  8782. case OMPC_safelen:
  8783. case OMPC_simdlen:
  8784. case OMPC_collapse:
  8785. case OMPC_default:
  8786. case OMPC_proc_bind:
  8787. case OMPC_private:
  8788. case OMPC_firstprivate:
  8789. case OMPC_lastprivate:
  8790. case OMPC_shared:
  8791. case OMPC_reduction:
  8792. case OMPC_task_reduction:
  8793. case OMPC_in_reduction:
  8794. case OMPC_linear:
  8795. case OMPC_aligned:
  8796. case OMPC_copyin:
  8797. case OMPC_copyprivate:
  8798. case OMPC_ordered:
  8799. case OMPC_nowait:
  8800. case OMPC_untied:
  8801. case OMPC_mergeable:
  8802. case OMPC_threadprivate:
  8803. case OMPC_flush:
  8804. case OMPC_read:
  8805. case OMPC_write:
  8806. case OMPC_update:
  8807. case OMPC_capture:
  8808. case OMPC_seq_cst:
  8809. case OMPC_depend:
  8810. case OMPC_device:
  8811. case OMPC_threads:
  8812. case OMPC_simd:
  8813. case OMPC_map:
  8814. case OMPC_num_teams:
  8815. case OMPC_thread_limit:
  8816. case OMPC_priority:
  8817. case OMPC_grainsize:
  8818. case OMPC_nogroup:
  8819. case OMPC_num_tasks:
  8820. case OMPC_hint:
  8821. case OMPC_unknown:
  8822. case OMPC_uniform:
  8823. case OMPC_to:
  8824. case OMPC_from:
  8825. case OMPC_use_device_ptr:
  8826. case OMPC_is_device_ptr:
  8827. case OMPC_unified_address:
  8828. case OMPC_unified_shared_memory:
  8829. case OMPC_reverse_offload:
  8830. case OMPC_dynamic_allocators:
  8831. case OMPC_atomic_default_mem_order:
  8832. llvm_unreachable("Clause is not allowed.");
  8833. }
  8834. return Res;
  8835. }
  8836. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  8837. OpenMPScheduleClauseModifier M2,
  8838. SourceLocation M1Loc, SourceLocation M2Loc) {
  8839. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  8840. SmallVector<unsigned, 2> Excluded;
  8841. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  8842. Excluded.push_back(M2);
  8843. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  8844. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  8845. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  8846. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  8847. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  8848. << getListOfPossibleValues(OMPC_schedule,
  8849. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  8850. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  8851. Excluded)
  8852. << getOpenMPClauseName(OMPC_schedule);
  8853. return true;
  8854. }
  8855. return false;
  8856. }
  8857. OMPClause *Sema::ActOnOpenMPScheduleClause(
  8858. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  8859. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  8860. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  8861. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  8862. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  8863. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  8864. return nullptr;
  8865. // OpenMP, 2.7.1, Loop Construct, Restrictions
  8866. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  8867. // but not both.
  8868. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  8869. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  8870. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  8871. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  8872. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  8873. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  8874. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  8875. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  8876. return nullptr;
  8877. }
  8878. if (Kind == OMPC_SCHEDULE_unknown) {
  8879. std::string Values;
  8880. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  8881. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  8882. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  8883. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  8884. Exclude);
  8885. } else {
  8886. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  8887. /*Last=*/OMPC_SCHEDULE_unknown);
  8888. }
  8889. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  8890. << Values << getOpenMPClauseName(OMPC_schedule);
  8891. return nullptr;
  8892. }
  8893. // OpenMP, 2.7.1, Loop Construct, Restrictions
  8894. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  8895. // schedule(guided).
  8896. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  8897. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  8898. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  8899. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  8900. diag::err_omp_schedule_nonmonotonic_static);
  8901. return nullptr;
  8902. }
  8903. Expr *ValExpr = ChunkSize;
  8904. Stmt *HelperValStmt = nullptr;
  8905. if (ChunkSize) {
  8906. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  8907. !ChunkSize->isInstantiationDependent() &&
  8908. !ChunkSize->containsUnexpandedParameterPack()) {
  8909. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  8910. ExprResult Val =
  8911. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  8912. if (Val.isInvalid())
  8913. return nullptr;
  8914. ValExpr = Val.get();
  8915. // OpenMP [2.7.1, Restrictions]
  8916. // chunk_size must be a loop invariant integer expression with a positive
  8917. // value.
  8918. llvm::APSInt Result;
  8919. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  8920. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  8921. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  8922. << "schedule" << 1 << ChunkSize->getSourceRange();
  8923. return nullptr;
  8924. }
  8925. } else if (getOpenMPCaptureRegionForClause(
  8926. DSAStack->getCurrentDirective(), OMPC_schedule) !=
  8927. OMPD_unknown &&
  8928. !CurContext->isDependentContext()) {
  8929. ValExpr = MakeFullExpr(ValExpr).get();
  8930. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  8931. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  8932. HelperValStmt = buildPreInits(Context, Captures);
  8933. }
  8934. }
  8935. }
  8936. return new (Context)
  8937. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  8938. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  8939. }
  8940. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  8941. SourceLocation StartLoc,
  8942. SourceLocation EndLoc) {
  8943. OMPClause *Res = nullptr;
  8944. switch (Kind) {
  8945. case OMPC_ordered:
  8946. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  8947. break;
  8948. case OMPC_nowait:
  8949. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  8950. break;
  8951. case OMPC_untied:
  8952. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  8953. break;
  8954. case OMPC_mergeable:
  8955. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  8956. break;
  8957. case OMPC_read:
  8958. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  8959. break;
  8960. case OMPC_write:
  8961. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  8962. break;
  8963. case OMPC_update:
  8964. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  8965. break;
  8966. case OMPC_capture:
  8967. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  8968. break;
  8969. case OMPC_seq_cst:
  8970. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  8971. break;
  8972. case OMPC_threads:
  8973. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  8974. break;
  8975. case OMPC_simd:
  8976. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  8977. break;
  8978. case OMPC_nogroup:
  8979. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  8980. break;
  8981. case OMPC_unified_address:
  8982. Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
  8983. break;
  8984. case OMPC_unified_shared_memory:
  8985. Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  8986. break;
  8987. case OMPC_reverse_offload:
  8988. Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
  8989. break;
  8990. case OMPC_dynamic_allocators:
  8991. Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
  8992. break;
  8993. case OMPC_if:
  8994. case OMPC_final:
  8995. case OMPC_num_threads:
  8996. case OMPC_safelen:
  8997. case OMPC_simdlen:
  8998. case OMPC_collapse:
  8999. case OMPC_schedule:
  9000. case OMPC_private:
  9001. case OMPC_firstprivate:
  9002. case OMPC_lastprivate:
  9003. case OMPC_shared:
  9004. case OMPC_reduction:
  9005. case OMPC_task_reduction:
  9006. case OMPC_in_reduction:
  9007. case OMPC_linear:
  9008. case OMPC_aligned:
  9009. case OMPC_copyin:
  9010. case OMPC_copyprivate:
  9011. case OMPC_default:
  9012. case OMPC_proc_bind:
  9013. case OMPC_threadprivate:
  9014. case OMPC_flush:
  9015. case OMPC_depend:
  9016. case OMPC_device:
  9017. case OMPC_map:
  9018. case OMPC_num_teams:
  9019. case OMPC_thread_limit:
  9020. case OMPC_priority:
  9021. case OMPC_grainsize:
  9022. case OMPC_num_tasks:
  9023. case OMPC_hint:
  9024. case OMPC_dist_schedule:
  9025. case OMPC_defaultmap:
  9026. case OMPC_unknown:
  9027. case OMPC_uniform:
  9028. case OMPC_to:
  9029. case OMPC_from:
  9030. case OMPC_use_device_ptr:
  9031. case OMPC_is_device_ptr:
  9032. case OMPC_atomic_default_mem_order:
  9033. llvm_unreachable("Clause is not allowed.");
  9034. }
  9035. return Res;
  9036. }
  9037. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  9038. SourceLocation EndLoc) {
  9039. DSAStack->setNowaitRegion();
  9040. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  9041. }
  9042. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  9043. SourceLocation EndLoc) {
  9044. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  9045. }
  9046. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  9047. SourceLocation EndLoc) {
  9048. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  9049. }
  9050. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  9051. SourceLocation EndLoc) {
  9052. return new (Context) OMPReadClause(StartLoc, EndLoc);
  9053. }
  9054. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  9055. SourceLocation EndLoc) {
  9056. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  9057. }
  9058. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  9059. SourceLocation EndLoc) {
  9060. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  9061. }
  9062. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  9063. SourceLocation EndLoc) {
  9064. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  9065. }
  9066. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  9067. SourceLocation EndLoc) {
  9068. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  9069. }
  9070. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  9071. SourceLocation EndLoc) {
  9072. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  9073. }
  9074. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  9075. SourceLocation EndLoc) {
  9076. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  9077. }
  9078. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  9079. SourceLocation EndLoc) {
  9080. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  9081. }
  9082. OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
  9083. SourceLocation EndLoc) {
  9084. return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
  9085. }
  9086. OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
  9087. SourceLocation EndLoc) {
  9088. return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  9089. }
  9090. OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
  9091. SourceLocation EndLoc) {
  9092. return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
  9093. }
  9094. OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
  9095. SourceLocation EndLoc) {
  9096. return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
  9097. }
  9098. OMPClause *Sema::ActOnOpenMPVarListClause(
  9099. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  9100. const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
  9101. CXXScopeSpec &ReductionOrMapperIdScopeSpec,
  9102. DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
  9103. OpenMPLinearClauseKind LinKind,
  9104. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  9105. ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
  9106. bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
  9107. SourceLocation StartLoc = Locs.StartLoc;
  9108. SourceLocation LParenLoc = Locs.LParenLoc;
  9109. SourceLocation EndLoc = Locs.EndLoc;
  9110. OMPClause *Res = nullptr;
  9111. switch (Kind) {
  9112. case OMPC_private:
  9113. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  9114. break;
  9115. case OMPC_firstprivate:
  9116. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  9117. break;
  9118. case OMPC_lastprivate:
  9119. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  9120. break;
  9121. case OMPC_shared:
  9122. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  9123. break;
  9124. case OMPC_reduction:
  9125. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  9126. EndLoc, ReductionOrMapperIdScopeSpec,
  9127. ReductionOrMapperId);
  9128. break;
  9129. case OMPC_task_reduction:
  9130. Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  9131. EndLoc, ReductionOrMapperIdScopeSpec,
  9132. ReductionOrMapperId);
  9133. break;
  9134. case OMPC_in_reduction:
  9135. Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  9136. EndLoc, ReductionOrMapperIdScopeSpec,
  9137. ReductionOrMapperId);
  9138. break;
  9139. case OMPC_linear:
  9140. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  9141. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  9142. break;
  9143. case OMPC_aligned:
  9144. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  9145. ColonLoc, EndLoc);
  9146. break;
  9147. case OMPC_copyin:
  9148. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  9149. break;
  9150. case OMPC_copyprivate:
  9151. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  9152. break;
  9153. case OMPC_flush:
  9154. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  9155. break;
  9156. case OMPC_depend:
  9157. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  9158. StartLoc, LParenLoc, EndLoc);
  9159. break;
  9160. case OMPC_map:
  9161. Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
  9162. ReductionOrMapperIdScopeSpec,
  9163. ReductionOrMapperId, MapType, IsMapTypeImplicit,
  9164. DepLinMapLoc, ColonLoc, VarList, Locs);
  9165. break;
  9166. case OMPC_to:
  9167. Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
  9168. ReductionOrMapperId, Locs);
  9169. break;
  9170. case OMPC_from:
  9171. Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
  9172. ReductionOrMapperId, Locs);
  9173. break;
  9174. case OMPC_use_device_ptr:
  9175. Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
  9176. break;
  9177. case OMPC_is_device_ptr:
  9178. Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
  9179. break;
  9180. case OMPC_if:
  9181. case OMPC_final:
  9182. case OMPC_num_threads:
  9183. case OMPC_safelen:
  9184. case OMPC_simdlen:
  9185. case OMPC_collapse:
  9186. case OMPC_default:
  9187. case OMPC_proc_bind:
  9188. case OMPC_schedule:
  9189. case OMPC_ordered:
  9190. case OMPC_nowait:
  9191. case OMPC_untied:
  9192. case OMPC_mergeable:
  9193. case OMPC_threadprivate:
  9194. case OMPC_read:
  9195. case OMPC_write:
  9196. case OMPC_update:
  9197. case OMPC_capture:
  9198. case OMPC_seq_cst:
  9199. case OMPC_device:
  9200. case OMPC_threads:
  9201. case OMPC_simd:
  9202. case OMPC_num_teams:
  9203. case OMPC_thread_limit:
  9204. case OMPC_priority:
  9205. case OMPC_grainsize:
  9206. case OMPC_nogroup:
  9207. case OMPC_num_tasks:
  9208. case OMPC_hint:
  9209. case OMPC_dist_schedule:
  9210. case OMPC_defaultmap:
  9211. case OMPC_unknown:
  9212. case OMPC_uniform:
  9213. case OMPC_unified_address:
  9214. case OMPC_unified_shared_memory:
  9215. case OMPC_reverse_offload:
  9216. case OMPC_dynamic_allocators:
  9217. case OMPC_atomic_default_mem_order:
  9218. llvm_unreachable("Clause is not allowed.");
  9219. }
  9220. return Res;
  9221. }
  9222. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  9223. ExprObjectKind OK, SourceLocation Loc) {
  9224. ExprResult Res = BuildDeclRefExpr(
  9225. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  9226. if (!Res.isUsable())
  9227. return ExprError();
  9228. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  9229. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  9230. if (!Res.isUsable())
  9231. return ExprError();
  9232. }
  9233. if (VK != VK_LValue && Res.get()->isGLValue()) {
  9234. Res = DefaultLvalueConversion(Res.get());
  9235. if (!Res.isUsable())
  9236. return ExprError();
  9237. }
  9238. return Res;
  9239. }
  9240. static std::pair<ValueDecl *, bool>
  9241. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  9242. SourceRange &ERange, bool AllowArraySection = false) {
  9243. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  9244. RefExpr->containsUnexpandedParameterPack())
  9245. return std::make_pair(nullptr, true);
  9246. // OpenMP [3.1, C/C++]
  9247. // A list item is a variable name.
  9248. // OpenMP [2.9.3.3, Restrictions, p.1]
  9249. // A variable that is part of another variable (as an array or
  9250. // structure element) cannot appear in a private clause.
  9251. RefExpr = RefExpr->IgnoreParens();
  9252. enum {
  9253. NoArrayExpr = -1,
  9254. ArraySubscript = 0,
  9255. OMPArraySection = 1
  9256. } IsArrayExpr = NoArrayExpr;
  9257. if (AllowArraySection) {
  9258. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  9259. Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  9260. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  9261. Base = TempASE->getBase()->IgnoreParenImpCasts();
  9262. RefExpr = Base;
  9263. IsArrayExpr = ArraySubscript;
  9264. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  9265. Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  9266. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  9267. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  9268. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  9269. Base = TempASE->getBase()->IgnoreParenImpCasts();
  9270. RefExpr = Base;
  9271. IsArrayExpr = OMPArraySection;
  9272. }
  9273. }
  9274. ELoc = RefExpr->getExprLoc();
  9275. ERange = RefExpr->getSourceRange();
  9276. RefExpr = RefExpr->IgnoreParenImpCasts();
  9277. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  9278. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  9279. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  9280. (S.getCurrentThisType().isNull() || !ME ||
  9281. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  9282. !isa<FieldDecl>(ME->getMemberDecl()))) {
  9283. if (IsArrayExpr != NoArrayExpr) {
  9284. S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
  9285. << ERange;
  9286. } else {
  9287. S.Diag(ELoc,
  9288. AllowArraySection
  9289. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  9290. : diag::err_omp_expected_var_name_member_expr)
  9291. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  9292. }
  9293. return std::make_pair(nullptr, false);
  9294. }
  9295. return std::make_pair(
  9296. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  9297. }
  9298. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  9299. SourceLocation StartLoc,
  9300. SourceLocation LParenLoc,
  9301. SourceLocation EndLoc) {
  9302. SmallVector<Expr *, 8> Vars;
  9303. SmallVector<Expr *, 8> PrivateCopies;
  9304. for (Expr *RefExpr : VarList) {
  9305. assert(RefExpr && "NULL expr in OpenMP private clause.");
  9306. SourceLocation ELoc;
  9307. SourceRange ERange;
  9308. Expr *SimpleRefExpr = RefExpr;
  9309. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9310. if (Res.second) {
  9311. // It will be analyzed later.
  9312. Vars.push_back(RefExpr);
  9313. PrivateCopies.push_back(nullptr);
  9314. }
  9315. ValueDecl *D = Res.first;
  9316. if (!D)
  9317. continue;
  9318. QualType Type = D->getType();
  9319. auto *VD = dyn_cast<VarDecl>(D);
  9320. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  9321. // A variable that appears in a private clause must not have an incomplete
  9322. // type or a reference type.
  9323. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  9324. continue;
  9325. Type = Type.getNonReferenceType();
  9326. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  9327. // A variable that is privatized must not have a const-qualified type
  9328. // unless it is of class type with a mutable member. This restriction does
  9329. // not apply to the firstprivate clause.
  9330. //
  9331. // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
  9332. // A variable that appears in a private clause must not have a
  9333. // const-qualified type unless it is of class type with a mutable member.
  9334. if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
  9335. continue;
  9336. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9337. // in a Construct]
  9338. // Variables with the predetermined data-sharing attributes may not be
  9339. // listed in data-sharing attributes clauses, except for the cases
  9340. // listed below. For these exceptions only, listing a predetermined
  9341. // variable in a data-sharing attribute clause is allowed and overrides
  9342. // the variable's predetermined data-sharing attributes.
  9343. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  9344. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  9345. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  9346. << getOpenMPClauseName(OMPC_private);
  9347. reportOriginalDsa(*this, DSAStack, D, DVar);
  9348. continue;
  9349. }
  9350. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9351. // Variably modified types are not supported for tasks.
  9352. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  9353. isOpenMPTaskingDirective(CurrDir)) {
  9354. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  9355. << getOpenMPClauseName(OMPC_private) << Type
  9356. << getOpenMPDirectiveName(CurrDir);
  9357. bool IsDecl =
  9358. !VD ||
  9359. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9360. Diag(D->getLocation(),
  9361. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9362. << D;
  9363. continue;
  9364. }
  9365. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  9366. // A list item cannot appear in both a map clause and a data-sharing
  9367. // attribute clause on the same construct
  9368. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  9369. OpenMPClauseKind ConflictKind;
  9370. if (DSAStack->checkMappableExprComponentListsForDecl(
  9371. VD, /*CurrentRegionOnly=*/true,
  9372. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  9373. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  9374. ConflictKind = WhereFoundClauseKind;
  9375. return true;
  9376. })) {
  9377. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  9378. << getOpenMPClauseName(OMPC_private)
  9379. << getOpenMPClauseName(ConflictKind)
  9380. << getOpenMPDirectiveName(CurrDir);
  9381. reportOriginalDsa(*this, DSAStack, D, DVar);
  9382. continue;
  9383. }
  9384. }
  9385. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  9386. // A variable of class type (or array thereof) that appears in a private
  9387. // clause requires an accessible, unambiguous default constructor for the
  9388. // class type.
  9389. // Generate helper private variable and initialize it with the default
  9390. // value. The address of the original variable is replaced by the address of
  9391. // the new private variable in CodeGen. This new variable is not added to
  9392. // IdResolver, so the code in the OpenMP region uses original variable for
  9393. // proper diagnostics.
  9394. Type = Type.getUnqualifiedType();
  9395. VarDecl *VDPrivate =
  9396. buildVarDecl(*this, ELoc, Type, D->getName(),
  9397. D->hasAttrs() ? &D->getAttrs() : nullptr,
  9398. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  9399. ActOnUninitializedDecl(VDPrivate);
  9400. if (VDPrivate->isInvalidDecl())
  9401. continue;
  9402. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  9403. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  9404. DeclRefExpr *Ref = nullptr;
  9405. if (!VD && !CurContext->isDependentContext())
  9406. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  9407. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  9408. Vars.push_back((VD || CurContext->isDependentContext())
  9409. ? RefExpr->IgnoreParens()
  9410. : Ref);
  9411. PrivateCopies.push_back(VDPrivateRefExpr);
  9412. }
  9413. if (Vars.empty())
  9414. return nullptr;
  9415. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  9416. PrivateCopies);
  9417. }
  9418. namespace {
  9419. class DiagsUninitializedSeveretyRAII {
  9420. private:
  9421. DiagnosticsEngine &Diags;
  9422. SourceLocation SavedLoc;
  9423. bool IsIgnored = false;
  9424. public:
  9425. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  9426. bool IsIgnored)
  9427. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  9428. if (!IsIgnored) {
  9429. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  9430. /*Map*/ diag::Severity::Ignored, Loc);
  9431. }
  9432. }
  9433. ~DiagsUninitializedSeveretyRAII() {
  9434. if (!IsIgnored)
  9435. Diags.popMappings(SavedLoc);
  9436. }
  9437. };
  9438. }
  9439. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  9440. SourceLocation StartLoc,
  9441. SourceLocation LParenLoc,
  9442. SourceLocation EndLoc) {
  9443. SmallVector<Expr *, 8> Vars;
  9444. SmallVector<Expr *, 8> PrivateCopies;
  9445. SmallVector<Expr *, 8> Inits;
  9446. SmallVector<Decl *, 4> ExprCaptures;
  9447. bool IsImplicitClause =
  9448. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  9449. SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
  9450. for (Expr *RefExpr : VarList) {
  9451. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  9452. SourceLocation ELoc;
  9453. SourceRange ERange;
  9454. Expr *SimpleRefExpr = RefExpr;
  9455. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9456. if (Res.second) {
  9457. // It will be analyzed later.
  9458. Vars.push_back(RefExpr);
  9459. PrivateCopies.push_back(nullptr);
  9460. Inits.push_back(nullptr);
  9461. }
  9462. ValueDecl *D = Res.first;
  9463. if (!D)
  9464. continue;
  9465. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  9466. QualType Type = D->getType();
  9467. auto *VD = dyn_cast<VarDecl>(D);
  9468. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  9469. // A variable that appears in a private clause must not have an incomplete
  9470. // type or a reference type.
  9471. if (RequireCompleteType(ELoc, Type,
  9472. diag::err_omp_firstprivate_incomplete_type))
  9473. continue;
  9474. Type = Type.getNonReferenceType();
  9475. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  9476. // A variable of class type (or array thereof) that appears in a private
  9477. // clause requires an accessible, unambiguous copy constructor for the
  9478. // class type.
  9479. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  9480. // If an implicit firstprivate variable found it was checked already.
  9481. DSAStackTy::DSAVarData TopDVar;
  9482. if (!IsImplicitClause) {
  9483. DSAStackTy::DSAVarData DVar =
  9484. DSAStack->getTopDSA(D, /*FromParent=*/false);
  9485. TopDVar = DVar;
  9486. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9487. bool IsConstant = ElemType.isConstant(Context);
  9488. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  9489. // A list item that specifies a given variable may not appear in more
  9490. // than one clause on the same directive, except that a variable may be
  9491. // specified in both firstprivate and lastprivate clauses.
  9492. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  9493. // A list item may appear in a firstprivate or lastprivate clause but not
  9494. // both.
  9495. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  9496. (isOpenMPDistributeDirective(CurrDir) ||
  9497. DVar.CKind != OMPC_lastprivate) &&
  9498. DVar.RefExpr) {
  9499. Diag(ELoc, diag::err_omp_wrong_dsa)
  9500. << getOpenMPClauseName(DVar.CKind)
  9501. << getOpenMPClauseName(OMPC_firstprivate);
  9502. reportOriginalDsa(*this, DSAStack, D, DVar);
  9503. continue;
  9504. }
  9505. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9506. // in a Construct]
  9507. // Variables with the predetermined data-sharing attributes may not be
  9508. // listed in data-sharing attributes clauses, except for the cases
  9509. // listed below. For these exceptions only, listing a predetermined
  9510. // variable in a data-sharing attribute clause is allowed and overrides
  9511. // the variable's predetermined data-sharing attributes.
  9512. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9513. // in a Construct, C/C++, p.2]
  9514. // Variables with const-qualified type having no mutable member may be
  9515. // listed in a firstprivate clause, even if they are static data members.
  9516. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  9517. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  9518. Diag(ELoc, diag::err_omp_wrong_dsa)
  9519. << getOpenMPClauseName(DVar.CKind)
  9520. << getOpenMPClauseName(OMPC_firstprivate);
  9521. reportOriginalDsa(*this, DSAStack, D, DVar);
  9522. continue;
  9523. }
  9524. // OpenMP [2.9.3.4, Restrictions, p.2]
  9525. // A list item that is private within a parallel region must not appear
  9526. // in a firstprivate clause on a worksharing construct if any of the
  9527. // worksharing regions arising from the worksharing construct ever bind
  9528. // to any of the parallel regions arising from the parallel construct.
  9529. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  9530. // A list item that is private within a teams region must not appear in a
  9531. // firstprivate clause on a distribute construct if any of the distribute
  9532. // regions arising from the distribute construct ever bind to any of the
  9533. // teams regions arising from the teams construct.
  9534. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  9535. // A list item that appears in a reduction clause of a teams construct
  9536. // must not appear in a firstprivate clause on a distribute construct if
  9537. // any of the distribute regions arising from the distribute construct
  9538. // ever bind to any of the teams regions arising from the teams construct.
  9539. if ((isOpenMPWorksharingDirective(CurrDir) ||
  9540. isOpenMPDistributeDirective(CurrDir)) &&
  9541. !isOpenMPParallelDirective(CurrDir) &&
  9542. !isOpenMPTeamsDirective(CurrDir)) {
  9543. DVar = DSAStack->getImplicitDSA(D, true);
  9544. if (DVar.CKind != OMPC_shared &&
  9545. (isOpenMPParallelDirective(DVar.DKind) ||
  9546. isOpenMPTeamsDirective(DVar.DKind) ||
  9547. DVar.DKind == OMPD_unknown)) {
  9548. Diag(ELoc, diag::err_omp_required_access)
  9549. << getOpenMPClauseName(OMPC_firstprivate)
  9550. << getOpenMPClauseName(OMPC_shared);
  9551. reportOriginalDsa(*this, DSAStack, D, DVar);
  9552. continue;
  9553. }
  9554. }
  9555. // OpenMP [2.9.3.4, Restrictions, p.3]
  9556. // A list item that appears in a reduction clause of a parallel construct
  9557. // must not appear in a firstprivate clause on a worksharing or task
  9558. // construct if any of the worksharing or task regions arising from the
  9559. // worksharing or task construct ever bind to any of the parallel regions
  9560. // arising from the parallel construct.
  9561. // OpenMP [2.9.3.4, Restrictions, p.4]
  9562. // A list item that appears in a reduction clause in worksharing
  9563. // construct must not appear in a firstprivate clause in a task construct
  9564. // encountered during execution of any of the worksharing regions arising
  9565. // from the worksharing construct.
  9566. if (isOpenMPTaskingDirective(CurrDir)) {
  9567. DVar = DSAStack->hasInnermostDSA(
  9568. D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
  9569. [](OpenMPDirectiveKind K) {
  9570. return isOpenMPParallelDirective(K) ||
  9571. isOpenMPWorksharingDirective(K) ||
  9572. isOpenMPTeamsDirective(K);
  9573. },
  9574. /*FromParent=*/true);
  9575. if (DVar.CKind == OMPC_reduction &&
  9576. (isOpenMPParallelDirective(DVar.DKind) ||
  9577. isOpenMPWorksharingDirective(DVar.DKind) ||
  9578. isOpenMPTeamsDirective(DVar.DKind))) {
  9579. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  9580. << getOpenMPDirectiveName(DVar.DKind);
  9581. reportOriginalDsa(*this, DSAStack, D, DVar);
  9582. continue;
  9583. }
  9584. }
  9585. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  9586. // A list item cannot appear in both a map clause and a data-sharing
  9587. // attribute clause on the same construct
  9588. if (isOpenMPTargetExecutionDirective(CurrDir)) {
  9589. OpenMPClauseKind ConflictKind;
  9590. if (DSAStack->checkMappableExprComponentListsForDecl(
  9591. VD, /*CurrentRegionOnly=*/true,
  9592. [&ConflictKind](
  9593. OMPClauseMappableExprCommon::MappableExprComponentListRef,
  9594. OpenMPClauseKind WhereFoundClauseKind) {
  9595. ConflictKind = WhereFoundClauseKind;
  9596. return true;
  9597. })) {
  9598. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  9599. << getOpenMPClauseName(OMPC_firstprivate)
  9600. << getOpenMPClauseName(ConflictKind)
  9601. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  9602. reportOriginalDsa(*this, DSAStack, D, DVar);
  9603. continue;
  9604. }
  9605. }
  9606. }
  9607. // Variably modified types are not supported for tasks.
  9608. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  9609. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  9610. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  9611. << getOpenMPClauseName(OMPC_firstprivate) << Type
  9612. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  9613. bool IsDecl =
  9614. !VD ||
  9615. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  9616. Diag(D->getLocation(),
  9617. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  9618. << D;
  9619. continue;
  9620. }
  9621. Type = Type.getUnqualifiedType();
  9622. VarDecl *VDPrivate =
  9623. buildVarDecl(*this, ELoc, Type, D->getName(),
  9624. D->hasAttrs() ? &D->getAttrs() : nullptr,
  9625. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  9626. // Generate helper private variable and initialize it with the value of the
  9627. // original variable. The address of the original variable is replaced by
  9628. // the address of the new private variable in the CodeGen. This new variable
  9629. // is not added to IdResolver, so the code in the OpenMP region uses
  9630. // original variable for proper diagnostics and variable capturing.
  9631. Expr *VDInitRefExpr = nullptr;
  9632. // For arrays generate initializer for single element and replace it by the
  9633. // original array element in CodeGen.
  9634. if (Type->isArrayType()) {
  9635. VarDecl *VDInit =
  9636. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  9637. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  9638. Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
  9639. ElemType = ElemType.getUnqualifiedType();
  9640. VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  9641. ".firstprivate.temp");
  9642. InitializedEntity Entity =
  9643. InitializedEntity::InitializeVariable(VDInitTemp);
  9644. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  9645. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  9646. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  9647. if (Result.isInvalid())
  9648. VDPrivate->setInvalidDecl();
  9649. else
  9650. VDPrivate->setInit(Result.getAs<Expr>());
  9651. // Remove temp variable declaration.
  9652. Context.Deallocate(VDInitTemp);
  9653. } else {
  9654. VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  9655. ".firstprivate.temp");
  9656. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  9657. RefExpr->getExprLoc());
  9658. AddInitializerToDecl(VDPrivate,
  9659. DefaultLvalueConversion(VDInitRefExpr).get(),
  9660. /*DirectInit=*/false);
  9661. }
  9662. if (VDPrivate->isInvalidDecl()) {
  9663. if (IsImplicitClause) {
  9664. Diag(RefExpr->getExprLoc(),
  9665. diag::note_omp_task_predetermined_firstprivate_here);
  9666. }
  9667. continue;
  9668. }
  9669. CurContext->addDecl(VDPrivate);
  9670. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  9671. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  9672. RefExpr->getExprLoc());
  9673. DeclRefExpr *Ref = nullptr;
  9674. if (!VD && !CurContext->isDependentContext()) {
  9675. if (TopDVar.CKind == OMPC_lastprivate) {
  9676. Ref = TopDVar.PrivateCopy;
  9677. } else {
  9678. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  9679. if (!isOpenMPCapturedDecl(D))
  9680. ExprCaptures.push_back(Ref->getDecl());
  9681. }
  9682. }
  9683. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  9684. Vars.push_back((VD || CurContext->isDependentContext())
  9685. ? RefExpr->IgnoreParens()
  9686. : Ref);
  9687. PrivateCopies.push_back(VDPrivateRefExpr);
  9688. Inits.push_back(VDInitRefExpr);
  9689. }
  9690. if (Vars.empty())
  9691. return nullptr;
  9692. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  9693. Vars, PrivateCopies, Inits,
  9694. buildPreInits(Context, ExprCaptures));
  9695. }
  9696. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  9697. SourceLocation StartLoc,
  9698. SourceLocation LParenLoc,
  9699. SourceLocation EndLoc) {
  9700. SmallVector<Expr *, 8> Vars;
  9701. SmallVector<Expr *, 8> SrcExprs;
  9702. SmallVector<Expr *, 8> DstExprs;
  9703. SmallVector<Expr *, 8> AssignmentOps;
  9704. SmallVector<Decl *, 4> ExprCaptures;
  9705. SmallVector<Expr *, 4> ExprPostUpdates;
  9706. for (Expr *RefExpr : VarList) {
  9707. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  9708. SourceLocation ELoc;
  9709. SourceRange ERange;
  9710. Expr *SimpleRefExpr = RefExpr;
  9711. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9712. if (Res.second) {
  9713. // It will be analyzed later.
  9714. Vars.push_back(RefExpr);
  9715. SrcExprs.push_back(nullptr);
  9716. DstExprs.push_back(nullptr);
  9717. AssignmentOps.push_back(nullptr);
  9718. }
  9719. ValueDecl *D = Res.first;
  9720. if (!D)
  9721. continue;
  9722. QualType Type = D->getType();
  9723. auto *VD = dyn_cast<VarDecl>(D);
  9724. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  9725. // A variable that appears in a lastprivate clause must not have an
  9726. // incomplete type or a reference type.
  9727. if (RequireCompleteType(ELoc, Type,
  9728. diag::err_omp_lastprivate_incomplete_type))
  9729. continue;
  9730. Type = Type.getNonReferenceType();
  9731. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  9732. // A variable that is privatized must not have a const-qualified type
  9733. // unless it is of class type with a mutable member. This restriction does
  9734. // not apply to the firstprivate clause.
  9735. //
  9736. // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
  9737. // A variable that appears in a lastprivate clause must not have a
  9738. // const-qualified type unless it is of class type with a mutable member.
  9739. if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
  9740. continue;
  9741. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  9742. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  9743. // in a Construct]
  9744. // Variables with the predetermined data-sharing attributes may not be
  9745. // listed in data-sharing attributes clauses, except for the cases
  9746. // listed below.
  9747. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  9748. // A list item may appear in a firstprivate or lastprivate clause but not
  9749. // both.
  9750. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  9751. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  9752. (isOpenMPDistributeDirective(CurrDir) ||
  9753. DVar.CKind != OMPC_firstprivate) &&
  9754. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  9755. Diag(ELoc, diag::err_omp_wrong_dsa)
  9756. << getOpenMPClauseName(DVar.CKind)
  9757. << getOpenMPClauseName(OMPC_lastprivate);
  9758. reportOriginalDsa(*this, DSAStack, D, DVar);
  9759. continue;
  9760. }
  9761. // OpenMP [2.14.3.5, Restrictions, p.2]
  9762. // A list item that is private within a parallel region, or that appears in
  9763. // the reduction clause of a parallel construct, must not appear in a
  9764. // lastprivate clause on a worksharing construct if any of the corresponding
  9765. // worksharing regions ever binds to any of the corresponding parallel
  9766. // regions.
  9767. DSAStackTy::DSAVarData TopDVar = DVar;
  9768. if (isOpenMPWorksharingDirective(CurrDir) &&
  9769. !isOpenMPParallelDirective(CurrDir) &&
  9770. !isOpenMPTeamsDirective(CurrDir)) {
  9771. DVar = DSAStack->getImplicitDSA(D, true);
  9772. if (DVar.CKind != OMPC_shared) {
  9773. Diag(ELoc, diag::err_omp_required_access)
  9774. << getOpenMPClauseName(OMPC_lastprivate)
  9775. << getOpenMPClauseName(OMPC_shared);
  9776. reportOriginalDsa(*this, DSAStack, D, DVar);
  9777. continue;
  9778. }
  9779. }
  9780. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  9781. // A variable of class type (or array thereof) that appears in a
  9782. // lastprivate clause requires an accessible, unambiguous default
  9783. // constructor for the class type, unless the list item is also specified
  9784. // in a firstprivate clause.
  9785. // A variable of class type (or array thereof) that appears in a
  9786. // lastprivate clause requires an accessible, unambiguous copy assignment
  9787. // operator for the class type.
  9788. Type = Context.getBaseElementType(Type).getNonReferenceType();
  9789. VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  9790. Type.getUnqualifiedType(), ".lastprivate.src",
  9791. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9792. DeclRefExpr *PseudoSrcExpr =
  9793. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  9794. VarDecl *DstVD =
  9795. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  9796. D->hasAttrs() ? &D->getAttrs() : nullptr);
  9797. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  9798. // For arrays generate assignment operation for single element and replace
  9799. // it by the original array element in CodeGen.
  9800. ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  9801. PseudoDstExpr, PseudoSrcExpr);
  9802. if (AssignmentOp.isInvalid())
  9803. continue;
  9804. AssignmentOp =
  9805. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  9806. if (AssignmentOp.isInvalid())
  9807. continue;
  9808. DeclRefExpr *Ref = nullptr;
  9809. if (!VD && !CurContext->isDependentContext()) {
  9810. if (TopDVar.CKind == OMPC_firstprivate) {
  9811. Ref = TopDVar.PrivateCopy;
  9812. } else {
  9813. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  9814. if (!isOpenMPCapturedDecl(D))
  9815. ExprCaptures.push_back(Ref->getDecl());
  9816. }
  9817. if (TopDVar.CKind == OMPC_firstprivate ||
  9818. (!isOpenMPCapturedDecl(D) &&
  9819. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  9820. ExprResult RefRes = DefaultLvalueConversion(Ref);
  9821. if (!RefRes.isUsable())
  9822. continue;
  9823. ExprResult PostUpdateRes =
  9824. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  9825. RefRes.get());
  9826. if (!PostUpdateRes.isUsable())
  9827. continue;
  9828. ExprPostUpdates.push_back(
  9829. IgnoredValueConversions(PostUpdateRes.get()).get());
  9830. }
  9831. }
  9832. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  9833. Vars.push_back((VD || CurContext->isDependentContext())
  9834. ? RefExpr->IgnoreParens()
  9835. : Ref);
  9836. SrcExprs.push_back(PseudoSrcExpr);
  9837. DstExprs.push_back(PseudoDstExpr);
  9838. AssignmentOps.push_back(AssignmentOp.get());
  9839. }
  9840. if (Vars.empty())
  9841. return nullptr;
  9842. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  9843. Vars, SrcExprs, DstExprs, AssignmentOps,
  9844. buildPreInits(Context, ExprCaptures),
  9845. buildPostUpdate(*this, ExprPostUpdates));
  9846. }
  9847. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  9848. SourceLocation StartLoc,
  9849. SourceLocation LParenLoc,
  9850. SourceLocation EndLoc) {
  9851. SmallVector<Expr *, 8> Vars;
  9852. for (Expr *RefExpr : VarList) {
  9853. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  9854. SourceLocation ELoc;
  9855. SourceRange ERange;
  9856. Expr *SimpleRefExpr = RefExpr;
  9857. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  9858. if (Res.second) {
  9859. // It will be analyzed later.
  9860. Vars.push_back(RefExpr);
  9861. }
  9862. ValueDecl *D = Res.first;
  9863. if (!D)
  9864. continue;
  9865. auto *VD = dyn_cast<VarDecl>(D);
  9866. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  9867. // in a Construct]
  9868. // Variables with the predetermined data-sharing attributes may not be
  9869. // listed in data-sharing attributes clauses, except for the cases
  9870. // listed below. For these exceptions only, listing a predetermined
  9871. // variable in a data-sharing attribute clause is allowed and overrides
  9872. // the variable's predetermined data-sharing attributes.
  9873. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  9874. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  9875. DVar.RefExpr) {
  9876. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  9877. << getOpenMPClauseName(OMPC_shared);
  9878. reportOriginalDsa(*this, DSAStack, D, DVar);
  9879. continue;
  9880. }
  9881. DeclRefExpr *Ref = nullptr;
  9882. if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  9883. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  9884. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  9885. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  9886. ? RefExpr->IgnoreParens()
  9887. : Ref);
  9888. }
  9889. if (Vars.empty())
  9890. return nullptr;
  9891. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  9892. }
  9893. namespace {
  9894. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  9895. DSAStackTy *Stack;
  9896. public:
  9897. bool VisitDeclRefExpr(DeclRefExpr *E) {
  9898. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  9899. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  9900. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  9901. return false;
  9902. if (DVar.CKind != OMPC_unknown)
  9903. return true;
  9904. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  9905. VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
  9906. /*FromParent=*/true);
  9907. return DVarPrivate.CKind != OMPC_unknown;
  9908. }
  9909. return false;
  9910. }
  9911. bool VisitStmt(Stmt *S) {
  9912. for (Stmt *Child : S->children()) {
  9913. if (Child && Visit(Child))
  9914. return true;
  9915. }
  9916. return false;
  9917. }
  9918. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  9919. };
  9920. } // namespace
  9921. namespace {
  9922. // Transform MemberExpression for specified FieldDecl of current class to
  9923. // DeclRefExpr to specified OMPCapturedExprDecl.
  9924. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  9925. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  9926. ValueDecl *Field = nullptr;
  9927. DeclRefExpr *CapturedExpr = nullptr;
  9928. public:
  9929. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  9930. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  9931. ExprResult TransformMemberExpr(MemberExpr *E) {
  9932. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  9933. E->getMemberDecl() == Field) {
  9934. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  9935. return CapturedExpr;
  9936. }
  9937. return BaseTransform::TransformMemberExpr(E);
  9938. }
  9939. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  9940. };
  9941. } // namespace
  9942. template <typename T, typename U>
  9943. static T filterLookupForUDReductionAndMapper(
  9944. SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
  9945. for (U &Set : Lookups) {
  9946. for (auto *D : Set) {
  9947. if (T Res = Gen(cast<ValueDecl>(D)))
  9948. return Res;
  9949. }
  9950. }
  9951. return T();
  9952. }
  9953. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
  9954. assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
  9955. for (auto RD : D->redecls()) {
  9956. // Don't bother with extra checks if we already know this one isn't visible.
  9957. if (RD == D)
  9958. continue;
  9959. auto ND = cast<NamedDecl>(RD);
  9960. if (LookupResult::isVisible(SemaRef, ND))
  9961. return ND;
  9962. }
  9963. return nullptr;
  9964. }
  9965. static void
  9966. argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
  9967. SourceLocation Loc, QualType Ty,
  9968. SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
  9969. // Find all of the associated namespaces and classes based on the
  9970. // arguments we have.
  9971. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  9972. Sema::AssociatedClassSet AssociatedClasses;
  9973. OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
  9974. SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
  9975. AssociatedClasses);
  9976. // C++ [basic.lookup.argdep]p3:
  9977. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  9978. // and let Y be the lookup set produced by argument dependent
  9979. // lookup (defined as follows). If X contains [...] then Y is
  9980. // empty. Otherwise Y is the set of declarations found in the
  9981. // namespaces associated with the argument types as described
  9982. // below. The set of declarations found by the lookup of the name
  9983. // is the union of X and Y.
  9984. //
  9985. // Here, we compute Y and add its members to the overloaded
  9986. // candidate set.
  9987. for (auto *NS : AssociatedNamespaces) {
  9988. // When considering an associated namespace, the lookup is the
  9989. // same as the lookup performed when the associated namespace is
  9990. // used as a qualifier (3.4.3.2) except that:
  9991. //
  9992. // -- Any using-directives in the associated namespace are
  9993. // ignored.
  9994. //
  9995. // -- Any namespace-scope friend functions declared in
  9996. // associated classes are visible within their respective
  9997. // namespaces even if they are not visible during an ordinary
  9998. // lookup (11.4).
  9999. DeclContext::lookup_result R = NS->lookup(Id.getName());
  10000. for (auto *D : R) {
  10001. auto *Underlying = D;
  10002. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  10003. Underlying = USD->getTargetDecl();
  10004. if (!isa<OMPDeclareReductionDecl>(Underlying) &&
  10005. !isa<OMPDeclareMapperDecl>(Underlying))
  10006. continue;
  10007. if (!SemaRef.isVisible(D)) {
  10008. D = findAcceptableDecl(SemaRef, D);
  10009. if (!D)
  10010. continue;
  10011. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  10012. Underlying = USD->getTargetDecl();
  10013. }
  10014. Lookups.emplace_back();
  10015. Lookups.back().addDecl(Underlying);
  10016. }
  10017. }
  10018. }
  10019. static ExprResult
  10020. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  10021. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  10022. const DeclarationNameInfo &ReductionId, QualType Ty,
  10023. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  10024. if (ReductionIdScopeSpec.isInvalid())
  10025. return ExprError();
  10026. SmallVector<UnresolvedSet<8>, 4> Lookups;
  10027. if (S) {
  10028. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  10029. Lookup.suppressDiagnostics();
  10030. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  10031. NamedDecl *D = Lookup.getRepresentativeDecl();
  10032. do {
  10033. S = S->getParent();
  10034. } while (S && !S->isDeclScope(D));
  10035. if (S)
  10036. S = S->getParent();
  10037. Lookups.emplace_back();
  10038. Lookups.back().append(Lookup.begin(), Lookup.end());
  10039. Lookup.clear();
  10040. }
  10041. } else if (auto *ULE =
  10042. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  10043. Lookups.push_back(UnresolvedSet<8>());
  10044. Decl *PrevD = nullptr;
  10045. for (NamedDecl *D : ULE->decls()) {
  10046. if (D == PrevD)
  10047. Lookups.push_back(UnresolvedSet<8>());
  10048. else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
  10049. Lookups.back().addDecl(DRD);
  10050. PrevD = D;
  10051. }
  10052. }
  10053. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  10054. Ty->isInstantiationDependentType() ||
  10055. Ty->containsUnexpandedParameterPack() ||
  10056. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  10057. return !D->isInvalidDecl() &&
  10058. (D->getType()->isDependentType() ||
  10059. D->getType()->isInstantiationDependentType() ||
  10060. D->getType()->containsUnexpandedParameterPack());
  10061. })) {
  10062. UnresolvedSet<8> ResSet;
  10063. for (const UnresolvedSet<8> &Set : Lookups) {
  10064. if (Set.empty())
  10065. continue;
  10066. ResSet.append(Set.begin(), Set.end());
  10067. // The last item marks the end of all declarations at the specified scope.
  10068. ResSet.addDecl(Set[Set.size() - 1]);
  10069. }
  10070. return UnresolvedLookupExpr::Create(
  10071. SemaRef.Context, /*NamingClass=*/nullptr,
  10072. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  10073. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  10074. }
  10075. // Lookup inside the classes.
  10076. // C++ [over.match.oper]p3:
  10077. // For a unary operator @ with an operand of a type whose
  10078. // cv-unqualified version is T1, and for a binary operator @ with
  10079. // a left operand of a type whose cv-unqualified version is T1 and
  10080. // a right operand of a type whose cv-unqualified version is T2,
  10081. // three sets of candidate functions, designated member
  10082. // candidates, non-member candidates and built-in candidates, are
  10083. // constructed as follows:
  10084. // -- If T1 is a complete class type or a class currently being
  10085. // defined, the set of member candidates is the result of the
  10086. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  10087. // the set of member candidates is empty.
  10088. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  10089. Lookup.suppressDiagnostics();
  10090. if (const auto *TyRec = Ty->getAs<RecordType>()) {
  10091. // Complete the type if it can be completed.
  10092. // If the type is neither complete nor being defined, bail out now.
  10093. if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
  10094. TyRec->getDecl()->getDefinition()) {
  10095. Lookup.clear();
  10096. SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
  10097. if (Lookup.empty()) {
  10098. Lookups.emplace_back();
  10099. Lookups.back().append(Lookup.begin(), Lookup.end());
  10100. }
  10101. }
  10102. }
  10103. // Perform ADL.
  10104. argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
  10105. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  10106. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  10107. if (!D->isInvalidDecl() &&
  10108. SemaRef.Context.hasSameType(D->getType(), Ty))
  10109. return D;
  10110. return nullptr;
  10111. }))
  10112. return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
  10113. VK_LValue, Loc);
  10114. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  10115. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  10116. if (!D->isInvalidDecl() &&
  10117. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  10118. !Ty.isMoreQualifiedThan(D->getType()))
  10119. return D;
  10120. return nullptr;
  10121. })) {
  10122. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  10123. /*DetectVirtual=*/false);
  10124. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  10125. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  10126. VD->getType().getUnqualifiedType()))) {
  10127. if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
  10128. /*DiagID=*/0) !=
  10129. Sema::AR_inaccessible) {
  10130. SemaRef.BuildBasePathArray(Paths, BasePath);
  10131. return SemaRef.BuildDeclRefExpr(
  10132. VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
  10133. }
  10134. }
  10135. }
  10136. }
  10137. if (ReductionIdScopeSpec.isSet()) {
  10138. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
  10139. return ExprError();
  10140. }
  10141. return ExprEmpty();
  10142. }
  10143. namespace {
  10144. /// Data for the reduction-based clauses.
  10145. struct ReductionData {
  10146. /// List of original reduction items.
  10147. SmallVector<Expr *, 8> Vars;
  10148. /// List of private copies of the reduction items.
  10149. SmallVector<Expr *, 8> Privates;
  10150. /// LHS expressions for the reduction_op expressions.
  10151. SmallVector<Expr *, 8> LHSs;
  10152. /// RHS expressions for the reduction_op expressions.
  10153. SmallVector<Expr *, 8> RHSs;
  10154. /// Reduction operation expression.
  10155. SmallVector<Expr *, 8> ReductionOps;
  10156. /// Taskgroup descriptors for the corresponding reduction items in
  10157. /// in_reduction clauses.
  10158. SmallVector<Expr *, 8> TaskgroupDescriptors;
  10159. /// List of captures for clause.
  10160. SmallVector<Decl *, 4> ExprCaptures;
  10161. /// List of postupdate expressions.
  10162. SmallVector<Expr *, 4> ExprPostUpdates;
  10163. ReductionData() = delete;
  10164. /// Reserves required memory for the reduction data.
  10165. ReductionData(unsigned Size) {
  10166. Vars.reserve(Size);
  10167. Privates.reserve(Size);
  10168. LHSs.reserve(Size);
  10169. RHSs.reserve(Size);
  10170. ReductionOps.reserve(Size);
  10171. TaskgroupDescriptors.reserve(Size);
  10172. ExprCaptures.reserve(Size);
  10173. ExprPostUpdates.reserve(Size);
  10174. }
  10175. /// Stores reduction item and reduction operation only (required for dependent
  10176. /// reduction item).
  10177. void push(Expr *Item, Expr *ReductionOp) {
  10178. Vars.emplace_back(Item);
  10179. Privates.emplace_back(nullptr);
  10180. LHSs.emplace_back(nullptr);
  10181. RHSs.emplace_back(nullptr);
  10182. ReductionOps.emplace_back(ReductionOp);
  10183. TaskgroupDescriptors.emplace_back(nullptr);
  10184. }
  10185. /// Stores reduction data.
  10186. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  10187. Expr *TaskgroupDescriptor) {
  10188. Vars.emplace_back(Item);
  10189. Privates.emplace_back(Private);
  10190. LHSs.emplace_back(LHS);
  10191. RHSs.emplace_back(RHS);
  10192. ReductionOps.emplace_back(ReductionOp);
  10193. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  10194. }
  10195. };
  10196. } // namespace
  10197. static bool checkOMPArraySectionConstantForReduction(
  10198. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  10199. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  10200. const Expr *Length = OASE->getLength();
  10201. if (Length == nullptr) {
  10202. // For array sections of the form [1:] or [:], we would need to analyze
  10203. // the lower bound...
  10204. if (OASE->getColonLoc().isValid())
  10205. return false;
  10206. // This is an array subscript which has implicit length 1!
  10207. SingleElement = true;
  10208. ArraySizes.push_back(llvm::APSInt::get(1));
  10209. } else {
  10210. Expr::EvalResult Result;
  10211. if (!Length->EvaluateAsInt(Result, Context))
  10212. return false;
  10213. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  10214. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  10215. ArraySizes.push_back(ConstantLengthValue);
  10216. }
  10217. // Get the base of this array section and walk up from there.
  10218. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  10219. // We require length = 1 for all array sections except the right-most to
  10220. // guarantee that the memory region is contiguous and has no holes in it.
  10221. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  10222. Length = TempOASE->getLength();
  10223. if (Length == nullptr) {
  10224. // For array sections of the form [1:] or [:], we would need to analyze
  10225. // the lower bound...
  10226. if (OASE->getColonLoc().isValid())
  10227. return false;
  10228. // This is an array subscript which has implicit length 1!
  10229. ArraySizes.push_back(llvm::APSInt::get(1));
  10230. } else {
  10231. Expr::EvalResult Result;
  10232. if (!Length->EvaluateAsInt(Result, Context))
  10233. return false;
  10234. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  10235. if (ConstantLengthValue.getSExtValue() != 1)
  10236. return false;
  10237. ArraySizes.push_back(ConstantLengthValue);
  10238. }
  10239. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  10240. }
  10241. // If we have a single element, we don't need to add the implicit lengths.
  10242. if (!SingleElement) {
  10243. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  10244. // Has implicit length 1!
  10245. ArraySizes.push_back(llvm::APSInt::get(1));
  10246. Base = TempASE->getBase()->IgnoreParenImpCasts();
  10247. }
  10248. }
  10249. // This array section can be privatized as a single value or as a constant
  10250. // sized array.
  10251. return true;
  10252. }
  10253. static bool actOnOMPReductionKindClause(
  10254. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  10255. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10256. SourceLocation ColonLoc, SourceLocation EndLoc,
  10257. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10258. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  10259. DeclarationName DN = ReductionId.getName();
  10260. OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
  10261. BinaryOperatorKind BOK = BO_Comma;
  10262. ASTContext &Context = S.Context;
  10263. // OpenMP [2.14.3.6, reduction clause]
  10264. // C
  10265. // reduction-identifier is either an identifier or one of the following
  10266. // operators: +, -, *, &, |, ^, && and ||
  10267. // C++
  10268. // reduction-identifier is either an id-expression or one of the following
  10269. // operators: +, -, *, &, |, ^, && and ||
  10270. switch (OOK) {
  10271. case OO_Plus:
  10272. case OO_Minus:
  10273. BOK = BO_Add;
  10274. break;
  10275. case OO_Star:
  10276. BOK = BO_Mul;
  10277. break;
  10278. case OO_Amp:
  10279. BOK = BO_And;
  10280. break;
  10281. case OO_Pipe:
  10282. BOK = BO_Or;
  10283. break;
  10284. case OO_Caret:
  10285. BOK = BO_Xor;
  10286. break;
  10287. case OO_AmpAmp:
  10288. BOK = BO_LAnd;
  10289. break;
  10290. case OO_PipePipe:
  10291. BOK = BO_LOr;
  10292. break;
  10293. case OO_New:
  10294. case OO_Delete:
  10295. case OO_Array_New:
  10296. case OO_Array_Delete:
  10297. case OO_Slash:
  10298. case OO_Percent:
  10299. case OO_Tilde:
  10300. case OO_Exclaim:
  10301. case OO_Equal:
  10302. case OO_Less:
  10303. case OO_Greater:
  10304. case OO_LessEqual:
  10305. case OO_GreaterEqual:
  10306. case OO_PlusEqual:
  10307. case OO_MinusEqual:
  10308. case OO_StarEqual:
  10309. case OO_SlashEqual:
  10310. case OO_PercentEqual:
  10311. case OO_CaretEqual:
  10312. case OO_AmpEqual:
  10313. case OO_PipeEqual:
  10314. case OO_LessLess:
  10315. case OO_GreaterGreater:
  10316. case OO_LessLessEqual:
  10317. case OO_GreaterGreaterEqual:
  10318. case OO_EqualEqual:
  10319. case OO_ExclaimEqual:
  10320. case OO_Spaceship:
  10321. case OO_PlusPlus:
  10322. case OO_MinusMinus:
  10323. case OO_Comma:
  10324. case OO_ArrowStar:
  10325. case OO_Arrow:
  10326. case OO_Call:
  10327. case OO_Subscript:
  10328. case OO_Conditional:
  10329. case OO_Coawait:
  10330. case NUM_OVERLOADED_OPERATORS:
  10331. llvm_unreachable("Unexpected reduction identifier");
  10332. case OO_None:
  10333. if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
  10334. if (II->isStr("max"))
  10335. BOK = BO_GT;
  10336. else if (II->isStr("min"))
  10337. BOK = BO_LT;
  10338. }
  10339. break;
  10340. }
  10341. SourceRange ReductionIdRange;
  10342. if (ReductionIdScopeSpec.isValid())
  10343. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  10344. else
  10345. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  10346. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  10347. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  10348. bool FirstIter = true;
  10349. for (Expr *RefExpr : VarList) {
  10350. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  10351. // OpenMP [2.1, C/C++]
  10352. // A list item is a variable or array section, subject to the restrictions
  10353. // specified in Section 2.4 on page 42 and in each of the sections
  10354. // describing clauses and directives for which a list appears.
  10355. // OpenMP [2.14.3.3, Restrictions, p.1]
  10356. // A variable that is part of another variable (as an array or
  10357. // structure element) cannot appear in a private clause.
  10358. if (!FirstIter && IR != ER)
  10359. ++IR;
  10360. FirstIter = false;
  10361. SourceLocation ELoc;
  10362. SourceRange ERange;
  10363. Expr *SimpleRefExpr = RefExpr;
  10364. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  10365. /*AllowArraySection=*/true);
  10366. if (Res.second) {
  10367. // Try to find 'declare reduction' corresponding construct before using
  10368. // builtin/overloaded operators.
  10369. QualType Type = Context.DependentTy;
  10370. CXXCastPath BasePath;
  10371. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  10372. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  10373. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  10374. Expr *ReductionOp = nullptr;
  10375. if (S.CurContext->isDependentContext() &&
  10376. (DeclareReductionRef.isUnset() ||
  10377. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  10378. ReductionOp = DeclareReductionRef.get();
  10379. // It will be analyzed later.
  10380. RD.push(RefExpr, ReductionOp);
  10381. }
  10382. ValueDecl *D = Res.first;
  10383. if (!D)
  10384. continue;
  10385. Expr *TaskgroupDescriptor = nullptr;
  10386. QualType Type;
  10387. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  10388. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  10389. if (ASE) {
  10390. Type = ASE->getType().getNonReferenceType();
  10391. } else if (OASE) {
  10392. QualType BaseType =
  10393. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  10394. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  10395. Type = ATy->getElementType();
  10396. else
  10397. Type = BaseType->getPointeeType();
  10398. Type = Type.getNonReferenceType();
  10399. } else {
  10400. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  10401. }
  10402. auto *VD = dyn_cast<VarDecl>(D);
  10403. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  10404. // A variable that appears in a private clause must not have an incomplete
  10405. // type or a reference type.
  10406. if (S.RequireCompleteType(ELoc, D->getType(),
  10407. diag::err_omp_reduction_incomplete_type))
  10408. continue;
  10409. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  10410. // A list item that appears in a reduction clause must not be
  10411. // const-qualified.
  10412. if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
  10413. /*AcceptIfMutable*/ false, ASE || OASE))
  10414. continue;
  10415. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  10416. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  10417. // If a list-item is a reference type then it must bind to the same object
  10418. // for all threads of the team.
  10419. if (!ASE && !OASE) {
  10420. if (VD) {
  10421. VarDecl *VDDef = VD->getDefinition();
  10422. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  10423. DSARefChecker Check(Stack);
  10424. if (Check.Visit(VDDef->getInit())) {
  10425. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  10426. << getOpenMPClauseName(ClauseKind) << ERange;
  10427. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  10428. continue;
  10429. }
  10430. }
  10431. }
  10432. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  10433. // in a Construct]
  10434. // Variables with the predetermined data-sharing attributes may not be
  10435. // listed in data-sharing attributes clauses, except for the cases
  10436. // listed below. For these exceptions only, listing a predetermined
  10437. // variable in a data-sharing attribute clause is allowed and overrides
  10438. // the variable's predetermined data-sharing attributes.
  10439. // OpenMP [2.14.3.6, Restrictions, p.3]
  10440. // Any number of reduction clauses can be specified on the directive,
  10441. // but a list item can appear only once in the reduction clauses for that
  10442. // directive.
  10443. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
  10444. if (DVar.CKind == OMPC_reduction) {
  10445. S.Diag(ELoc, diag::err_omp_once_referenced)
  10446. << getOpenMPClauseName(ClauseKind);
  10447. if (DVar.RefExpr)
  10448. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  10449. continue;
  10450. }
  10451. if (DVar.CKind != OMPC_unknown) {
  10452. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  10453. << getOpenMPClauseName(DVar.CKind)
  10454. << getOpenMPClauseName(OMPC_reduction);
  10455. reportOriginalDsa(S, Stack, D, DVar);
  10456. continue;
  10457. }
  10458. // OpenMP [2.14.3.6, Restrictions, p.1]
  10459. // A list item that appears in a reduction clause of a worksharing
  10460. // construct must be shared in the parallel regions to which any of the
  10461. // worksharing regions arising from the worksharing construct bind.
  10462. if (isOpenMPWorksharingDirective(CurrDir) &&
  10463. !isOpenMPParallelDirective(CurrDir) &&
  10464. !isOpenMPTeamsDirective(CurrDir)) {
  10465. DVar = Stack->getImplicitDSA(D, true);
  10466. if (DVar.CKind != OMPC_shared) {
  10467. S.Diag(ELoc, diag::err_omp_required_access)
  10468. << getOpenMPClauseName(OMPC_reduction)
  10469. << getOpenMPClauseName(OMPC_shared);
  10470. reportOriginalDsa(S, Stack, D, DVar);
  10471. continue;
  10472. }
  10473. }
  10474. }
  10475. // Try to find 'declare reduction' corresponding construct before using
  10476. // builtin/overloaded operators.
  10477. CXXCastPath BasePath;
  10478. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  10479. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  10480. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  10481. if (DeclareReductionRef.isInvalid())
  10482. continue;
  10483. if (S.CurContext->isDependentContext() &&
  10484. (DeclareReductionRef.isUnset() ||
  10485. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  10486. RD.push(RefExpr, DeclareReductionRef.get());
  10487. continue;
  10488. }
  10489. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  10490. // Not allowed reduction identifier is found.
  10491. S.Diag(ReductionId.getBeginLoc(),
  10492. diag::err_omp_unknown_reduction_identifier)
  10493. << Type << ReductionIdRange;
  10494. continue;
  10495. }
  10496. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  10497. // The type of a list item that appears in a reduction clause must be valid
  10498. // for the reduction-identifier. For a max or min reduction in C, the type
  10499. // of the list item must be an allowed arithmetic data type: char, int,
  10500. // float, double, or _Bool, possibly modified with long, short, signed, or
  10501. // unsigned. For a max or min reduction in C++, the type of the list item
  10502. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  10503. // double, or bool, possibly modified with long, short, signed, or unsigned.
  10504. if (DeclareReductionRef.isUnset()) {
  10505. if ((BOK == BO_GT || BOK == BO_LT) &&
  10506. !(Type->isScalarType() ||
  10507. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  10508. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  10509. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  10510. if (!ASE && !OASE) {
  10511. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10512. VarDecl::DeclarationOnly;
  10513. S.Diag(D->getLocation(),
  10514. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10515. << D;
  10516. }
  10517. continue;
  10518. }
  10519. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  10520. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  10521. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  10522. << getOpenMPClauseName(ClauseKind);
  10523. if (!ASE && !OASE) {
  10524. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10525. VarDecl::DeclarationOnly;
  10526. S.Diag(D->getLocation(),
  10527. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10528. << D;
  10529. }
  10530. continue;
  10531. }
  10532. }
  10533. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  10534. VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  10535. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10536. VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  10537. D->hasAttrs() ? &D->getAttrs() : nullptr);
  10538. QualType PrivateTy = Type;
  10539. // Try if we can determine constant lengths for all array sections and avoid
  10540. // the VLA.
  10541. bool ConstantLengthOASE = false;
  10542. if (OASE) {
  10543. bool SingleElement;
  10544. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  10545. ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
  10546. Context, OASE, SingleElement, ArraySizes);
  10547. // If we don't have a single element, we must emit a constant array type.
  10548. if (ConstantLengthOASE && !SingleElement) {
  10549. for (llvm::APSInt &Size : ArraySizes)
  10550. PrivateTy = Context.getConstantArrayType(
  10551. PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
  10552. }
  10553. }
  10554. if ((OASE && !ConstantLengthOASE) ||
  10555. (!OASE && !ASE &&
  10556. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  10557. if (!Context.getTargetInfo().isVLASupported() &&
  10558. S.shouldDiagnoseTargetSupportFromOpenMP()) {
  10559. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  10560. S.Diag(ELoc, diag::note_vla_unsupported);
  10561. continue;
  10562. }
  10563. // For arrays/array sections only:
  10564. // Create pseudo array type for private copy. The size for this array will
  10565. // be generated during codegen.
  10566. // For array subscripts or single variables Private Ty is the same as Type
  10567. // (type of the variable or single array element).
  10568. PrivateTy = Context.getVariableArrayType(
  10569. Type,
  10570. new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
  10571. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  10572. } else if (!ASE && !OASE &&
  10573. Context.getAsArrayType(D->getType().getNonReferenceType())) {
  10574. PrivateTy = D->getType().getNonReferenceType();
  10575. }
  10576. // Private copy.
  10577. VarDecl *PrivateVD =
  10578. buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  10579. D->hasAttrs() ? &D->getAttrs() : nullptr,
  10580. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  10581. // Add initializer for private variable.
  10582. Expr *Init = nullptr;
  10583. DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  10584. DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  10585. if (DeclareReductionRef.isUsable()) {
  10586. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  10587. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  10588. if (DRD->getInitializer()) {
  10589. Init = DRDRef;
  10590. RHSVD->setInit(DRDRef);
  10591. RHSVD->setInitStyle(VarDecl::CallInit);
  10592. }
  10593. } else {
  10594. switch (BOK) {
  10595. case BO_Add:
  10596. case BO_Xor:
  10597. case BO_Or:
  10598. case BO_LOr:
  10599. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  10600. if (Type->isScalarType() || Type->isAnyComplexType())
  10601. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  10602. break;
  10603. case BO_Mul:
  10604. case BO_LAnd:
  10605. if (Type->isScalarType() || Type->isAnyComplexType()) {
  10606. // '*' and '&&' reduction ops - initializer is '1'.
  10607. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  10608. }
  10609. break;
  10610. case BO_And: {
  10611. // '&' reduction op - initializer is '~0'.
  10612. QualType OrigType = Type;
  10613. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  10614. Type = ComplexTy->getElementType();
  10615. if (Type->isRealFloatingType()) {
  10616. llvm::APFloat InitValue =
  10617. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  10618. /*isIEEE=*/true);
  10619. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  10620. Type, ELoc);
  10621. } else if (Type->isScalarType()) {
  10622. uint64_t Size = Context.getTypeSize(Type);
  10623. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  10624. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  10625. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  10626. }
  10627. if (Init && OrigType->isAnyComplexType()) {
  10628. // Init = 0xFFFF + 0xFFFFi;
  10629. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  10630. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  10631. }
  10632. Type = OrigType;
  10633. break;
  10634. }
  10635. case BO_LT:
  10636. case BO_GT: {
  10637. // 'min' reduction op - initializer is 'Largest representable number in
  10638. // the reduction list item type'.
  10639. // 'max' reduction op - initializer is 'Least representable number in
  10640. // the reduction list item type'.
  10641. if (Type->isIntegerType() || Type->isPointerType()) {
  10642. bool IsSigned = Type->hasSignedIntegerRepresentation();
  10643. uint64_t Size = Context.getTypeSize(Type);
  10644. QualType IntTy =
  10645. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  10646. llvm::APInt InitValue =
  10647. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  10648. : llvm::APInt::getMinValue(Size)
  10649. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  10650. : llvm::APInt::getMaxValue(Size);
  10651. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  10652. if (Type->isPointerType()) {
  10653. // Cast to pointer type.
  10654. ExprResult CastExpr = S.BuildCStyleCastExpr(
  10655. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  10656. if (CastExpr.isInvalid())
  10657. continue;
  10658. Init = CastExpr.get();
  10659. }
  10660. } else if (Type->isRealFloatingType()) {
  10661. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  10662. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  10663. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  10664. Type, ELoc);
  10665. }
  10666. break;
  10667. }
  10668. case BO_PtrMemD:
  10669. case BO_PtrMemI:
  10670. case BO_MulAssign:
  10671. case BO_Div:
  10672. case BO_Rem:
  10673. case BO_Sub:
  10674. case BO_Shl:
  10675. case BO_Shr:
  10676. case BO_LE:
  10677. case BO_GE:
  10678. case BO_EQ:
  10679. case BO_NE:
  10680. case BO_Cmp:
  10681. case BO_AndAssign:
  10682. case BO_XorAssign:
  10683. case BO_OrAssign:
  10684. case BO_Assign:
  10685. case BO_AddAssign:
  10686. case BO_SubAssign:
  10687. case BO_DivAssign:
  10688. case BO_RemAssign:
  10689. case BO_ShlAssign:
  10690. case BO_ShrAssign:
  10691. case BO_Comma:
  10692. llvm_unreachable("Unexpected reduction operation");
  10693. }
  10694. }
  10695. if (Init && DeclareReductionRef.isUnset())
  10696. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  10697. else if (!Init)
  10698. S.ActOnUninitializedDecl(RHSVD);
  10699. if (RHSVD->isInvalidDecl())
  10700. continue;
  10701. if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
  10702. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  10703. << Type << ReductionIdRange;
  10704. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  10705. VarDecl::DeclarationOnly;
  10706. S.Diag(D->getLocation(),
  10707. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10708. << D;
  10709. continue;
  10710. }
  10711. // Store initializer for single element in private copy. Will be used during
  10712. // codegen.
  10713. PrivateVD->setInit(RHSVD->getInit());
  10714. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  10715. DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  10716. ExprResult ReductionOp;
  10717. if (DeclareReductionRef.isUsable()) {
  10718. QualType RedTy = DeclareReductionRef.get()->getType();
  10719. QualType PtrRedTy = Context.getPointerType(RedTy);
  10720. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  10721. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  10722. if (!BasePath.empty()) {
  10723. LHS = S.DefaultLvalueConversion(LHS.get());
  10724. RHS = S.DefaultLvalueConversion(RHS.get());
  10725. LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  10726. CK_UncheckedDerivedToBase, LHS.get(),
  10727. &BasePath, LHS.get()->getValueKind());
  10728. RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
  10729. CK_UncheckedDerivedToBase, RHS.get(),
  10730. &BasePath, RHS.get()->getValueKind());
  10731. }
  10732. FunctionProtoType::ExtProtoInfo EPI;
  10733. QualType Params[] = {PtrRedTy, PtrRedTy};
  10734. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  10735. auto *OVE = new (Context) OpaqueValueExpr(
  10736. ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
  10737. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  10738. Expr *Args[] = {LHS.get(), RHS.get()};
  10739. ReductionOp =
  10740. CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
  10741. } else {
  10742. ReductionOp = S.BuildBinOp(
  10743. Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
  10744. if (ReductionOp.isUsable()) {
  10745. if (BOK != BO_LT && BOK != BO_GT) {
  10746. ReductionOp =
  10747. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  10748. BO_Assign, LHSDRE, ReductionOp.get());
  10749. } else {
  10750. auto *ConditionalOp = new (Context)
  10751. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
  10752. Type, VK_LValue, OK_Ordinary);
  10753. ReductionOp =
  10754. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  10755. BO_Assign, LHSDRE, ConditionalOp);
  10756. }
  10757. if (ReductionOp.isUsable())
  10758. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
  10759. /*DiscardedValue*/ false);
  10760. }
  10761. if (!ReductionOp.isUsable())
  10762. continue;
  10763. }
  10764. // OpenMP [2.15.4.6, Restrictions, p.2]
  10765. // A list item that appears in an in_reduction clause of a task construct
  10766. // must appear in a task_reduction clause of a construct associated with a
  10767. // taskgroup region that includes the participating task in its taskgroup
  10768. // set. The construct associated with the innermost region that meets this
  10769. // condition must specify the same reduction-identifier as the in_reduction
  10770. // clause.
  10771. if (ClauseKind == OMPC_in_reduction) {
  10772. SourceRange ParentSR;
  10773. BinaryOperatorKind ParentBOK;
  10774. const Expr *ParentReductionOp;
  10775. Expr *ParentBOKTD, *ParentReductionOpTD;
  10776. DSAStackTy::DSAVarData ParentBOKDSA =
  10777. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  10778. ParentBOKTD);
  10779. DSAStackTy::DSAVarData ParentReductionOpDSA =
  10780. Stack->getTopMostTaskgroupReductionData(
  10781. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  10782. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  10783. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  10784. if (!IsParentBOK && !IsParentReductionOp) {
  10785. S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
  10786. continue;
  10787. }
  10788. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  10789. (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
  10790. IsParentReductionOp) {
  10791. bool EmitError = true;
  10792. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  10793. llvm::FoldingSetNodeID RedId, ParentRedId;
  10794. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  10795. DeclareReductionRef.get()->Profile(RedId, Context,
  10796. /*Canonical=*/true);
  10797. EmitError = RedId != ParentRedId;
  10798. }
  10799. if (EmitError) {
  10800. S.Diag(ReductionId.getBeginLoc(),
  10801. diag::err_omp_reduction_identifier_mismatch)
  10802. << ReductionIdRange << RefExpr->getSourceRange();
  10803. S.Diag(ParentSR.getBegin(),
  10804. diag::note_omp_previous_reduction_identifier)
  10805. << ParentSR
  10806. << (IsParentBOK ? ParentBOKDSA.RefExpr
  10807. : ParentReductionOpDSA.RefExpr)
  10808. ->getSourceRange();
  10809. continue;
  10810. }
  10811. }
  10812. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  10813. assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
  10814. }
  10815. DeclRefExpr *Ref = nullptr;
  10816. Expr *VarsExpr = RefExpr->IgnoreParens();
  10817. if (!VD && !S.CurContext->isDependentContext()) {
  10818. if (ASE || OASE) {
  10819. TransformExprToCaptures RebuildToCapture(S, D);
  10820. VarsExpr =
  10821. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  10822. Ref = RebuildToCapture.getCapturedExpr();
  10823. } else {
  10824. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  10825. }
  10826. if (!S.isOpenMPCapturedDecl(D)) {
  10827. RD.ExprCaptures.emplace_back(Ref->getDecl());
  10828. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  10829. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  10830. if (!RefRes.isUsable())
  10831. continue;
  10832. ExprResult PostUpdateRes =
  10833. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  10834. RefRes.get());
  10835. if (!PostUpdateRes.isUsable())
  10836. continue;
  10837. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  10838. Stack->getCurrentDirective() == OMPD_taskgroup) {
  10839. S.Diag(RefExpr->getExprLoc(),
  10840. diag::err_omp_reduction_non_addressable_expression)
  10841. << RefExpr->getSourceRange();
  10842. continue;
  10843. }
  10844. RD.ExprPostUpdates.emplace_back(
  10845. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  10846. }
  10847. }
  10848. }
  10849. // All reduction items are still marked as reduction (to do not increase
  10850. // code base size).
  10851. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
  10852. if (CurrDir == OMPD_taskgroup) {
  10853. if (DeclareReductionRef.isUsable())
  10854. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  10855. DeclareReductionRef.get());
  10856. else
  10857. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  10858. }
  10859. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  10860. TaskgroupDescriptor);
  10861. }
  10862. return RD.Vars.empty();
  10863. }
  10864. OMPClause *Sema::ActOnOpenMPReductionClause(
  10865. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10866. SourceLocation ColonLoc, SourceLocation EndLoc,
  10867. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10868. ArrayRef<Expr *> UnresolvedReductions) {
  10869. ReductionData RD(VarList.size());
  10870. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  10871. StartLoc, LParenLoc, ColonLoc, EndLoc,
  10872. ReductionIdScopeSpec, ReductionId,
  10873. UnresolvedReductions, RD))
  10874. return nullptr;
  10875. return OMPReductionClause::Create(
  10876. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  10877. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  10878. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  10879. buildPreInits(Context, RD.ExprCaptures),
  10880. buildPostUpdate(*this, RD.ExprPostUpdates));
  10881. }
  10882. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  10883. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10884. SourceLocation ColonLoc, SourceLocation EndLoc,
  10885. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10886. ArrayRef<Expr *> UnresolvedReductions) {
  10887. ReductionData RD(VarList.size());
  10888. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
  10889. StartLoc, LParenLoc, ColonLoc, EndLoc,
  10890. ReductionIdScopeSpec, ReductionId,
  10891. UnresolvedReductions, RD))
  10892. return nullptr;
  10893. return OMPTaskReductionClause::Create(
  10894. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  10895. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  10896. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  10897. buildPreInits(Context, RD.ExprCaptures),
  10898. buildPostUpdate(*this, RD.ExprPostUpdates));
  10899. }
  10900. OMPClause *Sema::ActOnOpenMPInReductionClause(
  10901. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  10902. SourceLocation ColonLoc, SourceLocation EndLoc,
  10903. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  10904. ArrayRef<Expr *> UnresolvedReductions) {
  10905. ReductionData RD(VarList.size());
  10906. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  10907. StartLoc, LParenLoc, ColonLoc, EndLoc,
  10908. ReductionIdScopeSpec, ReductionId,
  10909. UnresolvedReductions, RD))
  10910. return nullptr;
  10911. return OMPInReductionClause::Create(
  10912. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  10913. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  10914. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  10915. buildPreInits(Context, RD.ExprCaptures),
  10916. buildPostUpdate(*this, RD.ExprPostUpdates));
  10917. }
  10918. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  10919. SourceLocation LinLoc) {
  10920. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  10921. LinKind == OMPC_LINEAR_unknown) {
  10922. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  10923. return true;
  10924. }
  10925. return false;
  10926. }
  10927. bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
  10928. OpenMPLinearClauseKind LinKind,
  10929. QualType Type) {
  10930. const auto *VD = dyn_cast_or_null<VarDecl>(D);
  10931. // A variable must not have an incomplete type or a reference type.
  10932. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  10933. return true;
  10934. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  10935. !Type->isReferenceType()) {
  10936. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  10937. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  10938. return true;
  10939. }
  10940. Type = Type.getNonReferenceType();
  10941. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  10942. // A variable that is privatized must not have a const-qualified type
  10943. // unless it is of class type with a mutable member. This restriction does
  10944. // not apply to the firstprivate clause.
  10945. if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
  10946. return true;
  10947. // A list item must be of integral or pointer type.
  10948. Type = Type.getUnqualifiedType().getCanonicalType();
  10949. const auto *Ty = Type.getTypePtrOrNull();
  10950. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  10951. !Ty->isPointerType())) {
  10952. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  10953. if (D) {
  10954. bool IsDecl =
  10955. !VD ||
  10956. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  10957. Diag(D->getLocation(),
  10958. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  10959. << D;
  10960. }
  10961. return true;
  10962. }
  10963. return false;
  10964. }
  10965. OMPClause *Sema::ActOnOpenMPLinearClause(
  10966. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  10967. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  10968. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  10969. SmallVector<Expr *, 8> Vars;
  10970. SmallVector<Expr *, 8> Privates;
  10971. SmallVector<Expr *, 8> Inits;
  10972. SmallVector<Decl *, 4> ExprCaptures;
  10973. SmallVector<Expr *, 4> ExprPostUpdates;
  10974. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  10975. LinKind = OMPC_LINEAR_val;
  10976. for (Expr *RefExpr : VarList) {
  10977. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  10978. SourceLocation ELoc;
  10979. SourceRange ERange;
  10980. Expr *SimpleRefExpr = RefExpr;
  10981. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  10982. if (Res.second) {
  10983. // It will be analyzed later.
  10984. Vars.push_back(RefExpr);
  10985. Privates.push_back(nullptr);
  10986. Inits.push_back(nullptr);
  10987. }
  10988. ValueDecl *D = Res.first;
  10989. if (!D)
  10990. continue;
  10991. QualType Type = D->getType();
  10992. auto *VD = dyn_cast<VarDecl>(D);
  10993. // OpenMP [2.14.3.7, linear clause]
  10994. // A list-item cannot appear in more than one linear clause.
  10995. // A list-item that appears in a linear clause cannot appear in any
  10996. // other data-sharing attribute clause.
  10997. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  10998. if (DVar.RefExpr) {
  10999. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  11000. << getOpenMPClauseName(OMPC_linear);
  11001. reportOriginalDsa(*this, DSAStack, D, DVar);
  11002. continue;
  11003. }
  11004. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  11005. continue;
  11006. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  11007. // Build private copy of original var.
  11008. VarDecl *Private =
  11009. buildVarDecl(*this, ELoc, Type, D->getName(),
  11010. D->hasAttrs() ? &D->getAttrs() : nullptr,
  11011. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  11012. DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  11013. // Build var to save initial value.
  11014. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  11015. Expr *InitExpr;
  11016. DeclRefExpr *Ref = nullptr;
  11017. if (!VD && !CurContext->isDependentContext()) {
  11018. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  11019. if (!isOpenMPCapturedDecl(D)) {
  11020. ExprCaptures.push_back(Ref->getDecl());
  11021. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  11022. ExprResult RefRes = DefaultLvalueConversion(Ref);
  11023. if (!RefRes.isUsable())
  11024. continue;
  11025. ExprResult PostUpdateRes =
  11026. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  11027. SimpleRefExpr, RefRes.get());
  11028. if (!PostUpdateRes.isUsable())
  11029. continue;
  11030. ExprPostUpdates.push_back(
  11031. IgnoredValueConversions(PostUpdateRes.get()).get());
  11032. }
  11033. }
  11034. }
  11035. if (LinKind == OMPC_LINEAR_uval)
  11036. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  11037. else
  11038. InitExpr = VD ? SimpleRefExpr : Ref;
  11039. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  11040. /*DirectInit=*/false);
  11041. DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  11042. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  11043. Vars.push_back((VD || CurContext->isDependentContext())
  11044. ? RefExpr->IgnoreParens()
  11045. : Ref);
  11046. Privates.push_back(PrivateRef);
  11047. Inits.push_back(InitRef);
  11048. }
  11049. if (Vars.empty())
  11050. return nullptr;
  11051. Expr *StepExpr = Step;
  11052. Expr *CalcStepExpr = nullptr;
  11053. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  11054. !Step->isInstantiationDependent() &&
  11055. !Step->containsUnexpandedParameterPack()) {
  11056. SourceLocation StepLoc = Step->getBeginLoc();
  11057. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  11058. if (Val.isInvalid())
  11059. return nullptr;
  11060. StepExpr = Val.get();
  11061. // Build var to save the step value.
  11062. VarDecl *SaveVar =
  11063. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  11064. ExprResult SaveRef =
  11065. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  11066. ExprResult CalcStep =
  11067. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  11068. CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
  11069. // Warn about zero linear step (it would be probably better specified as
  11070. // making corresponding variables 'const').
  11071. llvm::APSInt Result;
  11072. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  11073. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  11074. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  11075. << (Vars.size() > 1);
  11076. if (!IsConstant && CalcStep.isUsable()) {
  11077. // Calculate the step beforehand instead of doing this on each iteration.
  11078. // (This is not used if the number of iterations may be kfold-ed).
  11079. CalcStepExpr = CalcStep.get();
  11080. }
  11081. }
  11082. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  11083. ColonLoc, EndLoc, Vars, Privates, Inits,
  11084. StepExpr, CalcStepExpr,
  11085. buildPreInits(Context, ExprCaptures),
  11086. buildPostUpdate(*this, ExprPostUpdates));
  11087. }
  11088. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  11089. Expr *NumIterations, Sema &SemaRef,
  11090. Scope *S, DSAStackTy *Stack) {
  11091. // Walk the vars and build update/final expressions for the CodeGen.
  11092. SmallVector<Expr *, 8> Updates;
  11093. SmallVector<Expr *, 8> Finals;
  11094. Expr *Step = Clause.getStep();
  11095. Expr *CalcStep = Clause.getCalcStep();
  11096. // OpenMP [2.14.3.7, linear clause]
  11097. // If linear-step is not specified it is assumed to be 1.
  11098. if (!Step)
  11099. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  11100. else if (CalcStep)
  11101. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  11102. bool HasErrors = false;
  11103. auto CurInit = Clause.inits().begin();
  11104. auto CurPrivate = Clause.privates().begin();
  11105. OpenMPLinearClauseKind LinKind = Clause.getModifier();
  11106. for (Expr *RefExpr : Clause.varlists()) {
  11107. SourceLocation ELoc;
  11108. SourceRange ERange;
  11109. Expr *SimpleRefExpr = RefExpr;
  11110. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
  11111. ValueDecl *D = Res.first;
  11112. if (Res.second || !D) {
  11113. Updates.push_back(nullptr);
  11114. Finals.push_back(nullptr);
  11115. HasErrors = true;
  11116. continue;
  11117. }
  11118. auto &&Info = Stack->isLoopControlVariable(D);
  11119. // OpenMP [2.15.11, distribute simd Construct]
  11120. // A list item may not appear in a linear clause, unless it is the loop
  11121. // iteration variable.
  11122. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  11123. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  11124. SemaRef.Diag(ELoc,
  11125. diag::err_omp_linear_distribute_var_non_loop_iteration);
  11126. Updates.push_back(nullptr);
  11127. Finals.push_back(nullptr);
  11128. HasErrors = true;
  11129. continue;
  11130. }
  11131. Expr *InitExpr = *CurInit;
  11132. // Build privatized reference to the current linear var.
  11133. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  11134. Expr *CapturedRef;
  11135. if (LinKind == OMPC_LINEAR_uval)
  11136. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  11137. else
  11138. CapturedRef =
  11139. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  11140. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  11141. /*RefersToCapture=*/true);
  11142. // Build update: Var = InitExpr + IV * Step
  11143. ExprResult Update;
  11144. if (!Info.first)
  11145. Update =
  11146. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
  11147. InitExpr, IV, Step, /* Subtract */ false);
  11148. else
  11149. Update = *CurPrivate;
  11150. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
  11151. /*DiscardedValue*/ false);
  11152. // Build final: Var = InitExpr + NumIterations * Step
  11153. ExprResult Final;
  11154. if (!Info.first)
  11155. Final =
  11156. buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  11157. InitExpr, NumIterations, Step, /*Subtract=*/false);
  11158. else
  11159. Final = *CurPrivate;
  11160. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
  11161. /*DiscardedValue*/ false);
  11162. if (!Update.isUsable() || !Final.isUsable()) {
  11163. Updates.push_back(nullptr);
  11164. Finals.push_back(nullptr);
  11165. HasErrors = true;
  11166. } else {
  11167. Updates.push_back(Update.get());
  11168. Finals.push_back(Final.get());
  11169. }
  11170. ++CurInit;
  11171. ++CurPrivate;
  11172. }
  11173. Clause.setUpdates(Updates);
  11174. Clause.setFinals(Finals);
  11175. return HasErrors;
  11176. }
  11177. OMPClause *Sema::ActOnOpenMPAlignedClause(
  11178. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  11179. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  11180. SmallVector<Expr *, 8> Vars;
  11181. for (Expr *RefExpr : VarList) {
  11182. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  11183. SourceLocation ELoc;
  11184. SourceRange ERange;
  11185. Expr *SimpleRefExpr = RefExpr;
  11186. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11187. if (Res.second) {
  11188. // It will be analyzed later.
  11189. Vars.push_back(RefExpr);
  11190. }
  11191. ValueDecl *D = Res.first;
  11192. if (!D)
  11193. continue;
  11194. QualType QType = D->getType();
  11195. auto *VD = dyn_cast<VarDecl>(D);
  11196. // OpenMP [2.8.1, simd construct, Restrictions]
  11197. // The type of list items appearing in the aligned clause must be
  11198. // array, pointer, reference to array, or reference to pointer.
  11199. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  11200. const Type *Ty = QType.getTypePtrOrNull();
  11201. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  11202. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  11203. << QType << getLangOpts().CPlusPlus << ERange;
  11204. bool IsDecl =
  11205. !VD ||
  11206. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11207. Diag(D->getLocation(),
  11208. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11209. << D;
  11210. continue;
  11211. }
  11212. // OpenMP [2.8.1, simd construct, Restrictions]
  11213. // A list-item cannot appear in more than one aligned clause.
  11214. if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  11215. Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
  11216. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  11217. << getOpenMPClauseName(OMPC_aligned);
  11218. continue;
  11219. }
  11220. DeclRefExpr *Ref = nullptr;
  11221. if (!VD && isOpenMPCapturedDecl(D))
  11222. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  11223. Vars.push_back(DefaultFunctionArrayConversion(
  11224. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  11225. .get());
  11226. }
  11227. // OpenMP [2.8.1, simd construct, Description]
  11228. // The parameter of the aligned clause, alignment, must be a constant
  11229. // positive integer expression.
  11230. // If no optional parameter is specified, implementation-defined default
  11231. // alignments for SIMD instructions on the target platforms are assumed.
  11232. if (Alignment != nullptr) {
  11233. ExprResult AlignResult =
  11234. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  11235. if (AlignResult.isInvalid())
  11236. return nullptr;
  11237. Alignment = AlignResult.get();
  11238. }
  11239. if (Vars.empty())
  11240. return nullptr;
  11241. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  11242. EndLoc, Vars, Alignment);
  11243. }
  11244. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  11245. SourceLocation StartLoc,
  11246. SourceLocation LParenLoc,
  11247. SourceLocation EndLoc) {
  11248. SmallVector<Expr *, 8> Vars;
  11249. SmallVector<Expr *, 8> SrcExprs;
  11250. SmallVector<Expr *, 8> DstExprs;
  11251. SmallVector<Expr *, 8> AssignmentOps;
  11252. for (Expr *RefExpr : VarList) {
  11253. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  11254. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  11255. // It will be analyzed later.
  11256. Vars.push_back(RefExpr);
  11257. SrcExprs.push_back(nullptr);
  11258. DstExprs.push_back(nullptr);
  11259. AssignmentOps.push_back(nullptr);
  11260. continue;
  11261. }
  11262. SourceLocation ELoc = RefExpr->getExprLoc();
  11263. // OpenMP [2.1, C/C++]
  11264. // A list item is a variable name.
  11265. // OpenMP [2.14.4.1, Restrictions, p.1]
  11266. // A list item that appears in a copyin clause must be threadprivate.
  11267. auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
  11268. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  11269. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  11270. << 0 << RefExpr->getSourceRange();
  11271. continue;
  11272. }
  11273. Decl *D = DE->getDecl();
  11274. auto *VD = cast<VarDecl>(D);
  11275. QualType Type = VD->getType();
  11276. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  11277. // It will be analyzed later.
  11278. Vars.push_back(DE);
  11279. SrcExprs.push_back(nullptr);
  11280. DstExprs.push_back(nullptr);
  11281. AssignmentOps.push_back(nullptr);
  11282. continue;
  11283. }
  11284. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  11285. // A list item that appears in a copyin clause must be threadprivate.
  11286. if (!DSAStack->isThreadPrivate(VD)) {
  11287. Diag(ELoc, diag::err_omp_required_access)
  11288. << getOpenMPClauseName(OMPC_copyin)
  11289. << getOpenMPDirectiveName(OMPD_threadprivate);
  11290. continue;
  11291. }
  11292. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  11293. // A variable of class type (or array thereof) that appears in a
  11294. // copyin clause requires an accessible, unambiguous copy assignment
  11295. // operator for the class type.
  11296. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  11297. VarDecl *SrcVD =
  11298. buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
  11299. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  11300. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
  11301. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  11302. VarDecl *DstVD =
  11303. buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
  11304. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  11305. DeclRefExpr *PseudoDstExpr =
  11306. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  11307. // For arrays generate assignment operation for single element and replace
  11308. // it by the original array element in CodeGen.
  11309. ExprResult AssignmentOp =
  11310. BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
  11311. PseudoSrcExpr);
  11312. if (AssignmentOp.isInvalid())
  11313. continue;
  11314. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  11315. /*DiscardedValue*/ false);
  11316. if (AssignmentOp.isInvalid())
  11317. continue;
  11318. DSAStack->addDSA(VD, DE, OMPC_copyin);
  11319. Vars.push_back(DE);
  11320. SrcExprs.push_back(PseudoSrcExpr);
  11321. DstExprs.push_back(PseudoDstExpr);
  11322. AssignmentOps.push_back(AssignmentOp.get());
  11323. }
  11324. if (Vars.empty())
  11325. return nullptr;
  11326. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  11327. SrcExprs, DstExprs, AssignmentOps);
  11328. }
  11329. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  11330. SourceLocation StartLoc,
  11331. SourceLocation LParenLoc,
  11332. SourceLocation EndLoc) {
  11333. SmallVector<Expr *, 8> Vars;
  11334. SmallVector<Expr *, 8> SrcExprs;
  11335. SmallVector<Expr *, 8> DstExprs;
  11336. SmallVector<Expr *, 8> AssignmentOps;
  11337. for (Expr *RefExpr : VarList) {
  11338. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  11339. SourceLocation ELoc;
  11340. SourceRange ERange;
  11341. Expr *SimpleRefExpr = RefExpr;
  11342. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  11343. if (Res.second) {
  11344. // It will be analyzed later.
  11345. Vars.push_back(RefExpr);
  11346. SrcExprs.push_back(nullptr);
  11347. DstExprs.push_back(nullptr);
  11348. AssignmentOps.push_back(nullptr);
  11349. }
  11350. ValueDecl *D = Res.first;
  11351. if (!D)
  11352. continue;
  11353. QualType Type = D->getType();
  11354. auto *VD = dyn_cast<VarDecl>(D);
  11355. // OpenMP [2.14.4.2, Restrictions, p.2]
  11356. // A list item that appears in a copyprivate clause may not appear in a
  11357. // private or firstprivate clause on the single construct.
  11358. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  11359. DSAStackTy::DSAVarData DVar =
  11360. DSAStack->getTopDSA(D, /*FromParent=*/false);
  11361. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  11362. DVar.RefExpr) {
  11363. Diag(ELoc, diag::err_omp_wrong_dsa)
  11364. << getOpenMPClauseName(DVar.CKind)
  11365. << getOpenMPClauseName(OMPC_copyprivate);
  11366. reportOriginalDsa(*this, DSAStack, D, DVar);
  11367. continue;
  11368. }
  11369. // OpenMP [2.11.4.2, Restrictions, p.1]
  11370. // All list items that appear in a copyprivate clause must be either
  11371. // threadprivate or private in the enclosing context.
  11372. if (DVar.CKind == OMPC_unknown) {
  11373. DVar = DSAStack->getImplicitDSA(D, false);
  11374. if (DVar.CKind == OMPC_shared) {
  11375. Diag(ELoc, diag::err_omp_required_access)
  11376. << getOpenMPClauseName(OMPC_copyprivate)
  11377. << "threadprivate or private in the enclosing context";
  11378. reportOriginalDsa(*this, DSAStack, D, DVar);
  11379. continue;
  11380. }
  11381. }
  11382. }
  11383. // Variably modified types are not supported.
  11384. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  11385. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  11386. << getOpenMPClauseName(OMPC_copyprivate) << Type
  11387. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  11388. bool IsDecl =
  11389. !VD ||
  11390. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  11391. Diag(D->getLocation(),
  11392. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  11393. << D;
  11394. continue;
  11395. }
  11396. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  11397. // A variable of class type (or array thereof) that appears in a
  11398. // copyin clause requires an accessible, unambiguous copy assignment
  11399. // operator for the class type.
  11400. Type = Context.getBaseElementType(Type.getNonReferenceType())
  11401. .getUnqualifiedType();
  11402. VarDecl *SrcVD =
  11403. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
  11404. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11405. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  11406. VarDecl *DstVD =
  11407. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
  11408. D->hasAttrs() ? &D->getAttrs() : nullptr);
  11409. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  11410. ExprResult AssignmentOp = BuildBinOp(
  11411. DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
  11412. if (AssignmentOp.isInvalid())
  11413. continue;
  11414. AssignmentOp =
  11415. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  11416. if (AssignmentOp.isInvalid())
  11417. continue;
  11418. // No need to mark vars as copyprivate, they are already threadprivate or
  11419. // implicitly private.
  11420. assert(VD || isOpenMPCapturedDecl(D));
  11421. Vars.push_back(
  11422. VD ? RefExpr->IgnoreParens()
  11423. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  11424. SrcExprs.push_back(PseudoSrcExpr);
  11425. DstExprs.push_back(PseudoDstExpr);
  11426. AssignmentOps.push_back(AssignmentOp.get());
  11427. }
  11428. if (Vars.empty())
  11429. return nullptr;
  11430. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11431. Vars, SrcExprs, DstExprs, AssignmentOps);
  11432. }
  11433. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  11434. SourceLocation StartLoc,
  11435. SourceLocation LParenLoc,
  11436. SourceLocation EndLoc) {
  11437. if (VarList.empty())
  11438. return nullptr;
  11439. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  11440. }
  11441. OMPClause *
  11442. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  11443. SourceLocation DepLoc, SourceLocation ColonLoc,
  11444. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  11445. SourceLocation LParenLoc, SourceLocation EndLoc) {
  11446. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  11447. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  11448. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  11449. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  11450. return nullptr;
  11451. }
  11452. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  11453. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  11454. DepKind == OMPC_DEPEND_sink)) {
  11455. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  11456. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  11457. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  11458. /*Last=*/OMPC_DEPEND_unknown, Except)
  11459. << getOpenMPClauseName(OMPC_depend);
  11460. return nullptr;
  11461. }
  11462. SmallVector<Expr *, 8> Vars;
  11463. DSAStackTy::OperatorOffsetTy OpsOffs;
  11464. llvm::APSInt DepCounter(/*BitWidth=*/32);
  11465. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  11466. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
  11467. if (const Expr *OrderedCountExpr =
  11468. DSAStack->getParentOrderedRegionParam().first) {
  11469. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  11470. TotalDepCount.setIsUnsigned(/*Val=*/true);
  11471. }
  11472. }
  11473. for (Expr *RefExpr : VarList) {
  11474. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  11475. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  11476. // It will be analyzed later.
  11477. Vars.push_back(RefExpr);
  11478. continue;
  11479. }
  11480. SourceLocation ELoc = RefExpr->getExprLoc();
  11481. Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
  11482. if (DepKind == OMPC_DEPEND_sink) {
  11483. if (DSAStack->getParentOrderedRegionParam().first &&
  11484. DepCounter >= TotalDepCount) {
  11485. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  11486. continue;
  11487. }
  11488. ++DepCounter;
  11489. // OpenMP [2.13.9, Summary]
  11490. // depend(dependence-type : vec), where dependence-type is:
  11491. // 'sink' and where vec is the iteration vector, which has the form:
  11492. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  11493. // where n is the value specified by the ordered clause in the loop
  11494. // directive, xi denotes the loop iteration variable of the i-th nested
  11495. // loop associated with the loop directive, and di is a constant
  11496. // non-negative integer.
  11497. if (CurContext->isDependentContext()) {
  11498. // It will be analyzed later.
  11499. Vars.push_back(RefExpr);
  11500. continue;
  11501. }
  11502. SimpleExpr = SimpleExpr->IgnoreImplicit();
  11503. OverloadedOperatorKind OOK = OO_None;
  11504. SourceLocation OOLoc;
  11505. Expr *LHS = SimpleExpr;
  11506. Expr *RHS = nullptr;
  11507. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  11508. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  11509. OOLoc = BO->getOperatorLoc();
  11510. LHS = BO->getLHS()->IgnoreParenImpCasts();
  11511. RHS = BO->getRHS()->IgnoreParenImpCasts();
  11512. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  11513. OOK = OCE->getOperator();
  11514. OOLoc = OCE->getOperatorLoc();
  11515. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  11516. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  11517. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  11518. OOK = MCE->getMethodDecl()
  11519. ->getNameInfo()
  11520. .getName()
  11521. .getCXXOverloadedOperator();
  11522. OOLoc = MCE->getCallee()->getExprLoc();
  11523. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  11524. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  11525. }
  11526. SourceLocation ELoc;
  11527. SourceRange ERange;
  11528. auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
  11529. if (Res.second) {
  11530. // It will be analyzed later.
  11531. Vars.push_back(RefExpr);
  11532. }
  11533. ValueDecl *D = Res.first;
  11534. if (!D)
  11535. continue;
  11536. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  11537. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  11538. continue;
  11539. }
  11540. if (RHS) {
  11541. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  11542. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  11543. if (RHSRes.isInvalid())
  11544. continue;
  11545. }
  11546. if (!CurContext->isDependentContext() &&
  11547. DSAStack->getParentOrderedRegionParam().first &&
  11548. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  11549. const ValueDecl *VD =
  11550. DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
  11551. if (VD)
  11552. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  11553. << 1 << VD;
  11554. else
  11555. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  11556. continue;
  11557. }
  11558. OpsOffs.emplace_back(RHS, OOK);
  11559. } else {
  11560. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  11561. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  11562. (ASE &&
  11563. !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
  11564. !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
  11565. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  11566. << RefExpr->getSourceRange();
  11567. continue;
  11568. }
  11569. bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
  11570. getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  11571. ExprResult Res =
  11572. CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
  11573. getDiagnostics().setSuppressAllDiagnostics(Suppress);
  11574. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
  11575. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  11576. << RefExpr->getSourceRange();
  11577. continue;
  11578. }
  11579. }
  11580. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  11581. }
  11582. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  11583. TotalDepCount > VarList.size() &&
  11584. DSAStack->getParentOrderedRegionParam().first &&
  11585. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  11586. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
  11587. << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  11588. }
  11589. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  11590. Vars.empty())
  11591. return nullptr;
  11592. auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  11593. DepKind, DepLoc, ColonLoc, Vars,
  11594. TotalDepCount.getZExtValue());
  11595. if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
  11596. DSAStack->isParentOrderedRegion())
  11597. DSAStack->addDoacrossDependClause(C, OpsOffs);
  11598. return C;
  11599. }
  11600. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  11601. SourceLocation LParenLoc,
  11602. SourceLocation EndLoc) {
  11603. Expr *ValExpr = Device;
  11604. Stmt *HelperValStmt = nullptr;
  11605. // OpenMP [2.9.1, Restrictions]
  11606. // The device expression must evaluate to a non-negative integer value.
  11607. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  11608. /*StrictlyPositive=*/false))
  11609. return nullptr;
  11610. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  11611. OpenMPDirectiveKind CaptureRegion =
  11612. getOpenMPCaptureRegionForClause(DKind, OMPC_device);
  11613. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  11614. ValExpr = MakeFullExpr(ValExpr).get();
  11615. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  11616. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  11617. HelperValStmt = buildPreInits(Context, Captures);
  11618. }
  11619. return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
  11620. StartLoc, LParenLoc, EndLoc);
  11621. }
  11622. static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  11623. DSAStackTy *Stack, QualType QTy,
  11624. bool FullCheck = true) {
  11625. NamedDecl *ND;
  11626. if (QTy->isIncompleteType(&ND)) {
  11627. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  11628. return false;
  11629. }
  11630. if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
  11631. !QTy.isTrivialType(SemaRef.Context))
  11632. SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
  11633. return true;
  11634. }
  11635. /// Return true if it can be proven that the provided array expression
  11636. /// (array section or array subscript) does NOT specify the whole size of the
  11637. /// array whose base type is \a BaseQTy.
  11638. static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  11639. const Expr *E,
  11640. QualType BaseQTy) {
  11641. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  11642. // If this is an array subscript, it refers to the whole size if the size of
  11643. // the dimension is constant and equals 1. Also, an array section assumes the
  11644. // format of an array subscript if no colon is used.
  11645. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
  11646. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  11647. return ATy->getSize().getSExtValue() != 1;
  11648. // Size can't be evaluated statically.
  11649. return false;
  11650. }
  11651. assert(OASE && "Expecting array section if not an array subscript.");
  11652. const Expr *LowerBound = OASE->getLowerBound();
  11653. const Expr *Length = OASE->getLength();
  11654. // If there is a lower bound that does not evaluates to zero, we are not
  11655. // covering the whole dimension.
  11656. if (LowerBound) {
  11657. Expr::EvalResult Result;
  11658. if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
  11659. return false; // Can't get the integer value as a constant.
  11660. llvm::APSInt ConstLowerBound = Result.Val.getInt();
  11661. if (ConstLowerBound.getSExtValue())
  11662. return true;
  11663. }
  11664. // If we don't have a length we covering the whole dimension.
  11665. if (!Length)
  11666. return false;
  11667. // If the base is a pointer, we don't have a way to get the size of the
  11668. // pointee.
  11669. if (BaseQTy->isPointerType())
  11670. return false;
  11671. // We can only check if the length is the same as the size of the dimension
  11672. // if we have a constant array.
  11673. const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  11674. if (!CATy)
  11675. return false;
  11676. Expr::EvalResult Result;
  11677. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  11678. return false; // Can't get the integer value as a constant.
  11679. llvm::APSInt ConstLength = Result.Val.getInt();
  11680. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  11681. }
  11682. // Return true if it can be proven that the provided array expression (array
  11683. // section or array subscript) does NOT specify a single element of the array
  11684. // whose base type is \a BaseQTy.
  11685. static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  11686. const Expr *E,
  11687. QualType BaseQTy) {
  11688. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  11689. // An array subscript always refer to a single element. Also, an array section
  11690. // assumes the format of an array subscript if no colon is used.
  11691. if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
  11692. return false;
  11693. assert(OASE && "Expecting array section if not an array subscript.");
  11694. const Expr *Length = OASE->getLength();
  11695. // If we don't have a length we have to check if the array has unitary size
  11696. // for this dimension. Also, we should always expect a length if the base type
  11697. // is pointer.
  11698. if (!Length) {
  11699. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  11700. return ATy->getSize().getSExtValue() != 1;
  11701. // We cannot assume anything.
  11702. return false;
  11703. }
  11704. // Check if the length evaluates to 1.
  11705. Expr::EvalResult Result;
  11706. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  11707. return false; // Can't get the integer value as a constant.
  11708. llvm::APSInt ConstLength = Result.Val.getInt();
  11709. return ConstLength.getSExtValue() != 1;
  11710. }
  11711. // Return the expression of the base of the mappable expression or null if it
  11712. // cannot be determined and do all the necessary checks to see if the expression
  11713. // is valid as a standalone mappable expression. In the process, record all the
  11714. // components of the expression.
  11715. static const Expr *checkMapClauseExpressionBase(
  11716. Sema &SemaRef, Expr *E,
  11717. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  11718. OpenMPClauseKind CKind, bool NoDiagnose) {
  11719. SourceLocation ELoc = E->getExprLoc();
  11720. SourceRange ERange = E->getSourceRange();
  11721. // The base of elements of list in a map clause have to be either:
  11722. // - a reference to variable or field.
  11723. // - a member expression.
  11724. // - an array expression.
  11725. //
  11726. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  11727. // reference to 'r'.
  11728. //
  11729. // If we have:
  11730. //
  11731. // struct SS {
  11732. // Bla S;
  11733. // foo() {
  11734. // #pragma omp target map (S.Arr[:12]);
  11735. // }
  11736. // }
  11737. //
  11738. // We want to retrieve the member expression 'this->S';
  11739. const Expr *RelevantExpr = nullptr;
  11740. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  11741. // If a list item is an array section, it must specify contiguous storage.
  11742. //
  11743. // For this restriction it is sufficient that we make sure only references
  11744. // to variables or fields and array expressions, and that no array sections
  11745. // exist except in the rightmost expression (unless they cover the whole
  11746. // dimension of the array). E.g. these would be invalid:
  11747. //
  11748. // r.ArrS[3:5].Arr[6:7]
  11749. //
  11750. // r.ArrS[3:5].x
  11751. //
  11752. // but these would be valid:
  11753. // r.ArrS[3].Arr[6:7]
  11754. //
  11755. // r.ArrS[3].x
  11756. bool AllowUnitySizeArraySection = true;
  11757. bool AllowWholeSizeArraySection = true;
  11758. while (!RelevantExpr) {
  11759. E = E->IgnoreParenImpCasts();
  11760. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  11761. if (!isa<VarDecl>(CurE->getDecl()))
  11762. return nullptr;
  11763. RelevantExpr = CurE;
  11764. // If we got a reference to a declaration, we should not expect any array
  11765. // section before that.
  11766. AllowUnitySizeArraySection = false;
  11767. AllowWholeSizeArraySection = false;
  11768. // Record the component.
  11769. CurComponents.emplace_back(CurE, CurE->getDecl());
  11770. } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  11771. Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  11772. if (isa<CXXThisExpr>(BaseE))
  11773. // We found a base expression: this->Val.
  11774. RelevantExpr = CurE;
  11775. else
  11776. E = BaseE;
  11777. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  11778. if (!NoDiagnose) {
  11779. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  11780. << CurE->getSourceRange();
  11781. return nullptr;
  11782. }
  11783. if (RelevantExpr)
  11784. return nullptr;
  11785. continue;
  11786. }
  11787. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  11788. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  11789. // A bit-field cannot appear in a map clause.
  11790. //
  11791. if (FD->isBitField()) {
  11792. if (!NoDiagnose) {
  11793. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  11794. << CurE->getSourceRange() << getOpenMPClauseName(CKind);
  11795. return nullptr;
  11796. }
  11797. if (RelevantExpr)
  11798. return nullptr;
  11799. continue;
  11800. }
  11801. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11802. // If the type of a list item is a reference to a type T then the type
  11803. // will be considered to be T for all purposes of this clause.
  11804. QualType CurType = BaseE->getType().getNonReferenceType();
  11805. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  11806. // A list item cannot be a variable that is a member of a structure with
  11807. // a union type.
  11808. //
  11809. if (CurType->isUnionType()) {
  11810. if (!NoDiagnose) {
  11811. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  11812. << CurE->getSourceRange();
  11813. return nullptr;
  11814. }
  11815. continue;
  11816. }
  11817. // If we got a member expression, we should not expect any array section
  11818. // before that:
  11819. //
  11820. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  11821. // If a list item is an element of a structure, only the rightmost symbol
  11822. // of the variable reference can be an array section.
  11823. //
  11824. AllowUnitySizeArraySection = false;
  11825. AllowWholeSizeArraySection = false;
  11826. // Record the component.
  11827. CurComponents.emplace_back(CurE, FD);
  11828. } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  11829. E = CurE->getBase()->IgnoreParenImpCasts();
  11830. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  11831. if (!NoDiagnose) {
  11832. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  11833. << 0 << CurE->getSourceRange();
  11834. return nullptr;
  11835. }
  11836. continue;
  11837. }
  11838. // If we got an array subscript that express the whole dimension we
  11839. // can have any array expressions before. If it only expressing part of
  11840. // the dimension, we can only have unitary-size array expressions.
  11841. if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
  11842. E->getType()))
  11843. AllowWholeSizeArraySection = false;
  11844. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  11845. Expr::EvalResult Result;
  11846. if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  11847. if (!Result.Val.getInt().isNullValue()) {
  11848. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  11849. diag::err_omp_invalid_map_this_expr);
  11850. SemaRef.Diag(CurE->getIdx()->getExprLoc(),
  11851. diag::note_omp_invalid_subscript_on_this_ptr_map);
  11852. }
  11853. }
  11854. RelevantExpr = TE;
  11855. }
  11856. // Record the component - we don't have any declaration associated.
  11857. CurComponents.emplace_back(CurE, nullptr);
  11858. } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  11859. assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
  11860. E = CurE->getBase()->IgnoreParenImpCasts();
  11861. QualType CurType =
  11862. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  11863. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  11864. // If the type of a list item is a reference to a type T then the type
  11865. // will be considered to be T for all purposes of this clause.
  11866. if (CurType->isReferenceType())
  11867. CurType = CurType->getPointeeType();
  11868. bool IsPointer = CurType->isAnyPointerType();
  11869. if (!IsPointer && !CurType->isArrayType()) {
  11870. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  11871. << 0 << CurE->getSourceRange();
  11872. return nullptr;
  11873. }
  11874. bool NotWhole =
  11875. checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
  11876. bool NotUnity =
  11877. checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
  11878. if (AllowWholeSizeArraySection) {
  11879. // Any array section is currently allowed. Allowing a whole size array
  11880. // section implies allowing a unity array section as well.
  11881. //
  11882. // If this array section refers to the whole dimension we can still
  11883. // accept other array sections before this one, except if the base is a
  11884. // pointer. Otherwise, only unitary sections are accepted.
  11885. if (NotWhole || IsPointer)
  11886. AllowWholeSizeArraySection = false;
  11887. } else if (AllowUnitySizeArraySection && NotUnity) {
  11888. // A unity or whole array section is not allowed and that is not
  11889. // compatible with the properties of the current array section.
  11890. SemaRef.Diag(
  11891. ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
  11892. << CurE->getSourceRange();
  11893. return nullptr;
  11894. }
  11895. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  11896. Expr::EvalResult ResultR;
  11897. Expr::EvalResult ResultL;
  11898. if (CurE->getLength()->EvaluateAsInt(ResultR,
  11899. SemaRef.getASTContext())) {
  11900. if (!ResultR.Val.getInt().isOneValue()) {
  11901. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  11902. diag::err_omp_invalid_map_this_expr);
  11903. SemaRef.Diag(CurE->getLength()->getExprLoc(),
  11904. diag::note_omp_invalid_length_on_this_ptr_mapping);
  11905. }
  11906. }
  11907. if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
  11908. ResultL, SemaRef.getASTContext())) {
  11909. if (!ResultL.Val.getInt().isNullValue()) {
  11910. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  11911. diag::err_omp_invalid_map_this_expr);
  11912. SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
  11913. diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
  11914. }
  11915. }
  11916. RelevantExpr = TE;
  11917. }
  11918. // Record the component - we don't have any declaration associated.
  11919. CurComponents.emplace_back(CurE, nullptr);
  11920. } else {
  11921. if (!NoDiagnose) {
  11922. // If nothing else worked, this is not a valid map clause expression.
  11923. SemaRef.Diag(
  11924. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  11925. << ERange;
  11926. }
  11927. return nullptr;
  11928. }
  11929. }
  11930. return RelevantExpr;
  11931. }
  11932. // Return true if expression E associated with value VD has conflicts with other
  11933. // map information.
  11934. static bool checkMapConflicts(
  11935. Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
  11936. bool CurrentRegionOnly,
  11937. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  11938. OpenMPClauseKind CKind) {
  11939. assert(VD && E);
  11940. SourceLocation ELoc = E->getExprLoc();
  11941. SourceRange ERange = E->getSourceRange();
  11942. // In order to easily check the conflicts we need to match each component of
  11943. // the expression under test with the components of the expressions that are
  11944. // already in the stack.
  11945. assert(!CurComponents.empty() && "Map clause expression with no components!");
  11946. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  11947. "Map clause expression with unexpected base!");
  11948. // Variables to help detecting enclosing problems in data environment nests.
  11949. bool IsEnclosedByDataEnvironmentExpr = false;
  11950. const Expr *EnclosingExpr = nullptr;
  11951. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  11952. VD, CurrentRegionOnly,
  11953. [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
  11954. ERange, CKind, &EnclosingExpr,
  11955. CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
  11956. StackComponents,
  11957. OpenMPClauseKind) {
  11958. assert(!StackComponents.empty() &&
  11959. "Map clause expression with no components!");
  11960. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  11961. "Map clause expression with unexpected base!");
  11962. (void)VD;
  11963. // The whole expression in the stack.
  11964. const Expr *RE = StackComponents.front().getAssociatedExpression();
  11965. // Expressions must start from the same base. Here we detect at which
  11966. // point both expressions diverge from each other and see if we can
  11967. // detect if the memory referred to both expressions is contiguous and
  11968. // do not overlap.
  11969. auto CI = CurComponents.rbegin();
  11970. auto CE = CurComponents.rend();
  11971. auto SI = StackComponents.rbegin();
  11972. auto SE = StackComponents.rend();
  11973. for (; CI != CE && SI != SE; ++CI, ++SI) {
  11974. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  11975. // At most one list item can be an array item derived from a given
  11976. // variable in map clauses of the same construct.
  11977. if (CurrentRegionOnly &&
  11978. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  11979. isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
  11980. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  11981. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
  11982. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  11983. diag::err_omp_multiple_array_items_in_map_clause)
  11984. << CI->getAssociatedExpression()->getSourceRange();
  11985. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  11986. diag::note_used_here)
  11987. << SI->getAssociatedExpression()->getSourceRange();
  11988. return true;
  11989. }
  11990. // Do both expressions have the same kind?
  11991. if (CI->getAssociatedExpression()->getStmtClass() !=
  11992. SI->getAssociatedExpression()->getStmtClass())
  11993. break;
  11994. // Are we dealing with different variables/fields?
  11995. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  11996. break;
  11997. }
  11998. // Check if the extra components of the expressions in the enclosing
  11999. // data environment are redundant for the current base declaration.
  12000. // If they are, the maps completely overlap, which is legal.
  12001. for (; SI != SE; ++SI) {
  12002. QualType Type;
  12003. if (const auto *ASE =
  12004. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  12005. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  12006. } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
  12007. SI->getAssociatedExpression())) {
  12008. const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
  12009. Type =
  12010. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  12011. }
  12012. if (Type.isNull() || Type->isAnyPointerType() ||
  12013. checkArrayExpressionDoesNotReferToWholeSize(
  12014. SemaRef, SI->getAssociatedExpression(), Type))
  12015. break;
  12016. }
  12017. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  12018. // List items of map clauses in the same construct must not share
  12019. // original storage.
  12020. //
  12021. // If the expressions are exactly the same or one is a subset of the
  12022. // other, it means they are sharing storage.
  12023. if (CI == CE && SI == SE) {
  12024. if (CurrentRegionOnly) {
  12025. if (CKind == OMPC_map) {
  12026. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  12027. } else {
  12028. assert(CKind == OMPC_to || CKind == OMPC_from);
  12029. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  12030. << ERange;
  12031. }
  12032. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  12033. << RE->getSourceRange();
  12034. return true;
  12035. }
  12036. // If we find the same expression in the enclosing data environment,
  12037. // that is legal.
  12038. IsEnclosedByDataEnvironmentExpr = true;
  12039. return false;
  12040. }
  12041. QualType DerivedType =
  12042. std::prev(CI)->getAssociatedDeclaration()->getType();
  12043. SourceLocation DerivedLoc =
  12044. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  12045. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  12046. // If the type of a list item is a reference to a type T then the type
  12047. // will be considered to be T for all purposes of this clause.
  12048. DerivedType = DerivedType.getNonReferenceType();
  12049. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  12050. // A variable for which the type is pointer and an array section
  12051. // derived from that variable must not appear as list items of map
  12052. // clauses of the same construct.
  12053. //
  12054. // Also, cover one of the cases in:
  12055. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  12056. // If any part of the original storage of a list item has corresponding
  12057. // storage in the device data environment, all of the original storage
  12058. // must have corresponding storage in the device data environment.
  12059. //
  12060. if (DerivedType->isAnyPointerType()) {
  12061. if (CI == CE || SI == SE) {
  12062. SemaRef.Diag(
  12063. DerivedLoc,
  12064. diag::err_omp_pointer_mapped_along_with_derived_section)
  12065. << DerivedLoc;
  12066. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  12067. << RE->getSourceRange();
  12068. return true;
  12069. }
  12070. if (CI->getAssociatedExpression()->getStmtClass() !=
  12071. SI->getAssociatedExpression()->getStmtClass() ||
  12072. CI->getAssociatedDeclaration()->getCanonicalDecl() ==
  12073. SI->getAssociatedDeclaration()->getCanonicalDecl()) {
  12074. assert(CI != CE && SI != SE);
  12075. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
  12076. << DerivedLoc;
  12077. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  12078. << RE->getSourceRange();
  12079. return true;
  12080. }
  12081. }
  12082. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  12083. // List items of map clauses in the same construct must not share
  12084. // original storage.
  12085. //
  12086. // An expression is a subset of the other.
  12087. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  12088. if (CKind == OMPC_map) {
  12089. if (CI != CE || SI != SE) {
  12090. // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
  12091. // a pointer.
  12092. auto Begin =
  12093. CI != CE ? CurComponents.begin() : StackComponents.begin();
  12094. auto End = CI != CE ? CurComponents.end() : StackComponents.end();
  12095. auto It = Begin;
  12096. while (It != End && !It->getAssociatedDeclaration())
  12097. std::advance(It, 1);
  12098. assert(It != End &&
  12099. "Expected at least one component with the declaration.");
  12100. if (It != Begin && It->getAssociatedDeclaration()
  12101. ->getType()
  12102. .getCanonicalType()
  12103. ->isAnyPointerType()) {
  12104. IsEnclosedByDataEnvironmentExpr = false;
  12105. EnclosingExpr = nullptr;
  12106. return false;
  12107. }
  12108. }
  12109. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  12110. } else {
  12111. assert(CKind == OMPC_to || CKind == OMPC_from);
  12112. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  12113. << ERange;
  12114. }
  12115. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  12116. << RE->getSourceRange();
  12117. return true;
  12118. }
  12119. // The current expression uses the same base as other expression in the
  12120. // data environment but does not contain it completely.
  12121. if (!CurrentRegionOnly && SI != SE)
  12122. EnclosingExpr = RE;
  12123. // The current expression is a subset of the expression in the data
  12124. // environment.
  12125. IsEnclosedByDataEnvironmentExpr |=
  12126. (!CurrentRegionOnly && CI != CE && SI == SE);
  12127. return false;
  12128. });
  12129. if (CurrentRegionOnly)
  12130. return FoundError;
  12131. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  12132. // If any part of the original storage of a list item has corresponding
  12133. // storage in the device data environment, all of the original storage must
  12134. // have corresponding storage in the device data environment.
  12135. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  12136. // If a list item is an element of a structure, and a different element of
  12137. // the structure has a corresponding list item in the device data environment
  12138. // prior to a task encountering the construct associated with the map clause,
  12139. // then the list item must also have a corresponding list item in the device
  12140. // data environment prior to the task encountering the construct.
  12141. //
  12142. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  12143. SemaRef.Diag(ELoc,
  12144. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  12145. << ERange;
  12146. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  12147. << EnclosingExpr->getSourceRange();
  12148. return true;
  12149. }
  12150. return FoundError;
  12151. }
  12152. // Look up the user-defined mapper given the mapper name and mapped type, and
  12153. // build a reference to it.
  12154. ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
  12155. CXXScopeSpec &MapperIdScopeSpec,
  12156. const DeclarationNameInfo &MapperId,
  12157. QualType Type, Expr *UnresolvedMapper) {
  12158. if (MapperIdScopeSpec.isInvalid())
  12159. return ExprError();
  12160. // Find all user-defined mappers with the given MapperId.
  12161. SmallVector<UnresolvedSet<8>, 4> Lookups;
  12162. LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
  12163. Lookup.suppressDiagnostics();
  12164. if (S) {
  12165. while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
  12166. NamedDecl *D = Lookup.getRepresentativeDecl();
  12167. while (S && !S->isDeclScope(D))
  12168. S = S->getParent();
  12169. if (S)
  12170. S = S->getParent();
  12171. Lookups.emplace_back();
  12172. Lookups.back().append(Lookup.begin(), Lookup.end());
  12173. Lookup.clear();
  12174. }
  12175. } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
  12176. // Extract the user-defined mappers with the given MapperId.
  12177. Lookups.push_back(UnresolvedSet<8>());
  12178. for (NamedDecl *D : ULE->decls()) {
  12179. auto *DMD = cast<OMPDeclareMapperDecl>(D);
  12180. assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
  12181. Lookups.back().addDecl(DMD);
  12182. }
  12183. }
  12184. // Defer the lookup for dependent types. The results will be passed through
  12185. // UnresolvedMapper on instantiation.
  12186. if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
  12187. Type->isInstantiationDependentType() ||
  12188. Type->containsUnexpandedParameterPack() ||
  12189. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  12190. return !D->isInvalidDecl() &&
  12191. (D->getType()->isDependentType() ||
  12192. D->getType()->isInstantiationDependentType() ||
  12193. D->getType()->containsUnexpandedParameterPack());
  12194. })) {
  12195. UnresolvedSet<8> URS;
  12196. for (const UnresolvedSet<8> &Set : Lookups) {
  12197. if (Set.empty())
  12198. continue;
  12199. URS.append(Set.begin(), Set.end());
  12200. }
  12201. return UnresolvedLookupExpr::Create(
  12202. SemaRef.Context, /*NamingClass=*/nullptr,
  12203. MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
  12204. /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
  12205. }
  12206. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  12207. // The type must be of struct, union or class type in C and C++
  12208. if (!Type->isStructureOrClassType() && !Type->isUnionType())
  12209. return ExprEmpty();
  12210. SourceLocation Loc = MapperId.getLoc();
  12211. // Perform argument dependent lookup.
  12212. if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
  12213. argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
  12214. // Return the first user-defined mapper with the desired type.
  12215. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  12216. Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
  12217. if (!D->isInvalidDecl() &&
  12218. SemaRef.Context.hasSameType(D->getType(), Type))
  12219. return D;
  12220. return nullptr;
  12221. }))
  12222. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  12223. // Find the first user-defined mapper with a type derived from the desired
  12224. // type.
  12225. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  12226. Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
  12227. if (!D->isInvalidDecl() &&
  12228. SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
  12229. !Type.isMoreQualifiedThan(D->getType()))
  12230. return D;
  12231. return nullptr;
  12232. })) {
  12233. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  12234. /*DetectVirtual=*/false);
  12235. if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
  12236. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  12237. VD->getType().getUnqualifiedType()))) {
  12238. if (SemaRef.CheckBaseClassAccess(
  12239. Loc, VD->getType(), Type, Paths.front(),
  12240. /*DiagID=*/0) != Sema::AR_inaccessible) {
  12241. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  12242. }
  12243. }
  12244. }
  12245. }
  12246. // Report error if a mapper is specified, but cannot be found.
  12247. if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
  12248. SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
  12249. << Type << MapperId.getName();
  12250. return ExprError();
  12251. }
  12252. return ExprEmpty();
  12253. }
  12254. namespace {
  12255. // Utility struct that gathers all the related lists associated with a mappable
  12256. // expression.
  12257. struct MappableVarListInfo {
  12258. // The list of expressions.
  12259. ArrayRef<Expr *> VarList;
  12260. // The list of processed expressions.
  12261. SmallVector<Expr *, 16> ProcessedVarList;
  12262. // The mappble components for each expression.
  12263. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  12264. // The base declaration of the variable.
  12265. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  12266. // The reference to the user-defined mapper associated with every expression.
  12267. SmallVector<Expr *, 16> UDMapperList;
  12268. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  12269. // We have a list of components and base declarations for each entry in the
  12270. // variable list.
  12271. VarComponents.reserve(VarList.size());
  12272. VarBaseDeclarations.reserve(VarList.size());
  12273. }
  12274. };
  12275. }
  12276. // Check the validity of the provided variable list for the provided clause kind
  12277. // \a CKind. In the check process the valid expressions, mappable expression
  12278. // components, variables, and user-defined mappers are extracted and used to
  12279. // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
  12280. // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
  12281. // and \a MapperId are expected to be valid if the clause kind is 'map'.
  12282. static void checkMappableExpressionList(
  12283. Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
  12284. MappableVarListInfo &MVLI, SourceLocation StartLoc,
  12285. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
  12286. ArrayRef<Expr *> UnresolvedMappers,
  12287. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  12288. bool IsMapTypeImplicit = false) {
  12289. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  12290. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  12291. "Unexpected clause kind with mappable expressions!");
  12292. // If the identifier of user-defined mapper is not specified, it is "default".
  12293. // We do not change the actual name in this clause to distinguish whether a
  12294. // mapper is specified explicitly, i.e., it is not explicitly specified when
  12295. // MapperId.getName() is empty.
  12296. if (!MapperId.getName() || MapperId.getName().isEmpty()) {
  12297. auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
  12298. MapperId.setName(DeclNames.getIdentifier(
  12299. &SemaRef.getASTContext().Idents.get("default")));
  12300. }
  12301. // Iterators to find the current unresolved mapper expression.
  12302. auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
  12303. bool UpdateUMIt = false;
  12304. Expr *UnresolvedMapper = nullptr;
  12305. // Keep track of the mappable components and base declarations in this clause.
  12306. // Each entry in the list is going to have a list of components associated. We
  12307. // record each set of the components so that we can build the clause later on.
  12308. // In the end we should have the same amount of declarations and component
  12309. // lists.
  12310. for (Expr *RE : MVLI.VarList) {
  12311. assert(RE && "Null expr in omp to/from/map clause");
  12312. SourceLocation ELoc = RE->getExprLoc();
  12313. // Find the current unresolved mapper expression.
  12314. if (UpdateUMIt && UMIt != UMEnd) {
  12315. UMIt++;
  12316. assert(
  12317. UMIt != UMEnd &&
  12318. "Expect the size of UnresolvedMappers to match with that of VarList");
  12319. }
  12320. UpdateUMIt = true;
  12321. if (UMIt != UMEnd)
  12322. UnresolvedMapper = *UMIt;
  12323. const Expr *VE = RE->IgnoreParenLValueCasts();
  12324. if (VE->isValueDependent() || VE->isTypeDependent() ||
  12325. VE->isInstantiationDependent() ||
  12326. VE->containsUnexpandedParameterPack()) {
  12327. // Try to find the associated user-defined mapper.
  12328. ExprResult ER = buildUserDefinedMapperRef(
  12329. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  12330. VE->getType().getCanonicalType(), UnresolvedMapper);
  12331. if (ER.isInvalid())
  12332. continue;
  12333. MVLI.UDMapperList.push_back(ER.get());
  12334. // We can only analyze this information once the missing information is
  12335. // resolved.
  12336. MVLI.ProcessedVarList.push_back(RE);
  12337. continue;
  12338. }
  12339. Expr *SimpleExpr = RE->IgnoreParenCasts();
  12340. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  12341. SemaRef.Diag(ELoc,
  12342. diag::err_omp_expected_named_var_member_or_array_expression)
  12343. << RE->getSourceRange();
  12344. continue;
  12345. }
  12346. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  12347. ValueDecl *CurDeclaration = nullptr;
  12348. // Obtain the array or member expression bases if required. Also, fill the
  12349. // components array with all the components identified in the process.
  12350. const Expr *BE = checkMapClauseExpressionBase(
  12351. SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
  12352. if (!BE)
  12353. continue;
  12354. assert(!CurComponents.empty() &&
  12355. "Invalid mappable expression information.");
  12356. if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
  12357. // Add store "this" pointer to class in DSAStackTy for future checking
  12358. DSAS->addMappedClassesQualTypes(TE->getType());
  12359. // Try to find the associated user-defined mapper.
  12360. ExprResult ER = buildUserDefinedMapperRef(
  12361. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  12362. VE->getType().getCanonicalType(), UnresolvedMapper);
  12363. if (ER.isInvalid())
  12364. continue;
  12365. MVLI.UDMapperList.push_back(ER.get());
  12366. // Skip restriction checking for variable or field declarations
  12367. MVLI.ProcessedVarList.push_back(RE);
  12368. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12369. MVLI.VarComponents.back().append(CurComponents.begin(),
  12370. CurComponents.end());
  12371. MVLI.VarBaseDeclarations.push_back(nullptr);
  12372. continue;
  12373. }
  12374. // For the following checks, we rely on the base declaration which is
  12375. // expected to be associated with the last component. The declaration is
  12376. // expected to be a variable or a field (if 'this' is being mapped).
  12377. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  12378. assert(CurDeclaration && "Null decl on map clause.");
  12379. assert(
  12380. CurDeclaration->isCanonicalDecl() &&
  12381. "Expecting components to have associated only canonical declarations.");
  12382. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  12383. const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  12384. assert((VD || FD) && "Only variables or fields are expected here!");
  12385. (void)FD;
  12386. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  12387. // threadprivate variables cannot appear in a map clause.
  12388. // OpenMP 4.5 [2.10.5, target update Construct]
  12389. // threadprivate variables cannot appear in a from clause.
  12390. if (VD && DSAS->isThreadPrivate(VD)) {
  12391. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  12392. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  12393. << getOpenMPClauseName(CKind);
  12394. reportOriginalDsa(SemaRef, DSAS, VD, DVar);
  12395. continue;
  12396. }
  12397. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  12398. // A list item cannot appear in both a map clause and a data-sharing
  12399. // attribute clause on the same construct.
  12400. // Check conflicts with other map clause expressions. We check the conflicts
  12401. // with the current construct separately from the enclosing data
  12402. // environment, because the restrictions are different. We only have to
  12403. // check conflicts across regions for the map clauses.
  12404. if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  12405. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  12406. break;
  12407. if (CKind == OMPC_map &&
  12408. checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  12409. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  12410. break;
  12411. // OpenMP 4.5 [2.10.5, target update Construct]
  12412. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  12413. // If the type of a list item is a reference to a type T then the type will
  12414. // be considered to be T for all purposes of this clause.
  12415. auto I = llvm::find_if(
  12416. CurComponents,
  12417. [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
  12418. return MC.getAssociatedDeclaration();
  12419. });
  12420. assert(I != CurComponents.end() && "Null decl on map clause.");
  12421. QualType Type =
  12422. I->getAssociatedDeclaration()->getType().getNonReferenceType();
  12423. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  12424. // A list item in a to or from clause must have a mappable type.
  12425. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  12426. // A list item must have a mappable type.
  12427. if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  12428. DSAS, Type))
  12429. continue;
  12430. if (CKind == OMPC_map) {
  12431. // target enter data
  12432. // OpenMP [2.10.2, Restrictions, p. 99]
  12433. // A map-type must be specified in all map clauses and must be either
  12434. // to or alloc.
  12435. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  12436. if (DKind == OMPD_target_enter_data &&
  12437. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  12438. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  12439. << (IsMapTypeImplicit ? 1 : 0)
  12440. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  12441. << getOpenMPDirectiveName(DKind);
  12442. continue;
  12443. }
  12444. // target exit_data
  12445. // OpenMP [2.10.3, Restrictions, p. 102]
  12446. // A map-type must be specified in all map clauses and must be either
  12447. // from, release, or delete.
  12448. if (DKind == OMPD_target_exit_data &&
  12449. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  12450. MapType == OMPC_MAP_delete)) {
  12451. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  12452. << (IsMapTypeImplicit ? 1 : 0)
  12453. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  12454. << getOpenMPDirectiveName(DKind);
  12455. continue;
  12456. }
  12457. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  12458. // A list item cannot appear in both a map clause and a data-sharing
  12459. // attribute clause on the same construct
  12460. if (VD && isOpenMPTargetExecutionDirective(DKind)) {
  12461. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  12462. if (isOpenMPPrivate(DVar.CKind)) {
  12463. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  12464. << getOpenMPClauseName(DVar.CKind)
  12465. << getOpenMPClauseName(OMPC_map)
  12466. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  12467. reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
  12468. continue;
  12469. }
  12470. }
  12471. }
  12472. // Try to find the associated user-defined mapper.
  12473. ExprResult ER = buildUserDefinedMapperRef(
  12474. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  12475. Type.getCanonicalType(), UnresolvedMapper);
  12476. if (ER.isInvalid())
  12477. continue;
  12478. MVLI.UDMapperList.push_back(ER.get());
  12479. // Save the current expression.
  12480. MVLI.ProcessedVarList.push_back(RE);
  12481. // Store the components in the stack so that they can be used to check
  12482. // against other clauses later on.
  12483. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  12484. /*WhereFoundClauseKind=*/OMPC_map);
  12485. // Save the components and declaration to create the clause. For purposes of
  12486. // the clause creation, any component list that has has base 'this' uses
  12487. // null as base declaration.
  12488. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  12489. MVLI.VarComponents.back().append(CurComponents.begin(),
  12490. CurComponents.end());
  12491. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  12492. : CurDeclaration);
  12493. }
  12494. }
  12495. OMPClause *Sema::ActOnOpenMPMapClause(
  12496. ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  12497. ArrayRef<SourceLocation> MapTypeModifiersLoc,
  12498. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
  12499. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
  12500. SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
  12501. const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
  12502. OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
  12503. OMPC_MAP_MODIFIER_unknown,
  12504. OMPC_MAP_MODIFIER_unknown};
  12505. SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
  12506. // Process map-type-modifiers, flag errors for duplicate modifiers.
  12507. unsigned Count = 0;
  12508. for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
  12509. if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
  12510. llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
  12511. Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
  12512. continue;
  12513. }
  12514. assert(Count < OMPMapClause::NumberOfModifiers &&
  12515. "Modifiers exceed the allowed number of map type modifiers");
  12516. Modifiers[Count] = MapTypeModifiers[I];
  12517. ModifiersLoc[Count] = MapTypeModifiersLoc[I];
  12518. ++Count;
  12519. }
  12520. MappableVarListInfo MVLI(VarList);
  12521. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
  12522. MapperIdScopeSpec, MapperId, UnresolvedMappers,
  12523. MapType, IsMapTypeImplicit);
  12524. // We need to produce a map clause even if we don't have variables so that
  12525. // other diagnostics related with non-existing map clauses are accurate.
  12526. return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
  12527. MVLI.VarBaseDeclarations, MVLI.VarComponents,
  12528. MVLI.UDMapperList, Modifiers, ModifiersLoc,
  12529. MapperIdScopeSpec.getWithLocInContext(Context),
  12530. MapperId, MapType, IsMapTypeImplicit, MapLoc);
  12531. }
  12532. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  12533. TypeResult ParsedType) {
  12534. assert(ParsedType.isUsable());
  12535. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  12536. if (ReductionType.isNull())
  12537. return QualType();
  12538. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  12539. // A type name in a declare reduction directive cannot be a function type, an
  12540. // array type, a reference type, or a type qualified with const, volatile or
  12541. // restrict.
  12542. if (ReductionType.hasQualifiers()) {
  12543. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  12544. return QualType();
  12545. }
  12546. if (ReductionType->isFunctionType()) {
  12547. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  12548. return QualType();
  12549. }
  12550. if (ReductionType->isReferenceType()) {
  12551. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  12552. return QualType();
  12553. }
  12554. if (ReductionType->isArrayType()) {
  12555. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  12556. return QualType();
  12557. }
  12558. return ReductionType;
  12559. }
  12560. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  12561. Scope *S, DeclContext *DC, DeclarationName Name,
  12562. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  12563. AccessSpecifier AS, Decl *PrevDeclInScope) {
  12564. SmallVector<Decl *, 8> Decls;
  12565. Decls.reserve(ReductionTypes.size());
  12566. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  12567. forRedeclarationInCurContext());
  12568. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  12569. // A reduction-identifier may not be re-declared in the current scope for the
  12570. // same type or for a type that is compatible according to the base language
  12571. // rules.
  12572. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  12573. OMPDeclareReductionDecl *PrevDRD = nullptr;
  12574. bool InCompoundScope = true;
  12575. if (S != nullptr) {
  12576. // Find previous declaration with the same name not referenced in other
  12577. // declarations.
  12578. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  12579. InCompoundScope =
  12580. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  12581. LookupName(Lookup, S);
  12582. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  12583. /*AllowInlineNamespace=*/false);
  12584. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  12585. LookupResult::Filter Filter = Lookup.makeFilter();
  12586. while (Filter.hasNext()) {
  12587. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  12588. if (InCompoundScope) {
  12589. auto I = UsedAsPrevious.find(PrevDecl);
  12590. if (I == UsedAsPrevious.end())
  12591. UsedAsPrevious[PrevDecl] = false;
  12592. if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
  12593. UsedAsPrevious[D] = true;
  12594. }
  12595. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  12596. PrevDecl->getLocation();
  12597. }
  12598. Filter.done();
  12599. if (InCompoundScope) {
  12600. for (const auto &PrevData : UsedAsPrevious) {
  12601. if (!PrevData.second) {
  12602. PrevDRD = PrevData.first;
  12603. break;
  12604. }
  12605. }
  12606. }
  12607. } else if (PrevDeclInScope != nullptr) {
  12608. auto *PrevDRDInScope = PrevDRD =
  12609. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  12610. do {
  12611. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  12612. PrevDRDInScope->getLocation();
  12613. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  12614. } while (PrevDRDInScope != nullptr);
  12615. }
  12616. for (const auto &TyData : ReductionTypes) {
  12617. const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  12618. bool Invalid = false;
  12619. if (I != PreviousRedeclTypes.end()) {
  12620. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  12621. << TyData.first;
  12622. Diag(I->second, diag::note_previous_definition);
  12623. Invalid = true;
  12624. }
  12625. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  12626. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  12627. Name, TyData.first, PrevDRD);
  12628. DC->addDecl(DRD);
  12629. DRD->setAccess(AS);
  12630. Decls.push_back(DRD);
  12631. if (Invalid)
  12632. DRD->setInvalidDecl();
  12633. else
  12634. PrevDRD = DRD;
  12635. }
  12636. return DeclGroupPtrTy::make(
  12637. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  12638. }
  12639. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  12640. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12641. // Enter new function scope.
  12642. PushFunctionScope();
  12643. setFunctionHasBranchProtectedScope();
  12644. getCurFunction()->setHasOMPDeclareReductionCombiner();
  12645. if (S != nullptr)
  12646. PushDeclContext(S, DRD);
  12647. else
  12648. CurContext = DRD;
  12649. PushExpressionEvaluationContext(
  12650. ExpressionEvaluationContext::PotentiallyEvaluated);
  12651. QualType ReductionType = DRD->getType();
  12652. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  12653. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  12654. // uses semantics of argument handles by value, but it should be passed by
  12655. // reference. C lang does not support references, so pass all parameters as
  12656. // pointers.
  12657. // Create 'T omp_in;' variable.
  12658. VarDecl *OmpInParm =
  12659. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  12660. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  12661. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  12662. // uses semantics of argument handles by value, but it should be passed by
  12663. // reference. C lang does not support references, so pass all parameters as
  12664. // pointers.
  12665. // Create 'T omp_out;' variable.
  12666. VarDecl *OmpOutParm =
  12667. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  12668. if (S != nullptr) {
  12669. PushOnScopeChains(OmpInParm, S);
  12670. PushOnScopeChains(OmpOutParm, S);
  12671. } else {
  12672. DRD->addDecl(OmpInParm);
  12673. DRD->addDecl(OmpOutParm);
  12674. }
  12675. Expr *InE =
  12676. ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
  12677. Expr *OutE =
  12678. ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
  12679. DRD->setCombinerData(InE, OutE);
  12680. }
  12681. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  12682. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12683. DiscardCleanupsInEvaluationContext();
  12684. PopExpressionEvaluationContext();
  12685. PopDeclContext();
  12686. PopFunctionScopeInfo();
  12687. if (Combiner != nullptr)
  12688. DRD->setCombiner(Combiner);
  12689. else
  12690. DRD->setInvalidDecl();
  12691. }
  12692. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  12693. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12694. // Enter new function scope.
  12695. PushFunctionScope();
  12696. setFunctionHasBranchProtectedScope();
  12697. if (S != nullptr)
  12698. PushDeclContext(S, DRD);
  12699. else
  12700. CurContext = DRD;
  12701. PushExpressionEvaluationContext(
  12702. ExpressionEvaluationContext::PotentiallyEvaluated);
  12703. QualType ReductionType = DRD->getType();
  12704. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  12705. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  12706. // uses semantics of argument handles by value, but it should be passed by
  12707. // reference. C lang does not support references, so pass all parameters as
  12708. // pointers.
  12709. // Create 'T omp_priv;' variable.
  12710. VarDecl *OmpPrivParm =
  12711. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  12712. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  12713. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  12714. // uses semantics of argument handles by value, but it should be passed by
  12715. // reference. C lang does not support references, so pass all parameters as
  12716. // pointers.
  12717. // Create 'T omp_orig;' variable.
  12718. VarDecl *OmpOrigParm =
  12719. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  12720. if (S != nullptr) {
  12721. PushOnScopeChains(OmpPrivParm, S);
  12722. PushOnScopeChains(OmpOrigParm, S);
  12723. } else {
  12724. DRD->addDecl(OmpPrivParm);
  12725. DRD->addDecl(OmpOrigParm);
  12726. }
  12727. Expr *OrigE =
  12728. ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
  12729. Expr *PrivE =
  12730. ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
  12731. DRD->setInitializerData(OrigE, PrivE);
  12732. return OmpPrivParm;
  12733. }
  12734. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  12735. VarDecl *OmpPrivParm) {
  12736. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  12737. DiscardCleanupsInEvaluationContext();
  12738. PopExpressionEvaluationContext();
  12739. PopDeclContext();
  12740. PopFunctionScopeInfo();
  12741. if (Initializer != nullptr) {
  12742. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  12743. } else if (OmpPrivParm->hasInit()) {
  12744. DRD->setInitializer(OmpPrivParm->getInit(),
  12745. OmpPrivParm->isDirectInit()
  12746. ? OMPDeclareReductionDecl::DirectInit
  12747. : OMPDeclareReductionDecl::CopyInit);
  12748. } else {
  12749. DRD->setInvalidDecl();
  12750. }
  12751. }
  12752. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  12753. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  12754. for (Decl *D : DeclReductions.get()) {
  12755. if (IsValid) {
  12756. if (S)
  12757. PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
  12758. /*AddToContext=*/false);
  12759. } else {
  12760. D->setInvalidDecl();
  12761. }
  12762. }
  12763. return DeclReductions;
  12764. }
  12765. TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
  12766. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12767. QualType T = TInfo->getType();
  12768. if (D.isInvalidType())
  12769. return true;
  12770. if (getLangOpts().CPlusPlus) {
  12771. // Check that there are no default arguments (C++ only).
  12772. CheckExtraCXXDefaultArguments(D);
  12773. }
  12774. return CreateParsedType(T, TInfo);
  12775. }
  12776. QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
  12777. TypeResult ParsedType) {
  12778. assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
  12779. QualType MapperType = GetTypeFromParser(ParsedType.get());
  12780. assert(!MapperType.isNull() && "Expect valid mapper type");
  12781. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  12782. // The type must be of struct, union or class type in C and C++
  12783. if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
  12784. Diag(TyLoc, diag::err_omp_mapper_wrong_type);
  12785. return QualType();
  12786. }
  12787. return MapperType;
  12788. }
  12789. OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
  12790. Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
  12791. SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
  12792. Decl *PrevDeclInScope) {
  12793. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
  12794. forRedeclarationInCurContext());
  12795. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  12796. // A mapper-identifier may not be redeclared in the current scope for the
  12797. // same type or for a type that is compatible according to the base language
  12798. // rules.
  12799. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  12800. OMPDeclareMapperDecl *PrevDMD = nullptr;
  12801. bool InCompoundScope = true;
  12802. if (S != nullptr) {
  12803. // Find previous declaration with the same name not referenced in other
  12804. // declarations.
  12805. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  12806. InCompoundScope =
  12807. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  12808. LookupName(Lookup, S);
  12809. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  12810. /*AllowInlineNamespace=*/false);
  12811. llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
  12812. LookupResult::Filter Filter = Lookup.makeFilter();
  12813. while (Filter.hasNext()) {
  12814. auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
  12815. if (InCompoundScope) {
  12816. auto I = UsedAsPrevious.find(PrevDecl);
  12817. if (I == UsedAsPrevious.end())
  12818. UsedAsPrevious[PrevDecl] = false;
  12819. if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
  12820. UsedAsPrevious[D] = true;
  12821. }
  12822. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  12823. PrevDecl->getLocation();
  12824. }
  12825. Filter.done();
  12826. if (InCompoundScope) {
  12827. for (const auto &PrevData : UsedAsPrevious) {
  12828. if (!PrevData.second) {
  12829. PrevDMD = PrevData.first;
  12830. break;
  12831. }
  12832. }
  12833. }
  12834. } else if (PrevDeclInScope) {
  12835. auto *PrevDMDInScope = PrevDMD =
  12836. cast<OMPDeclareMapperDecl>(PrevDeclInScope);
  12837. do {
  12838. PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
  12839. PrevDMDInScope->getLocation();
  12840. PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
  12841. } while (PrevDMDInScope != nullptr);
  12842. }
  12843. const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
  12844. bool Invalid = false;
  12845. if (I != PreviousRedeclTypes.end()) {
  12846. Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
  12847. << MapperType << Name;
  12848. Diag(I->second, diag::note_previous_definition);
  12849. Invalid = true;
  12850. }
  12851. auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
  12852. MapperType, VN, PrevDMD);
  12853. DC->addDecl(DMD);
  12854. DMD->setAccess(AS);
  12855. if (Invalid)
  12856. DMD->setInvalidDecl();
  12857. // Enter new function scope.
  12858. PushFunctionScope();
  12859. setFunctionHasBranchProtectedScope();
  12860. CurContext = DMD;
  12861. return DMD;
  12862. }
  12863. void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
  12864. Scope *S,
  12865. QualType MapperType,
  12866. SourceLocation StartLoc,
  12867. DeclarationName VN) {
  12868. VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
  12869. if (S)
  12870. PushOnScopeChains(VD, S);
  12871. else
  12872. DMD->addDecl(VD);
  12873. Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
  12874. DMD->setMapperVarRef(MapperVarRefExpr);
  12875. }
  12876. Sema::DeclGroupPtrTy
  12877. Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
  12878. ArrayRef<OMPClause *> ClauseList) {
  12879. PopDeclContext();
  12880. PopFunctionScopeInfo();
  12881. if (D) {
  12882. if (S)
  12883. PushOnScopeChains(D, S, /*AddToContext=*/false);
  12884. D->CreateClauses(Context, ClauseList);
  12885. }
  12886. return DeclGroupPtrTy::make(DeclGroupRef(D));
  12887. }
  12888. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  12889. SourceLocation StartLoc,
  12890. SourceLocation LParenLoc,
  12891. SourceLocation EndLoc) {
  12892. Expr *ValExpr = NumTeams;
  12893. Stmt *HelperValStmt = nullptr;
  12894. // OpenMP [teams Constrcut, Restrictions]
  12895. // The num_teams expression must evaluate to a positive integer value.
  12896. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  12897. /*StrictlyPositive=*/true))
  12898. return nullptr;
  12899. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  12900. OpenMPDirectiveKind CaptureRegion =
  12901. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
  12902. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  12903. ValExpr = MakeFullExpr(ValExpr).get();
  12904. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  12905. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  12906. HelperValStmt = buildPreInits(Context, Captures);
  12907. }
  12908. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  12909. StartLoc, LParenLoc, EndLoc);
  12910. }
  12911. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  12912. SourceLocation StartLoc,
  12913. SourceLocation LParenLoc,
  12914. SourceLocation EndLoc) {
  12915. Expr *ValExpr = ThreadLimit;
  12916. Stmt *HelperValStmt = nullptr;
  12917. // OpenMP [teams Constrcut, Restrictions]
  12918. // The thread_limit expression must evaluate to a positive integer value.
  12919. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  12920. /*StrictlyPositive=*/true))
  12921. return nullptr;
  12922. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  12923. OpenMPDirectiveKind CaptureRegion =
  12924. getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
  12925. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  12926. ValExpr = MakeFullExpr(ValExpr).get();
  12927. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  12928. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  12929. HelperValStmt = buildPreInits(Context, Captures);
  12930. }
  12931. return new (Context) OMPThreadLimitClause(
  12932. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  12933. }
  12934. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  12935. SourceLocation StartLoc,
  12936. SourceLocation LParenLoc,
  12937. SourceLocation EndLoc) {
  12938. Expr *ValExpr = Priority;
  12939. // OpenMP [2.9.1, task Constrcut]
  12940. // The priority-value is a non-negative numerical scalar expression.
  12941. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  12942. /*StrictlyPositive=*/false))
  12943. return nullptr;
  12944. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  12945. }
  12946. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  12947. SourceLocation StartLoc,
  12948. SourceLocation LParenLoc,
  12949. SourceLocation EndLoc) {
  12950. Expr *ValExpr = Grainsize;
  12951. // OpenMP [2.9.2, taskloop Constrcut]
  12952. // The parameter of the grainsize clause must be a positive integer
  12953. // expression.
  12954. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  12955. /*StrictlyPositive=*/true))
  12956. return nullptr;
  12957. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  12958. }
  12959. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  12960. SourceLocation StartLoc,
  12961. SourceLocation LParenLoc,
  12962. SourceLocation EndLoc) {
  12963. Expr *ValExpr = NumTasks;
  12964. // OpenMP [2.9.2, taskloop Constrcut]
  12965. // The parameter of the num_tasks clause must be a positive integer
  12966. // expression.
  12967. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  12968. /*StrictlyPositive=*/true))
  12969. return nullptr;
  12970. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  12971. }
  12972. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  12973. SourceLocation LParenLoc,
  12974. SourceLocation EndLoc) {
  12975. // OpenMP [2.13.2, critical construct, Description]
  12976. // ... where hint-expression is an integer constant expression that evaluates
  12977. // to a valid lock hint.
  12978. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  12979. if (HintExpr.isInvalid())
  12980. return nullptr;
  12981. return new (Context)
  12982. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  12983. }
  12984. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  12985. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  12986. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  12987. SourceLocation EndLoc) {
  12988. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  12989. std::string Values;
  12990. Values += "'";
  12991. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  12992. Values += "'";
  12993. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  12994. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  12995. return nullptr;
  12996. }
  12997. Expr *ValExpr = ChunkSize;
  12998. Stmt *HelperValStmt = nullptr;
  12999. if (ChunkSize) {
  13000. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  13001. !ChunkSize->isInstantiationDependent() &&
  13002. !ChunkSize->containsUnexpandedParameterPack()) {
  13003. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  13004. ExprResult Val =
  13005. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  13006. if (Val.isInvalid())
  13007. return nullptr;
  13008. ValExpr = Val.get();
  13009. // OpenMP [2.7.1, Restrictions]
  13010. // chunk_size must be a loop invariant integer expression with a positive
  13011. // value.
  13012. llvm::APSInt Result;
  13013. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  13014. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  13015. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  13016. << "dist_schedule" << ChunkSize->getSourceRange();
  13017. return nullptr;
  13018. }
  13019. } else if (getOpenMPCaptureRegionForClause(
  13020. DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
  13021. OMPD_unknown &&
  13022. !CurContext->isDependentContext()) {
  13023. ValExpr = MakeFullExpr(ValExpr).get();
  13024. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  13025. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  13026. HelperValStmt = buildPreInits(Context, Captures);
  13027. }
  13028. }
  13029. }
  13030. return new (Context)
  13031. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  13032. Kind, ValExpr, HelperValStmt);
  13033. }
  13034. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  13035. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  13036. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  13037. SourceLocation KindLoc, SourceLocation EndLoc) {
  13038. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  13039. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
  13040. std::string Value;
  13041. SourceLocation Loc;
  13042. Value += "'";
  13043. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  13044. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  13045. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  13046. Loc = MLoc;
  13047. } else {
  13048. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  13049. OMPC_DEFAULTMAP_scalar);
  13050. Loc = KindLoc;
  13051. }
  13052. Value += "'";
  13053. Diag(Loc, diag::err_omp_unexpected_clause_value)
  13054. << Value << getOpenMPClauseName(OMPC_defaultmap);
  13055. return nullptr;
  13056. }
  13057. DSAStack->setDefaultDMAToFromScalar(StartLoc);
  13058. return new (Context)
  13059. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  13060. }
  13061. bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
  13062. DeclContext *CurLexicalContext = getCurLexicalContext();
  13063. if (!CurLexicalContext->isFileContext() &&
  13064. !CurLexicalContext->isExternCContext() &&
  13065. !CurLexicalContext->isExternCXXContext() &&
  13066. !isa<CXXRecordDecl>(CurLexicalContext) &&
  13067. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  13068. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  13069. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  13070. Diag(Loc, diag::err_omp_region_not_file_context);
  13071. return false;
  13072. }
  13073. ++DeclareTargetNestingLevel;
  13074. return true;
  13075. }
  13076. void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
  13077. assert(DeclareTargetNestingLevel > 0 &&
  13078. "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
  13079. --DeclareTargetNestingLevel;
  13080. }
  13081. void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
  13082. CXXScopeSpec &ScopeSpec,
  13083. const DeclarationNameInfo &Id,
  13084. OMPDeclareTargetDeclAttr::MapTypeTy MT,
  13085. NamedDeclSetType &SameDirectiveDecls) {
  13086. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  13087. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  13088. if (Lookup.isAmbiguous())
  13089. return;
  13090. Lookup.suppressDiagnostics();
  13091. if (!Lookup.isSingleResult()) {
  13092. if (TypoCorrection Corrected =
  13093. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
  13094. llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
  13095. CTK_ErrorRecovery)) {
  13096. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  13097. << Id.getName());
  13098. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  13099. return;
  13100. }
  13101. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  13102. return;
  13103. }
  13104. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  13105. if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
  13106. isa<FunctionTemplateDecl>(ND)) {
  13107. if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
  13108. Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
  13109. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  13110. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  13111. cast<ValueDecl>(ND));
  13112. if (!Res) {
  13113. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
  13114. ND->addAttr(A);
  13115. if (ASTMutationListener *ML = Context.getASTMutationListener())
  13116. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  13117. checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
  13118. } else if (*Res != MT) {
  13119. Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
  13120. << Id.getName();
  13121. }
  13122. } else {
  13123. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  13124. }
  13125. }
  13126. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  13127. Sema &SemaRef, Decl *D) {
  13128. if (!D || !isa<VarDecl>(D))
  13129. return;
  13130. auto *VD = cast<VarDecl>(D);
  13131. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  13132. return;
  13133. SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
  13134. SemaRef.Diag(SL, diag::note_used_here) << SR;
  13135. }
  13136. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  13137. Sema &SemaRef, DSAStackTy *Stack,
  13138. ValueDecl *VD) {
  13139. return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
  13140. checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
  13141. /*FullCheck=*/false);
  13142. }
  13143. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
  13144. SourceLocation IdLoc) {
  13145. if (!D || D->isInvalidDecl())
  13146. return;
  13147. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  13148. SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
  13149. if (auto *VD = dyn_cast<VarDecl>(D)) {
  13150. // Only global variables can be marked as declare target.
  13151. if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
  13152. !VD->isStaticDataMember())
  13153. return;
  13154. // 2.10.6: threadprivate variable cannot appear in a declare target
  13155. // directive.
  13156. if (DSAStack->isThreadPrivate(VD)) {
  13157. Diag(SL, diag::err_omp_threadprivate_in_target);
  13158. reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  13159. return;
  13160. }
  13161. }
  13162. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  13163. D = FTD->getTemplatedDecl();
  13164. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  13165. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  13166. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
  13167. if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  13168. assert(IdLoc.isValid() && "Source location is expected");
  13169. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  13170. Diag(FD->getLocation(), diag::note_defined_here) << FD;
  13171. return;
  13172. }
  13173. }
  13174. if (auto *VD = dyn_cast<ValueDecl>(D)) {
  13175. // Problem if any with var declared with incomplete type will be reported
  13176. // as normal, so no need to check it here.
  13177. if ((E || !VD->getType()->isIncompleteType()) &&
  13178. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
  13179. return;
  13180. if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
  13181. // Checking declaration inside declare target region.
  13182. if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
  13183. isa<FunctionTemplateDecl>(D)) {
  13184. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  13185. Context, OMPDeclareTargetDeclAttr::MT_To);
  13186. D->addAttr(A);
  13187. if (ASTMutationListener *ML = Context.getASTMutationListener())
  13188. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  13189. }
  13190. return;
  13191. }
  13192. }
  13193. if (!E)
  13194. return;
  13195. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  13196. }
  13197. OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
  13198. CXXScopeSpec &MapperIdScopeSpec,
  13199. DeclarationNameInfo &MapperId,
  13200. const OMPVarListLocTy &Locs,
  13201. ArrayRef<Expr *> UnresolvedMappers) {
  13202. MappableVarListInfo MVLI(VarList);
  13203. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
  13204. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  13205. if (MVLI.ProcessedVarList.empty())
  13206. return nullptr;
  13207. return OMPToClause::Create(
  13208. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  13209. MVLI.VarComponents, MVLI.UDMapperList,
  13210. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  13211. }
  13212. OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
  13213. CXXScopeSpec &MapperIdScopeSpec,
  13214. DeclarationNameInfo &MapperId,
  13215. const OMPVarListLocTy &Locs,
  13216. ArrayRef<Expr *> UnresolvedMappers) {
  13217. MappableVarListInfo MVLI(VarList);
  13218. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
  13219. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  13220. if (MVLI.ProcessedVarList.empty())
  13221. return nullptr;
  13222. return OMPFromClause::Create(
  13223. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  13224. MVLI.VarComponents, MVLI.UDMapperList,
  13225. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  13226. }
  13227. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  13228. const OMPVarListLocTy &Locs) {
  13229. MappableVarListInfo MVLI(VarList);
  13230. SmallVector<Expr *, 8> PrivateCopies;
  13231. SmallVector<Expr *, 8> Inits;
  13232. for (Expr *RefExpr : VarList) {
  13233. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  13234. SourceLocation ELoc;
  13235. SourceRange ERange;
  13236. Expr *SimpleRefExpr = RefExpr;
  13237. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  13238. if (Res.second) {
  13239. // It will be analyzed later.
  13240. MVLI.ProcessedVarList.push_back(RefExpr);
  13241. PrivateCopies.push_back(nullptr);
  13242. Inits.push_back(nullptr);
  13243. }
  13244. ValueDecl *D = Res.first;
  13245. if (!D)
  13246. continue;
  13247. QualType Type = D->getType();
  13248. Type = Type.getNonReferenceType().getUnqualifiedType();
  13249. auto *VD = dyn_cast<VarDecl>(D);
  13250. // Item should be a pointer or reference to pointer.
  13251. if (!Type->isPointerType()) {
  13252. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  13253. << 0 << RefExpr->getSourceRange();
  13254. continue;
  13255. }
  13256. // Build the private variable and the expression that refers to it.
  13257. auto VDPrivate =
  13258. buildVarDecl(*this, ELoc, Type, D->getName(),
  13259. D->hasAttrs() ? &D->getAttrs() : nullptr,
  13260. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  13261. if (VDPrivate->isInvalidDecl())
  13262. continue;
  13263. CurContext->addDecl(VDPrivate);
  13264. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  13265. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  13266. // Add temporary variable to initialize the private copy of the pointer.
  13267. VarDecl *VDInit =
  13268. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  13269. DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
  13270. *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
  13271. AddInitializerToDecl(VDPrivate,
  13272. DefaultLvalueConversion(VDInitRefExpr).get(),
  13273. /*DirectInit=*/false);
  13274. // If required, build a capture to implement the privatization initialized
  13275. // with the current list item value.
  13276. DeclRefExpr *Ref = nullptr;
  13277. if (!VD)
  13278. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  13279. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  13280. PrivateCopies.push_back(VDPrivateRefExpr);
  13281. Inits.push_back(VDInitRefExpr);
  13282. // We need to add a data sharing attribute for this variable to make sure it
  13283. // is correctly captured. A variable that shows up in a use_device_ptr has
  13284. // similar properties of a first private variable.
  13285. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  13286. // Create a mappable component for the list item. List items in this clause
  13287. // only need a component.
  13288. MVLI.VarBaseDeclarations.push_back(D);
  13289. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  13290. MVLI.VarComponents.back().push_back(
  13291. OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
  13292. }
  13293. if (MVLI.ProcessedVarList.empty())
  13294. return nullptr;
  13295. return OMPUseDevicePtrClause::Create(
  13296. Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
  13297. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  13298. }
  13299. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  13300. const OMPVarListLocTy &Locs) {
  13301. MappableVarListInfo MVLI(VarList);
  13302. for (Expr *RefExpr : VarList) {
  13303. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  13304. SourceLocation ELoc;
  13305. SourceRange ERange;
  13306. Expr *SimpleRefExpr = RefExpr;
  13307. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  13308. if (Res.second) {
  13309. // It will be analyzed later.
  13310. MVLI.ProcessedVarList.push_back(RefExpr);
  13311. }
  13312. ValueDecl *D = Res.first;
  13313. if (!D)
  13314. continue;
  13315. QualType Type = D->getType();
  13316. // item should be a pointer or array or reference to pointer or array
  13317. if (!Type.getNonReferenceType()->isPointerType() &&
  13318. !Type.getNonReferenceType()->isArrayType()) {
  13319. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  13320. << 0 << RefExpr->getSourceRange();
  13321. continue;
  13322. }
  13323. // Check if the declaration in the clause does not show up in any data
  13324. // sharing attribute.
  13325. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  13326. if (isOpenMPPrivate(DVar.CKind)) {
  13327. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  13328. << getOpenMPClauseName(DVar.CKind)
  13329. << getOpenMPClauseName(OMPC_is_device_ptr)
  13330. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  13331. reportOriginalDsa(*this, DSAStack, D, DVar);
  13332. continue;
  13333. }
  13334. const Expr *ConflictExpr;
  13335. if (DSAStack->checkMappableExprComponentListsForDecl(
  13336. D, /*CurrentRegionOnly=*/true,
  13337. [&ConflictExpr](
  13338. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  13339. OpenMPClauseKind) -> bool {
  13340. ConflictExpr = R.front().getAssociatedExpression();
  13341. return true;
  13342. })) {
  13343. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  13344. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  13345. << ConflictExpr->getSourceRange();
  13346. continue;
  13347. }
  13348. // Store the components in the stack so that they can be used to check
  13349. // against other clauses later on.
  13350. OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
  13351. DSAStack->addMappableExpressionComponents(
  13352. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  13353. // Record the expression we've just processed.
  13354. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  13355. // Create a mappable component for the list item. List items in this clause
  13356. // only need a component. We use a null declaration to signal fields in
  13357. // 'this'.
  13358. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  13359. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  13360. "Unexpected device pointer expression!");
  13361. MVLI.VarBaseDeclarations.push_back(
  13362. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  13363. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  13364. MVLI.VarComponents.back().push_back(MC);
  13365. }
  13366. if (MVLI.ProcessedVarList.empty())
  13367. return nullptr;
  13368. return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
  13369. MVLI.VarBaseDeclarations,
  13370. MVLI.VarComponents);
  13371. }