SemaOpenMP.cpp 395 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372
  1. //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. /// \file
  10. /// \brief This file implements semantic analysis for OpenMP directives and
  11. /// clauses.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "TreeTransform.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTMutationListener.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/Basic/OpenMPKinds.h"
  24. #include "clang/Basic/TargetInfo.h"
  25. #include "clang/Lex/Preprocessor.h"
  26. #include "clang/Sema/Initialization.h"
  27. #include "clang/Sema/Lookup.h"
  28. #include "clang/Sema/Scope.h"
  29. #include "clang/Sema/ScopeInfo.h"
  30. #include "clang/Sema/SemaInternal.h"
  31. using namespace clang;
  32. //===----------------------------------------------------------------------===//
  33. // Stack of data-sharing attributes for variables
  34. //===----------------------------------------------------------------------===//
  35. namespace {
  36. /// \brief Default data sharing attributes, which can be applied to directive.
  37. enum DefaultDataSharingAttributes {
  38. DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
  39. DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
  40. DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'.
  41. };
  42. template <class T> struct MatchesAny {
  43. explicit MatchesAny(ArrayRef<T> Arr) : Arr(std::move(Arr)) {}
  44. bool operator()(T Kind) {
  45. for (auto KindEl : Arr)
  46. if (KindEl == Kind)
  47. return true;
  48. return false;
  49. }
  50. private:
  51. ArrayRef<T> Arr;
  52. };
  53. struct MatchesAlways {
  54. MatchesAlways() {}
  55. template <class T> bool operator()(T) { return true; }
  56. };
  57. typedef MatchesAny<OpenMPClauseKind> MatchesAnyClause;
  58. typedef MatchesAny<OpenMPDirectiveKind> MatchesAnyDirective;
  59. /// \brief Stack for tracking declarations used in OpenMP directives and
  60. /// clauses and their data-sharing attributes.
  61. class DSAStackTy {
  62. public:
  63. struct DSAVarData {
  64. OpenMPDirectiveKind DKind;
  65. OpenMPClauseKind CKind;
  66. Expr *RefExpr;
  67. SourceLocation ImplicitDSALoc;
  68. DSAVarData()
  69. : DKind(OMPD_unknown), CKind(OMPC_unknown), RefExpr(nullptr),
  70. ImplicitDSALoc() {}
  71. };
  72. private:
  73. typedef SmallVector<Expr *, 4> MapInfo;
  74. struct DSAInfo {
  75. OpenMPClauseKind Attributes;
  76. Expr *RefExpr;
  77. };
  78. typedef llvm::SmallDenseMap<ValueDecl *, DSAInfo, 64> DeclSAMapTy;
  79. typedef llvm::SmallDenseMap<ValueDecl *, Expr *, 64> AlignedMapTy;
  80. typedef llvm::DenseMap<ValueDecl *, unsigned> LoopControlVariablesMapTy;
  81. typedef llvm::SmallDenseMap<ValueDecl *, MapInfo, 64> MappedDeclsTy;
  82. typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
  83. CriticalsWithHintsTy;
  84. struct SharingMapTy {
  85. DeclSAMapTy SharingMap;
  86. AlignedMapTy AlignedMap;
  87. MappedDeclsTy MappedDecls;
  88. LoopControlVariablesMapTy LCVMap;
  89. DefaultDataSharingAttributes DefaultAttr;
  90. SourceLocation DefaultAttrLoc;
  91. OpenMPDirectiveKind Directive;
  92. DeclarationNameInfo DirectiveName;
  93. Scope *CurScope;
  94. SourceLocation ConstructLoc;
  95. /// \brief first argument (Expr *) contains optional argument of the
  96. /// 'ordered' clause, the second one is true if the regions has 'ordered'
  97. /// clause, false otherwise.
  98. llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
  99. bool NowaitRegion;
  100. bool CancelRegion;
  101. unsigned AssociatedLoops;
  102. SourceLocation InnerTeamsRegionLoc;
  103. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  104. Scope *CurScope, SourceLocation Loc)
  105. : SharingMap(), AlignedMap(), LCVMap(), DefaultAttr(DSA_unspecified),
  106. Directive(DKind), DirectiveName(std::move(Name)), CurScope(CurScope),
  107. ConstructLoc(Loc), OrderedRegion(), NowaitRegion(false),
  108. CancelRegion(false), AssociatedLoops(1), InnerTeamsRegionLoc() {}
  109. SharingMapTy()
  110. : SharingMap(), AlignedMap(), LCVMap(), DefaultAttr(DSA_unspecified),
  111. Directive(OMPD_unknown), DirectiveName(), CurScope(nullptr),
  112. ConstructLoc(), OrderedRegion(), NowaitRegion(false),
  113. CancelRegion(false), AssociatedLoops(1), InnerTeamsRegionLoc() {}
  114. };
  115. typedef SmallVector<SharingMapTy, 64> StackTy;
  116. /// \brief Stack of used declaration and their data-sharing attributes.
  117. StackTy Stack;
  118. /// \brief true, if check for DSA must be from parent directive, false, if
  119. /// from current directive.
  120. OpenMPClauseKind ClauseKindMode;
  121. Sema &SemaRef;
  122. bool ForceCapturing;
  123. CriticalsWithHintsTy Criticals;
  124. typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
  125. DSAVarData getDSA(StackTy::reverse_iterator Iter, ValueDecl *D);
  126. /// \brief Checks if the variable is a local for OpenMP region.
  127. bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
  128. public:
  129. explicit DSAStackTy(Sema &S)
  130. : Stack(1), ClauseKindMode(OMPC_unknown), SemaRef(S),
  131. ForceCapturing(false) {}
  132. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  133. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  134. bool isForceVarCapturing() const { return ForceCapturing; }
  135. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  136. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  137. Scope *CurScope, SourceLocation Loc) {
  138. Stack.push_back(SharingMapTy(DKind, DirName, CurScope, Loc));
  139. Stack.back().DefaultAttrLoc = Loc;
  140. }
  141. void pop() {
  142. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty!");
  143. Stack.pop_back();
  144. }
  145. void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
  146. Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
  147. }
  148. const std::pair<OMPCriticalDirective *, llvm::APSInt>
  149. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  150. auto I = Criticals.find(Name.getAsString());
  151. if (I != Criticals.end())
  152. return I->second;
  153. return std::make_pair(nullptr, llvm::APSInt());
  154. }
  155. /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
  156. /// add it and return NULL; otherwise return previous occurrence's expression
  157. /// for diagnostics.
  158. Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
  159. /// \brief Register specified variable as loop control variable.
  160. void addLoopControlVariable(ValueDecl *D);
  161. /// \brief Check if the specified variable is a loop control variable for
  162. /// current region.
  163. /// \return The index of the loop control variable in the list of associated
  164. /// for-loops (from outer to inner).
  165. unsigned isLoopControlVariable(ValueDecl *D);
  166. /// \brief Check if the specified variable is a loop control variable for
  167. /// parent region.
  168. /// \return The index of the loop control variable in the list of associated
  169. /// for-loops (from outer to inner).
  170. unsigned isParentLoopControlVariable(ValueDecl *D);
  171. /// \brief Get the loop control variable for the I-th loop (or nullptr) in
  172. /// parent directive.
  173. ValueDecl *getParentLoopControlVariable(unsigned I);
  174. /// \brief Adds explicit data sharing attribute to the specified declaration.
  175. void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A);
  176. /// \brief Returns data sharing attributes from top of the stack for the
  177. /// specified declaration.
  178. DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  179. /// \brief Returns data-sharing attributes for the specified declaration.
  180. DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
  181. /// \brief Checks if the specified variables has data-sharing attributes which
  182. /// match specified \a CPred predicate in any directive which matches \a DPred
  183. /// predicate.
  184. template <class ClausesPredicate, class DirectivesPredicate>
  185. DSAVarData hasDSA(ValueDecl *D, ClausesPredicate CPred,
  186. DirectivesPredicate DPred, bool FromParent);
  187. /// \brief Checks if the specified variables has data-sharing attributes which
  188. /// match specified \a CPred predicate in any innermost directive which
  189. /// matches \a DPred predicate.
  190. template <class ClausesPredicate, class DirectivesPredicate>
  191. DSAVarData hasInnermostDSA(ValueDecl *D, ClausesPredicate CPred,
  192. DirectivesPredicate DPred, bool FromParent);
  193. /// \brief Checks if the specified variables has explicit data-sharing
  194. /// attributes which match specified \a CPred predicate at the specified
  195. /// OpenMP region.
  196. bool hasExplicitDSA(ValueDecl *D,
  197. const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  198. unsigned Level);
  199. /// \brief Returns true if the directive at level \Level matches in the
  200. /// specified \a DPred predicate.
  201. bool hasExplicitDirective(
  202. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  203. unsigned Level);
  204. /// \brief Finds a directive which matches specified \a DPred predicate.
  205. template <class NamedDirectivesPredicate>
  206. bool hasDirective(NamedDirectivesPredicate DPred, bool FromParent);
  207. /// \brief Returns currently analyzed directive.
  208. OpenMPDirectiveKind getCurrentDirective() const {
  209. return Stack.back().Directive;
  210. }
  211. /// \brief Returns parent directive.
  212. OpenMPDirectiveKind getParentDirective() const {
  213. if (Stack.size() > 2)
  214. return Stack[Stack.size() - 2].Directive;
  215. return OMPD_unknown;
  216. }
  217. /// \brief Return the directive associated with the provided scope.
  218. OpenMPDirectiveKind getDirectiveForScope(const Scope *S) const;
  219. /// \brief Set default data sharing attribute to none.
  220. void setDefaultDSANone(SourceLocation Loc) {
  221. Stack.back().DefaultAttr = DSA_none;
  222. Stack.back().DefaultAttrLoc = Loc;
  223. }
  224. /// \brief Set default data sharing attribute to shared.
  225. void setDefaultDSAShared(SourceLocation Loc) {
  226. Stack.back().DefaultAttr = DSA_shared;
  227. Stack.back().DefaultAttrLoc = Loc;
  228. }
  229. DefaultDataSharingAttributes getDefaultDSA() const {
  230. return Stack.back().DefaultAttr;
  231. }
  232. SourceLocation getDefaultDSALocation() const {
  233. return Stack.back().DefaultAttrLoc;
  234. }
  235. /// \brief Checks if the specified variable is a threadprivate.
  236. bool isThreadPrivate(VarDecl *D) {
  237. DSAVarData DVar = getTopDSA(D, false);
  238. return isOpenMPThreadPrivate(DVar.CKind);
  239. }
  240. /// \brief Marks current region as ordered (it has an 'ordered' clause).
  241. void setOrderedRegion(bool IsOrdered, Expr *Param) {
  242. Stack.back().OrderedRegion.setInt(IsOrdered);
  243. Stack.back().OrderedRegion.setPointer(Param);
  244. }
  245. /// \brief Returns true, if parent region is ordered (has associated
  246. /// 'ordered' clause), false - otherwise.
  247. bool isParentOrderedRegion() const {
  248. if (Stack.size() > 2)
  249. return Stack[Stack.size() - 2].OrderedRegion.getInt();
  250. return false;
  251. }
  252. /// \brief Returns optional parameter for the ordered region.
  253. Expr *getParentOrderedRegionParam() const {
  254. if (Stack.size() > 2)
  255. return Stack[Stack.size() - 2].OrderedRegion.getPointer();
  256. return nullptr;
  257. }
  258. /// \brief Marks current region as nowait (it has a 'nowait' clause).
  259. void setNowaitRegion(bool IsNowait = true) {
  260. Stack.back().NowaitRegion = IsNowait;
  261. }
  262. /// \brief Returns true, if parent region is nowait (has associated
  263. /// 'nowait' clause), false - otherwise.
  264. bool isParentNowaitRegion() const {
  265. if (Stack.size() > 2)
  266. return Stack[Stack.size() - 2].NowaitRegion;
  267. return false;
  268. }
  269. /// \brief Marks parent region as cancel region.
  270. void setParentCancelRegion(bool Cancel = true) {
  271. if (Stack.size() > 2)
  272. Stack[Stack.size() - 2].CancelRegion =
  273. Stack[Stack.size() - 2].CancelRegion || Cancel;
  274. }
  275. /// \brief Return true if current region has inner cancel construct.
  276. bool isCancelRegion() const {
  277. return Stack.back().CancelRegion;
  278. }
  279. /// \brief Set collapse value for the region.
  280. void setAssociatedLoops(unsigned Val) { Stack.back().AssociatedLoops = Val; }
  281. /// \brief Return collapse value for region.
  282. unsigned getAssociatedLoops() const { return Stack.back().AssociatedLoops; }
  283. /// \brief Marks current target region as one with closely nested teams
  284. /// region.
  285. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  286. if (Stack.size() > 2)
  287. Stack[Stack.size() - 2].InnerTeamsRegionLoc = TeamsRegionLoc;
  288. }
  289. /// \brief Returns true, if current region has closely nested teams region.
  290. bool hasInnerTeamsRegion() const {
  291. return getInnerTeamsRegionLoc().isValid();
  292. }
  293. /// \brief Returns location of the nested teams region (if any).
  294. SourceLocation getInnerTeamsRegionLoc() const {
  295. if (Stack.size() > 1)
  296. return Stack.back().InnerTeamsRegionLoc;
  297. return SourceLocation();
  298. }
  299. Scope *getCurScope() const { return Stack.back().CurScope; }
  300. Scope *getCurScope() { return Stack.back().CurScope; }
  301. SourceLocation getConstructLoc() { return Stack.back().ConstructLoc; }
  302. // Do the check specified in MapInfoCheck and return true if any issue is
  303. // found.
  304. template <class MapInfoCheck>
  305. bool checkMapInfoForVar(ValueDecl *VD, bool CurrentRegionOnly,
  306. MapInfoCheck Check) {
  307. auto SI = Stack.rbegin();
  308. auto SE = Stack.rend();
  309. if (SI == SE)
  310. return false;
  311. if (CurrentRegionOnly) {
  312. SE = std::next(SI);
  313. } else {
  314. ++SI;
  315. }
  316. for (; SI != SE; ++SI) {
  317. auto MI = SI->MappedDecls.find(VD);
  318. if (MI != SI->MappedDecls.end()) {
  319. for (Expr *E : MI->second) {
  320. if (Check(E))
  321. return true;
  322. }
  323. }
  324. }
  325. return false;
  326. }
  327. void addExprToVarMapInfo(ValueDecl *VD, Expr *E) {
  328. if (Stack.size() > 1) {
  329. Stack.back().MappedDecls[VD].push_back(E);
  330. }
  331. }
  332. };
  333. bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
  334. return isOpenMPParallelDirective(DKind) || DKind == OMPD_task ||
  335. isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown ||
  336. isOpenMPTaskLoopDirective(DKind);
  337. }
  338. } // namespace
  339. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  340. auto *VD = dyn_cast<VarDecl>(D);
  341. auto *FD = dyn_cast<FieldDecl>(D);
  342. if (VD != nullptr) {
  343. VD = VD->getCanonicalDecl();
  344. D = VD;
  345. } else {
  346. assert(FD);
  347. FD = FD->getCanonicalDecl();
  348. D = FD;
  349. }
  350. return D;
  351. }
  352. DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator Iter,
  353. ValueDecl *D) {
  354. D = getCanonicalDecl(D);
  355. auto *VD = dyn_cast<VarDecl>(D);
  356. auto *FD = dyn_cast<FieldDecl>(D);
  357. DSAVarData DVar;
  358. if (Iter == std::prev(Stack.rend())) {
  359. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  360. // in a region but not in construct]
  361. // File-scope or namespace-scope variables referenced in called routines
  362. // in the region are shared unless they appear in a threadprivate
  363. // directive.
  364. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
  365. DVar.CKind = OMPC_shared;
  366. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  367. // in a region but not in construct]
  368. // Variables with static storage duration that are declared in called
  369. // routines in the region are shared.
  370. if (VD && VD->hasGlobalStorage())
  371. DVar.CKind = OMPC_shared;
  372. // Non-static data members are shared by default.
  373. if (FD)
  374. DVar.CKind = OMPC_shared;
  375. return DVar;
  376. }
  377. DVar.DKind = Iter->Directive;
  378. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  379. // in a Construct, C/C++, predetermined, p.1]
  380. // Variables with automatic storage duration that are declared in a scope
  381. // inside the construct are private.
  382. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  383. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  384. DVar.CKind = OMPC_private;
  385. return DVar;
  386. }
  387. // Explicitly specified attributes and local variables with predetermined
  388. // attributes.
  389. if (Iter->SharingMap.count(D)) {
  390. DVar.RefExpr = Iter->SharingMap[D].RefExpr;
  391. DVar.CKind = Iter->SharingMap[D].Attributes;
  392. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  393. return DVar;
  394. }
  395. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  396. // in a Construct, C/C++, implicitly determined, p.1]
  397. // In a parallel or task construct, the data-sharing attributes of these
  398. // variables are determined by the default clause, if present.
  399. switch (Iter->DefaultAttr) {
  400. case DSA_shared:
  401. DVar.CKind = OMPC_shared;
  402. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  403. return DVar;
  404. case DSA_none:
  405. return DVar;
  406. case DSA_unspecified:
  407. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  408. // in a Construct, implicitly determined, p.2]
  409. // In a parallel construct, if no default clause is present, these
  410. // variables are shared.
  411. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  412. if (isOpenMPParallelDirective(DVar.DKind) ||
  413. isOpenMPTeamsDirective(DVar.DKind)) {
  414. DVar.CKind = OMPC_shared;
  415. return DVar;
  416. }
  417. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  418. // in a Construct, implicitly determined, p.4]
  419. // In a task construct, if no default clause is present, a variable that in
  420. // the enclosing context is determined to be shared by all implicit tasks
  421. // bound to the current team is shared.
  422. if (DVar.DKind == OMPD_task) {
  423. DSAVarData DVarTemp;
  424. for (StackTy::reverse_iterator I = std::next(Iter), EE = Stack.rend();
  425. I != EE; ++I) {
  426. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  427. // Referenced
  428. // in a Construct, implicitly determined, p.6]
  429. // In a task construct, if no default clause is present, a variable
  430. // whose data-sharing attribute is not determined by the rules above is
  431. // firstprivate.
  432. DVarTemp = getDSA(I, D);
  433. if (DVarTemp.CKind != OMPC_shared) {
  434. DVar.RefExpr = nullptr;
  435. DVar.DKind = OMPD_task;
  436. DVar.CKind = OMPC_firstprivate;
  437. return DVar;
  438. }
  439. if (isParallelOrTaskRegion(I->Directive))
  440. break;
  441. }
  442. DVar.DKind = OMPD_task;
  443. DVar.CKind =
  444. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  445. return DVar;
  446. }
  447. }
  448. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  449. // in a Construct, implicitly determined, p.3]
  450. // For constructs other than task, if no default clause is present, these
  451. // variables inherit their data-sharing attributes from the enclosing
  452. // context.
  453. return getDSA(std::next(Iter), D);
  454. }
  455. Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
  456. assert(Stack.size() > 1 && "Data sharing attributes stack is empty");
  457. D = getCanonicalDecl(D);
  458. auto It = Stack.back().AlignedMap.find(D);
  459. if (It == Stack.back().AlignedMap.end()) {
  460. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  461. Stack.back().AlignedMap[D] = NewDE;
  462. return nullptr;
  463. } else {
  464. assert(It->second && "Unexpected nullptr expr in the aligned map");
  465. return It->second;
  466. }
  467. return nullptr;
  468. }
  469. void DSAStackTy::addLoopControlVariable(ValueDecl *D) {
  470. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
  471. D = getCanonicalDecl(D);
  472. Stack.back().LCVMap.insert(std::make_pair(D, Stack.back().LCVMap.size() + 1));
  473. }
  474. unsigned DSAStackTy::isLoopControlVariable(ValueDecl *D) {
  475. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
  476. D = getCanonicalDecl(D);
  477. return Stack.back().LCVMap.count(D) > 0 ? Stack.back().LCVMap[D] : 0;
  478. }
  479. unsigned DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
  480. assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
  481. D = getCanonicalDecl(D);
  482. return Stack[Stack.size() - 2].LCVMap.count(D) > 0
  483. ? Stack[Stack.size() - 2].LCVMap[D]
  484. : 0;
  485. }
  486. ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
  487. assert(Stack.size() > 2 && "Data-sharing attributes stack is empty");
  488. if (Stack[Stack.size() - 2].LCVMap.size() < I)
  489. return nullptr;
  490. for (auto &Pair : Stack[Stack.size() - 2].LCVMap) {
  491. if (Pair.second == I)
  492. return Pair.first;
  493. }
  494. return nullptr;
  495. }
  496. void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A) {
  497. D = getCanonicalDecl(D);
  498. if (A == OMPC_threadprivate) {
  499. Stack[0].SharingMap[D].Attributes = A;
  500. Stack[0].SharingMap[D].RefExpr = E;
  501. } else {
  502. assert(Stack.size() > 1 && "Data-sharing attributes stack is empty");
  503. Stack.back().SharingMap[D].Attributes = A;
  504. Stack.back().SharingMap[D].RefExpr = E;
  505. }
  506. }
  507. bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
  508. D = D->getCanonicalDecl();
  509. if (Stack.size() > 2) {
  510. reverse_iterator I = Iter, E = std::prev(Stack.rend());
  511. Scope *TopScope = nullptr;
  512. while (I != E && !isParallelOrTaskRegion(I->Directive)) {
  513. ++I;
  514. }
  515. if (I == E)
  516. return false;
  517. TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
  518. Scope *CurScope = getCurScope();
  519. while (CurScope != TopScope && !CurScope->isDeclScope(D)) {
  520. CurScope = CurScope->getParent();
  521. }
  522. return CurScope != TopScope;
  523. }
  524. return false;
  525. }
  526. /// \brief Build a variable declaration for OpenMP loop iteration variable.
  527. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  528. StringRef Name, const AttrVec *Attrs = nullptr) {
  529. DeclContext *DC = SemaRef.CurContext;
  530. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  531. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  532. VarDecl *Decl =
  533. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  534. if (Attrs) {
  535. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  536. I != E; ++I)
  537. Decl->addAttr(*I);
  538. }
  539. Decl->setImplicit();
  540. return Decl;
  541. }
  542. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  543. SourceLocation Loc,
  544. bool RefersToCapture = false) {
  545. D->setReferenced();
  546. D->markUsed(S.Context);
  547. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  548. SourceLocation(), D, RefersToCapture, Loc, Ty,
  549. VK_LValue);
  550. }
  551. DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
  552. D = getCanonicalDecl(D);
  553. DSAVarData DVar;
  554. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  555. // in a Construct, C/C++, predetermined, p.1]
  556. // Variables appearing in threadprivate directives are threadprivate.
  557. auto *VD = dyn_cast<VarDecl>(D);
  558. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  559. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  560. SemaRef.getLangOpts().OpenMPUseTLS &&
  561. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  562. (VD && VD->getStorageClass() == SC_Register &&
  563. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  564. addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  565. D->getLocation()),
  566. OMPC_threadprivate);
  567. }
  568. if (Stack[0].SharingMap.count(D)) {
  569. DVar.RefExpr = Stack[0].SharingMap[D].RefExpr;
  570. DVar.CKind = OMPC_threadprivate;
  571. return DVar;
  572. }
  573. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  574. // in a Construct, C/C++, predetermined, p.4]
  575. // Static data members are shared.
  576. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  577. // in a Construct, C/C++, predetermined, p.7]
  578. // Variables with static storage duration that are declared in a scope
  579. // inside the construct are shared.
  580. if (VD && VD->isStaticDataMember()) {
  581. DSAVarData DVarTemp =
  582. hasDSA(D, isOpenMPPrivate, MatchesAlways(), FromParent);
  583. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  584. return DVar;
  585. DVar.CKind = OMPC_shared;
  586. return DVar;
  587. }
  588. QualType Type = D->getType().getNonReferenceType().getCanonicalType();
  589. bool IsConstant = Type.isConstant(SemaRef.getASTContext());
  590. Type = SemaRef.getASTContext().getBaseElementType(Type);
  591. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  592. // in a Construct, C/C++, predetermined, p.6]
  593. // Variables with const qualified type having no mutable member are
  594. // shared.
  595. CXXRecordDecl *RD =
  596. SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
  597. if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  598. if (auto *CTD = CTSD->getSpecializedTemplate())
  599. RD = CTD->getTemplatedDecl();
  600. if (IsConstant &&
  601. !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasMutableFields())) {
  602. // Variables with const-qualified type having no mutable member may be
  603. // listed in a firstprivate clause, even if they are static data members.
  604. DSAVarData DVarTemp = hasDSA(D, MatchesAnyClause(OMPC_firstprivate),
  605. MatchesAlways(), FromParent);
  606. if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
  607. return DVar;
  608. DVar.CKind = OMPC_shared;
  609. return DVar;
  610. }
  611. // Explicitly specified attributes and local variables with predetermined
  612. // attributes.
  613. auto StartI = std::next(Stack.rbegin());
  614. auto EndI = std::prev(Stack.rend());
  615. if (FromParent && StartI != EndI) {
  616. StartI = std::next(StartI);
  617. }
  618. auto I = std::prev(StartI);
  619. if (I->SharingMap.count(D)) {
  620. DVar.RefExpr = I->SharingMap[D].RefExpr;
  621. DVar.CKind = I->SharingMap[D].Attributes;
  622. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  623. }
  624. return DVar;
  625. }
  626. DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  627. bool FromParent) {
  628. D = getCanonicalDecl(D);
  629. auto StartI = Stack.rbegin();
  630. auto EndI = std::prev(Stack.rend());
  631. if (FromParent && StartI != EndI) {
  632. StartI = std::next(StartI);
  633. }
  634. return getDSA(StartI, D);
  635. }
  636. template <class ClausesPredicate, class DirectivesPredicate>
  637. DSAStackTy::DSAVarData DSAStackTy::hasDSA(ValueDecl *D, ClausesPredicate CPred,
  638. DirectivesPredicate DPred,
  639. bool FromParent) {
  640. D = getCanonicalDecl(D);
  641. auto StartI = std::next(Stack.rbegin());
  642. auto EndI = std::prev(Stack.rend());
  643. if (FromParent && StartI != EndI) {
  644. StartI = std::next(StartI);
  645. }
  646. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  647. if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
  648. continue;
  649. DSAVarData DVar = getDSA(I, D);
  650. if (CPred(DVar.CKind))
  651. return DVar;
  652. }
  653. return DSAVarData();
  654. }
  655. template <class ClausesPredicate, class DirectivesPredicate>
  656. DSAStackTy::DSAVarData
  657. DSAStackTy::hasInnermostDSA(ValueDecl *D, ClausesPredicate CPred,
  658. DirectivesPredicate DPred, bool FromParent) {
  659. D = getCanonicalDecl(D);
  660. auto StartI = std::next(Stack.rbegin());
  661. auto EndI = std::prev(Stack.rend());
  662. if (FromParent && StartI != EndI) {
  663. StartI = std::next(StartI);
  664. }
  665. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  666. if (!DPred(I->Directive))
  667. break;
  668. DSAVarData DVar = getDSA(I, D);
  669. if (CPred(DVar.CKind))
  670. return DVar;
  671. return DSAVarData();
  672. }
  673. return DSAVarData();
  674. }
  675. bool DSAStackTy::hasExplicitDSA(
  676. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
  677. unsigned Level) {
  678. if (CPred(ClauseKindMode))
  679. return true;
  680. if (isClauseParsingMode())
  681. ++Level;
  682. D = getCanonicalDecl(D);
  683. auto StartI = Stack.rbegin();
  684. auto EndI = std::prev(Stack.rend());
  685. if (std::distance(StartI, EndI) <= (int)Level)
  686. return false;
  687. std::advance(StartI, Level);
  688. return (StartI->SharingMap.count(D) > 0) && StartI->SharingMap[D].RefExpr &&
  689. CPred(StartI->SharingMap[D].Attributes);
  690. }
  691. bool DSAStackTy::hasExplicitDirective(
  692. const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
  693. unsigned Level) {
  694. if (isClauseParsingMode())
  695. ++Level;
  696. auto StartI = Stack.rbegin();
  697. auto EndI = std::prev(Stack.rend());
  698. if (std::distance(StartI, EndI) <= (int)Level)
  699. return false;
  700. std::advance(StartI, Level);
  701. return DPred(StartI->Directive);
  702. }
  703. template <class NamedDirectivesPredicate>
  704. bool DSAStackTy::hasDirective(NamedDirectivesPredicate DPred, bool FromParent) {
  705. auto StartI = std::next(Stack.rbegin());
  706. auto EndI = std::prev(Stack.rend());
  707. if (FromParent && StartI != EndI) {
  708. StartI = std::next(StartI);
  709. }
  710. for (auto I = StartI, EE = EndI; I != EE; ++I) {
  711. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  712. return true;
  713. }
  714. return false;
  715. }
  716. OpenMPDirectiveKind DSAStackTy::getDirectiveForScope(const Scope *S) const {
  717. for (auto I = Stack.rbegin(), EE = Stack.rend(); I != EE; ++I)
  718. if (I->CurScope == S)
  719. return I->Directive;
  720. return OMPD_unknown;
  721. }
  722. void Sema::InitDataSharingAttributesStack() {
  723. VarDataSharingAttributesStack = new DSAStackTy(*this);
  724. }
  725. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  726. bool Sema::IsOpenMPCapturedByRef(ValueDecl *D,
  727. const CapturedRegionScopeInfo *RSI) {
  728. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  729. auto &Ctx = getASTContext();
  730. bool IsByRef = true;
  731. // Find the directive that is associated with the provided scope.
  732. auto DKind = DSAStack->getDirectiveForScope(RSI->TheScope);
  733. auto Ty = D->getType();
  734. if (isOpenMPTargetExecutionDirective(DKind)) {
  735. // This table summarizes how a given variable should be passed to the device
  736. // given its type and the clauses where it appears. This table is based on
  737. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  738. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  739. //
  740. // =========================================================================
  741. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  742. // | |(tofrom:scalar)| | pvt | | | |
  743. // =========================================================================
  744. // | scl | | | | - | | bycopy|
  745. // | scl | | - | x | - | - | bycopy|
  746. // | scl | | x | - | - | - | null |
  747. // | scl | x | | | - | | byref |
  748. // | scl | x | - | x | - | - | bycopy|
  749. // | scl | x | x | - | - | - | null |
  750. // | scl | | - | - | - | x | byref |
  751. // | scl | x | - | - | - | x | byref |
  752. //
  753. // | agg | n.a. | | | - | | byref |
  754. // | agg | n.a. | - | x | - | - | byref |
  755. // | agg | n.a. | x | - | - | - | null |
  756. // | agg | n.a. | - | - | - | x | byref |
  757. // | agg | n.a. | - | - | - | x[] | byref |
  758. //
  759. // | ptr | n.a. | | | - | | bycopy|
  760. // | ptr | n.a. | - | x | - | - | bycopy|
  761. // | ptr | n.a. | x | - | - | - | null |
  762. // | ptr | n.a. | - | - | - | x | byref |
  763. // | ptr | n.a. | - | - | - | x[] | bycopy|
  764. // | ptr | n.a. | - | - | x | | bycopy|
  765. // | ptr | n.a. | - | - | x | x | bycopy|
  766. // | ptr | n.a. | - | - | x | x[] | bycopy|
  767. // =========================================================================
  768. // Legend:
  769. // scl - scalar
  770. // ptr - pointer
  771. // agg - aggregate
  772. // x - applies
  773. // - - invalid in this combination
  774. // [] - mapped with an array section
  775. // byref - should be mapped by reference
  776. // byval - should be mapped by value
  777. // null - initialize a local variable to null on the device
  778. //
  779. // Observations:
  780. // - All scalar declarations that show up in a map clause have to be passed
  781. // by reference, because they may have been mapped in the enclosing data
  782. // environment.
  783. // - If the scalar value does not fit the size of uintptr, it has to be
  784. // passed by reference, regardless the result in the table above.
  785. // - For pointers mapped by value that have either an implicit map or an
  786. // array section, the runtime library may pass the NULL value to the
  787. // device instead of the value passed to it by the compiler.
  788. // FIXME: Right now, only implicit maps are implemented. Properly mapping
  789. // values requires having the map, private, and firstprivate clauses SEMA
  790. // and parsing in place, which we don't yet.
  791. if (Ty->isReferenceType())
  792. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  793. IsByRef = !Ty->isScalarType();
  794. }
  795. // When passing data by value, we need to make sure it fits the uintptr size
  796. // and alignment, because the runtime library only deals with uintptr types.
  797. // If it does not fit the uintptr size, we need to pass the data by reference
  798. // instead.
  799. if (!IsByRef &&
  800. (Ctx.getTypeSizeInChars(Ty) >
  801. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  802. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType())))
  803. IsByRef = true;
  804. return IsByRef;
  805. }
  806. bool Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
  807. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  808. D = getCanonicalDecl(D);
  809. // If we are attempting to capture a global variable in a directive with
  810. // 'target' we return true so that this global is also mapped to the device.
  811. //
  812. // FIXME: If the declaration is enclosed in a 'declare target' directive,
  813. // then it should not be captured. Therefore, an extra check has to be
  814. // inserted here once support for 'declare target' is added.
  815. //
  816. auto *VD = dyn_cast<VarDecl>(D);
  817. if (VD && !VD->hasLocalStorage()) {
  818. if (DSAStack->getCurrentDirective() == OMPD_target &&
  819. !DSAStack->isClauseParsingMode()) {
  820. return true;
  821. }
  822. if (DSAStack->getCurScope() &&
  823. DSAStack->hasDirective(
  824. [](OpenMPDirectiveKind K, const DeclarationNameInfo &DNI,
  825. SourceLocation Loc) -> bool {
  826. return isOpenMPTargetExecutionDirective(K);
  827. },
  828. false)) {
  829. return true;
  830. }
  831. }
  832. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  833. (!DSAStack->isClauseParsingMode() ||
  834. DSAStack->getParentDirective() != OMPD_unknown)) {
  835. if (DSAStack->isLoopControlVariable(D) ||
  836. (VD && VD->hasLocalStorage() &&
  837. isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
  838. (VD && DSAStack->isForceVarCapturing()))
  839. return true;
  840. auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  841. if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
  842. return true;
  843. DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate, MatchesAlways(),
  844. DSAStack->isClauseParsingMode());
  845. return DVarPrivate.CKind != OMPC_unknown;
  846. }
  847. return false;
  848. }
  849. bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
  850. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  851. return DSAStack->hasExplicitDSA(
  852. D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level);
  853. }
  854. bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
  855. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  856. // Return true if the current level is no longer enclosed in a target region.
  857. auto *VD = dyn_cast<VarDecl>(D);
  858. return VD && !VD->hasLocalStorage() &&
  859. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  860. Level);
  861. }
  862. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  863. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  864. const DeclarationNameInfo &DirName,
  865. Scope *CurScope, SourceLocation Loc) {
  866. DSAStack->push(DKind, DirName, CurScope, Loc);
  867. PushExpressionEvaluationContext(PotentiallyEvaluated);
  868. }
  869. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  870. DSAStack->setClauseParsingMode(K);
  871. }
  872. void Sema::EndOpenMPClause() {
  873. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  874. }
  875. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  876. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  877. // A variable of class type (or array thereof) that appears in a lastprivate
  878. // clause requires an accessible, unambiguous default constructor for the
  879. // class type, unless the list item is also specified in a firstprivate
  880. // clause.
  881. if (auto D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  882. for (auto *C : D->clauses()) {
  883. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  884. SmallVector<Expr *, 8> PrivateCopies;
  885. for (auto *DE : Clause->varlists()) {
  886. if (DE->isValueDependent() || DE->isTypeDependent()) {
  887. PrivateCopies.push_back(nullptr);
  888. continue;
  889. }
  890. DE = DE->IgnoreParens();
  891. VarDecl *VD = nullptr;
  892. FieldDecl *FD = nullptr;
  893. ValueDecl *D;
  894. if (auto *DRE = dyn_cast<DeclRefExpr>(DE)) {
  895. VD = cast<VarDecl>(DRE->getDecl());
  896. D = VD;
  897. } else {
  898. assert(isa<MemberExpr>(DE));
  899. FD = cast<FieldDecl>(cast<MemberExpr>(DE)->getMemberDecl());
  900. D = FD;
  901. }
  902. QualType Type = D->getType().getNonReferenceType();
  903. auto DVar = DSAStack->getTopDSA(D, false);
  904. if (DVar.CKind == OMPC_lastprivate) {
  905. // Generate helper private variable and initialize it with the
  906. // default value. The address of the original variable is replaced
  907. // by the address of the new private variable in CodeGen. This new
  908. // variable is not added to IdResolver, so the code in the OpenMP
  909. // region uses original variable for proper diagnostics.
  910. auto *VDPrivate = buildVarDecl(
  911. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  912. D->getName(), D->hasAttrs() ? &D->getAttrs() : nullptr);
  913. ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
  914. if (VDPrivate->isInvalidDecl())
  915. continue;
  916. PrivateCopies.push_back(buildDeclRefExpr(
  917. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  918. } else {
  919. // The variable is also a firstprivate, so initialization sequence
  920. // for private copy is generated already.
  921. PrivateCopies.push_back(nullptr);
  922. }
  923. }
  924. // Set initializers to private copies if no errors were found.
  925. if (PrivateCopies.size() == Clause->varlist_size())
  926. Clause->setPrivateCopies(PrivateCopies);
  927. }
  928. }
  929. }
  930. DSAStack->pop();
  931. DiscardCleanupsInEvaluationContext();
  932. PopExpressionEvaluationContext();
  933. }
  934. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  935. Expr *NumIterations, Sema &SemaRef,
  936. Scope *S);
  937. namespace {
  938. class VarDeclFilterCCC : public CorrectionCandidateCallback {
  939. private:
  940. Sema &SemaRef;
  941. public:
  942. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  943. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  944. NamedDecl *ND = Candidate.getCorrectionDecl();
  945. if (VarDecl *VD = dyn_cast_or_null<VarDecl>(ND)) {
  946. return VD->hasGlobalStorage() &&
  947. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  948. SemaRef.getCurScope());
  949. }
  950. return false;
  951. }
  952. };
  953. } // namespace
  954. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  955. CXXScopeSpec &ScopeSpec,
  956. const DeclarationNameInfo &Id) {
  957. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  958. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  959. if (Lookup.isAmbiguous())
  960. return ExprError();
  961. VarDecl *VD;
  962. if (!Lookup.isSingleResult()) {
  963. if (TypoCorrection Corrected = CorrectTypo(
  964. Id, LookupOrdinaryName, CurScope, nullptr,
  965. llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
  966. diagnoseTypo(Corrected,
  967. PDiag(Lookup.empty()
  968. ? diag::err_undeclared_var_use_suggest
  969. : diag::err_omp_expected_var_arg_suggest)
  970. << Id.getName());
  971. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  972. } else {
  973. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  974. : diag::err_omp_expected_var_arg)
  975. << Id.getName();
  976. return ExprError();
  977. }
  978. } else {
  979. if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  980. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  981. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  982. return ExprError();
  983. }
  984. }
  985. Lookup.suppressDiagnostics();
  986. // OpenMP [2.9.2, Syntax, C/C++]
  987. // Variables must be file-scope, namespace-scope, or static block-scope.
  988. if (!VD->hasGlobalStorage()) {
  989. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  990. << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
  991. bool IsDecl =
  992. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  993. Diag(VD->getLocation(),
  994. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  995. << VD;
  996. return ExprError();
  997. }
  998. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  999. NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
  1000. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  1001. // A threadprivate directive for file-scope variables must appear outside
  1002. // any definition or declaration.
  1003. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  1004. !getCurLexicalContext()->isTranslationUnit()) {
  1005. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1006. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1007. bool IsDecl =
  1008. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1009. Diag(VD->getLocation(),
  1010. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1011. << VD;
  1012. return ExprError();
  1013. }
  1014. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  1015. // A threadprivate directive for static class member variables must appear
  1016. // in the class definition, in the same scope in which the member
  1017. // variables are declared.
  1018. if (CanonicalVD->isStaticDataMember() &&
  1019. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  1020. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1021. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1022. bool IsDecl =
  1023. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1024. Diag(VD->getLocation(),
  1025. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1026. << VD;
  1027. return ExprError();
  1028. }
  1029. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  1030. // A threadprivate directive for namespace-scope variables must appear
  1031. // outside any definition or declaration other than the namespace
  1032. // definition itself.
  1033. if (CanonicalVD->getDeclContext()->isNamespace() &&
  1034. (!getCurLexicalContext()->isFileContext() ||
  1035. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  1036. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1037. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1038. bool IsDecl =
  1039. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1040. Diag(VD->getLocation(),
  1041. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1042. << VD;
  1043. return ExprError();
  1044. }
  1045. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  1046. // A threadprivate directive for static block-scope variables must appear
  1047. // in the scope of the variable and not in a nested scope.
  1048. if (CanonicalVD->isStaticLocal() && CurScope &&
  1049. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  1050. Diag(Id.getLoc(), diag::err_omp_var_scope)
  1051. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1052. bool IsDecl =
  1053. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1054. Diag(VD->getLocation(),
  1055. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1056. << VD;
  1057. return ExprError();
  1058. }
  1059. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  1060. // A threadprivate directive must lexically precede all references to any
  1061. // of the variables in its list.
  1062. if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
  1063. Diag(Id.getLoc(), diag::err_omp_var_used)
  1064. << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
  1065. return ExprError();
  1066. }
  1067. QualType ExprType = VD->getType().getNonReferenceType();
  1068. ExprResult DE = buildDeclRefExpr(*this, VD, ExprType, Id.getLoc());
  1069. return DE;
  1070. }
  1071. Sema::DeclGroupPtrTy
  1072. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  1073. ArrayRef<Expr *> VarList) {
  1074. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  1075. CurContext->addDecl(D);
  1076. return DeclGroupPtrTy::make(DeclGroupRef(D));
  1077. }
  1078. return nullptr;
  1079. }
  1080. namespace {
  1081. class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  1082. Sema &SemaRef;
  1083. public:
  1084. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  1085. if (auto VD = dyn_cast<VarDecl>(E->getDecl())) {
  1086. if (VD->hasLocalStorage()) {
  1087. SemaRef.Diag(E->getLocStart(),
  1088. diag::err_omp_local_var_in_threadprivate_init)
  1089. << E->getSourceRange();
  1090. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  1091. << VD << VD->getSourceRange();
  1092. return true;
  1093. }
  1094. }
  1095. return false;
  1096. }
  1097. bool VisitStmt(const Stmt *S) {
  1098. for (auto Child : S->children()) {
  1099. if (Child && Visit(Child))
  1100. return true;
  1101. }
  1102. return false;
  1103. }
  1104. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  1105. };
  1106. } // namespace
  1107. OMPThreadPrivateDecl *
  1108. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  1109. SmallVector<Expr *, 8> Vars;
  1110. for (auto &RefExpr : VarList) {
  1111. DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
  1112. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  1113. SourceLocation ILoc = DE->getExprLoc();
  1114. QualType QType = VD->getType();
  1115. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  1116. // It will be analyzed later.
  1117. Vars.push_back(DE);
  1118. continue;
  1119. }
  1120. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1121. // A threadprivate variable must not have an incomplete type.
  1122. if (RequireCompleteType(ILoc, VD->getType(),
  1123. diag::err_omp_threadprivate_incomplete_type)) {
  1124. continue;
  1125. }
  1126. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  1127. // A threadprivate variable must not have a reference type.
  1128. if (VD->getType()->isReferenceType()) {
  1129. Diag(ILoc, diag::err_omp_ref_type_arg)
  1130. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  1131. bool IsDecl =
  1132. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1133. Diag(VD->getLocation(),
  1134. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1135. << VD;
  1136. continue;
  1137. }
  1138. // Check if this is a TLS variable. If TLS is not being supported, produce
  1139. // the corresponding diagnostic.
  1140. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  1141. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1142. getLangOpts().OpenMPUseTLS &&
  1143. getASTContext().getTargetInfo().isTLSSupported())) ||
  1144. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  1145. !VD->isLocalVarDecl())) {
  1146. Diag(ILoc, diag::err_omp_var_thread_local)
  1147. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  1148. bool IsDecl =
  1149. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  1150. Diag(VD->getLocation(),
  1151. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1152. << VD;
  1153. continue;
  1154. }
  1155. // Check if initial value of threadprivate variable reference variable with
  1156. // local storage (it is not supported by runtime).
  1157. if (auto Init = VD->getAnyInitializer()) {
  1158. LocalVarRefChecker Checker(*this);
  1159. if (Checker.Visit(Init))
  1160. continue;
  1161. }
  1162. Vars.push_back(RefExpr);
  1163. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  1164. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  1165. Context, SourceRange(Loc, Loc)));
  1166. if (auto *ML = Context.getASTMutationListener())
  1167. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  1168. }
  1169. OMPThreadPrivateDecl *D = nullptr;
  1170. if (!Vars.empty()) {
  1171. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  1172. Vars);
  1173. D->setAccess(AS_public);
  1174. }
  1175. return D;
  1176. }
  1177. static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
  1178. const ValueDecl *D, DSAStackTy::DSAVarData DVar,
  1179. bool IsLoopIterVar = false) {
  1180. if (DVar.RefExpr) {
  1181. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  1182. << getOpenMPClauseName(DVar.CKind);
  1183. return;
  1184. }
  1185. enum {
  1186. PDSA_StaticMemberShared,
  1187. PDSA_StaticLocalVarShared,
  1188. PDSA_LoopIterVarPrivate,
  1189. PDSA_LoopIterVarLinear,
  1190. PDSA_LoopIterVarLastprivate,
  1191. PDSA_ConstVarShared,
  1192. PDSA_GlobalVarShared,
  1193. PDSA_TaskVarFirstprivate,
  1194. PDSA_LocalVarPrivate,
  1195. PDSA_Implicit
  1196. } Reason = PDSA_Implicit;
  1197. bool ReportHint = false;
  1198. auto ReportLoc = D->getLocation();
  1199. auto *VD = dyn_cast<VarDecl>(D);
  1200. if (IsLoopIterVar) {
  1201. if (DVar.CKind == OMPC_private)
  1202. Reason = PDSA_LoopIterVarPrivate;
  1203. else if (DVar.CKind == OMPC_lastprivate)
  1204. Reason = PDSA_LoopIterVarLastprivate;
  1205. else
  1206. Reason = PDSA_LoopIterVarLinear;
  1207. } else if (DVar.DKind == OMPD_task && DVar.CKind == OMPC_firstprivate) {
  1208. Reason = PDSA_TaskVarFirstprivate;
  1209. ReportLoc = DVar.ImplicitDSALoc;
  1210. } else if (VD && VD->isStaticLocal())
  1211. Reason = PDSA_StaticLocalVarShared;
  1212. else if (VD && VD->isStaticDataMember())
  1213. Reason = PDSA_StaticMemberShared;
  1214. else if (VD && VD->isFileVarDecl())
  1215. Reason = PDSA_GlobalVarShared;
  1216. else if (D->getType().isConstant(SemaRef.getASTContext()))
  1217. Reason = PDSA_ConstVarShared;
  1218. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  1219. ReportHint = true;
  1220. Reason = PDSA_LocalVarPrivate;
  1221. }
  1222. if (Reason != PDSA_Implicit) {
  1223. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  1224. << Reason << ReportHint
  1225. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  1226. } else if (DVar.ImplicitDSALoc.isValid()) {
  1227. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  1228. << getOpenMPClauseName(DVar.CKind);
  1229. }
  1230. }
  1231. namespace {
  1232. class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
  1233. DSAStackTy *Stack;
  1234. Sema &SemaRef;
  1235. bool ErrorFound;
  1236. CapturedStmt *CS;
  1237. llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
  1238. llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
  1239. public:
  1240. void VisitDeclRefExpr(DeclRefExpr *E) {
  1241. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  1242. // Skip internally declared variables.
  1243. if (VD->isLocalVarDecl() && !CS->capturesVariable(VD))
  1244. return;
  1245. auto DVar = Stack->getTopDSA(VD, false);
  1246. // Check if the variable has explicit DSA set and stop analysis if it so.
  1247. if (DVar.RefExpr) return;
  1248. auto ELoc = E->getExprLoc();
  1249. auto DKind = Stack->getCurrentDirective();
  1250. // The default(none) clause requires that each variable that is referenced
  1251. // in the construct, and does not have a predetermined data-sharing
  1252. // attribute, must have its data-sharing attribute explicitly determined
  1253. // by being listed in a data-sharing attribute clause.
  1254. if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
  1255. isParallelOrTaskRegion(DKind) &&
  1256. VarsWithInheritedDSA.count(VD) == 0) {
  1257. VarsWithInheritedDSA[VD] = E;
  1258. return;
  1259. }
  1260. // OpenMP [2.9.3.6, Restrictions, p.2]
  1261. // A list item that appears in a reduction clause of the innermost
  1262. // enclosing worksharing or parallel construct may not be accessed in an
  1263. // explicit task.
  1264. DVar = Stack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
  1265. [](OpenMPDirectiveKind K) -> bool {
  1266. return isOpenMPParallelDirective(K) ||
  1267. isOpenMPWorksharingDirective(K) ||
  1268. isOpenMPTeamsDirective(K);
  1269. },
  1270. false);
  1271. if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
  1272. ErrorFound = true;
  1273. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1274. ReportOriginalDSA(SemaRef, Stack, VD, DVar);
  1275. return;
  1276. }
  1277. // Define implicit data-sharing attributes for task.
  1278. DVar = Stack->getImplicitDSA(VD, false);
  1279. if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
  1280. ImplicitFirstprivate.push_back(E);
  1281. }
  1282. }
  1283. void VisitMemberExpr(MemberExpr *E) {
  1284. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  1285. if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
  1286. auto DVar = Stack->getTopDSA(FD, false);
  1287. // Check if the variable has explicit DSA set and stop analysis if it
  1288. // so.
  1289. if (DVar.RefExpr)
  1290. return;
  1291. auto ELoc = E->getExprLoc();
  1292. auto DKind = Stack->getCurrentDirective();
  1293. // OpenMP [2.9.3.6, Restrictions, p.2]
  1294. // A list item that appears in a reduction clause of the innermost
  1295. // enclosing worksharing or parallel construct may not be accessed in
  1296. // an
  1297. // explicit task.
  1298. DVar =
  1299. Stack->hasInnermostDSA(FD, MatchesAnyClause(OMPC_reduction),
  1300. [](OpenMPDirectiveKind K) -> bool {
  1301. return isOpenMPParallelDirective(K) ||
  1302. isOpenMPWorksharingDirective(K) ||
  1303. isOpenMPTeamsDirective(K);
  1304. },
  1305. false);
  1306. if (DKind == OMPD_task && DVar.CKind == OMPC_reduction) {
  1307. ErrorFound = true;
  1308. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  1309. ReportOriginalDSA(SemaRef, Stack, FD, DVar);
  1310. return;
  1311. }
  1312. // Define implicit data-sharing attributes for task.
  1313. DVar = Stack->getImplicitDSA(FD, false);
  1314. if (DKind == OMPD_task && DVar.CKind != OMPC_shared)
  1315. ImplicitFirstprivate.push_back(E);
  1316. }
  1317. }
  1318. }
  1319. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  1320. for (auto *C : S->clauses()) {
  1321. // Skip analysis of arguments of implicitly defined firstprivate clause
  1322. // for task directives.
  1323. if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid()))
  1324. for (auto *CC : C->children()) {
  1325. if (CC)
  1326. Visit(CC);
  1327. }
  1328. }
  1329. }
  1330. void VisitStmt(Stmt *S) {
  1331. for (auto *C : S->children()) {
  1332. if (C && !isa<OMPExecutableDirective>(C))
  1333. Visit(C);
  1334. }
  1335. }
  1336. bool isErrorFound() { return ErrorFound; }
  1337. ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; }
  1338. llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
  1339. return VarsWithInheritedDSA;
  1340. }
  1341. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  1342. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
  1343. };
  1344. } // namespace
  1345. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  1346. switch (DKind) {
  1347. case OMPD_parallel: {
  1348. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1349. QualType KmpInt32PtrTy =
  1350. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  1351. Sema::CapturedParamNameType Params[] = {
  1352. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1353. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1354. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1355. };
  1356. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1357. Params);
  1358. break;
  1359. }
  1360. case OMPD_simd: {
  1361. Sema::CapturedParamNameType Params[] = {
  1362. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1363. };
  1364. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1365. Params);
  1366. break;
  1367. }
  1368. case OMPD_for: {
  1369. Sema::CapturedParamNameType Params[] = {
  1370. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1371. };
  1372. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1373. Params);
  1374. break;
  1375. }
  1376. case OMPD_for_simd: {
  1377. Sema::CapturedParamNameType Params[] = {
  1378. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1379. };
  1380. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1381. Params);
  1382. break;
  1383. }
  1384. case OMPD_sections: {
  1385. Sema::CapturedParamNameType Params[] = {
  1386. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1387. };
  1388. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1389. Params);
  1390. break;
  1391. }
  1392. case OMPD_section: {
  1393. Sema::CapturedParamNameType Params[] = {
  1394. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1395. };
  1396. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1397. Params);
  1398. break;
  1399. }
  1400. case OMPD_single: {
  1401. Sema::CapturedParamNameType Params[] = {
  1402. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1403. };
  1404. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1405. Params);
  1406. break;
  1407. }
  1408. case OMPD_master: {
  1409. Sema::CapturedParamNameType Params[] = {
  1410. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1411. };
  1412. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1413. Params);
  1414. break;
  1415. }
  1416. case OMPD_critical: {
  1417. Sema::CapturedParamNameType Params[] = {
  1418. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1419. };
  1420. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1421. Params);
  1422. break;
  1423. }
  1424. case OMPD_parallel_for: {
  1425. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1426. QualType KmpInt32PtrTy =
  1427. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  1428. Sema::CapturedParamNameType Params[] = {
  1429. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1430. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1431. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1432. };
  1433. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1434. Params);
  1435. break;
  1436. }
  1437. case OMPD_parallel_for_simd: {
  1438. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1439. QualType KmpInt32PtrTy =
  1440. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  1441. Sema::CapturedParamNameType Params[] = {
  1442. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1443. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1444. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1445. };
  1446. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1447. Params);
  1448. break;
  1449. }
  1450. case OMPD_parallel_sections: {
  1451. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1452. QualType KmpInt32PtrTy =
  1453. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  1454. Sema::CapturedParamNameType Params[] = {
  1455. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1456. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1457. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1458. };
  1459. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1460. Params);
  1461. break;
  1462. }
  1463. case OMPD_task: {
  1464. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1465. QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
  1466. FunctionProtoType::ExtProtoInfo EPI;
  1467. EPI.Variadic = true;
  1468. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  1469. Sema::CapturedParamNameType Params[] = {
  1470. std::make_pair(".global_tid.", KmpInt32Ty),
  1471. std::make_pair(".part_id.", KmpInt32Ty),
  1472. std::make_pair(".privates.",
  1473. Context.VoidPtrTy.withConst().withRestrict()),
  1474. std::make_pair(
  1475. ".copy_fn.",
  1476. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  1477. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1478. };
  1479. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1480. Params);
  1481. // Mark this captured region as inlined, because we don't use outlined
  1482. // function directly.
  1483. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  1484. AlwaysInlineAttr::CreateImplicit(
  1485. Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
  1486. break;
  1487. }
  1488. case OMPD_ordered: {
  1489. Sema::CapturedParamNameType Params[] = {
  1490. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1491. };
  1492. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1493. Params);
  1494. break;
  1495. }
  1496. case OMPD_atomic: {
  1497. Sema::CapturedParamNameType Params[] = {
  1498. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1499. };
  1500. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1501. Params);
  1502. break;
  1503. }
  1504. case OMPD_target_data:
  1505. case OMPD_target:
  1506. case OMPD_target_parallel: {
  1507. Sema::CapturedParamNameType Params[] = {
  1508. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1509. };
  1510. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1511. Params);
  1512. break;
  1513. }
  1514. case OMPD_teams: {
  1515. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
  1516. QualType KmpInt32PtrTy =
  1517. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  1518. Sema::CapturedParamNameType Params[] = {
  1519. std::make_pair(".global_tid.", KmpInt32PtrTy),
  1520. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  1521. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1522. };
  1523. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1524. Params);
  1525. break;
  1526. }
  1527. case OMPD_taskgroup: {
  1528. Sema::CapturedParamNameType Params[] = {
  1529. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1530. };
  1531. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1532. Params);
  1533. break;
  1534. }
  1535. case OMPD_taskloop: {
  1536. Sema::CapturedParamNameType Params[] = {
  1537. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1538. };
  1539. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1540. Params);
  1541. break;
  1542. }
  1543. case OMPD_taskloop_simd: {
  1544. Sema::CapturedParamNameType Params[] = {
  1545. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1546. };
  1547. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1548. Params);
  1549. break;
  1550. }
  1551. case OMPD_distribute: {
  1552. Sema::CapturedParamNameType Params[] = {
  1553. std::make_pair(StringRef(), QualType()) // __context with shared vars
  1554. };
  1555. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  1556. Params);
  1557. break;
  1558. }
  1559. case OMPD_threadprivate:
  1560. case OMPD_taskyield:
  1561. case OMPD_barrier:
  1562. case OMPD_taskwait:
  1563. case OMPD_cancellation_point:
  1564. case OMPD_cancel:
  1565. case OMPD_flush:
  1566. case OMPD_target_enter_data:
  1567. case OMPD_target_exit_data:
  1568. llvm_unreachable("OpenMP Directive is not allowed");
  1569. case OMPD_unknown:
  1570. llvm_unreachable("Unknown OpenMP directive");
  1571. }
  1572. }
  1573. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  1574. ArrayRef<OMPClause *> Clauses) {
  1575. if (!S.isUsable()) {
  1576. ActOnCapturedRegionError();
  1577. return StmtError();
  1578. }
  1579. OMPOrderedClause *OC = nullptr;
  1580. OMPScheduleClause *SC = nullptr;
  1581. SmallVector<OMPLinearClause *, 4> LCs;
  1582. // This is required for proper codegen.
  1583. for (auto *Clause : Clauses) {
  1584. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  1585. Clause->getClauseKind() == OMPC_copyprivate ||
  1586. (getLangOpts().OpenMPUseTLS &&
  1587. getASTContext().getTargetInfo().isTLSSupported() &&
  1588. Clause->getClauseKind() == OMPC_copyin)) {
  1589. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  1590. // Mark all variables in private list clauses as used in inner region.
  1591. for (auto *VarRef : Clause->children()) {
  1592. if (auto *E = cast_or_null<Expr>(VarRef)) {
  1593. MarkDeclarationsReferencedInExpr(E);
  1594. }
  1595. }
  1596. DSAStack->setForceVarCapturing(/*V=*/false);
  1597. } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) &&
  1598. Clause->getClauseKind() == OMPC_schedule) {
  1599. // Mark all variables in private list clauses as used in inner region.
  1600. // Required for proper codegen of combined directives.
  1601. // TODO: add processing for other clauses.
  1602. if (auto *E = cast_or_null<Expr>(
  1603. cast<OMPScheduleClause>(Clause)->getHelperChunkSize()))
  1604. MarkDeclarationsReferencedInExpr(E);
  1605. }
  1606. if (Clause->getClauseKind() == OMPC_schedule)
  1607. SC = cast<OMPScheduleClause>(Clause);
  1608. else if (Clause->getClauseKind() == OMPC_ordered)
  1609. OC = cast<OMPOrderedClause>(Clause);
  1610. else if (Clause->getClauseKind() == OMPC_linear)
  1611. LCs.push_back(cast<OMPLinearClause>(Clause));
  1612. }
  1613. bool ErrorFound = false;
  1614. // OpenMP, 2.7.1 Loop Construct, Restrictions
  1615. // The nonmonotonic modifier cannot be specified if an ordered clause is
  1616. // specified.
  1617. if (SC &&
  1618. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  1619. SC->getSecondScheduleModifier() ==
  1620. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  1621. OC) {
  1622. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  1623. ? SC->getFirstScheduleModifierLoc()
  1624. : SC->getSecondScheduleModifierLoc(),
  1625. diag::err_omp_schedule_nonmonotonic_ordered)
  1626. << SourceRange(OC->getLocStart(), OC->getLocEnd());
  1627. ErrorFound = true;
  1628. }
  1629. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  1630. for (auto *C : LCs) {
  1631. Diag(C->getLocStart(), diag::err_omp_linear_ordered)
  1632. << SourceRange(OC->getLocStart(), OC->getLocEnd());
  1633. }
  1634. ErrorFound = true;
  1635. }
  1636. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  1637. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  1638. OC->getNumForLoops()) {
  1639. Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
  1640. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  1641. ErrorFound = true;
  1642. }
  1643. if (ErrorFound) {
  1644. ActOnCapturedRegionError();
  1645. return StmtError();
  1646. }
  1647. return ActOnCapturedRegionEnd(S.get());
  1648. }
  1649. static bool CheckNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
  1650. OpenMPDirectiveKind CurrentRegion,
  1651. const DeclarationNameInfo &CurrentName,
  1652. OpenMPDirectiveKind CancelRegion,
  1653. SourceLocation StartLoc) {
  1654. // Allowed nesting of constructs
  1655. // +------------------+-----------------+------------------------------------+
  1656. // | Parent directive | Child directive | Closely (!), No-Closely(+), Both(*)|
  1657. // +------------------+-----------------+------------------------------------+
  1658. // | parallel | parallel | * |
  1659. // | parallel | for | * |
  1660. // | parallel | for simd | * |
  1661. // | parallel | master | * |
  1662. // | parallel | critical | * |
  1663. // | parallel | simd | * |
  1664. // | parallel | sections | * |
  1665. // | parallel | section | + |
  1666. // | parallel | single | * |
  1667. // | parallel | parallel for | * |
  1668. // | parallel |parallel for simd| * |
  1669. // | parallel |parallel sections| * |
  1670. // | parallel | task | * |
  1671. // | parallel | taskyield | * |
  1672. // | parallel | barrier | * |
  1673. // | parallel | taskwait | * |
  1674. // | parallel | taskgroup | * |
  1675. // | parallel | flush | * |
  1676. // | parallel | ordered | + |
  1677. // | parallel | atomic | * |
  1678. // | parallel | target | * |
  1679. // | parallel | target parallel | * |
  1680. // | parallel | target enter | * |
  1681. // | | data | |
  1682. // | parallel | target exit | * |
  1683. // | | data | |
  1684. // | parallel | teams | + |
  1685. // | parallel | cancellation | |
  1686. // | | point | ! |
  1687. // | parallel | cancel | ! |
  1688. // | parallel | taskloop | * |
  1689. // | parallel | taskloop simd | * |
  1690. // | parallel | distribute | |
  1691. // +------------------+-----------------+------------------------------------+
  1692. // | for | parallel | * |
  1693. // | for | for | + |
  1694. // | for | for simd | + |
  1695. // | for | master | + |
  1696. // | for | critical | * |
  1697. // | for | simd | * |
  1698. // | for | sections | + |
  1699. // | for | section | + |
  1700. // | for | single | + |
  1701. // | for | parallel for | * |
  1702. // | for |parallel for simd| * |
  1703. // | for |parallel sections| * |
  1704. // | for | task | * |
  1705. // | for | taskyield | * |
  1706. // | for | barrier | + |
  1707. // | for | taskwait | * |
  1708. // | for | taskgroup | * |
  1709. // | for | flush | * |
  1710. // | for | ordered | * (if construct is ordered) |
  1711. // | for | atomic | * |
  1712. // | for | target | * |
  1713. // | for | target parallel | * |
  1714. // | for | target enter | * |
  1715. // | | data | |
  1716. // | for | target exit | * |
  1717. // | | data | |
  1718. // | for | teams | + |
  1719. // | for | cancellation | |
  1720. // | | point | ! |
  1721. // | for | cancel | ! |
  1722. // | for | taskloop | * |
  1723. // | for | taskloop simd | * |
  1724. // | for | distribute | |
  1725. // +------------------+-----------------+------------------------------------+
  1726. // | master | parallel | * |
  1727. // | master | for | + |
  1728. // | master | for simd | + |
  1729. // | master | master | * |
  1730. // | master | critical | * |
  1731. // | master | simd | * |
  1732. // | master | sections | + |
  1733. // | master | section | + |
  1734. // | master | single | + |
  1735. // | master | parallel for | * |
  1736. // | master |parallel for simd| * |
  1737. // | master |parallel sections| * |
  1738. // | master | task | * |
  1739. // | master | taskyield | * |
  1740. // | master | barrier | + |
  1741. // | master | taskwait | * |
  1742. // | master | taskgroup | * |
  1743. // | master | flush | * |
  1744. // | master | ordered | + |
  1745. // | master | atomic | * |
  1746. // | master | target | * |
  1747. // | master | target parallel | * |
  1748. // | master | target enter | * |
  1749. // | | data | |
  1750. // | master | target exit | * |
  1751. // | | data | |
  1752. // | master | teams | + |
  1753. // | master | cancellation | |
  1754. // | | point | |
  1755. // | master | cancel | |
  1756. // | master | taskloop | * |
  1757. // | master | taskloop simd | * |
  1758. // | master | distribute | |
  1759. // +------------------+-----------------+------------------------------------+
  1760. // | critical | parallel | * |
  1761. // | critical | for | + |
  1762. // | critical | for simd | + |
  1763. // | critical | master | * |
  1764. // | critical | critical | * (should have different names) |
  1765. // | critical | simd | * |
  1766. // | critical | sections | + |
  1767. // | critical | section | + |
  1768. // | critical | single | + |
  1769. // | critical | parallel for | * |
  1770. // | critical |parallel for simd| * |
  1771. // | critical |parallel sections| * |
  1772. // | critical | task | * |
  1773. // | critical | taskyield | * |
  1774. // | critical | barrier | + |
  1775. // | critical | taskwait | * |
  1776. // | critical | taskgroup | * |
  1777. // | critical | ordered | + |
  1778. // | critical | atomic | * |
  1779. // | critical | target | * |
  1780. // | critical | target parallel | * |
  1781. // | critical | target enter | * |
  1782. // | | data | |
  1783. // | critical | target exit | * |
  1784. // | | data | |
  1785. // | critical | teams | + |
  1786. // | critical | cancellation | |
  1787. // | | point | |
  1788. // | critical | cancel | |
  1789. // | critical | taskloop | * |
  1790. // | critical | taskloop simd | * |
  1791. // | critical | distribute | |
  1792. // +------------------+-----------------+------------------------------------+
  1793. // | simd | parallel | |
  1794. // | simd | for | |
  1795. // | simd | for simd | |
  1796. // | simd | master | |
  1797. // | simd | critical | |
  1798. // | simd | simd | * |
  1799. // | simd | sections | |
  1800. // | simd | section | |
  1801. // | simd | single | |
  1802. // | simd | parallel for | |
  1803. // | simd |parallel for simd| |
  1804. // | simd |parallel sections| |
  1805. // | simd | task | |
  1806. // | simd | taskyield | |
  1807. // | simd | barrier | |
  1808. // | simd | taskwait | |
  1809. // | simd | taskgroup | |
  1810. // | simd | flush | |
  1811. // | simd | ordered | + (with simd clause) |
  1812. // | simd | atomic | |
  1813. // | simd | target | |
  1814. // | simd | target parallel | |
  1815. // | simd | target enter | |
  1816. // | | data | |
  1817. // | simd | target exit | |
  1818. // | | data | |
  1819. // | simd | teams | |
  1820. // | simd | cancellation | |
  1821. // | | point | |
  1822. // | simd | cancel | |
  1823. // | simd | taskloop | |
  1824. // | simd | taskloop simd | |
  1825. // | simd | distribute | |
  1826. // +------------------+-----------------+------------------------------------+
  1827. // | for simd | parallel | |
  1828. // | for simd | for | |
  1829. // | for simd | for simd | |
  1830. // | for simd | master | |
  1831. // | for simd | critical | |
  1832. // | for simd | simd | * |
  1833. // | for simd | sections | |
  1834. // | for simd | section | |
  1835. // | for simd | single | |
  1836. // | for simd | parallel for | |
  1837. // | for simd |parallel for simd| |
  1838. // | for simd |parallel sections| |
  1839. // | for simd | task | |
  1840. // | for simd | taskyield | |
  1841. // | for simd | barrier | |
  1842. // | for simd | taskwait | |
  1843. // | for simd | taskgroup | |
  1844. // | for simd | flush | |
  1845. // | for simd | ordered | + (with simd clause) |
  1846. // | for simd | atomic | |
  1847. // | for simd | target | |
  1848. // | for simd | target parallel | |
  1849. // | for simd | target enter | |
  1850. // | | data | |
  1851. // | for simd | target exit | |
  1852. // | | data | |
  1853. // | for simd | teams | |
  1854. // | for simd | cancellation | |
  1855. // | | point | |
  1856. // | for simd | cancel | |
  1857. // | for simd | taskloop | |
  1858. // | for simd | taskloop simd | |
  1859. // | for simd | distribute | |
  1860. // +------------------+-----------------+------------------------------------+
  1861. // | parallel for simd| parallel | |
  1862. // | parallel for simd| for | |
  1863. // | parallel for simd| for simd | |
  1864. // | parallel for simd| master | |
  1865. // | parallel for simd| critical | |
  1866. // | parallel for simd| simd | * |
  1867. // | parallel for simd| sections | |
  1868. // | parallel for simd| section | |
  1869. // | parallel for simd| single | |
  1870. // | parallel for simd| parallel for | |
  1871. // | parallel for simd|parallel for simd| |
  1872. // | parallel for simd|parallel sections| |
  1873. // | parallel for simd| task | |
  1874. // | parallel for simd| taskyield | |
  1875. // | parallel for simd| barrier | |
  1876. // | parallel for simd| taskwait | |
  1877. // | parallel for simd| taskgroup | |
  1878. // | parallel for simd| flush | |
  1879. // | parallel for simd| ordered | + (with simd clause) |
  1880. // | parallel for simd| atomic | |
  1881. // | parallel for simd| target | |
  1882. // | parallel for simd| target parallel | |
  1883. // | parallel for simd| target enter | |
  1884. // | | data | |
  1885. // | parallel for simd| target exit | |
  1886. // | | data | |
  1887. // | parallel for simd| teams | |
  1888. // | parallel for simd| cancellation | |
  1889. // | | point | |
  1890. // | parallel for simd| cancel | |
  1891. // | parallel for simd| taskloop | |
  1892. // | parallel for simd| taskloop simd | |
  1893. // | parallel for simd| distribute | |
  1894. // +------------------+-----------------+------------------------------------+
  1895. // | sections | parallel | * |
  1896. // | sections | for | + |
  1897. // | sections | for simd | + |
  1898. // | sections | master | + |
  1899. // | sections | critical | * |
  1900. // | sections | simd | * |
  1901. // | sections | sections | + |
  1902. // | sections | section | * |
  1903. // | sections | single | + |
  1904. // | sections | parallel for | * |
  1905. // | sections |parallel for simd| * |
  1906. // | sections |parallel sections| * |
  1907. // | sections | task | * |
  1908. // | sections | taskyield | * |
  1909. // | sections | barrier | + |
  1910. // | sections | taskwait | * |
  1911. // | sections | taskgroup | * |
  1912. // | sections | flush | * |
  1913. // | sections | ordered | + |
  1914. // | sections | atomic | * |
  1915. // | sections | target | * |
  1916. // | sections | target parallel | * |
  1917. // | sections | target enter | * |
  1918. // | | data | |
  1919. // | sections | target exit | * |
  1920. // | | data | |
  1921. // | sections | teams | + |
  1922. // | sections | cancellation | |
  1923. // | | point | ! |
  1924. // | sections | cancel | ! |
  1925. // | sections | taskloop | * |
  1926. // | sections | taskloop simd | * |
  1927. // | sections | distribute | |
  1928. // +------------------+-----------------+------------------------------------+
  1929. // | section | parallel | * |
  1930. // | section | for | + |
  1931. // | section | for simd | + |
  1932. // | section | master | + |
  1933. // | section | critical | * |
  1934. // | section | simd | * |
  1935. // | section | sections | + |
  1936. // | section | section | + |
  1937. // | section | single | + |
  1938. // | section | parallel for | * |
  1939. // | section |parallel for simd| * |
  1940. // | section |parallel sections| * |
  1941. // | section | task | * |
  1942. // | section | taskyield | * |
  1943. // | section | barrier | + |
  1944. // | section | taskwait | * |
  1945. // | section | taskgroup | * |
  1946. // | section | flush | * |
  1947. // | section | ordered | + |
  1948. // | section | atomic | * |
  1949. // | section | target | * |
  1950. // | section | target parallel | * |
  1951. // | section | target enter | * |
  1952. // | | data | |
  1953. // | section | target exit | * |
  1954. // | | data | |
  1955. // | section | teams | + |
  1956. // | section | cancellation | |
  1957. // | | point | ! |
  1958. // | section | cancel | ! |
  1959. // | section | taskloop | * |
  1960. // | section | taskloop simd | * |
  1961. // | section | distribute | |
  1962. // +------------------+-----------------+------------------------------------+
  1963. // | single | parallel | * |
  1964. // | single | for | + |
  1965. // | single | for simd | + |
  1966. // | single | master | + |
  1967. // | single | critical | * |
  1968. // | single | simd | * |
  1969. // | single | sections | + |
  1970. // | single | section | + |
  1971. // | single | single | + |
  1972. // | single | parallel for | * |
  1973. // | single |parallel for simd| * |
  1974. // | single |parallel sections| * |
  1975. // | single | task | * |
  1976. // | single | taskyield | * |
  1977. // | single | barrier | + |
  1978. // | single | taskwait | * |
  1979. // | single | taskgroup | * |
  1980. // | single | flush | * |
  1981. // | single | ordered | + |
  1982. // | single | atomic | * |
  1983. // | single | target | * |
  1984. // | single | target parallel | * |
  1985. // | single | target enter | * |
  1986. // | | data | |
  1987. // | single | target exit | * |
  1988. // | | data | |
  1989. // | single | teams | + |
  1990. // | single | cancellation | |
  1991. // | | point | |
  1992. // | single | cancel | |
  1993. // | single | taskloop | * |
  1994. // | single | taskloop simd | * |
  1995. // | single | distribute | |
  1996. // +------------------+-----------------+------------------------------------+
  1997. // | parallel for | parallel | * |
  1998. // | parallel for | for | + |
  1999. // | parallel for | for simd | + |
  2000. // | parallel for | master | + |
  2001. // | parallel for | critical | * |
  2002. // | parallel for | simd | * |
  2003. // | parallel for | sections | + |
  2004. // | parallel for | section | + |
  2005. // | parallel for | single | + |
  2006. // | parallel for | parallel for | * |
  2007. // | parallel for |parallel for simd| * |
  2008. // | parallel for |parallel sections| * |
  2009. // | parallel for | task | * |
  2010. // | parallel for | taskyield | * |
  2011. // | parallel for | barrier | + |
  2012. // | parallel for | taskwait | * |
  2013. // | parallel for | taskgroup | * |
  2014. // | parallel for | flush | * |
  2015. // | parallel for | ordered | * (if construct is ordered) |
  2016. // | parallel for | atomic | * |
  2017. // | parallel for | target | * |
  2018. // | parallel for | target parallel | * |
  2019. // | parallel for | target enter | * |
  2020. // | | data | |
  2021. // | parallel for | target exit | * |
  2022. // | | data | |
  2023. // | parallel for | teams | + |
  2024. // | parallel for | cancellation | |
  2025. // | | point | ! |
  2026. // | parallel for | cancel | ! |
  2027. // | parallel for | taskloop | * |
  2028. // | parallel for | taskloop simd | * |
  2029. // | parallel for | distribute | |
  2030. // +------------------+-----------------+------------------------------------+
  2031. // | parallel sections| parallel | * |
  2032. // | parallel sections| for | + |
  2033. // | parallel sections| for simd | + |
  2034. // | parallel sections| master | + |
  2035. // | parallel sections| critical | + |
  2036. // | parallel sections| simd | * |
  2037. // | parallel sections| sections | + |
  2038. // | parallel sections| section | * |
  2039. // | parallel sections| single | + |
  2040. // | parallel sections| parallel for | * |
  2041. // | parallel sections|parallel for simd| * |
  2042. // | parallel sections|parallel sections| * |
  2043. // | parallel sections| task | * |
  2044. // | parallel sections| taskyield | * |
  2045. // | parallel sections| barrier | + |
  2046. // | parallel sections| taskwait | * |
  2047. // | parallel sections| taskgroup | * |
  2048. // | parallel sections| flush | * |
  2049. // | parallel sections| ordered | + |
  2050. // | parallel sections| atomic | * |
  2051. // | parallel sections| target | * |
  2052. // | parallel sections| target parallel | * |
  2053. // | parallel sections| target enter | * |
  2054. // | | data | |
  2055. // | parallel sections| target exit | * |
  2056. // | | data | |
  2057. // | parallel sections| teams | + |
  2058. // | parallel sections| cancellation | |
  2059. // | | point | ! |
  2060. // | parallel sections| cancel | ! |
  2061. // | parallel sections| taskloop | * |
  2062. // | parallel sections| taskloop simd | * |
  2063. // | parallel sections| distribute | |
  2064. // +------------------+-----------------+------------------------------------+
  2065. // | task | parallel | * |
  2066. // | task | for | + |
  2067. // | task | for simd | + |
  2068. // | task | master | + |
  2069. // | task | critical | * |
  2070. // | task | simd | * |
  2071. // | task | sections | + |
  2072. // | task | section | + |
  2073. // | task | single | + |
  2074. // | task | parallel for | * |
  2075. // | task |parallel for simd| * |
  2076. // | task |parallel sections| * |
  2077. // | task | task | * |
  2078. // | task | taskyield | * |
  2079. // | task | barrier | + |
  2080. // | task | taskwait | * |
  2081. // | task | taskgroup | * |
  2082. // | task | flush | * |
  2083. // | task | ordered | + |
  2084. // | task | atomic | * |
  2085. // | task | target | * |
  2086. // | task | target parallel | * |
  2087. // | task | target enter | * |
  2088. // | | data | |
  2089. // | task | target exit | * |
  2090. // | | data | |
  2091. // | task | teams | + |
  2092. // | task | cancellation | |
  2093. // | | point | ! |
  2094. // | task | cancel | ! |
  2095. // | task | taskloop | * |
  2096. // | task | taskloop simd | * |
  2097. // | task | distribute | |
  2098. // +------------------+-----------------+------------------------------------+
  2099. // | ordered | parallel | * |
  2100. // | ordered | for | + |
  2101. // | ordered | for simd | + |
  2102. // | ordered | master | * |
  2103. // | ordered | critical | * |
  2104. // | ordered | simd | * |
  2105. // | ordered | sections | + |
  2106. // | ordered | section | + |
  2107. // | ordered | single | + |
  2108. // | ordered | parallel for | * |
  2109. // | ordered |parallel for simd| * |
  2110. // | ordered |parallel sections| * |
  2111. // | ordered | task | * |
  2112. // | ordered | taskyield | * |
  2113. // | ordered | barrier | + |
  2114. // | ordered | taskwait | * |
  2115. // | ordered | taskgroup | * |
  2116. // | ordered | flush | * |
  2117. // | ordered | ordered | + |
  2118. // | ordered | atomic | * |
  2119. // | ordered | target | * |
  2120. // | ordered | target parallel | * |
  2121. // | ordered | target enter | * |
  2122. // | | data | |
  2123. // | ordered | target exit | * |
  2124. // | | data | |
  2125. // | ordered | teams | + |
  2126. // | ordered | cancellation | |
  2127. // | | point | |
  2128. // | ordered | cancel | |
  2129. // | ordered | taskloop | * |
  2130. // | ordered | taskloop simd | * |
  2131. // | ordered | distribute | |
  2132. // +------------------+-----------------+------------------------------------+
  2133. // | atomic | parallel | |
  2134. // | atomic | for | |
  2135. // | atomic | for simd | |
  2136. // | atomic | master | |
  2137. // | atomic | critical | |
  2138. // | atomic | simd | |
  2139. // | atomic | sections | |
  2140. // | atomic | section | |
  2141. // | atomic | single | |
  2142. // | atomic | parallel for | |
  2143. // | atomic |parallel for simd| |
  2144. // | atomic |parallel sections| |
  2145. // | atomic | task | |
  2146. // | atomic | taskyield | |
  2147. // | atomic | barrier | |
  2148. // | atomic | taskwait | |
  2149. // | atomic | taskgroup | |
  2150. // | atomic | flush | |
  2151. // | atomic | ordered | |
  2152. // | atomic | atomic | |
  2153. // | atomic | target | |
  2154. // | atomic | target parallel | |
  2155. // | atomic | target enter | |
  2156. // | | data | |
  2157. // | atomic | target exit | |
  2158. // | | data | |
  2159. // | atomic | teams | |
  2160. // | atomic | cancellation | |
  2161. // | | point | |
  2162. // | atomic | cancel | |
  2163. // | atomic | taskloop | |
  2164. // | atomic | taskloop simd | |
  2165. // | atomic | distribute | |
  2166. // +------------------+-----------------+------------------------------------+
  2167. // | target | parallel | * |
  2168. // | target | for | * |
  2169. // | target | for simd | * |
  2170. // | target | master | * |
  2171. // | target | critical | * |
  2172. // | target | simd | * |
  2173. // | target | sections | * |
  2174. // | target | section | * |
  2175. // | target | single | * |
  2176. // | target | parallel for | * |
  2177. // | target |parallel for simd| * |
  2178. // | target |parallel sections| * |
  2179. // | target | task | * |
  2180. // | target | taskyield | * |
  2181. // | target | barrier | * |
  2182. // | target | taskwait | * |
  2183. // | target | taskgroup | * |
  2184. // | target | flush | * |
  2185. // | target | ordered | * |
  2186. // | target | atomic | * |
  2187. // | target | target | |
  2188. // | target | target parallel | |
  2189. // | target | target enter | |
  2190. // | | data | |
  2191. // | target | target exit | |
  2192. // | | data | |
  2193. // | target | teams | * |
  2194. // | target | cancellation | |
  2195. // | | point | |
  2196. // | target | cancel | |
  2197. // | target | taskloop | * |
  2198. // | target | taskloop simd | * |
  2199. // | target | distribute | |
  2200. // +------------------+-----------------+------------------------------------+
  2201. // | target parallel | parallel | * |
  2202. // | target parallel | for | * |
  2203. // | target parallel | for simd | * |
  2204. // | target parallel | master | * |
  2205. // | target parallel | critical | * |
  2206. // | target parallel | simd | * |
  2207. // | target parallel | sections | * |
  2208. // | target parallel | section | * |
  2209. // | target parallel | single | * |
  2210. // | target parallel | parallel for | * |
  2211. // | target parallel |parallel for simd| * |
  2212. // | target parallel |parallel sections| * |
  2213. // | target parallel | task | * |
  2214. // | target parallel | taskyield | * |
  2215. // | target parallel | barrier | * |
  2216. // | target parallel | taskwait | * |
  2217. // | target parallel | taskgroup | * |
  2218. // | target parallel | flush | * |
  2219. // | target parallel | ordered | * |
  2220. // | target parallel | atomic | * |
  2221. // | target parallel | target | |
  2222. // | target parallel | target parallel | |
  2223. // | target parallel | target enter | |
  2224. // | | data | |
  2225. // | target parallel | target exit | |
  2226. // | | data | |
  2227. // | target parallel | teams | |
  2228. // | target parallel | cancellation | |
  2229. // | | point | ! |
  2230. // | target parallel | cancel | ! |
  2231. // | target parallel | taskloop | * |
  2232. // | target parallel | taskloop simd | * |
  2233. // | target parallel | distribute | |
  2234. // +------------------+-----------------+------------------------------------+
  2235. // | teams | parallel | * |
  2236. // | teams | for | + |
  2237. // | teams | for simd | + |
  2238. // | teams | master | + |
  2239. // | teams | critical | + |
  2240. // | teams | simd | + |
  2241. // | teams | sections | + |
  2242. // | teams | section | + |
  2243. // | teams | single | + |
  2244. // | teams | parallel for | * |
  2245. // | teams |parallel for simd| * |
  2246. // | teams |parallel sections| * |
  2247. // | teams | task | + |
  2248. // | teams | taskyield | + |
  2249. // | teams | barrier | + |
  2250. // | teams | taskwait | + |
  2251. // | teams | taskgroup | + |
  2252. // | teams | flush | + |
  2253. // | teams | ordered | + |
  2254. // | teams | atomic | + |
  2255. // | teams | target | + |
  2256. // | teams | target parallel | + |
  2257. // | teams | target enter | + |
  2258. // | | data | |
  2259. // | teams | target exit | + |
  2260. // | | data | |
  2261. // | teams | teams | + |
  2262. // | teams | cancellation | |
  2263. // | | point | |
  2264. // | teams | cancel | |
  2265. // | teams | taskloop | + |
  2266. // | teams | taskloop simd | + |
  2267. // | teams | distribute | ! |
  2268. // +------------------+-----------------+------------------------------------+
  2269. // | taskloop | parallel | * |
  2270. // | taskloop | for | + |
  2271. // | taskloop | for simd | + |
  2272. // | taskloop | master | + |
  2273. // | taskloop | critical | * |
  2274. // | taskloop | simd | * |
  2275. // | taskloop | sections | + |
  2276. // | taskloop | section | + |
  2277. // | taskloop | single | + |
  2278. // | taskloop | parallel for | * |
  2279. // | taskloop |parallel for simd| * |
  2280. // | taskloop |parallel sections| * |
  2281. // | taskloop | task | * |
  2282. // | taskloop | taskyield | * |
  2283. // | taskloop | barrier | + |
  2284. // | taskloop | taskwait | * |
  2285. // | taskloop | taskgroup | * |
  2286. // | taskloop | flush | * |
  2287. // | taskloop | ordered | + |
  2288. // | taskloop | atomic | * |
  2289. // | taskloop | target | * |
  2290. // | taskloop | target parallel | * |
  2291. // | taskloop | target enter | * |
  2292. // | | data | |
  2293. // | taskloop | target exit | * |
  2294. // | | data | |
  2295. // | taskloop | teams | + |
  2296. // | taskloop | cancellation | |
  2297. // | | point | |
  2298. // | taskloop | cancel | |
  2299. // | taskloop | taskloop | * |
  2300. // | taskloop | distribute | |
  2301. // +------------------+-----------------+------------------------------------+
  2302. // | taskloop simd | parallel | |
  2303. // | taskloop simd | for | |
  2304. // | taskloop simd | for simd | |
  2305. // | taskloop simd | master | |
  2306. // | taskloop simd | critical | |
  2307. // | taskloop simd | simd | * |
  2308. // | taskloop simd | sections | |
  2309. // | taskloop simd | section | |
  2310. // | taskloop simd | single | |
  2311. // | taskloop simd | parallel for | |
  2312. // | taskloop simd |parallel for simd| |
  2313. // | taskloop simd |parallel sections| |
  2314. // | taskloop simd | task | |
  2315. // | taskloop simd | taskyield | |
  2316. // | taskloop simd | barrier | |
  2317. // | taskloop simd | taskwait | |
  2318. // | taskloop simd | taskgroup | |
  2319. // | taskloop simd | flush | |
  2320. // | taskloop simd | ordered | + (with simd clause) |
  2321. // | taskloop simd | atomic | |
  2322. // | taskloop simd | target | |
  2323. // | taskloop simd | target parallel | |
  2324. // | taskloop simd | target enter | |
  2325. // | | data | |
  2326. // | taskloop simd | target exit | |
  2327. // | | data | |
  2328. // | taskloop simd | teams | |
  2329. // | taskloop simd | cancellation | |
  2330. // | | point | |
  2331. // | taskloop simd | cancel | |
  2332. // | taskloop simd | taskloop | |
  2333. // | taskloop simd | taskloop simd | |
  2334. // | taskloop simd | distribute | |
  2335. // +------------------+-----------------+------------------------------------+
  2336. // | distribute | parallel | * |
  2337. // | distribute | for | * |
  2338. // | distribute | for simd | * |
  2339. // | distribute | master | * |
  2340. // | distribute | critical | * |
  2341. // | distribute | simd | * |
  2342. // | distribute | sections | * |
  2343. // | distribute | section | * |
  2344. // | distribute | single | * |
  2345. // | distribute | parallel for | * |
  2346. // | distribute |parallel for simd| * |
  2347. // | distribute |parallel sections| * |
  2348. // | distribute | task | * |
  2349. // | distribute | taskyield | * |
  2350. // | distribute | barrier | * |
  2351. // | distribute | taskwait | * |
  2352. // | distribute | taskgroup | * |
  2353. // | distribute | flush | * |
  2354. // | distribute | ordered | + |
  2355. // | distribute | atomic | * |
  2356. // | distribute | target | |
  2357. // | distribute | target parallel | |
  2358. // | distribute | target enter | |
  2359. // | | data | |
  2360. // | distribute | target exit | |
  2361. // | | data | |
  2362. // | distribute | teams | |
  2363. // | distribute | cancellation | + |
  2364. // | | point | |
  2365. // | distribute | cancel | + |
  2366. // | distribute | taskloop | * |
  2367. // | distribute | taskloop simd | * |
  2368. // | distribute | distribute | |
  2369. // +------------------+-----------------+------------------------------------+
  2370. if (Stack->getCurScope()) {
  2371. auto ParentRegion = Stack->getParentDirective();
  2372. auto OffendingRegion = ParentRegion;
  2373. bool NestingProhibited = false;
  2374. bool CloseNesting = true;
  2375. enum {
  2376. NoRecommend,
  2377. ShouldBeInParallelRegion,
  2378. ShouldBeInOrderedRegion,
  2379. ShouldBeInTargetRegion,
  2380. ShouldBeInTeamsRegion
  2381. } Recommend = NoRecommend;
  2382. if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered &&
  2383. CurrentRegion != OMPD_simd) {
  2384. // OpenMP [2.16, Nesting of Regions]
  2385. // OpenMP constructs may not be nested inside a simd region.
  2386. // OpenMP [2.8.1,simd Construct, Restrictions]
  2387. // An ordered construct with the simd clause is the only OpenMP construct
  2388. // that can appear in the simd region.
  2389. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  2390. return true;
  2391. }
  2392. if (ParentRegion == OMPD_atomic) {
  2393. // OpenMP [2.16, Nesting of Regions]
  2394. // OpenMP constructs may not be nested inside an atomic region.
  2395. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  2396. return true;
  2397. }
  2398. if (CurrentRegion == OMPD_section) {
  2399. // OpenMP [2.7.2, sections Construct, Restrictions]
  2400. // Orphaned section directives are prohibited. That is, the section
  2401. // directives must appear within the sections construct and must not be
  2402. // encountered elsewhere in the sections region.
  2403. if (ParentRegion != OMPD_sections &&
  2404. ParentRegion != OMPD_parallel_sections) {
  2405. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  2406. << (ParentRegion != OMPD_unknown)
  2407. << getOpenMPDirectiveName(ParentRegion);
  2408. return true;
  2409. }
  2410. return false;
  2411. }
  2412. // Allow some constructs to be orphaned (they could be used in functions,
  2413. // called from OpenMP regions with the required preconditions).
  2414. if (ParentRegion == OMPD_unknown)
  2415. return false;
  2416. if (CurrentRegion == OMPD_cancellation_point ||
  2417. CurrentRegion == OMPD_cancel) {
  2418. // OpenMP [2.16, Nesting of Regions]
  2419. // A cancellation point construct for which construct-type-clause is
  2420. // taskgroup must be nested inside a task construct. A cancellation
  2421. // point construct for which construct-type-clause is not taskgroup must
  2422. // be closely nested inside an OpenMP construct that matches the type
  2423. // specified in construct-type-clause.
  2424. // A cancel construct for which construct-type-clause is taskgroup must be
  2425. // nested inside a task construct. A cancel construct for which
  2426. // construct-type-clause is not taskgroup must be closely nested inside an
  2427. // OpenMP construct that matches the type specified in
  2428. // construct-type-clause.
  2429. NestingProhibited =
  2430. !((CancelRegion == OMPD_parallel &&
  2431. (ParentRegion == OMPD_parallel ||
  2432. ParentRegion == OMPD_target_parallel)) ||
  2433. (CancelRegion == OMPD_for &&
  2434. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for)) ||
  2435. (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
  2436. (CancelRegion == OMPD_sections &&
  2437. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  2438. ParentRegion == OMPD_parallel_sections)));
  2439. } else if (CurrentRegion == OMPD_master) {
  2440. // OpenMP [2.16, Nesting of Regions]
  2441. // A master region may not be closely nested inside a worksharing,
  2442. // atomic, or explicit task region.
  2443. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  2444. ParentRegion == OMPD_task ||
  2445. isOpenMPTaskLoopDirective(ParentRegion);
  2446. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  2447. // OpenMP [2.16, Nesting of Regions]
  2448. // A critical region may not be nested (closely or otherwise) inside a
  2449. // critical region with the same name. Note that this restriction is not
  2450. // sufficient to prevent deadlock.
  2451. SourceLocation PreviousCriticalLoc;
  2452. bool DeadLock =
  2453. Stack->hasDirective([CurrentName, &PreviousCriticalLoc](
  2454. OpenMPDirectiveKind K,
  2455. const DeclarationNameInfo &DNI,
  2456. SourceLocation Loc)
  2457. ->bool {
  2458. if (K == OMPD_critical &&
  2459. DNI.getName() == CurrentName.getName()) {
  2460. PreviousCriticalLoc = Loc;
  2461. return true;
  2462. } else
  2463. return false;
  2464. },
  2465. false /* skip top directive */);
  2466. if (DeadLock) {
  2467. SemaRef.Diag(StartLoc,
  2468. diag::err_omp_prohibited_region_critical_same_name)
  2469. << CurrentName.getName();
  2470. if (PreviousCriticalLoc.isValid())
  2471. SemaRef.Diag(PreviousCriticalLoc,
  2472. diag::note_omp_previous_critical_region);
  2473. return true;
  2474. }
  2475. } else if (CurrentRegion == OMPD_barrier) {
  2476. // OpenMP [2.16, Nesting of Regions]
  2477. // A barrier region may not be closely nested inside a worksharing,
  2478. // explicit task, critical, ordered, atomic, or master region.
  2479. NestingProhibited =
  2480. isOpenMPWorksharingDirective(ParentRegion) ||
  2481. ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
  2482. ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered ||
  2483. isOpenMPTaskLoopDirective(ParentRegion);
  2484. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  2485. !isOpenMPParallelDirective(CurrentRegion)) {
  2486. // OpenMP [2.16, Nesting of Regions]
  2487. // A worksharing region may not be closely nested inside a worksharing,
  2488. // explicit task, critical, ordered, atomic, or master region.
  2489. NestingProhibited =
  2490. isOpenMPWorksharingDirective(ParentRegion) ||
  2491. ParentRegion == OMPD_task || ParentRegion == OMPD_master ||
  2492. ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered ||
  2493. isOpenMPTaskLoopDirective(ParentRegion);
  2494. Recommend = ShouldBeInParallelRegion;
  2495. } else if (CurrentRegion == OMPD_ordered) {
  2496. // OpenMP [2.16, Nesting of Regions]
  2497. // An ordered region may not be closely nested inside a critical,
  2498. // atomic, or explicit task region.
  2499. // An ordered region must be closely nested inside a loop region (or
  2500. // parallel loop region) with an ordered clause.
  2501. // OpenMP [2.8.1,simd Construct, Restrictions]
  2502. // An ordered construct with the simd clause is the only OpenMP construct
  2503. // that can appear in the simd region.
  2504. NestingProhibited = ParentRegion == OMPD_critical ||
  2505. ParentRegion == OMPD_task ||
  2506. isOpenMPTaskLoopDirective(ParentRegion) ||
  2507. !(isOpenMPSimdDirective(ParentRegion) ||
  2508. Stack->isParentOrderedRegion());
  2509. Recommend = ShouldBeInOrderedRegion;
  2510. } else if (isOpenMPTeamsDirective(CurrentRegion)) {
  2511. // OpenMP [2.16, Nesting of Regions]
  2512. // If specified, a teams construct must be contained within a target
  2513. // construct.
  2514. NestingProhibited = ParentRegion != OMPD_target;
  2515. Recommend = ShouldBeInTargetRegion;
  2516. Stack->setParentTeamsRegionLoc(Stack->getConstructLoc());
  2517. }
  2518. if (!NestingProhibited && isOpenMPTeamsDirective(ParentRegion)) {
  2519. // OpenMP [2.16, Nesting of Regions]
  2520. // distribute, parallel, parallel sections, parallel workshare, and the
  2521. // parallel loop and parallel loop SIMD constructs are the only OpenMP
  2522. // constructs that can be closely nested in the teams region.
  2523. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  2524. !isOpenMPDistributeDirective(CurrentRegion);
  2525. Recommend = ShouldBeInParallelRegion;
  2526. }
  2527. if (!NestingProhibited && isOpenMPDistributeDirective(CurrentRegion)) {
  2528. // OpenMP 4.5 [2.17 Nesting of Regions]
  2529. // The region associated with the distribute construct must be strictly
  2530. // nested inside a teams region
  2531. NestingProhibited = !isOpenMPTeamsDirective(ParentRegion);
  2532. Recommend = ShouldBeInTeamsRegion;
  2533. }
  2534. if (!NestingProhibited &&
  2535. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  2536. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  2537. // OpenMP 4.5 [2.17 Nesting of Regions]
  2538. // If a target, target update, target data, target enter data, or
  2539. // target exit data construct is encountered during execution of a
  2540. // target region, the behavior is unspecified.
  2541. NestingProhibited = Stack->hasDirective(
  2542. [&OffendingRegion](OpenMPDirectiveKind K,
  2543. const DeclarationNameInfo &DNI,
  2544. SourceLocation Loc) -> bool {
  2545. if (isOpenMPTargetExecutionDirective(K)) {
  2546. OffendingRegion = K;
  2547. return true;
  2548. } else
  2549. return false;
  2550. },
  2551. false /* don't skip top directive */);
  2552. CloseNesting = false;
  2553. }
  2554. if (NestingProhibited) {
  2555. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  2556. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  2557. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  2558. return true;
  2559. }
  2560. }
  2561. return false;
  2562. }
  2563. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  2564. ArrayRef<OMPClause *> Clauses,
  2565. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  2566. bool ErrorFound = false;
  2567. unsigned NamedModifiersNumber = 0;
  2568. SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
  2569. OMPD_unknown + 1);
  2570. SmallVector<SourceLocation, 4> NameModifierLoc;
  2571. for (const auto *C : Clauses) {
  2572. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  2573. // At most one if clause without a directive-name-modifier can appear on
  2574. // the directive.
  2575. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  2576. if (FoundNameModifiers[CurNM]) {
  2577. S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
  2578. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  2579. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  2580. ErrorFound = true;
  2581. } else if (CurNM != OMPD_unknown) {
  2582. NameModifierLoc.push_back(IC->getNameModifierLoc());
  2583. ++NamedModifiersNumber;
  2584. }
  2585. FoundNameModifiers[CurNM] = IC;
  2586. if (CurNM == OMPD_unknown)
  2587. continue;
  2588. // Check if the specified name modifier is allowed for the current
  2589. // directive.
  2590. // At most one if clause with the particular directive-name-modifier can
  2591. // appear on the directive.
  2592. bool MatchFound = false;
  2593. for (auto NM : AllowedNameModifiers) {
  2594. if (CurNM == NM) {
  2595. MatchFound = true;
  2596. break;
  2597. }
  2598. }
  2599. if (!MatchFound) {
  2600. S.Diag(IC->getNameModifierLoc(),
  2601. diag::err_omp_wrong_if_directive_name_modifier)
  2602. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  2603. ErrorFound = true;
  2604. }
  2605. }
  2606. }
  2607. // If any if clause on the directive includes a directive-name-modifier then
  2608. // all if clauses on the directive must include a directive-name-modifier.
  2609. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  2610. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  2611. S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
  2612. diag::err_omp_no_more_if_clause);
  2613. } else {
  2614. std::string Values;
  2615. std::string Sep(", ");
  2616. unsigned AllowedCnt = 0;
  2617. unsigned TotalAllowedNum =
  2618. AllowedNameModifiers.size() - NamedModifiersNumber;
  2619. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  2620. ++Cnt) {
  2621. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  2622. if (!FoundNameModifiers[NM]) {
  2623. Values += "'";
  2624. Values += getOpenMPDirectiveName(NM);
  2625. Values += "'";
  2626. if (AllowedCnt + 2 == TotalAllowedNum)
  2627. Values += " or ";
  2628. else if (AllowedCnt + 1 != TotalAllowedNum)
  2629. Values += Sep;
  2630. ++AllowedCnt;
  2631. }
  2632. }
  2633. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
  2634. diag::err_omp_unnamed_if_clause)
  2635. << (TotalAllowedNum > 1) << Values;
  2636. }
  2637. for (auto Loc : NameModifierLoc) {
  2638. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  2639. }
  2640. ErrorFound = true;
  2641. }
  2642. return ErrorFound;
  2643. }
  2644. StmtResult Sema::ActOnOpenMPExecutableDirective(
  2645. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  2646. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  2647. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  2648. StmtResult Res = StmtError();
  2649. if (CheckNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  2650. StartLoc))
  2651. return StmtError();
  2652. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  2653. llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
  2654. bool ErrorFound = false;
  2655. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  2656. if (AStmt) {
  2657. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  2658. // Check default data sharing attributes for referenced variables.
  2659. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  2660. DSAChecker.Visit(cast<CapturedStmt>(AStmt)->getCapturedStmt());
  2661. if (DSAChecker.isErrorFound())
  2662. return StmtError();
  2663. // Generate list of implicitly defined firstprivate variables.
  2664. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  2665. if (!DSAChecker.getImplicitFirstprivate().empty()) {
  2666. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  2667. DSAChecker.getImplicitFirstprivate(), SourceLocation(),
  2668. SourceLocation(), SourceLocation())) {
  2669. ClausesWithImplicit.push_back(Implicit);
  2670. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  2671. DSAChecker.getImplicitFirstprivate().size();
  2672. } else
  2673. ErrorFound = true;
  2674. }
  2675. }
  2676. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  2677. switch (Kind) {
  2678. case OMPD_parallel:
  2679. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  2680. EndLoc);
  2681. AllowedNameModifiers.push_back(OMPD_parallel);
  2682. break;
  2683. case OMPD_simd:
  2684. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2685. VarsWithInheritedDSA);
  2686. break;
  2687. case OMPD_for:
  2688. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  2689. VarsWithInheritedDSA);
  2690. break;
  2691. case OMPD_for_simd:
  2692. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2693. EndLoc, VarsWithInheritedDSA);
  2694. break;
  2695. case OMPD_sections:
  2696. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  2697. EndLoc);
  2698. break;
  2699. case OMPD_section:
  2700. assert(ClausesWithImplicit.empty() &&
  2701. "No clauses are allowed for 'omp section' directive");
  2702. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  2703. break;
  2704. case OMPD_single:
  2705. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  2706. EndLoc);
  2707. break;
  2708. case OMPD_master:
  2709. assert(ClausesWithImplicit.empty() &&
  2710. "No clauses are allowed for 'omp master' directive");
  2711. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  2712. break;
  2713. case OMPD_critical:
  2714. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  2715. StartLoc, EndLoc);
  2716. break;
  2717. case OMPD_parallel_for:
  2718. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  2719. EndLoc, VarsWithInheritedDSA);
  2720. AllowedNameModifiers.push_back(OMPD_parallel);
  2721. break;
  2722. case OMPD_parallel_for_simd:
  2723. Res = ActOnOpenMPParallelForSimdDirective(
  2724. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  2725. AllowedNameModifiers.push_back(OMPD_parallel);
  2726. break;
  2727. case OMPD_parallel_sections:
  2728. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  2729. StartLoc, EndLoc);
  2730. AllowedNameModifiers.push_back(OMPD_parallel);
  2731. break;
  2732. case OMPD_task:
  2733. Res =
  2734. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2735. AllowedNameModifiers.push_back(OMPD_task);
  2736. break;
  2737. case OMPD_taskyield:
  2738. assert(ClausesWithImplicit.empty() &&
  2739. "No clauses are allowed for 'omp taskyield' directive");
  2740. assert(AStmt == nullptr &&
  2741. "No associated statement allowed for 'omp taskyield' directive");
  2742. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  2743. break;
  2744. case OMPD_barrier:
  2745. assert(ClausesWithImplicit.empty() &&
  2746. "No clauses are allowed for 'omp barrier' directive");
  2747. assert(AStmt == nullptr &&
  2748. "No associated statement allowed for 'omp barrier' directive");
  2749. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  2750. break;
  2751. case OMPD_taskwait:
  2752. assert(ClausesWithImplicit.empty() &&
  2753. "No clauses are allowed for 'omp taskwait' directive");
  2754. assert(AStmt == nullptr &&
  2755. "No associated statement allowed for 'omp taskwait' directive");
  2756. Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
  2757. break;
  2758. case OMPD_taskgroup:
  2759. assert(ClausesWithImplicit.empty() &&
  2760. "No clauses are allowed for 'omp taskgroup' directive");
  2761. Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc);
  2762. break;
  2763. case OMPD_flush:
  2764. assert(AStmt == nullptr &&
  2765. "No associated statement allowed for 'omp flush' directive");
  2766. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  2767. break;
  2768. case OMPD_ordered:
  2769. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  2770. EndLoc);
  2771. break;
  2772. case OMPD_atomic:
  2773. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  2774. EndLoc);
  2775. break;
  2776. case OMPD_teams:
  2777. Res =
  2778. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  2779. break;
  2780. case OMPD_target:
  2781. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  2782. EndLoc);
  2783. AllowedNameModifiers.push_back(OMPD_target);
  2784. break;
  2785. case OMPD_target_parallel:
  2786. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  2787. StartLoc, EndLoc);
  2788. AllowedNameModifiers.push_back(OMPD_target);
  2789. AllowedNameModifiers.push_back(OMPD_parallel);
  2790. break;
  2791. case OMPD_cancellation_point:
  2792. assert(ClausesWithImplicit.empty() &&
  2793. "No clauses are allowed for 'omp cancellation point' directive");
  2794. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  2795. "cancellation point' directive");
  2796. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  2797. break;
  2798. case OMPD_cancel:
  2799. assert(AStmt == nullptr &&
  2800. "No associated statement allowed for 'omp cancel' directive");
  2801. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  2802. CancelRegion);
  2803. AllowedNameModifiers.push_back(OMPD_cancel);
  2804. break;
  2805. case OMPD_target_data:
  2806. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  2807. EndLoc);
  2808. AllowedNameModifiers.push_back(OMPD_target_data);
  2809. break;
  2810. case OMPD_target_enter_data:
  2811. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  2812. EndLoc);
  2813. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  2814. break;
  2815. case OMPD_target_exit_data:
  2816. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  2817. EndLoc);
  2818. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  2819. break;
  2820. case OMPD_taskloop:
  2821. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  2822. EndLoc, VarsWithInheritedDSA);
  2823. AllowedNameModifiers.push_back(OMPD_taskloop);
  2824. break;
  2825. case OMPD_taskloop_simd:
  2826. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  2827. EndLoc, VarsWithInheritedDSA);
  2828. AllowedNameModifiers.push_back(OMPD_taskloop);
  2829. break;
  2830. case OMPD_distribute:
  2831. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  2832. EndLoc, VarsWithInheritedDSA);
  2833. break;
  2834. case OMPD_threadprivate:
  2835. llvm_unreachable("OpenMP Directive is not allowed");
  2836. case OMPD_unknown:
  2837. llvm_unreachable("Unknown OpenMP directive");
  2838. }
  2839. for (auto P : VarsWithInheritedDSA) {
  2840. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  2841. << P.first << P.second->getSourceRange();
  2842. }
  2843. ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
  2844. if (!AllowedNameModifiers.empty())
  2845. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  2846. ErrorFound;
  2847. if (ErrorFound)
  2848. return StmtError();
  2849. return Res;
  2850. }
  2851. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  2852. Stmt *AStmt,
  2853. SourceLocation StartLoc,
  2854. SourceLocation EndLoc) {
  2855. if (!AStmt)
  2856. return StmtError();
  2857. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  2858. // 1.2.2 OpenMP Language Terminology
  2859. // Structured block - An executable statement with a single entry at the
  2860. // top and a single exit at the bottom.
  2861. // The point of exit cannot be a branch out of the structured block.
  2862. // longjmp() and throw() must not violate the entry/exit criteria.
  2863. CS->getCapturedDecl()->setNothrow();
  2864. getCurFunction()->setHasBranchProtectedScope();
  2865. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  2866. DSAStack->isCancelRegion());
  2867. }
  2868. namespace {
  2869. /// \brief Helper class for checking canonical form of the OpenMP loops and
  2870. /// extracting iteration space of each loop in the loop nest, that will be used
  2871. /// for IR generation.
  2872. class OpenMPIterationSpaceChecker {
  2873. /// \brief Reference to Sema.
  2874. Sema &SemaRef;
  2875. /// \brief A location for diagnostics (when there is no some better location).
  2876. SourceLocation DefaultLoc;
  2877. /// \brief A location for diagnostics (when increment is not compatible).
  2878. SourceLocation ConditionLoc;
  2879. /// \brief A source location for referring to loop init later.
  2880. SourceRange InitSrcRange;
  2881. /// \brief A source location for referring to condition later.
  2882. SourceRange ConditionSrcRange;
  2883. /// \brief A source location for referring to increment later.
  2884. SourceRange IncrementSrcRange;
  2885. /// \brief Loop variable.
  2886. VarDecl *Var;
  2887. /// \brief Reference to loop variable.
  2888. DeclRefExpr *VarRef;
  2889. /// \brief Lower bound (initializer for the var).
  2890. Expr *LB;
  2891. /// \brief Upper bound.
  2892. Expr *UB;
  2893. /// \brief Loop step (increment).
  2894. Expr *Step;
  2895. /// \brief This flag is true when condition is one of:
  2896. /// Var < UB
  2897. /// Var <= UB
  2898. /// UB > Var
  2899. /// UB >= Var
  2900. bool TestIsLessOp;
  2901. /// \brief This flag is true when condition is strict ( < or > ).
  2902. bool TestIsStrictOp;
  2903. /// \brief This flag is true when step is subtracted on each iteration.
  2904. bool SubtractStep;
  2905. public:
  2906. OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
  2907. : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc),
  2908. InitSrcRange(SourceRange()), ConditionSrcRange(SourceRange()),
  2909. IncrementSrcRange(SourceRange()), Var(nullptr), VarRef(nullptr),
  2910. LB(nullptr), UB(nullptr), Step(nullptr), TestIsLessOp(false),
  2911. TestIsStrictOp(false), SubtractStep(false) {}
  2912. /// \brief Check init-expr for canonical loop form and save loop counter
  2913. /// variable - #Var and its initialization value - #LB.
  2914. bool CheckInit(Stmt *S, bool EmitDiags = true);
  2915. /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
  2916. /// for less/greater and for strict/non-strict comparison.
  2917. bool CheckCond(Expr *S);
  2918. /// \brief Check incr-expr for canonical loop form and return true if it
  2919. /// does not conform, otherwise save loop step (#Step).
  2920. bool CheckInc(Expr *S);
  2921. /// \brief Return the loop counter variable.
  2922. VarDecl *GetLoopVar() const { return Var; }
  2923. /// \brief Return the reference expression to loop counter variable.
  2924. DeclRefExpr *GetLoopVarRefExpr() const { return VarRef; }
  2925. /// \brief Source range of the loop init.
  2926. SourceRange GetInitSrcRange() const { return InitSrcRange; }
  2927. /// \brief Source range of the loop condition.
  2928. SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
  2929. /// \brief Source range of the loop increment.
  2930. SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
  2931. /// \brief True if the step should be subtracted.
  2932. bool ShouldSubtractStep() const { return SubtractStep; }
  2933. /// \brief Build the expression to calculate the number of iterations.
  2934. Expr *BuildNumIterations(Scope *S, const bool LimitedType) const;
  2935. /// \brief Build the precondition expression for the loops.
  2936. Expr *BuildPreCond(Scope *S, Expr *Cond) const;
  2937. /// \brief Build reference expression to the counter be used for codegen.
  2938. Expr *BuildCounterVar() const;
  2939. /// \brief Build reference expression to the private counter be used for
  2940. /// codegen.
  2941. Expr *BuildPrivateCounterVar() const;
  2942. /// \brief Build initization of the counter be used for codegen.
  2943. Expr *BuildCounterInit() const;
  2944. /// \brief Build step of the counter be used for codegen.
  2945. Expr *BuildCounterStep() const;
  2946. /// \brief Return true if any expression is dependent.
  2947. bool Dependent() const;
  2948. private:
  2949. /// \brief Check the right-hand side of an assignment in the increment
  2950. /// expression.
  2951. bool CheckIncRHS(Expr *RHS);
  2952. /// \brief Helper to set loop counter variable and its initializer.
  2953. bool SetVarAndLB(VarDecl *NewVar, DeclRefExpr *NewVarRefExpr, Expr *NewLB);
  2954. /// \brief Helper to set upper bound.
  2955. bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
  2956. SourceLocation SL);
  2957. /// \brief Helper to set loop increment.
  2958. bool SetStep(Expr *NewStep, bool Subtract);
  2959. };
  2960. bool OpenMPIterationSpaceChecker::Dependent() const {
  2961. if (!Var) {
  2962. assert(!LB && !UB && !Step);
  2963. return false;
  2964. }
  2965. return Var->getType()->isDependentType() || (LB && LB->isValueDependent()) ||
  2966. (UB && UB->isValueDependent()) || (Step && Step->isValueDependent());
  2967. }
  2968. template <typename T>
  2969. static T *getExprAsWritten(T *E) {
  2970. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
  2971. E = ExprTemp->getSubExpr();
  2972. if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  2973. E = MTE->GetTemporaryExpr();
  2974. while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  2975. E = Binder->getSubExpr();
  2976. if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  2977. E = ICE->getSubExprAsWritten();
  2978. return E->IgnoreParens();
  2979. }
  2980. bool OpenMPIterationSpaceChecker::SetVarAndLB(VarDecl *NewVar,
  2981. DeclRefExpr *NewVarRefExpr,
  2982. Expr *NewLB) {
  2983. // State consistency checking to ensure correct usage.
  2984. assert(Var == nullptr && LB == nullptr && VarRef == nullptr &&
  2985. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  2986. if (!NewVar || !NewLB)
  2987. return true;
  2988. Var = NewVar;
  2989. VarRef = NewVarRefExpr;
  2990. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  2991. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  2992. if ((Ctor->isCopyOrMoveConstructor() ||
  2993. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  2994. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  2995. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  2996. LB = NewLB;
  2997. return false;
  2998. }
  2999. bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
  3000. SourceRange SR, SourceLocation SL) {
  3001. // State consistency checking to ensure correct usage.
  3002. assert(Var != nullptr && LB != nullptr && UB == nullptr && Step == nullptr &&
  3003. !TestIsLessOp && !TestIsStrictOp);
  3004. if (!NewUB)
  3005. return true;
  3006. UB = NewUB;
  3007. TestIsLessOp = LessOp;
  3008. TestIsStrictOp = StrictOp;
  3009. ConditionSrcRange = SR;
  3010. ConditionLoc = SL;
  3011. return false;
  3012. }
  3013. bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
  3014. // State consistency checking to ensure correct usage.
  3015. assert(Var != nullptr && LB != nullptr && Step == nullptr);
  3016. if (!NewStep)
  3017. return true;
  3018. if (!NewStep->isValueDependent()) {
  3019. // Check that the step is integer expression.
  3020. SourceLocation StepLoc = NewStep->getLocStart();
  3021. ExprResult Val =
  3022. SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep);
  3023. if (Val.isInvalid())
  3024. return true;
  3025. NewStep = Val.get();
  3026. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  3027. // If test-expr is of form var relational-op b and relational-op is < or
  3028. // <= then incr-expr must cause var to increase on each iteration of the
  3029. // loop. If test-expr is of form var relational-op b and relational-op is
  3030. // > or >= then incr-expr must cause var to decrease on each iteration of
  3031. // the loop.
  3032. // If test-expr is of form b relational-op var and relational-op is < or
  3033. // <= then incr-expr must cause var to decrease on each iteration of the
  3034. // loop. If test-expr is of form b relational-op var and relational-op is
  3035. // > or >= then incr-expr must cause var to increase on each iteration of
  3036. // the loop.
  3037. llvm::APSInt Result;
  3038. bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
  3039. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  3040. bool IsConstNeg =
  3041. IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
  3042. bool IsConstPos =
  3043. IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
  3044. bool IsConstZero = IsConstant && !Result.getBoolValue();
  3045. if (UB && (IsConstZero ||
  3046. (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
  3047. : (IsConstPos || (IsUnsigned && !Subtract))))) {
  3048. SemaRef.Diag(NewStep->getExprLoc(),
  3049. diag::err_omp_loop_incr_not_compatible)
  3050. << Var << TestIsLessOp << NewStep->getSourceRange();
  3051. SemaRef.Diag(ConditionLoc,
  3052. diag::note_omp_loop_cond_requres_compatible_incr)
  3053. << TestIsLessOp << ConditionSrcRange;
  3054. return true;
  3055. }
  3056. if (TestIsLessOp == Subtract) {
  3057. NewStep = SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus,
  3058. NewStep).get();
  3059. Subtract = !Subtract;
  3060. }
  3061. }
  3062. Step = NewStep;
  3063. SubtractStep = Subtract;
  3064. return false;
  3065. }
  3066. bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
  3067. // Check init-expr for canonical loop form and save loop counter
  3068. // variable - #Var and its initialization value - #LB.
  3069. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  3070. // var = lb
  3071. // integer-type var = lb
  3072. // random-access-iterator-type var = lb
  3073. // pointer-type var = lb
  3074. //
  3075. if (!S) {
  3076. if (EmitDiags) {
  3077. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  3078. }
  3079. return true;
  3080. }
  3081. InitSrcRange = S->getSourceRange();
  3082. if (Expr *E = dyn_cast<Expr>(S))
  3083. S = E->IgnoreParens();
  3084. if (auto BO = dyn_cast<BinaryOperator>(S)) {
  3085. if (BO->getOpcode() == BO_Assign)
  3086. if (auto DRE = dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens()))
  3087. return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
  3088. BO->getRHS());
  3089. } else if (auto DS = dyn_cast<DeclStmt>(S)) {
  3090. if (DS->isSingleDecl()) {
  3091. if (auto Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  3092. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  3093. // Accept non-canonical init form here but emit ext. warning.
  3094. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  3095. SemaRef.Diag(S->getLocStart(),
  3096. diag::ext_omp_loop_not_canonical_init)
  3097. << S->getSourceRange();
  3098. return SetVarAndLB(Var, nullptr, Var->getInit());
  3099. }
  3100. }
  3101. }
  3102. } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S))
  3103. if (CE->getOperator() == OO_Equal)
  3104. if (auto DRE = dyn_cast<DeclRefExpr>(CE->getArg(0)))
  3105. return SetVarAndLB(dyn_cast<VarDecl>(DRE->getDecl()), DRE,
  3106. CE->getArg(1));
  3107. if (EmitDiags) {
  3108. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
  3109. << S->getSourceRange();
  3110. }
  3111. return true;
  3112. }
  3113. /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
  3114. /// variable (which may be the loop variable) if possible.
  3115. static const VarDecl *GetInitVarDecl(const Expr *E) {
  3116. if (!E)
  3117. return nullptr;
  3118. E = getExprAsWritten(E);
  3119. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  3120. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  3121. if ((Ctor->isCopyOrMoveConstructor() ||
  3122. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  3123. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  3124. E = CE->getArg(0)->IgnoreParenImpCasts();
  3125. auto DRE = dyn_cast_or_null<DeclRefExpr>(E);
  3126. if (!DRE)
  3127. return nullptr;
  3128. return dyn_cast<VarDecl>(DRE->getDecl());
  3129. }
  3130. bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
  3131. // Check test-expr for canonical form, save upper-bound UB, flags for
  3132. // less/greater and for strict/non-strict comparison.
  3133. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  3134. // var relational-op b
  3135. // b relational-op var
  3136. //
  3137. if (!S) {
  3138. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << Var;
  3139. return true;
  3140. }
  3141. S = getExprAsWritten(S);
  3142. SourceLocation CondLoc = S->getLocStart();
  3143. if (auto BO = dyn_cast<BinaryOperator>(S)) {
  3144. if (BO->isRelationalOp()) {
  3145. if (GetInitVarDecl(BO->getLHS()) == Var)
  3146. return SetUB(BO->getRHS(),
  3147. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
  3148. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3149. BO->getSourceRange(), BO->getOperatorLoc());
  3150. if (GetInitVarDecl(BO->getRHS()) == Var)
  3151. return SetUB(BO->getLHS(),
  3152. (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
  3153. (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
  3154. BO->getSourceRange(), BO->getOperatorLoc());
  3155. }
  3156. } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3157. if (CE->getNumArgs() == 2) {
  3158. auto Op = CE->getOperator();
  3159. switch (Op) {
  3160. case OO_Greater:
  3161. case OO_GreaterEqual:
  3162. case OO_Less:
  3163. case OO_LessEqual:
  3164. if (GetInitVarDecl(CE->getArg(0)) == Var)
  3165. return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
  3166. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  3167. CE->getOperatorLoc());
  3168. if (GetInitVarDecl(CE->getArg(1)) == Var)
  3169. return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
  3170. Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
  3171. CE->getOperatorLoc());
  3172. break;
  3173. default:
  3174. break;
  3175. }
  3176. }
  3177. }
  3178. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  3179. << S->getSourceRange() << Var;
  3180. return true;
  3181. }
  3182. bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
  3183. // RHS of canonical loop form increment can be:
  3184. // var + incr
  3185. // incr + var
  3186. // var - incr
  3187. //
  3188. RHS = RHS->IgnoreParenImpCasts();
  3189. if (auto BO = dyn_cast<BinaryOperator>(RHS)) {
  3190. if (BO->isAdditiveOp()) {
  3191. bool IsAdd = BO->getOpcode() == BO_Add;
  3192. if (GetInitVarDecl(BO->getLHS()) == Var)
  3193. return SetStep(BO->getRHS(), !IsAdd);
  3194. if (IsAdd && GetInitVarDecl(BO->getRHS()) == Var)
  3195. return SetStep(BO->getLHS(), false);
  3196. }
  3197. } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  3198. bool IsAdd = CE->getOperator() == OO_Plus;
  3199. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  3200. if (GetInitVarDecl(CE->getArg(0)) == Var)
  3201. return SetStep(CE->getArg(1), !IsAdd);
  3202. if (IsAdd && GetInitVarDecl(CE->getArg(1)) == Var)
  3203. return SetStep(CE->getArg(0), false);
  3204. }
  3205. }
  3206. SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  3207. << RHS->getSourceRange() << Var;
  3208. return true;
  3209. }
  3210. bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
  3211. // Check incr-expr for canonical loop form and return true if it
  3212. // does not conform.
  3213. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  3214. // ++var
  3215. // var++
  3216. // --var
  3217. // var--
  3218. // var += incr
  3219. // var -= incr
  3220. // var = var + incr
  3221. // var = incr + var
  3222. // var = var - incr
  3223. //
  3224. if (!S) {
  3225. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << Var;
  3226. return true;
  3227. }
  3228. IncrementSrcRange = S->getSourceRange();
  3229. S = S->IgnoreParens();
  3230. if (auto UO = dyn_cast<UnaryOperator>(S)) {
  3231. if (UO->isIncrementDecrementOp() && GetInitVarDecl(UO->getSubExpr()) == Var)
  3232. return SetStep(
  3233. SemaRef.ActOnIntegerConstant(UO->getLocStart(),
  3234. (UO->isDecrementOp() ? -1 : 1)).get(),
  3235. false);
  3236. } else if (auto BO = dyn_cast<BinaryOperator>(S)) {
  3237. switch (BO->getOpcode()) {
  3238. case BO_AddAssign:
  3239. case BO_SubAssign:
  3240. if (GetInitVarDecl(BO->getLHS()) == Var)
  3241. return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  3242. break;
  3243. case BO_Assign:
  3244. if (GetInitVarDecl(BO->getLHS()) == Var)
  3245. return CheckIncRHS(BO->getRHS());
  3246. break;
  3247. default:
  3248. break;
  3249. }
  3250. } else if (auto CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  3251. switch (CE->getOperator()) {
  3252. case OO_PlusPlus:
  3253. case OO_MinusMinus:
  3254. if (GetInitVarDecl(CE->getArg(0)) == Var)
  3255. return SetStep(
  3256. SemaRef.ActOnIntegerConstant(
  3257. CE->getLocStart(),
  3258. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)).get(),
  3259. false);
  3260. break;
  3261. case OO_PlusEqual:
  3262. case OO_MinusEqual:
  3263. if (GetInitVarDecl(CE->getArg(0)) == Var)
  3264. return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  3265. break;
  3266. case OO_Equal:
  3267. if (GetInitVarDecl(CE->getArg(0)) == Var)
  3268. return CheckIncRHS(CE->getArg(1));
  3269. break;
  3270. default:
  3271. break;
  3272. }
  3273. }
  3274. SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
  3275. << S->getSourceRange() << Var;
  3276. return true;
  3277. }
  3278. namespace {
  3279. // Transform variables declared in GNU statement expressions to new ones to
  3280. // avoid crash on codegen.
  3281. class TransformToNewDefs : public TreeTransform<TransformToNewDefs> {
  3282. typedef TreeTransform<TransformToNewDefs> BaseTransform;
  3283. public:
  3284. TransformToNewDefs(Sema &SemaRef) : BaseTransform(SemaRef) {}
  3285. Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
  3286. if (auto *VD = cast<VarDecl>(D))
  3287. if (!isa<ParmVarDecl>(D) && !isa<VarTemplateSpecializationDecl>(D) &&
  3288. !isa<ImplicitParamDecl>(D)) {
  3289. auto *NewVD = VarDecl::Create(
  3290. SemaRef.Context, VD->getDeclContext(), VD->getLocStart(),
  3291. VD->getLocation(), VD->getIdentifier(), VD->getType(),
  3292. VD->getTypeSourceInfo(), VD->getStorageClass());
  3293. NewVD->setTSCSpec(VD->getTSCSpec());
  3294. NewVD->setInit(VD->getInit());
  3295. NewVD->setInitStyle(VD->getInitStyle());
  3296. NewVD->setExceptionVariable(VD->isExceptionVariable());
  3297. NewVD->setNRVOVariable(VD->isNRVOVariable());
  3298. NewVD->setCXXForRangeDecl(VD->isInExternCXXContext());
  3299. NewVD->setConstexpr(VD->isConstexpr());
  3300. NewVD->setInitCapture(VD->isInitCapture());
  3301. NewVD->setPreviousDeclInSameBlockScope(
  3302. VD->isPreviousDeclInSameBlockScope());
  3303. VD->getDeclContext()->addHiddenDecl(NewVD);
  3304. if (VD->hasAttrs())
  3305. NewVD->setAttrs(VD->getAttrs());
  3306. transformedLocalDecl(VD, NewVD);
  3307. return NewVD;
  3308. }
  3309. return BaseTransform::TransformDefinition(Loc, D);
  3310. }
  3311. ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
  3312. if (auto *NewD = TransformDecl(E->getExprLoc(), E->getDecl()))
  3313. if (E->getDecl() != NewD) {
  3314. NewD->setReferenced();
  3315. NewD->markUsed(SemaRef.Context);
  3316. return DeclRefExpr::Create(
  3317. SemaRef.Context, E->getQualifierLoc(), E->getTemplateKeywordLoc(),
  3318. cast<ValueDecl>(NewD), E->refersToEnclosingVariableOrCapture(),
  3319. E->getNameInfo(), E->getType(), E->getValueKind());
  3320. }
  3321. return BaseTransform::TransformDeclRefExpr(E);
  3322. }
  3323. };
  3324. }
  3325. /// \brief Build the expression to calculate the number of iterations.
  3326. Expr *
  3327. OpenMPIterationSpaceChecker::BuildNumIterations(Scope *S,
  3328. const bool LimitedType) const {
  3329. TransformToNewDefs Transform(SemaRef);
  3330. ExprResult Diff;
  3331. auto VarType = Var->getType().getNonReferenceType();
  3332. if (VarType->isIntegerType() || VarType->isPointerType() ||
  3333. SemaRef.getLangOpts().CPlusPlus) {
  3334. // Upper - Lower
  3335. auto *UBExpr = TestIsLessOp ? UB : LB;
  3336. auto *LBExpr = TestIsLessOp ? LB : UB;
  3337. Expr *Upper = Transform.TransformExpr(UBExpr).get();
  3338. Expr *Lower = Transform.TransformExpr(LBExpr).get();
  3339. if (!Upper || !Lower)
  3340. return nullptr;
  3341. Upper = SemaRef.PerformImplicitConversion(Upper, UBExpr->getType(),
  3342. Sema::AA_Converting,
  3343. /*AllowExplicit=*/true)
  3344. .get();
  3345. Lower = SemaRef.PerformImplicitConversion(Lower, LBExpr->getType(),
  3346. Sema::AA_Converting,
  3347. /*AllowExplicit=*/true)
  3348. .get();
  3349. if (!Upper || !Lower)
  3350. return nullptr;
  3351. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  3352. if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
  3353. // BuildBinOp already emitted error, this one is to point user to upper
  3354. // and lower bound, and to tell what is passed to 'operator-'.
  3355. SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
  3356. << Upper->getSourceRange() << Lower->getSourceRange();
  3357. return nullptr;
  3358. }
  3359. }
  3360. if (!Diff.isUsable())
  3361. return nullptr;
  3362. // Upper - Lower [- 1]
  3363. if (TestIsStrictOp)
  3364. Diff = SemaRef.BuildBinOp(
  3365. S, DefaultLoc, BO_Sub, Diff.get(),
  3366. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  3367. if (!Diff.isUsable())
  3368. return nullptr;
  3369. // Upper - Lower [- 1] + Step
  3370. auto NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
  3371. if (NewStep.isInvalid())
  3372. return nullptr;
  3373. NewStep = SemaRef.PerformImplicitConversion(
  3374. NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
  3375. /*AllowExplicit=*/true);
  3376. if (NewStep.isInvalid())
  3377. return nullptr;
  3378. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  3379. if (!Diff.isUsable())
  3380. return nullptr;
  3381. // Parentheses (for dumping/debugging purposes only).
  3382. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  3383. if (!Diff.isUsable())
  3384. return nullptr;
  3385. // (Upper - Lower [- 1] + Step) / Step
  3386. NewStep = Transform.TransformExpr(Step->IgnoreImplicit());
  3387. if (NewStep.isInvalid())
  3388. return nullptr;
  3389. NewStep = SemaRef.PerformImplicitConversion(
  3390. NewStep.get(), Step->IgnoreImplicit()->getType(), Sema::AA_Converting,
  3391. /*AllowExplicit=*/true);
  3392. if (NewStep.isInvalid())
  3393. return nullptr;
  3394. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  3395. if (!Diff.isUsable())
  3396. return nullptr;
  3397. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  3398. QualType Type = Diff.get()->getType();
  3399. auto &C = SemaRef.Context;
  3400. bool UseVarType = VarType->hasIntegerRepresentation() &&
  3401. C.getTypeSize(Type) > C.getTypeSize(VarType);
  3402. if (!Type->isIntegerType() || UseVarType) {
  3403. unsigned NewSize =
  3404. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  3405. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  3406. : Type->hasSignedIntegerRepresentation();
  3407. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  3408. Diff = SemaRef.PerformImplicitConversion(
  3409. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  3410. if (!Diff.isUsable())
  3411. return nullptr;
  3412. }
  3413. if (LimitedType) {
  3414. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  3415. if (NewSize != C.getTypeSize(Type)) {
  3416. if (NewSize < C.getTypeSize(Type)) {
  3417. assert(NewSize == 64 && "incorrect loop var size");
  3418. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  3419. << InitSrcRange << ConditionSrcRange;
  3420. }
  3421. QualType NewType = C.getIntTypeForBitwidth(
  3422. NewSize, Type->hasSignedIntegerRepresentation() ||
  3423. C.getTypeSize(Type) < NewSize);
  3424. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  3425. Sema::AA_Converting, true);
  3426. if (!Diff.isUsable())
  3427. return nullptr;
  3428. }
  3429. }
  3430. return Diff.get();
  3431. }
  3432. Expr *OpenMPIterationSpaceChecker::BuildPreCond(Scope *S, Expr *Cond) const {
  3433. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  3434. bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
  3435. SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
  3436. TransformToNewDefs Transform(SemaRef);
  3437. auto NewLB = Transform.TransformExpr(LB);
  3438. auto NewUB = Transform.TransformExpr(UB);
  3439. if (NewLB.isInvalid() || NewUB.isInvalid())
  3440. return Cond;
  3441. NewLB = SemaRef.PerformImplicitConversion(NewLB.get(), LB->getType(),
  3442. Sema::AA_Converting,
  3443. /*AllowExplicit=*/true);
  3444. NewUB = SemaRef.PerformImplicitConversion(NewUB.get(), UB->getType(),
  3445. Sema::AA_Converting,
  3446. /*AllowExplicit=*/true);
  3447. if (NewLB.isInvalid() || NewUB.isInvalid())
  3448. return Cond;
  3449. auto CondExpr = SemaRef.BuildBinOp(
  3450. S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
  3451. : (TestIsStrictOp ? BO_GT : BO_GE),
  3452. NewLB.get(), NewUB.get());
  3453. if (CondExpr.isUsable()) {
  3454. CondExpr = SemaRef.PerformImplicitConversion(
  3455. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  3456. /*AllowExplicit=*/true);
  3457. }
  3458. SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
  3459. // Otherwise use original loop conditon and evaluate it in runtime.
  3460. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  3461. }
  3462. /// \brief Build reference expression to the counter be used for codegen.
  3463. Expr *OpenMPIterationSpaceChecker::BuildCounterVar() const {
  3464. return buildDeclRefExpr(SemaRef, Var, Var->getType().getNonReferenceType(),
  3465. DefaultLoc);
  3466. }
  3467. Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
  3468. if (Var && !Var->isInvalidDecl()) {
  3469. auto Type = Var->getType().getNonReferenceType();
  3470. auto *PrivateVar =
  3471. buildVarDecl(SemaRef, DefaultLoc, Type, Var->getName(),
  3472. Var->hasAttrs() ? &Var->getAttrs() : nullptr);
  3473. if (PrivateVar->isInvalidDecl())
  3474. return nullptr;
  3475. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  3476. }
  3477. return nullptr;
  3478. }
  3479. /// \brief Build initization of the counter be used for codegen.
  3480. Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
  3481. /// \brief Build step of the counter be used for codegen.
  3482. Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
  3483. /// \brief Iteration space of a single for loop.
  3484. struct LoopIterationSpace {
  3485. /// \brief Condition of the loop.
  3486. Expr *PreCond;
  3487. /// \brief This expression calculates the number of iterations in the loop.
  3488. /// It is always possible to calculate it before starting the loop.
  3489. Expr *NumIterations;
  3490. /// \brief The loop counter variable.
  3491. Expr *CounterVar;
  3492. /// \brief Private loop counter variable.
  3493. Expr *PrivateCounterVar;
  3494. /// \brief This is initializer for the initial value of #CounterVar.
  3495. Expr *CounterInit;
  3496. /// \brief This is step for the #CounterVar used to generate its update:
  3497. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  3498. Expr *CounterStep;
  3499. /// \brief Should step be subtracted?
  3500. bool Subtract;
  3501. /// \brief Source range of the loop init.
  3502. SourceRange InitSrcRange;
  3503. /// \brief Source range of the loop condition.
  3504. SourceRange CondSrcRange;
  3505. /// \brief Source range of the loop increment.
  3506. SourceRange IncSrcRange;
  3507. };
  3508. } // namespace
  3509. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  3510. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  3511. assert(Init && "Expected loop in canonical form.");
  3512. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  3513. if (AssociatedLoops > 0 &&
  3514. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  3515. OpenMPIterationSpaceChecker ISC(*this, ForLoc);
  3516. if (!ISC.CheckInit(Init, /*EmitDiags=*/false))
  3517. DSAStack->addLoopControlVariable(ISC.GetLoopVar());
  3518. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  3519. }
  3520. }
  3521. /// \brief Called on a for stmt to check and extract its iteration space
  3522. /// for further processing (such as collapsing).
  3523. static bool CheckOpenMPIterationSpace(
  3524. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  3525. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  3526. Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
  3527. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
  3528. LoopIterationSpace &ResultIterSpace) {
  3529. // OpenMP [2.6, Canonical Loop Form]
  3530. // for (init-expr; test-expr; incr-expr) structured-block
  3531. auto For = dyn_cast_or_null<ForStmt>(S);
  3532. if (!For) {
  3533. SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
  3534. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  3535. << getOpenMPDirectiveName(DKind) << NestedLoopCount
  3536. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  3537. if (NestedLoopCount > 1) {
  3538. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  3539. SemaRef.Diag(DSA.getConstructLoc(),
  3540. diag::note_omp_collapse_ordered_expr)
  3541. << 2 << CollapseLoopCountExpr->getSourceRange()
  3542. << OrderedLoopCountExpr->getSourceRange();
  3543. else if (CollapseLoopCountExpr)
  3544. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  3545. diag::note_omp_collapse_ordered_expr)
  3546. << 0 << CollapseLoopCountExpr->getSourceRange();
  3547. else
  3548. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  3549. diag::note_omp_collapse_ordered_expr)
  3550. << 1 << OrderedLoopCountExpr->getSourceRange();
  3551. }
  3552. return true;
  3553. }
  3554. assert(For->getBody());
  3555. OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
  3556. // Check init.
  3557. auto Init = For->getInit();
  3558. if (ISC.CheckInit(Init)) {
  3559. return true;
  3560. }
  3561. bool HasErrors = false;
  3562. // Check loop variable's type.
  3563. auto Var = ISC.GetLoopVar();
  3564. // OpenMP [2.6, Canonical Loop Form]
  3565. // Var is one of the following:
  3566. // A variable of signed or unsigned integer type.
  3567. // For C++, a variable of a random access iterator type.
  3568. // For C, a variable of a pointer type.
  3569. auto VarType = Var->getType().getNonReferenceType();
  3570. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  3571. !VarType->isPointerType() &&
  3572. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  3573. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
  3574. << SemaRef.getLangOpts().CPlusPlus;
  3575. HasErrors = true;
  3576. }
  3577. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in a
  3578. // Construct
  3579. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3580. // parallel for construct is (are) private.
  3581. // The loop iteration variable in the associated for-loop of a simd construct
  3582. // with just one associated for-loop is linear with a constant-linear-step
  3583. // that is the increment of the associated for-loop.
  3584. // Exclude loop var from the list of variables with implicitly defined data
  3585. // sharing attributes.
  3586. VarsWithImplicitDSA.erase(Var);
  3587. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced in
  3588. // a Construct, C/C++].
  3589. // The loop iteration variable in the associated for-loop of a simd construct
  3590. // with just one associated for-loop may be listed in a linear clause with a
  3591. // constant-linear-step that is the increment of the associated for-loop.
  3592. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  3593. // parallel for construct may be listed in a private or lastprivate clause.
  3594. DSAStackTy::DSAVarData DVar = DSA.getTopDSA(Var, false);
  3595. auto LoopVarRefExpr = ISC.GetLoopVarRefExpr();
  3596. // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
  3597. // declared in the loop and it is predetermined as a private.
  3598. auto PredeterminedCKind =
  3599. isOpenMPSimdDirective(DKind)
  3600. ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
  3601. : OMPC_private;
  3602. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  3603. DVar.CKind != PredeterminedCKind) ||
  3604. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  3605. isOpenMPDistributeDirective(DKind)) &&
  3606. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  3607. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  3608. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  3609. SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
  3610. << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
  3611. << getOpenMPClauseName(PredeterminedCKind);
  3612. if (DVar.RefExpr == nullptr)
  3613. DVar.CKind = PredeterminedCKind;
  3614. ReportOriginalDSA(SemaRef, &DSA, Var, DVar, /*IsLoopIterVar=*/true);
  3615. HasErrors = true;
  3616. } else if (LoopVarRefExpr != nullptr) {
  3617. // Make the loop iteration variable private (for worksharing constructs),
  3618. // linear (for simd directives with the only one associated loop) or
  3619. // lastprivate (for simd directives with several collapsed or ordered
  3620. // loops).
  3621. if (DVar.CKind == OMPC_unknown)
  3622. DVar = DSA.hasDSA(Var, isOpenMPPrivate, MatchesAlways(),
  3623. /*FromParent=*/false);
  3624. DSA.addDSA(Var, LoopVarRefExpr, PredeterminedCKind);
  3625. }
  3626. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  3627. // Check test-expr.
  3628. HasErrors |= ISC.CheckCond(For->getCond());
  3629. // Check incr-expr.
  3630. HasErrors |= ISC.CheckInc(For->getInc());
  3631. if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  3632. return HasErrors;
  3633. // Build the loop's iteration space representation.
  3634. ResultIterSpace.PreCond = ISC.BuildPreCond(DSA.getCurScope(), For->getCond());
  3635. ResultIterSpace.NumIterations = ISC.BuildNumIterations(
  3636. DSA.getCurScope(), (isOpenMPWorksharingDirective(DKind) ||
  3637. isOpenMPTaskLoopDirective(DKind) ||
  3638. isOpenMPDistributeDirective(DKind)));
  3639. ResultIterSpace.CounterVar = ISC.BuildCounterVar();
  3640. ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
  3641. ResultIterSpace.CounterInit = ISC.BuildCounterInit();
  3642. ResultIterSpace.CounterStep = ISC.BuildCounterStep();
  3643. ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
  3644. ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
  3645. ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
  3646. ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
  3647. HasErrors |= (ResultIterSpace.PreCond == nullptr ||
  3648. ResultIterSpace.NumIterations == nullptr ||
  3649. ResultIterSpace.CounterVar == nullptr ||
  3650. ResultIterSpace.PrivateCounterVar == nullptr ||
  3651. ResultIterSpace.CounterInit == nullptr ||
  3652. ResultIterSpace.CounterStep == nullptr);
  3653. return HasErrors;
  3654. }
  3655. /// \brief Build 'VarRef = Start.
  3656. static ExprResult BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc,
  3657. ExprResult VarRef, ExprResult Start) {
  3658. TransformToNewDefs Transform(SemaRef);
  3659. // Build 'VarRef = Start.
  3660. auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
  3661. if (NewStart.isInvalid())
  3662. return ExprError();
  3663. NewStart = SemaRef.PerformImplicitConversion(
  3664. NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
  3665. Sema::AA_Converting,
  3666. /*AllowExplicit=*/true);
  3667. if (NewStart.isInvalid())
  3668. return ExprError();
  3669. NewStart = SemaRef.PerformImplicitConversion(
  3670. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  3671. /*AllowExplicit=*/true);
  3672. if (!NewStart.isUsable())
  3673. return ExprError();
  3674. auto Init =
  3675. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  3676. return Init;
  3677. }
  3678. /// \brief Build 'VarRef = Start + Iter * Step'.
  3679. static ExprResult BuildCounterUpdate(Sema &SemaRef, Scope *S,
  3680. SourceLocation Loc, ExprResult VarRef,
  3681. ExprResult Start, ExprResult Iter,
  3682. ExprResult Step, bool Subtract) {
  3683. // Add parentheses (for debugging purposes only).
  3684. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  3685. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  3686. !Step.isUsable())
  3687. return ExprError();
  3688. TransformToNewDefs Transform(SemaRef);
  3689. auto NewStep = Transform.TransformExpr(Step.get()->IgnoreImplicit());
  3690. if (NewStep.isInvalid())
  3691. return ExprError();
  3692. NewStep = SemaRef.PerformImplicitConversion(
  3693. NewStep.get(), Step.get()->IgnoreImplicit()->getType(),
  3694. Sema::AA_Converting,
  3695. /*AllowExplicit=*/true);
  3696. if (NewStep.isInvalid())
  3697. return ExprError();
  3698. ExprResult Update =
  3699. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  3700. if (!Update.isUsable())
  3701. return ExprError();
  3702. // Build 'VarRef = Start + Iter * Step'.
  3703. auto NewStart = Transform.TransformExpr(Start.get()->IgnoreImplicit());
  3704. if (NewStart.isInvalid())
  3705. return ExprError();
  3706. NewStart = SemaRef.PerformImplicitConversion(
  3707. NewStart.get(), Start.get()->IgnoreImplicit()->getType(),
  3708. Sema::AA_Converting,
  3709. /*AllowExplicit=*/true);
  3710. if (NewStart.isInvalid())
  3711. return ExprError();
  3712. Update = SemaRef.BuildBinOp(S, Loc, (Subtract ? BO_Sub : BO_Add),
  3713. NewStart.get(), Update.get());
  3714. if (!Update.isUsable())
  3715. return ExprError();
  3716. Update = SemaRef.PerformImplicitConversion(
  3717. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  3718. if (!Update.isUsable())
  3719. return ExprError();
  3720. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  3721. return Update;
  3722. }
  3723. /// \brief Convert integer expression \a E to make it have at least \a Bits
  3724. /// bits.
  3725. static ExprResult WidenIterationCount(unsigned Bits, Expr *E,
  3726. Sema &SemaRef) {
  3727. if (E == nullptr)
  3728. return ExprError();
  3729. auto &C = SemaRef.Context;
  3730. QualType OldType = E->getType();
  3731. unsigned HasBits = C.getTypeSize(OldType);
  3732. if (HasBits >= Bits)
  3733. return ExprResult(E);
  3734. // OK to convert to signed, because new type has more bits than old.
  3735. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  3736. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  3737. true);
  3738. }
  3739. /// \brief Check if the given expression \a E is a constant integer that fits
  3740. /// into \a Bits bits.
  3741. static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
  3742. if (E == nullptr)
  3743. return false;
  3744. llvm::APSInt Result;
  3745. if (E->isIntegerConstantExpr(Result, SemaRef.Context))
  3746. return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
  3747. return false;
  3748. }
  3749. /// \brief Called on a for stmt to check itself and nested loops (if any).
  3750. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  3751. /// number of collapsed loops otherwise.
  3752. static unsigned
  3753. CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  3754. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  3755. DSAStackTy &DSA,
  3756. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
  3757. OMPLoopDirective::HelperExprs &Built) {
  3758. unsigned NestedLoopCount = 1;
  3759. if (CollapseLoopCountExpr) {
  3760. // Found 'collapse' clause - calculate collapse number.
  3761. llvm::APSInt Result;
  3762. if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
  3763. NestedLoopCount = Result.getLimitedValue();
  3764. }
  3765. if (OrderedLoopCountExpr) {
  3766. // Found 'ordered' clause - calculate collapse number.
  3767. llvm::APSInt Result;
  3768. if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  3769. if (Result.getLimitedValue() < NestedLoopCount) {
  3770. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  3771. diag::err_omp_wrong_ordered_loop_count)
  3772. << OrderedLoopCountExpr->getSourceRange();
  3773. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  3774. diag::note_collapse_loop_count)
  3775. << CollapseLoopCountExpr->getSourceRange();
  3776. }
  3777. NestedLoopCount = Result.getLimitedValue();
  3778. }
  3779. }
  3780. // This is helper routine for loop directives (e.g., 'for', 'simd',
  3781. // 'for simd', etc.).
  3782. SmallVector<LoopIterationSpace, 4> IterSpaces;
  3783. IterSpaces.resize(NestedLoopCount);
  3784. Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
  3785. for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  3786. if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
  3787. NestedLoopCount, CollapseLoopCountExpr,
  3788. OrderedLoopCountExpr, VarsWithImplicitDSA,
  3789. IterSpaces[Cnt]))
  3790. return 0;
  3791. // Move on to the next nested for loop, or to the loop body.
  3792. // OpenMP [2.8.1, simd construct, Restrictions]
  3793. // All loops associated with the construct must be perfectly nested; that
  3794. // is, there must be no intervening code nor any OpenMP directive between
  3795. // any two loops.
  3796. CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
  3797. }
  3798. Built.clear(/* size */ NestedLoopCount);
  3799. if (SemaRef.CurContext->isDependentContext())
  3800. return NestedLoopCount;
  3801. // An example of what is generated for the following code:
  3802. //
  3803. // #pragma omp simd collapse(2) ordered(2)
  3804. // for (i = 0; i < NI; ++i)
  3805. // for (k = 0; k < NK; ++k)
  3806. // for (j = J0; j < NJ; j+=2) {
  3807. // <loop body>
  3808. // }
  3809. //
  3810. // We generate the code below.
  3811. // Note: the loop body may be outlined in CodeGen.
  3812. // Note: some counters may be C++ classes, operator- is used to find number of
  3813. // iterations and operator+= to calculate counter value.
  3814. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  3815. // or i64 is currently supported).
  3816. //
  3817. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  3818. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  3819. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  3820. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  3821. // // similar updates for vars in clauses (e.g. 'linear')
  3822. // <loop body (using local i and j)>
  3823. // }
  3824. // i = NI; // assign final values of counters
  3825. // j = NJ;
  3826. //
  3827. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  3828. // the iteration counts of the collapsed for loops.
  3829. // Precondition tests if there is at least one iteration (all conditions are
  3830. // true).
  3831. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  3832. auto N0 = IterSpaces[0].NumIterations;
  3833. ExprResult LastIteration32 = WidenIterationCount(
  3834. 32 /* Bits */, SemaRef.PerformImplicitConversion(
  3835. N0->IgnoreImpCasts(), N0->getType(),
  3836. Sema::AA_Converting, /*AllowExplicit=*/true)
  3837. .get(),
  3838. SemaRef);
  3839. ExprResult LastIteration64 = WidenIterationCount(
  3840. 64 /* Bits */, SemaRef.PerformImplicitConversion(
  3841. N0->IgnoreImpCasts(), N0->getType(),
  3842. Sema::AA_Converting, /*AllowExplicit=*/true)
  3843. .get(),
  3844. SemaRef);
  3845. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  3846. return NestedLoopCount;
  3847. auto &C = SemaRef.Context;
  3848. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  3849. Scope *CurScope = DSA.getCurScope();
  3850. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  3851. if (PreCond.isUsable()) {
  3852. PreCond = SemaRef.BuildBinOp(CurScope, SourceLocation(), BO_LAnd,
  3853. PreCond.get(), IterSpaces[Cnt].PreCond);
  3854. }
  3855. auto N = IterSpaces[Cnt].NumIterations;
  3856. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  3857. if (LastIteration32.isUsable())
  3858. LastIteration32 = SemaRef.BuildBinOp(
  3859. CurScope, SourceLocation(), BO_Mul, LastIteration32.get(),
  3860. SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  3861. Sema::AA_Converting,
  3862. /*AllowExplicit=*/true)
  3863. .get());
  3864. if (LastIteration64.isUsable())
  3865. LastIteration64 = SemaRef.BuildBinOp(
  3866. CurScope, SourceLocation(), BO_Mul, LastIteration64.get(),
  3867. SemaRef.PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  3868. Sema::AA_Converting,
  3869. /*AllowExplicit=*/true)
  3870. .get());
  3871. }
  3872. // Choose either the 32-bit or 64-bit version.
  3873. ExprResult LastIteration = LastIteration64;
  3874. if (LastIteration32.isUsable() &&
  3875. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  3876. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  3877. FitsInto(
  3878. 32 /* Bits */,
  3879. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  3880. LastIteration64.get(), SemaRef)))
  3881. LastIteration = LastIteration32;
  3882. if (!LastIteration.isUsable())
  3883. return 0;
  3884. // Save the number of iterations.
  3885. ExprResult NumIterations = LastIteration;
  3886. {
  3887. LastIteration = SemaRef.BuildBinOp(
  3888. CurScope, SourceLocation(), BO_Sub, LastIteration.get(),
  3889. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  3890. if (!LastIteration.isUsable())
  3891. return 0;
  3892. }
  3893. // Calculate the last iteration number beforehand instead of doing this on
  3894. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  3895. llvm::APSInt Result;
  3896. bool IsConstant =
  3897. LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
  3898. ExprResult CalcLastIteration;
  3899. if (!IsConstant) {
  3900. SourceLocation SaveLoc;
  3901. VarDecl *SaveVar =
  3902. buildVarDecl(SemaRef, SaveLoc, LastIteration.get()->getType(),
  3903. ".omp.last.iteration");
  3904. ExprResult SaveRef = buildDeclRefExpr(
  3905. SemaRef, SaveVar, LastIteration.get()->getType(), SaveLoc);
  3906. CalcLastIteration = SemaRef.BuildBinOp(CurScope, SaveLoc, BO_Assign,
  3907. SaveRef.get(), LastIteration.get());
  3908. LastIteration = SaveRef;
  3909. // Prepare SaveRef + 1.
  3910. NumIterations = SemaRef.BuildBinOp(
  3911. CurScope, SaveLoc, BO_Add, SaveRef.get(),
  3912. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  3913. if (!NumIterations.isUsable())
  3914. return 0;
  3915. }
  3916. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  3917. QualType VType = LastIteration.get()->getType();
  3918. // Build variables passed into runtime, nesessary for worksharing directives.
  3919. ExprResult LB, UB, IL, ST, EUB;
  3920. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  3921. isOpenMPDistributeDirective(DKind)) {
  3922. // Lower bound variable, initialized with zero.
  3923. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  3924. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  3925. SemaRef.AddInitializerToDecl(
  3926. LBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  3927. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  3928. // Upper bound variable, initialized with last iteration number.
  3929. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  3930. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  3931. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  3932. /*DirectInit*/ false,
  3933. /*TypeMayContainAuto*/ false);
  3934. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  3935. // This will be used to implement clause 'lastprivate'.
  3936. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  3937. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  3938. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  3939. SemaRef.AddInitializerToDecl(
  3940. ILDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  3941. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  3942. // Stride variable returned by runtime (we initialize it to 1 by default).
  3943. VarDecl *STDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.stride");
  3944. ST = buildDeclRefExpr(SemaRef, STDecl, VType, InitLoc);
  3945. SemaRef.AddInitializerToDecl(
  3946. STDecl, SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  3947. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  3948. // Build expression: UB = min(UB, LastIteration)
  3949. // It is nesessary for CodeGen of directives with static scheduling.
  3950. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  3951. UB.get(), LastIteration.get());
  3952. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  3953. InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
  3954. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  3955. CondOp.get());
  3956. EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
  3957. }
  3958. // Build the iteration variable and its initialization before loop.
  3959. ExprResult IV;
  3960. ExprResult Init;
  3961. {
  3962. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.iv");
  3963. IV = buildDeclRefExpr(SemaRef, IVDecl, VType, InitLoc);
  3964. Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
  3965. isOpenMPTaskLoopDirective(DKind) ||
  3966. isOpenMPDistributeDirective(DKind))
  3967. ? LB.get()
  3968. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  3969. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  3970. Init = SemaRef.ActOnFinishFullExpr(Init.get());
  3971. }
  3972. // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
  3973. SourceLocation CondLoc;
  3974. ExprResult Cond =
  3975. (isOpenMPWorksharingDirective(DKind) ||
  3976. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
  3977. ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
  3978. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  3979. NumIterations.get());
  3980. // Loop increment (IV = IV + 1)
  3981. SourceLocation IncLoc;
  3982. ExprResult Inc =
  3983. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  3984. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  3985. if (!Inc.isUsable())
  3986. return 0;
  3987. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  3988. Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
  3989. if (!Inc.isUsable())
  3990. return 0;
  3991. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  3992. // Used for directives with static scheduling.
  3993. ExprResult NextLB, NextUB;
  3994. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  3995. isOpenMPDistributeDirective(DKind)) {
  3996. // LB + ST
  3997. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  3998. if (!NextLB.isUsable())
  3999. return 0;
  4000. // LB = LB + ST
  4001. NextLB =
  4002. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  4003. NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
  4004. if (!NextLB.isUsable())
  4005. return 0;
  4006. // UB + ST
  4007. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  4008. if (!NextUB.isUsable())
  4009. return 0;
  4010. // UB = UB + ST
  4011. NextUB =
  4012. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  4013. NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
  4014. if (!NextUB.isUsable())
  4015. return 0;
  4016. }
  4017. // Build updates and final values of the loop counters.
  4018. bool HasErrors = false;
  4019. Built.Counters.resize(NestedLoopCount);
  4020. Built.Inits.resize(NestedLoopCount);
  4021. Built.Updates.resize(NestedLoopCount);
  4022. Built.Finals.resize(NestedLoopCount);
  4023. {
  4024. ExprResult Div;
  4025. // Go from inner nested loop to outer.
  4026. for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
  4027. LoopIterationSpace &IS = IterSpaces[Cnt];
  4028. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  4029. // Build: Iter = (IV / Div) % IS.NumIters
  4030. // where Div is product of previous iterations' IS.NumIters.
  4031. ExprResult Iter;
  4032. if (Div.isUsable()) {
  4033. Iter =
  4034. SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
  4035. } else {
  4036. Iter = IV;
  4037. assert((Cnt == (int)NestedLoopCount - 1) &&
  4038. "unusable div expected on first iteration only");
  4039. }
  4040. if (Cnt != 0 && Iter.isUsable())
  4041. Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
  4042. IS.NumIterations);
  4043. if (!Iter.isUsable()) {
  4044. HasErrors = true;
  4045. break;
  4046. }
  4047. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  4048. auto *CounterVar = buildDeclRefExpr(
  4049. SemaRef, cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()),
  4050. IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  4051. /*RefersToCapture=*/true);
  4052. ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  4053. IS.CounterInit);
  4054. if (!Init.isUsable()) {
  4055. HasErrors = true;
  4056. break;
  4057. }
  4058. ExprResult Update =
  4059. BuildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
  4060. IS.CounterInit, Iter, IS.CounterStep, IS.Subtract);
  4061. if (!Update.isUsable()) {
  4062. HasErrors = true;
  4063. break;
  4064. }
  4065. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  4066. ExprResult Final = BuildCounterUpdate(
  4067. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
  4068. IS.NumIterations, IS.CounterStep, IS.Subtract);
  4069. if (!Final.isUsable()) {
  4070. HasErrors = true;
  4071. break;
  4072. }
  4073. // Build Div for the next iteration: Div <- Div * IS.NumIters
  4074. if (Cnt != 0) {
  4075. if (Div.isUnset())
  4076. Div = IS.NumIterations;
  4077. else
  4078. Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
  4079. IS.NumIterations);
  4080. // Add parentheses (for debugging purposes only).
  4081. if (Div.isUsable())
  4082. Div = SemaRef.ActOnParenExpr(UpdLoc, UpdLoc, Div.get());
  4083. if (!Div.isUsable()) {
  4084. HasErrors = true;
  4085. break;
  4086. }
  4087. }
  4088. if (!Update.isUsable() || !Final.isUsable()) {
  4089. HasErrors = true;
  4090. break;
  4091. }
  4092. // Save results
  4093. Built.Counters[Cnt] = IS.CounterVar;
  4094. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  4095. Built.Inits[Cnt] = Init.get();
  4096. Built.Updates[Cnt] = Update.get();
  4097. Built.Finals[Cnt] = Final.get();
  4098. }
  4099. }
  4100. if (HasErrors)
  4101. return 0;
  4102. // Save results
  4103. Built.IterationVarRef = IV.get();
  4104. Built.LastIteration = LastIteration.get();
  4105. Built.NumIterations = NumIterations.get();
  4106. Built.CalcLastIteration =
  4107. SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
  4108. Built.PreCond = PreCond.get();
  4109. Built.Cond = Cond.get();
  4110. Built.Init = Init.get();
  4111. Built.Inc = Inc.get();
  4112. Built.LB = LB.get();
  4113. Built.UB = UB.get();
  4114. Built.IL = IL.get();
  4115. Built.ST = ST.get();
  4116. Built.EUB = EUB.get();
  4117. Built.NLB = NextLB.get();
  4118. Built.NUB = NextUB.get();
  4119. return NestedLoopCount;
  4120. }
  4121. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  4122. auto CollapseClauses =
  4123. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  4124. if (CollapseClauses.begin() != CollapseClauses.end())
  4125. return (*CollapseClauses.begin())->getNumForLoops();
  4126. return nullptr;
  4127. }
  4128. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  4129. auto OrderedClauses =
  4130. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  4131. if (OrderedClauses.begin() != OrderedClauses.end())
  4132. return (*OrderedClauses.begin())->getNumForLoops();
  4133. return nullptr;
  4134. }
  4135. static bool checkSimdlenSafelenValues(Sema &S, const Expr *Simdlen,
  4136. const Expr *Safelen) {
  4137. llvm::APSInt SimdlenRes, SafelenRes;
  4138. if (Simdlen->isValueDependent() || Simdlen->isTypeDependent() ||
  4139. Simdlen->isInstantiationDependent() ||
  4140. Simdlen->containsUnexpandedParameterPack())
  4141. return false;
  4142. if (Safelen->isValueDependent() || Safelen->isTypeDependent() ||
  4143. Safelen->isInstantiationDependent() ||
  4144. Safelen->containsUnexpandedParameterPack())
  4145. return false;
  4146. Simdlen->EvaluateAsInt(SimdlenRes, S.Context);
  4147. Safelen->EvaluateAsInt(SafelenRes, S.Context);
  4148. // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
  4149. // If both simdlen and safelen clauses are specified, the value of the simdlen
  4150. // parameter must be less than or equal to the value of the safelen parameter.
  4151. if (SimdlenRes > SafelenRes) {
  4152. S.Diag(Simdlen->getExprLoc(), diag::err_omp_wrong_simdlen_safelen_values)
  4153. << Simdlen->getSourceRange() << Safelen->getSourceRange();
  4154. return true;
  4155. }
  4156. return false;
  4157. }
  4158. StmtResult Sema::ActOnOpenMPSimdDirective(
  4159. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4160. SourceLocation EndLoc,
  4161. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4162. if (!AStmt)
  4163. return StmtError();
  4164. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4165. OMPLoopDirective::HelperExprs B;
  4166. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4167. // define the nested loops number.
  4168. unsigned NestedLoopCount = CheckOpenMPLoop(
  4169. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  4170. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  4171. if (NestedLoopCount == 0)
  4172. return StmtError();
  4173. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4174. "omp simd loop exprs were not built");
  4175. if (!CurContext->isDependentContext()) {
  4176. // Finalize the clauses that need pre-built expressions for CodeGen.
  4177. for (auto C : Clauses) {
  4178. if (auto LC = dyn_cast<OMPLinearClause>(C))
  4179. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4180. B.NumIterations, *this, CurScope))
  4181. return StmtError();
  4182. }
  4183. }
  4184. // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
  4185. // If both simdlen and safelen clauses are specified, the value of the simdlen
  4186. // parameter must be less than or equal to the value of the safelen parameter.
  4187. OMPSafelenClause *Safelen = nullptr;
  4188. OMPSimdlenClause *Simdlen = nullptr;
  4189. for (auto *Clause : Clauses) {
  4190. if (Clause->getClauseKind() == OMPC_safelen)
  4191. Safelen = cast<OMPSafelenClause>(Clause);
  4192. else if (Clause->getClauseKind() == OMPC_simdlen)
  4193. Simdlen = cast<OMPSimdlenClause>(Clause);
  4194. if (Safelen && Simdlen)
  4195. break;
  4196. }
  4197. if (Simdlen && Safelen &&
  4198. checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
  4199. Safelen->getSafelen()))
  4200. return StmtError();
  4201. getCurFunction()->setHasBranchProtectedScope();
  4202. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4203. Clauses, AStmt, B);
  4204. }
  4205. StmtResult Sema::ActOnOpenMPForDirective(
  4206. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4207. SourceLocation EndLoc,
  4208. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4209. if (!AStmt)
  4210. return StmtError();
  4211. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4212. OMPLoopDirective::HelperExprs B;
  4213. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4214. // define the nested loops number.
  4215. unsigned NestedLoopCount = CheckOpenMPLoop(
  4216. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  4217. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  4218. if (NestedLoopCount == 0)
  4219. return StmtError();
  4220. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4221. "omp for loop exprs were not built");
  4222. if (!CurContext->isDependentContext()) {
  4223. // Finalize the clauses that need pre-built expressions for CodeGen.
  4224. for (auto C : Clauses) {
  4225. if (auto LC = dyn_cast<OMPLinearClause>(C))
  4226. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4227. B.NumIterations, *this, CurScope))
  4228. return StmtError();
  4229. }
  4230. }
  4231. getCurFunction()->setHasBranchProtectedScope();
  4232. return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4233. Clauses, AStmt, B, DSAStack->isCancelRegion());
  4234. }
  4235. StmtResult Sema::ActOnOpenMPForSimdDirective(
  4236. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4237. SourceLocation EndLoc,
  4238. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4239. if (!AStmt)
  4240. return StmtError();
  4241. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4242. OMPLoopDirective::HelperExprs B;
  4243. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4244. // define the nested loops number.
  4245. unsigned NestedLoopCount =
  4246. CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  4247. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  4248. VarsWithImplicitDSA, B);
  4249. if (NestedLoopCount == 0)
  4250. return StmtError();
  4251. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4252. "omp for simd loop exprs were not built");
  4253. if (!CurContext->isDependentContext()) {
  4254. // Finalize the clauses that need pre-built expressions for CodeGen.
  4255. for (auto C : Clauses) {
  4256. if (auto LC = dyn_cast<OMPLinearClause>(C))
  4257. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4258. B.NumIterations, *this, CurScope))
  4259. return StmtError();
  4260. }
  4261. }
  4262. // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
  4263. // If both simdlen and safelen clauses are specified, the value of the simdlen
  4264. // parameter must be less than or equal to the value of the safelen parameter.
  4265. OMPSafelenClause *Safelen = nullptr;
  4266. OMPSimdlenClause *Simdlen = nullptr;
  4267. for (auto *Clause : Clauses) {
  4268. if (Clause->getClauseKind() == OMPC_safelen)
  4269. Safelen = cast<OMPSafelenClause>(Clause);
  4270. else if (Clause->getClauseKind() == OMPC_simdlen)
  4271. Simdlen = cast<OMPSimdlenClause>(Clause);
  4272. if (Safelen && Simdlen)
  4273. break;
  4274. }
  4275. if (Simdlen && Safelen &&
  4276. checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
  4277. Safelen->getSafelen()))
  4278. return StmtError();
  4279. getCurFunction()->setHasBranchProtectedScope();
  4280. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  4281. Clauses, AStmt, B);
  4282. }
  4283. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  4284. Stmt *AStmt,
  4285. SourceLocation StartLoc,
  4286. SourceLocation EndLoc) {
  4287. if (!AStmt)
  4288. return StmtError();
  4289. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4290. auto BaseStmt = AStmt;
  4291. while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  4292. BaseStmt = CS->getCapturedStmt();
  4293. if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  4294. auto S = C->children();
  4295. if (S.begin() == S.end())
  4296. return StmtError();
  4297. // All associated statements must be '#pragma omp section' except for
  4298. // the first one.
  4299. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  4300. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  4301. if (SectionStmt)
  4302. Diag(SectionStmt->getLocStart(),
  4303. diag::err_omp_sections_substmt_not_section);
  4304. return StmtError();
  4305. }
  4306. cast<OMPSectionDirective>(SectionStmt)
  4307. ->setHasCancel(DSAStack->isCancelRegion());
  4308. }
  4309. } else {
  4310. Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
  4311. return StmtError();
  4312. }
  4313. getCurFunction()->setHasBranchProtectedScope();
  4314. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4315. DSAStack->isCancelRegion());
  4316. }
  4317. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  4318. SourceLocation StartLoc,
  4319. SourceLocation EndLoc) {
  4320. if (!AStmt)
  4321. return StmtError();
  4322. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4323. getCurFunction()->setHasBranchProtectedScope();
  4324. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  4325. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  4326. DSAStack->isCancelRegion());
  4327. }
  4328. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  4329. Stmt *AStmt,
  4330. SourceLocation StartLoc,
  4331. SourceLocation EndLoc) {
  4332. if (!AStmt)
  4333. return StmtError();
  4334. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4335. getCurFunction()->setHasBranchProtectedScope();
  4336. // OpenMP [2.7.3, single Construct, Restrictions]
  4337. // The copyprivate clause must not be used with the nowait clause.
  4338. OMPClause *Nowait = nullptr;
  4339. OMPClause *Copyprivate = nullptr;
  4340. for (auto *Clause : Clauses) {
  4341. if (Clause->getClauseKind() == OMPC_nowait)
  4342. Nowait = Clause;
  4343. else if (Clause->getClauseKind() == OMPC_copyprivate)
  4344. Copyprivate = Clause;
  4345. if (Copyprivate && Nowait) {
  4346. Diag(Copyprivate->getLocStart(),
  4347. diag::err_omp_single_copyprivate_with_nowait);
  4348. Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
  4349. return StmtError();
  4350. }
  4351. }
  4352. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  4353. }
  4354. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  4355. SourceLocation StartLoc,
  4356. SourceLocation EndLoc) {
  4357. if (!AStmt)
  4358. return StmtError();
  4359. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4360. getCurFunction()->setHasBranchProtectedScope();
  4361. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  4362. }
  4363. StmtResult Sema::ActOnOpenMPCriticalDirective(
  4364. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  4365. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  4366. if (!AStmt)
  4367. return StmtError();
  4368. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4369. bool ErrorFound = false;
  4370. llvm::APSInt Hint;
  4371. SourceLocation HintLoc;
  4372. bool DependentHint = false;
  4373. for (auto *C : Clauses) {
  4374. if (C->getClauseKind() == OMPC_hint) {
  4375. if (!DirName.getName()) {
  4376. Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
  4377. ErrorFound = true;
  4378. }
  4379. Expr *E = cast<OMPHintClause>(C)->getHint();
  4380. if (E->isTypeDependent() || E->isValueDependent() ||
  4381. E->isInstantiationDependent())
  4382. DependentHint = true;
  4383. else {
  4384. Hint = E->EvaluateKnownConstInt(Context);
  4385. HintLoc = C->getLocStart();
  4386. }
  4387. }
  4388. }
  4389. if (ErrorFound)
  4390. return StmtError();
  4391. auto Pair = DSAStack->getCriticalWithHint(DirName);
  4392. if (Pair.first && DirName.getName() && !DependentHint) {
  4393. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  4394. Diag(StartLoc, diag::err_omp_critical_with_hint);
  4395. if (HintLoc.isValid()) {
  4396. Diag(HintLoc, diag::note_omp_critical_hint_here)
  4397. << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
  4398. } else
  4399. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  4400. if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  4401. Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
  4402. << 1
  4403. << C->getHint()->EvaluateKnownConstInt(Context).toString(
  4404. /*Radix=*/10, /*Signed=*/false);
  4405. } else
  4406. Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
  4407. }
  4408. }
  4409. getCurFunction()->setHasBranchProtectedScope();
  4410. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  4411. Clauses, AStmt);
  4412. if (!Pair.first && DirName.getName() && !DependentHint)
  4413. DSAStack->addCriticalWithHint(Dir, Hint);
  4414. return Dir;
  4415. }
  4416. StmtResult Sema::ActOnOpenMPParallelForDirective(
  4417. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4418. SourceLocation EndLoc,
  4419. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4420. if (!AStmt)
  4421. return StmtError();
  4422. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  4423. // 1.2.2 OpenMP Language Terminology
  4424. // Structured block - An executable statement with a single entry at the
  4425. // top and a single exit at the bottom.
  4426. // The point of exit cannot be a branch out of the structured block.
  4427. // longjmp() and throw() must not violate the entry/exit criteria.
  4428. CS->getCapturedDecl()->setNothrow();
  4429. OMPLoopDirective::HelperExprs B;
  4430. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4431. // define the nested loops number.
  4432. unsigned NestedLoopCount =
  4433. CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  4434. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  4435. VarsWithImplicitDSA, B);
  4436. if (NestedLoopCount == 0)
  4437. return StmtError();
  4438. assert((CurContext->isDependentContext() || B.builtAll()) &&
  4439. "omp parallel for loop exprs were not built");
  4440. if (!CurContext->isDependentContext()) {
  4441. // Finalize the clauses that need pre-built expressions for CodeGen.
  4442. for (auto C : Clauses) {
  4443. if (auto LC = dyn_cast<OMPLinearClause>(C))
  4444. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4445. B.NumIterations, *this, CurScope))
  4446. return StmtError();
  4447. }
  4448. }
  4449. getCurFunction()->setHasBranchProtectedScope();
  4450. return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
  4451. NestedLoopCount, Clauses, AStmt, B,
  4452. DSAStack->isCancelRegion());
  4453. }
  4454. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  4455. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  4456. SourceLocation EndLoc,
  4457. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  4458. if (!AStmt)
  4459. return StmtError();
  4460. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  4461. // 1.2.2 OpenMP Language Terminology
  4462. // Structured block - An executable statement with a single entry at the
  4463. // top and a single exit at the bottom.
  4464. // The point of exit cannot be a branch out of the structured block.
  4465. // longjmp() and throw() must not violate the entry/exit criteria.
  4466. CS->getCapturedDecl()->setNothrow();
  4467. OMPLoopDirective::HelperExprs B;
  4468. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  4469. // define the nested loops number.
  4470. unsigned NestedLoopCount =
  4471. CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  4472. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  4473. VarsWithImplicitDSA, B);
  4474. if (NestedLoopCount == 0)
  4475. return StmtError();
  4476. if (!CurContext->isDependentContext()) {
  4477. // Finalize the clauses that need pre-built expressions for CodeGen.
  4478. for (auto C : Clauses) {
  4479. if (auto LC = dyn_cast<OMPLinearClause>(C))
  4480. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  4481. B.NumIterations, *this, CurScope))
  4482. return StmtError();
  4483. }
  4484. }
  4485. // OpenMP 4.1 [2.8.1, simd Construct, Restrictions]
  4486. // If both simdlen and safelen clauses are specified, the value of the simdlen
  4487. // parameter must be less than or equal to the value of the safelen parameter.
  4488. OMPSafelenClause *Safelen = nullptr;
  4489. OMPSimdlenClause *Simdlen = nullptr;
  4490. for (auto *Clause : Clauses) {
  4491. if (Clause->getClauseKind() == OMPC_safelen)
  4492. Safelen = cast<OMPSafelenClause>(Clause);
  4493. else if (Clause->getClauseKind() == OMPC_simdlen)
  4494. Simdlen = cast<OMPSimdlenClause>(Clause);
  4495. if (Safelen && Simdlen)
  4496. break;
  4497. }
  4498. if (Simdlen && Safelen &&
  4499. checkSimdlenSafelenValues(*this, Simdlen->getSimdlen(),
  4500. Safelen->getSafelen()))
  4501. return StmtError();
  4502. getCurFunction()->setHasBranchProtectedScope();
  4503. return OMPParallelForSimdDirective::Create(
  4504. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  4505. }
  4506. StmtResult
  4507. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  4508. Stmt *AStmt, SourceLocation StartLoc,
  4509. SourceLocation EndLoc) {
  4510. if (!AStmt)
  4511. return StmtError();
  4512. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4513. auto BaseStmt = AStmt;
  4514. while (CapturedStmt *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  4515. BaseStmt = CS->getCapturedStmt();
  4516. if (auto C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  4517. auto S = C->children();
  4518. if (S.begin() == S.end())
  4519. return StmtError();
  4520. // All associated statements must be '#pragma omp section' except for
  4521. // the first one.
  4522. for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
  4523. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  4524. if (SectionStmt)
  4525. Diag(SectionStmt->getLocStart(),
  4526. diag::err_omp_parallel_sections_substmt_not_section);
  4527. return StmtError();
  4528. }
  4529. cast<OMPSectionDirective>(SectionStmt)
  4530. ->setHasCancel(DSAStack->isCancelRegion());
  4531. }
  4532. } else {
  4533. Diag(AStmt->getLocStart(),
  4534. diag::err_omp_parallel_sections_not_compound_stmt);
  4535. return StmtError();
  4536. }
  4537. getCurFunction()->setHasBranchProtectedScope();
  4538. return OMPParallelSectionsDirective::Create(
  4539. Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
  4540. }
  4541. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  4542. Stmt *AStmt, SourceLocation StartLoc,
  4543. SourceLocation EndLoc) {
  4544. if (!AStmt)
  4545. return StmtError();
  4546. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  4547. // 1.2.2 OpenMP Language Terminology
  4548. // Structured block - An executable statement with a single entry at the
  4549. // top and a single exit at the bottom.
  4550. // The point of exit cannot be a branch out of the structured block.
  4551. // longjmp() and throw() must not violate the entry/exit criteria.
  4552. CS->getCapturedDecl()->setNothrow();
  4553. getCurFunction()->setHasBranchProtectedScope();
  4554. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  4555. DSAStack->isCancelRegion());
  4556. }
  4557. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  4558. SourceLocation EndLoc) {
  4559. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  4560. }
  4561. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  4562. SourceLocation EndLoc) {
  4563. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  4564. }
  4565. StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
  4566. SourceLocation EndLoc) {
  4567. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
  4568. }
  4569. StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt,
  4570. SourceLocation StartLoc,
  4571. SourceLocation EndLoc) {
  4572. if (!AStmt)
  4573. return StmtError();
  4574. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4575. getCurFunction()->setHasBranchProtectedScope();
  4576. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt);
  4577. }
  4578. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  4579. SourceLocation StartLoc,
  4580. SourceLocation EndLoc) {
  4581. assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
  4582. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  4583. }
  4584. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  4585. Stmt *AStmt,
  4586. SourceLocation StartLoc,
  4587. SourceLocation EndLoc) {
  4588. OMPClause *DependFound = nullptr;
  4589. OMPClause *DependSourceClause = nullptr;
  4590. OMPClause *DependSinkClause = nullptr;
  4591. bool ErrorFound = false;
  4592. OMPThreadsClause *TC = nullptr;
  4593. OMPSIMDClause *SC = nullptr;
  4594. for (auto *C : Clauses) {
  4595. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  4596. DependFound = C;
  4597. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  4598. if (DependSourceClause) {
  4599. Diag(C->getLocStart(), diag::err_omp_more_one_clause)
  4600. << getOpenMPDirectiveName(OMPD_ordered)
  4601. << getOpenMPClauseName(OMPC_depend) << 2;
  4602. ErrorFound = true;
  4603. } else
  4604. DependSourceClause = C;
  4605. if (DependSinkClause) {
  4606. Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
  4607. << 0;
  4608. ErrorFound = true;
  4609. }
  4610. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  4611. if (DependSourceClause) {
  4612. Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
  4613. << 1;
  4614. ErrorFound = true;
  4615. }
  4616. DependSinkClause = C;
  4617. }
  4618. } else if (C->getClauseKind() == OMPC_threads)
  4619. TC = cast<OMPThreadsClause>(C);
  4620. else if (C->getClauseKind() == OMPC_simd)
  4621. SC = cast<OMPSIMDClause>(C);
  4622. }
  4623. if (!ErrorFound && !SC &&
  4624. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  4625. // OpenMP [2.8.1,simd Construct, Restrictions]
  4626. // An ordered construct with the simd clause is the only OpenMP construct
  4627. // that can appear in the simd region.
  4628. Diag(StartLoc, diag::err_omp_prohibited_region_simd);
  4629. ErrorFound = true;
  4630. } else if (DependFound && (TC || SC)) {
  4631. Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
  4632. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  4633. ErrorFound = true;
  4634. } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
  4635. Diag(DependFound->getLocStart(),
  4636. diag::err_omp_ordered_directive_without_param);
  4637. ErrorFound = true;
  4638. } else if (TC || Clauses.empty()) {
  4639. if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
  4640. SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
  4641. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  4642. << (TC != nullptr);
  4643. Diag(Param->getLocStart(), diag::note_omp_ordered_param);
  4644. ErrorFound = true;
  4645. }
  4646. }
  4647. if ((!AStmt && !DependFound) || ErrorFound)
  4648. return StmtError();
  4649. if (AStmt) {
  4650. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  4651. getCurFunction()->setHasBranchProtectedScope();
  4652. }
  4653. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  4654. }
  4655. namespace {
  4656. /// \brief Helper class for checking expression in 'omp atomic [update]'
  4657. /// construct.
  4658. class OpenMPAtomicUpdateChecker {
  4659. /// \brief Error results for atomic update expressions.
  4660. enum ExprAnalysisErrorCode {
  4661. /// \brief A statement is not an expression statement.
  4662. NotAnExpression,
  4663. /// \brief Expression is not builtin binary or unary operation.
  4664. NotABinaryOrUnaryExpression,
  4665. /// \brief Unary operation is not post-/pre- increment/decrement operation.
  4666. NotAnUnaryIncDecExpression,
  4667. /// \brief An expression is not of scalar type.
  4668. NotAScalarType,
  4669. /// \brief A binary operation is not an assignment operation.
  4670. NotAnAssignmentOp,
  4671. /// \brief RHS part of the binary operation is not a binary expression.
  4672. NotABinaryExpression,
  4673. /// \brief RHS part is not additive/multiplicative/shift/biwise binary
  4674. /// expression.
  4675. NotABinaryOperator,
  4676. /// \brief RHS binary operation does not have reference to the updated LHS
  4677. /// part.
  4678. NotAnUpdateExpression,
  4679. /// \brief No errors is found.
  4680. NoError
  4681. };
  4682. /// \brief Reference to Sema.
  4683. Sema &SemaRef;
  4684. /// \brief A location for note diagnostics (when error is found).
  4685. SourceLocation NoteLoc;
  4686. /// \brief 'x' lvalue part of the source atomic expression.
  4687. Expr *X;
  4688. /// \brief 'expr' rvalue part of the source atomic expression.
  4689. Expr *E;
  4690. /// \brief Helper expression of the form
  4691. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  4692. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  4693. Expr *UpdateExpr;
  4694. /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
  4695. /// important for non-associative operations.
  4696. bool IsXLHSInRHSPart;
  4697. BinaryOperatorKind Op;
  4698. SourceLocation OpLoc;
  4699. /// \brief true if the source expression is a postfix unary operation, false
  4700. /// if it is a prefix unary operation.
  4701. bool IsPostfixUpdate;
  4702. public:
  4703. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  4704. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  4705. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  4706. /// \brief Check specified statement that it is suitable for 'atomic update'
  4707. /// constructs and extract 'x', 'expr' and Operation from the original
  4708. /// expression. If DiagId and NoteId == 0, then only check is performed
  4709. /// without error notification.
  4710. /// \param DiagId Diagnostic which should be emitted if error is found.
  4711. /// \param NoteId Diagnostic note for the main error message.
  4712. /// \return true if statement is not an update expression, false otherwise.
  4713. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  4714. /// \brief Return the 'x' lvalue part of the source atomic expression.
  4715. Expr *getX() const { return X; }
  4716. /// \brief Return the 'expr' rvalue part of the source atomic expression.
  4717. Expr *getExpr() const { return E; }
  4718. /// \brief Return the update expression used in calculation of the updated
  4719. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  4720. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  4721. Expr *getUpdateExpr() const { return UpdateExpr; }
  4722. /// \brief Return true if 'x' is LHS in RHS part of full update expression,
  4723. /// false otherwise.
  4724. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  4725. /// \brief true if the source expression is a postfix unary operation, false
  4726. /// if it is a prefix unary operation.
  4727. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  4728. private:
  4729. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  4730. unsigned NoteId = 0);
  4731. };
  4732. } // namespace
  4733. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  4734. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  4735. ExprAnalysisErrorCode ErrorFound = NoError;
  4736. SourceLocation ErrorLoc, NoteLoc;
  4737. SourceRange ErrorRange, NoteRange;
  4738. // Allowed constructs are:
  4739. // x = x binop expr;
  4740. // x = expr binop x;
  4741. if (AtomicBinOp->getOpcode() == BO_Assign) {
  4742. X = AtomicBinOp->getLHS();
  4743. if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  4744. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  4745. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  4746. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  4747. AtomicInnerBinOp->isBitwiseOp()) {
  4748. Op = AtomicInnerBinOp->getOpcode();
  4749. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  4750. auto *LHS = AtomicInnerBinOp->getLHS();
  4751. auto *RHS = AtomicInnerBinOp->getRHS();
  4752. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  4753. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  4754. /*Canonical=*/true);
  4755. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  4756. /*Canonical=*/true);
  4757. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  4758. /*Canonical=*/true);
  4759. if (XId == LHSId) {
  4760. E = RHS;
  4761. IsXLHSInRHSPart = true;
  4762. } else if (XId == RHSId) {
  4763. E = LHS;
  4764. IsXLHSInRHSPart = false;
  4765. } else {
  4766. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  4767. ErrorRange = AtomicInnerBinOp->getSourceRange();
  4768. NoteLoc = X->getExprLoc();
  4769. NoteRange = X->getSourceRange();
  4770. ErrorFound = NotAnUpdateExpression;
  4771. }
  4772. } else {
  4773. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  4774. ErrorRange = AtomicInnerBinOp->getSourceRange();
  4775. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  4776. NoteRange = SourceRange(NoteLoc, NoteLoc);
  4777. ErrorFound = NotABinaryOperator;
  4778. }
  4779. } else {
  4780. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  4781. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  4782. ErrorFound = NotABinaryExpression;
  4783. }
  4784. } else {
  4785. ErrorLoc = AtomicBinOp->getExprLoc();
  4786. ErrorRange = AtomicBinOp->getSourceRange();
  4787. NoteLoc = AtomicBinOp->getOperatorLoc();
  4788. NoteRange = SourceRange(NoteLoc, NoteLoc);
  4789. ErrorFound = NotAnAssignmentOp;
  4790. }
  4791. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  4792. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  4793. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  4794. return true;
  4795. } else if (SemaRef.CurContext->isDependentContext())
  4796. E = X = UpdateExpr = nullptr;
  4797. return ErrorFound != NoError;
  4798. }
  4799. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  4800. unsigned NoteId) {
  4801. ExprAnalysisErrorCode ErrorFound = NoError;
  4802. SourceLocation ErrorLoc, NoteLoc;
  4803. SourceRange ErrorRange, NoteRange;
  4804. // Allowed constructs are:
  4805. // x++;
  4806. // x--;
  4807. // ++x;
  4808. // --x;
  4809. // x binop= expr;
  4810. // x = x binop expr;
  4811. // x = expr binop x;
  4812. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  4813. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  4814. if (AtomicBody->getType()->isScalarType() ||
  4815. AtomicBody->isInstantiationDependent()) {
  4816. if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  4817. AtomicBody->IgnoreParenImpCasts())) {
  4818. // Check for Compound Assignment Operation
  4819. Op = BinaryOperator::getOpForCompoundAssignment(
  4820. AtomicCompAssignOp->getOpcode());
  4821. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  4822. E = AtomicCompAssignOp->getRHS();
  4823. X = AtomicCompAssignOp->getLHS();
  4824. IsXLHSInRHSPart = true;
  4825. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  4826. AtomicBody->IgnoreParenImpCasts())) {
  4827. // Check for Binary Operation
  4828. if(checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  4829. return true;
  4830. } else if (auto *AtomicUnaryOp =
  4831. dyn_cast<UnaryOperator>(AtomicBody->IgnoreParenImpCasts())) {
  4832. // Check for Unary Operation
  4833. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  4834. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  4835. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  4836. OpLoc = AtomicUnaryOp->getOperatorLoc();
  4837. X = AtomicUnaryOp->getSubExpr();
  4838. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  4839. IsXLHSInRHSPart = true;
  4840. } else {
  4841. ErrorFound = NotAnUnaryIncDecExpression;
  4842. ErrorLoc = AtomicUnaryOp->getExprLoc();
  4843. ErrorRange = AtomicUnaryOp->getSourceRange();
  4844. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  4845. NoteRange = SourceRange(NoteLoc, NoteLoc);
  4846. }
  4847. } else if (!AtomicBody->isInstantiationDependent()) {
  4848. ErrorFound = NotABinaryOrUnaryExpression;
  4849. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  4850. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  4851. }
  4852. } else {
  4853. ErrorFound = NotAScalarType;
  4854. NoteLoc = ErrorLoc = AtomicBody->getLocStart();
  4855. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  4856. }
  4857. } else {
  4858. ErrorFound = NotAnExpression;
  4859. NoteLoc = ErrorLoc = S->getLocStart();
  4860. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  4861. }
  4862. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  4863. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  4864. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  4865. return true;
  4866. } else if (SemaRef.CurContext->isDependentContext())
  4867. E = X = UpdateExpr = nullptr;
  4868. if (ErrorFound == NoError && E && X) {
  4869. // Build an update expression of form 'OpaqueValueExpr(x) binop
  4870. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  4871. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  4872. auto *OVEX = new (SemaRef.getASTContext())
  4873. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
  4874. auto *OVEExpr = new (SemaRef.getASTContext())
  4875. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
  4876. auto Update =
  4877. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  4878. IsXLHSInRHSPart ? OVEExpr : OVEX);
  4879. if (Update.isInvalid())
  4880. return true;
  4881. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  4882. Sema::AA_Casting);
  4883. if (Update.isInvalid())
  4884. return true;
  4885. UpdateExpr = Update.get();
  4886. }
  4887. return ErrorFound != NoError;
  4888. }
  4889. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  4890. Stmt *AStmt,
  4891. SourceLocation StartLoc,
  4892. SourceLocation EndLoc) {
  4893. if (!AStmt)
  4894. return StmtError();
  4895. auto CS = cast<CapturedStmt>(AStmt);
  4896. // 1.2.2 OpenMP Language Terminology
  4897. // Structured block - An executable statement with a single entry at the
  4898. // top and a single exit at the bottom.
  4899. // The point of exit cannot be a branch out of the structured block.
  4900. // longjmp() and throw() must not violate the entry/exit criteria.
  4901. OpenMPClauseKind AtomicKind = OMPC_unknown;
  4902. SourceLocation AtomicKindLoc;
  4903. for (auto *C : Clauses) {
  4904. if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
  4905. C->getClauseKind() == OMPC_update ||
  4906. C->getClauseKind() == OMPC_capture) {
  4907. if (AtomicKind != OMPC_unknown) {
  4908. Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
  4909. << SourceRange(C->getLocStart(), C->getLocEnd());
  4910. Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
  4911. << getOpenMPClauseName(AtomicKind);
  4912. } else {
  4913. AtomicKind = C->getClauseKind();
  4914. AtomicKindLoc = C->getLocStart();
  4915. }
  4916. }
  4917. }
  4918. auto Body = CS->getCapturedStmt();
  4919. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  4920. Body = EWC->getSubExpr();
  4921. Expr *X = nullptr;
  4922. Expr *V = nullptr;
  4923. Expr *E = nullptr;
  4924. Expr *UE = nullptr;
  4925. bool IsXLHSInRHSPart = false;
  4926. bool IsPostfixUpdate = false;
  4927. // OpenMP [2.12.6, atomic Construct]
  4928. // In the next expressions:
  4929. // * x and v (as applicable) are both l-value expressions with scalar type.
  4930. // * During the execution of an atomic region, multiple syntactic
  4931. // occurrences of x must designate the same storage location.
  4932. // * Neither of v and expr (as applicable) may access the storage location
  4933. // designated by x.
  4934. // * Neither of x and expr (as applicable) may access the storage location
  4935. // designated by v.
  4936. // * expr is an expression with scalar type.
  4937. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  4938. // * binop, binop=, ++, and -- are not overloaded operators.
  4939. // * The expression x binop expr must be numerically equivalent to x binop
  4940. // (expr). This requirement is satisfied if the operators in expr have
  4941. // precedence greater than binop, or by using parentheses around expr or
  4942. // subexpressions of expr.
  4943. // * The expression expr binop x must be numerically equivalent to (expr)
  4944. // binop x. This requirement is satisfied if the operators in expr have
  4945. // precedence equal to or greater than binop, or by using parentheses around
  4946. // expr or subexpressions of expr.
  4947. // * For forms that allow multiple occurrences of x, the number of times
  4948. // that x is evaluated is unspecified.
  4949. if (AtomicKind == OMPC_read) {
  4950. enum {
  4951. NotAnExpression,
  4952. NotAnAssignmentOp,
  4953. NotAScalarType,
  4954. NotAnLValue,
  4955. NoError
  4956. } ErrorFound = NoError;
  4957. SourceLocation ErrorLoc, NoteLoc;
  4958. SourceRange ErrorRange, NoteRange;
  4959. // If clause is read:
  4960. // v = x;
  4961. if (auto AtomicBody = dyn_cast<Expr>(Body)) {
  4962. auto AtomicBinOp =
  4963. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  4964. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  4965. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  4966. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  4967. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  4968. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  4969. if (!X->isLValue() || !V->isLValue()) {
  4970. auto NotLValueExpr = X->isLValue() ? V : X;
  4971. ErrorFound = NotAnLValue;
  4972. ErrorLoc = AtomicBinOp->getExprLoc();
  4973. ErrorRange = AtomicBinOp->getSourceRange();
  4974. NoteLoc = NotLValueExpr->getExprLoc();
  4975. NoteRange = NotLValueExpr->getSourceRange();
  4976. }
  4977. } else if (!X->isInstantiationDependent() ||
  4978. !V->isInstantiationDependent()) {
  4979. auto NotScalarExpr =
  4980. (X->isInstantiationDependent() || X->getType()->isScalarType())
  4981. ? V
  4982. : X;
  4983. ErrorFound = NotAScalarType;
  4984. ErrorLoc = AtomicBinOp->getExprLoc();
  4985. ErrorRange = AtomicBinOp->getSourceRange();
  4986. NoteLoc = NotScalarExpr->getExprLoc();
  4987. NoteRange = NotScalarExpr->getSourceRange();
  4988. }
  4989. } else if (!AtomicBody->isInstantiationDependent()) {
  4990. ErrorFound = NotAnAssignmentOp;
  4991. ErrorLoc = AtomicBody->getExprLoc();
  4992. ErrorRange = AtomicBody->getSourceRange();
  4993. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  4994. : AtomicBody->getExprLoc();
  4995. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  4996. : AtomicBody->getSourceRange();
  4997. }
  4998. } else {
  4999. ErrorFound = NotAnExpression;
  5000. NoteLoc = ErrorLoc = Body->getLocStart();
  5001. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5002. }
  5003. if (ErrorFound != NoError) {
  5004. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  5005. << ErrorRange;
  5006. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  5007. << NoteRange;
  5008. return StmtError();
  5009. } else if (CurContext->isDependentContext())
  5010. V = X = nullptr;
  5011. } else if (AtomicKind == OMPC_write) {
  5012. enum {
  5013. NotAnExpression,
  5014. NotAnAssignmentOp,
  5015. NotAScalarType,
  5016. NotAnLValue,
  5017. NoError
  5018. } ErrorFound = NoError;
  5019. SourceLocation ErrorLoc, NoteLoc;
  5020. SourceRange ErrorRange, NoteRange;
  5021. // If clause is write:
  5022. // x = expr;
  5023. if (auto AtomicBody = dyn_cast<Expr>(Body)) {
  5024. auto AtomicBinOp =
  5025. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5026. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5027. X = AtomicBinOp->getLHS();
  5028. E = AtomicBinOp->getRHS();
  5029. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  5030. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  5031. if (!X->isLValue()) {
  5032. ErrorFound = NotAnLValue;
  5033. ErrorLoc = AtomicBinOp->getExprLoc();
  5034. ErrorRange = AtomicBinOp->getSourceRange();
  5035. NoteLoc = X->getExprLoc();
  5036. NoteRange = X->getSourceRange();
  5037. }
  5038. } else if (!X->isInstantiationDependent() ||
  5039. !E->isInstantiationDependent()) {
  5040. auto NotScalarExpr =
  5041. (X->isInstantiationDependent() || X->getType()->isScalarType())
  5042. ? E
  5043. : X;
  5044. ErrorFound = NotAScalarType;
  5045. ErrorLoc = AtomicBinOp->getExprLoc();
  5046. ErrorRange = AtomicBinOp->getSourceRange();
  5047. NoteLoc = NotScalarExpr->getExprLoc();
  5048. NoteRange = NotScalarExpr->getSourceRange();
  5049. }
  5050. } else if (!AtomicBody->isInstantiationDependent()) {
  5051. ErrorFound = NotAnAssignmentOp;
  5052. ErrorLoc = AtomicBody->getExprLoc();
  5053. ErrorRange = AtomicBody->getSourceRange();
  5054. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5055. : AtomicBody->getExprLoc();
  5056. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5057. : AtomicBody->getSourceRange();
  5058. }
  5059. } else {
  5060. ErrorFound = NotAnExpression;
  5061. NoteLoc = ErrorLoc = Body->getLocStart();
  5062. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  5063. }
  5064. if (ErrorFound != NoError) {
  5065. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  5066. << ErrorRange;
  5067. Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
  5068. << NoteRange;
  5069. return StmtError();
  5070. } else if (CurContext->isDependentContext())
  5071. E = X = nullptr;
  5072. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  5073. // If clause is update:
  5074. // x++;
  5075. // x--;
  5076. // ++x;
  5077. // --x;
  5078. // x binop= expr;
  5079. // x = x binop expr;
  5080. // x = expr binop x;
  5081. OpenMPAtomicUpdateChecker Checker(*this);
  5082. if (Checker.checkStatement(
  5083. Body, (AtomicKind == OMPC_update)
  5084. ? diag::err_omp_atomic_update_not_expression_statement
  5085. : diag::err_omp_atomic_not_expression_statement,
  5086. diag::note_omp_atomic_update))
  5087. return StmtError();
  5088. if (!CurContext->isDependentContext()) {
  5089. E = Checker.getExpr();
  5090. X = Checker.getX();
  5091. UE = Checker.getUpdateExpr();
  5092. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5093. }
  5094. } else if (AtomicKind == OMPC_capture) {
  5095. enum {
  5096. NotAnAssignmentOp,
  5097. NotACompoundStatement,
  5098. NotTwoSubstatements,
  5099. NotASpecificExpression,
  5100. NoError
  5101. } ErrorFound = NoError;
  5102. SourceLocation ErrorLoc, NoteLoc;
  5103. SourceRange ErrorRange, NoteRange;
  5104. if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
  5105. // If clause is a capture:
  5106. // v = x++;
  5107. // v = x--;
  5108. // v = ++x;
  5109. // v = --x;
  5110. // v = x binop= expr;
  5111. // v = x = x binop expr;
  5112. // v = x = expr binop x;
  5113. auto *AtomicBinOp =
  5114. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  5115. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  5116. V = AtomicBinOp->getLHS();
  5117. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  5118. OpenMPAtomicUpdateChecker Checker(*this);
  5119. if (Checker.checkStatement(
  5120. Body, diag::err_omp_atomic_capture_not_expression_statement,
  5121. diag::note_omp_atomic_update))
  5122. return StmtError();
  5123. E = Checker.getExpr();
  5124. X = Checker.getX();
  5125. UE = Checker.getUpdateExpr();
  5126. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5127. IsPostfixUpdate = Checker.isPostfixUpdate();
  5128. } else if (!AtomicBody->isInstantiationDependent()) {
  5129. ErrorLoc = AtomicBody->getExprLoc();
  5130. ErrorRange = AtomicBody->getSourceRange();
  5131. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  5132. : AtomicBody->getExprLoc();
  5133. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  5134. : AtomicBody->getSourceRange();
  5135. ErrorFound = NotAnAssignmentOp;
  5136. }
  5137. if (ErrorFound != NoError) {
  5138. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  5139. << ErrorRange;
  5140. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  5141. return StmtError();
  5142. } else if (CurContext->isDependentContext()) {
  5143. UE = V = E = X = nullptr;
  5144. }
  5145. } else {
  5146. // If clause is a capture:
  5147. // { v = x; x = expr; }
  5148. // { v = x; x++; }
  5149. // { v = x; x--; }
  5150. // { v = x; ++x; }
  5151. // { v = x; --x; }
  5152. // { v = x; x binop= expr; }
  5153. // { v = x; x = x binop expr; }
  5154. // { v = x; x = expr binop x; }
  5155. // { x++; v = x; }
  5156. // { x--; v = x; }
  5157. // { ++x; v = x; }
  5158. // { --x; v = x; }
  5159. // { x binop= expr; v = x; }
  5160. // { x = x binop expr; v = x; }
  5161. // { x = expr binop x; v = x; }
  5162. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  5163. // Check that this is { expr1; expr2; }
  5164. if (CS->size() == 2) {
  5165. auto *First = CS->body_front();
  5166. auto *Second = CS->body_back();
  5167. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  5168. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  5169. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  5170. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  5171. // Need to find what subexpression is 'v' and what is 'x'.
  5172. OpenMPAtomicUpdateChecker Checker(*this);
  5173. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  5174. BinaryOperator *BinOp = nullptr;
  5175. if (IsUpdateExprFound) {
  5176. BinOp = dyn_cast<BinaryOperator>(First);
  5177. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  5178. }
  5179. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  5180. // { v = x; x++; }
  5181. // { v = x; x--; }
  5182. // { v = x; ++x; }
  5183. // { v = x; --x; }
  5184. // { v = x; x binop= expr; }
  5185. // { v = x; x = x binop expr; }
  5186. // { v = x; x = expr binop x; }
  5187. // Check that the first expression has form v = x.
  5188. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  5189. llvm::FoldingSetNodeID XId, PossibleXId;
  5190. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  5191. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  5192. IsUpdateExprFound = XId == PossibleXId;
  5193. if (IsUpdateExprFound) {
  5194. V = BinOp->getLHS();
  5195. X = Checker.getX();
  5196. E = Checker.getExpr();
  5197. UE = Checker.getUpdateExpr();
  5198. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5199. IsPostfixUpdate = true;
  5200. }
  5201. }
  5202. if (!IsUpdateExprFound) {
  5203. IsUpdateExprFound = !Checker.checkStatement(First);
  5204. BinOp = nullptr;
  5205. if (IsUpdateExprFound) {
  5206. BinOp = dyn_cast<BinaryOperator>(Second);
  5207. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  5208. }
  5209. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  5210. // { x++; v = x; }
  5211. // { x--; v = x; }
  5212. // { ++x; v = x; }
  5213. // { --x; v = x; }
  5214. // { x binop= expr; v = x; }
  5215. // { x = x binop expr; v = x; }
  5216. // { x = expr binop x; v = x; }
  5217. // Check that the second expression has form v = x.
  5218. auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  5219. llvm::FoldingSetNodeID XId, PossibleXId;
  5220. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  5221. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  5222. IsUpdateExprFound = XId == PossibleXId;
  5223. if (IsUpdateExprFound) {
  5224. V = BinOp->getLHS();
  5225. X = Checker.getX();
  5226. E = Checker.getExpr();
  5227. UE = Checker.getUpdateExpr();
  5228. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  5229. IsPostfixUpdate = false;
  5230. }
  5231. }
  5232. }
  5233. if (!IsUpdateExprFound) {
  5234. // { v = x; x = expr; }
  5235. auto *FirstExpr = dyn_cast<Expr>(First);
  5236. auto *SecondExpr = dyn_cast<Expr>(Second);
  5237. if (!FirstExpr || !SecondExpr ||
  5238. !(FirstExpr->isInstantiationDependent() ||
  5239. SecondExpr->isInstantiationDependent())) {
  5240. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  5241. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  5242. ErrorFound = NotAnAssignmentOp;
  5243. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  5244. : First->getLocStart();
  5245. NoteRange = ErrorRange = FirstBinOp
  5246. ? FirstBinOp->getSourceRange()
  5247. : SourceRange(ErrorLoc, ErrorLoc);
  5248. } else {
  5249. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  5250. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  5251. ErrorFound = NotAnAssignmentOp;
  5252. NoteLoc = ErrorLoc = SecondBinOp
  5253. ? SecondBinOp->getOperatorLoc()
  5254. : Second->getLocStart();
  5255. NoteRange = ErrorRange =
  5256. SecondBinOp ? SecondBinOp->getSourceRange()
  5257. : SourceRange(ErrorLoc, ErrorLoc);
  5258. } else {
  5259. auto *PossibleXRHSInFirst =
  5260. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  5261. auto *PossibleXLHSInSecond =
  5262. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  5263. llvm::FoldingSetNodeID X1Id, X2Id;
  5264. PossibleXRHSInFirst->Profile(X1Id, Context,
  5265. /*Canonical=*/true);
  5266. PossibleXLHSInSecond->Profile(X2Id, Context,
  5267. /*Canonical=*/true);
  5268. IsUpdateExprFound = X1Id == X2Id;
  5269. if (IsUpdateExprFound) {
  5270. V = FirstBinOp->getLHS();
  5271. X = SecondBinOp->getLHS();
  5272. E = SecondBinOp->getRHS();
  5273. UE = nullptr;
  5274. IsXLHSInRHSPart = false;
  5275. IsPostfixUpdate = true;
  5276. } else {
  5277. ErrorFound = NotASpecificExpression;
  5278. ErrorLoc = FirstBinOp->getExprLoc();
  5279. ErrorRange = FirstBinOp->getSourceRange();
  5280. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  5281. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  5282. }
  5283. }
  5284. }
  5285. }
  5286. }
  5287. } else {
  5288. NoteLoc = ErrorLoc = Body->getLocStart();
  5289. NoteRange = ErrorRange =
  5290. SourceRange(Body->getLocStart(), Body->getLocStart());
  5291. ErrorFound = NotTwoSubstatements;
  5292. }
  5293. } else {
  5294. NoteLoc = ErrorLoc = Body->getLocStart();
  5295. NoteRange = ErrorRange =
  5296. SourceRange(Body->getLocStart(), Body->getLocStart());
  5297. ErrorFound = NotACompoundStatement;
  5298. }
  5299. if (ErrorFound != NoError) {
  5300. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  5301. << ErrorRange;
  5302. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  5303. return StmtError();
  5304. } else if (CurContext->isDependentContext()) {
  5305. UE = V = E = X = nullptr;
  5306. }
  5307. }
  5308. }
  5309. getCurFunction()->setHasBranchProtectedScope();
  5310. return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  5311. X, V, E, UE, IsXLHSInRHSPart,
  5312. IsPostfixUpdate);
  5313. }
  5314. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  5315. Stmt *AStmt,
  5316. SourceLocation StartLoc,
  5317. SourceLocation EndLoc) {
  5318. if (!AStmt)
  5319. return StmtError();
  5320. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5321. // 1.2.2 OpenMP Language Terminology
  5322. // Structured block - An executable statement with a single entry at the
  5323. // top and a single exit at the bottom.
  5324. // The point of exit cannot be a branch out of the structured block.
  5325. // longjmp() and throw() must not violate the entry/exit criteria.
  5326. CS->getCapturedDecl()->setNothrow();
  5327. // OpenMP [2.16, Nesting of Regions]
  5328. // If specified, a teams construct must be contained within a target
  5329. // construct. That target construct must contain no statements or directives
  5330. // outside of the teams construct.
  5331. if (DSAStack->hasInnerTeamsRegion()) {
  5332. auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true);
  5333. bool OMPTeamsFound = true;
  5334. if (auto *CS = dyn_cast<CompoundStmt>(S)) {
  5335. auto I = CS->body_begin();
  5336. while (I != CS->body_end()) {
  5337. auto OED = dyn_cast<OMPExecutableDirective>(*I);
  5338. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
  5339. OMPTeamsFound = false;
  5340. break;
  5341. }
  5342. ++I;
  5343. }
  5344. assert(I != CS->body_end() && "Not found statement");
  5345. S = *I;
  5346. }
  5347. if (!OMPTeamsFound) {
  5348. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  5349. Diag(DSAStack->getInnerTeamsRegionLoc(),
  5350. diag::note_omp_nested_teams_construct_here);
  5351. Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
  5352. << isa<OMPExecutableDirective>(S);
  5353. return StmtError();
  5354. }
  5355. }
  5356. getCurFunction()->setHasBranchProtectedScope();
  5357. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5358. }
  5359. StmtResult
  5360. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  5361. Stmt *AStmt, SourceLocation StartLoc,
  5362. SourceLocation EndLoc) {
  5363. if (!AStmt)
  5364. return StmtError();
  5365. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5366. // 1.2.2 OpenMP Language Terminology
  5367. // Structured block - An executable statement with a single entry at the
  5368. // top and a single exit at the bottom.
  5369. // The point of exit cannot be a branch out of the structured block.
  5370. // longjmp() and throw() must not violate the entry/exit criteria.
  5371. CS->getCapturedDecl()->setNothrow();
  5372. getCurFunction()->setHasBranchProtectedScope();
  5373. return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5374. AStmt);
  5375. }
  5376. /// \brief Check for existence of a map clause in the list of clauses.
  5377. static bool HasMapClause(ArrayRef<OMPClause *> Clauses) {
  5378. for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
  5379. I != E; ++I) {
  5380. if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) {
  5381. return true;
  5382. }
  5383. }
  5384. return false;
  5385. }
  5386. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  5387. Stmt *AStmt,
  5388. SourceLocation StartLoc,
  5389. SourceLocation EndLoc) {
  5390. if (!AStmt)
  5391. return StmtError();
  5392. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5393. // OpenMP [2.10.1, Restrictions, p. 97]
  5394. // At least one map clause must appear on the directive.
  5395. if (!HasMapClause(Clauses)) {
  5396. Diag(StartLoc, diag::err_omp_no_map_for_directive) <<
  5397. getOpenMPDirectiveName(OMPD_target_data);
  5398. return StmtError();
  5399. }
  5400. getCurFunction()->setHasBranchProtectedScope();
  5401. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5402. AStmt);
  5403. }
  5404. StmtResult
  5405. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  5406. SourceLocation StartLoc,
  5407. SourceLocation EndLoc) {
  5408. // OpenMP [2.10.2, Restrictions, p. 99]
  5409. // At least one map clause must appear on the directive.
  5410. if (!HasMapClause(Clauses)) {
  5411. Diag(StartLoc, diag::err_omp_no_map_for_directive)
  5412. << getOpenMPDirectiveName(OMPD_target_enter_data);
  5413. return StmtError();
  5414. }
  5415. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc,
  5416. Clauses);
  5417. }
  5418. StmtResult
  5419. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  5420. SourceLocation StartLoc,
  5421. SourceLocation EndLoc) {
  5422. // OpenMP [2.10.3, Restrictions, p. 102]
  5423. // At least one map clause must appear on the directive.
  5424. if (!HasMapClause(Clauses)) {
  5425. Diag(StartLoc, diag::err_omp_no_map_for_directive)
  5426. << getOpenMPDirectiveName(OMPD_target_exit_data);
  5427. return StmtError();
  5428. }
  5429. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses);
  5430. }
  5431. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  5432. Stmt *AStmt, SourceLocation StartLoc,
  5433. SourceLocation EndLoc) {
  5434. if (!AStmt)
  5435. return StmtError();
  5436. CapturedStmt *CS = cast<CapturedStmt>(AStmt);
  5437. // 1.2.2 OpenMP Language Terminology
  5438. // Structured block - An executable statement with a single entry at the
  5439. // top and a single exit at the bottom.
  5440. // The point of exit cannot be a branch out of the structured block.
  5441. // longjmp() and throw() must not violate the entry/exit criteria.
  5442. CS->getCapturedDecl()->setNothrow();
  5443. getCurFunction()->setHasBranchProtectedScope();
  5444. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  5445. }
  5446. StmtResult
  5447. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  5448. SourceLocation EndLoc,
  5449. OpenMPDirectiveKind CancelRegion) {
  5450. if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
  5451. CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
  5452. Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  5453. << getOpenMPDirectiveName(CancelRegion);
  5454. return StmtError();
  5455. }
  5456. if (DSAStack->isParentNowaitRegion()) {
  5457. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  5458. return StmtError();
  5459. }
  5460. if (DSAStack->isParentOrderedRegion()) {
  5461. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  5462. return StmtError();
  5463. }
  5464. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  5465. CancelRegion);
  5466. }
  5467. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  5468. SourceLocation StartLoc,
  5469. SourceLocation EndLoc,
  5470. OpenMPDirectiveKind CancelRegion) {
  5471. if (CancelRegion != OMPD_parallel && CancelRegion != OMPD_for &&
  5472. CancelRegion != OMPD_sections && CancelRegion != OMPD_taskgroup) {
  5473. Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  5474. << getOpenMPDirectiveName(CancelRegion);
  5475. return StmtError();
  5476. }
  5477. if (DSAStack->isParentNowaitRegion()) {
  5478. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  5479. return StmtError();
  5480. }
  5481. if (DSAStack->isParentOrderedRegion()) {
  5482. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  5483. return StmtError();
  5484. }
  5485. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  5486. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  5487. CancelRegion);
  5488. }
  5489. static bool checkGrainsizeNumTasksClauses(Sema &S,
  5490. ArrayRef<OMPClause *> Clauses) {
  5491. OMPClause *PrevClause = nullptr;
  5492. bool ErrorFound = false;
  5493. for (auto *C : Clauses) {
  5494. if (C->getClauseKind() == OMPC_grainsize ||
  5495. C->getClauseKind() == OMPC_num_tasks) {
  5496. if (!PrevClause)
  5497. PrevClause = C;
  5498. else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  5499. S.Diag(C->getLocStart(),
  5500. diag::err_omp_grainsize_num_tasks_mutually_exclusive)
  5501. << getOpenMPClauseName(C->getClauseKind())
  5502. << getOpenMPClauseName(PrevClause->getClauseKind());
  5503. S.Diag(PrevClause->getLocStart(),
  5504. diag::note_omp_previous_grainsize_num_tasks)
  5505. << getOpenMPClauseName(PrevClause->getClauseKind());
  5506. ErrorFound = true;
  5507. }
  5508. }
  5509. }
  5510. return ErrorFound;
  5511. }
  5512. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  5513. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5514. SourceLocation EndLoc,
  5515. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5516. if (!AStmt)
  5517. return StmtError();
  5518. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5519. OMPLoopDirective::HelperExprs B;
  5520. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5521. // define the nested loops number.
  5522. unsigned NestedLoopCount =
  5523. CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  5524. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  5525. VarsWithImplicitDSA, B);
  5526. if (NestedLoopCount == 0)
  5527. return StmtError();
  5528. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5529. "omp for loop exprs were not built");
  5530. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  5531. // The grainsize clause and num_tasks clause are mutually exclusive and may
  5532. // not appear on the same taskloop directive.
  5533. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  5534. return StmtError();
  5535. getCurFunction()->setHasBranchProtectedScope();
  5536. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  5537. NestedLoopCount, Clauses, AStmt, B);
  5538. }
  5539. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  5540. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5541. SourceLocation EndLoc,
  5542. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5543. if (!AStmt)
  5544. return StmtError();
  5545. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5546. OMPLoopDirective::HelperExprs B;
  5547. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  5548. // define the nested loops number.
  5549. unsigned NestedLoopCount =
  5550. CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  5551. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  5552. VarsWithImplicitDSA, B);
  5553. if (NestedLoopCount == 0)
  5554. return StmtError();
  5555. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5556. "omp for loop exprs were not built");
  5557. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  5558. // The grainsize clause and num_tasks clause are mutually exclusive and may
  5559. // not appear on the same taskloop directive.
  5560. if (checkGrainsizeNumTasksClauses(*this, Clauses))
  5561. return StmtError();
  5562. getCurFunction()->setHasBranchProtectedScope();
  5563. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  5564. NestedLoopCount, Clauses, AStmt, B);
  5565. }
  5566. StmtResult Sema::ActOnOpenMPDistributeDirective(
  5567. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  5568. SourceLocation EndLoc,
  5569. llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
  5570. if (!AStmt)
  5571. return StmtError();
  5572. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5573. OMPLoopDirective::HelperExprs B;
  5574. // In presence of clause 'collapse' with number of loops, it will
  5575. // define the nested loops number.
  5576. unsigned NestedLoopCount =
  5577. CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  5578. nullptr /*ordered not a clause on distribute*/, AStmt,
  5579. *this, *DSAStack, VarsWithImplicitDSA, B);
  5580. if (NestedLoopCount == 0)
  5581. return StmtError();
  5582. assert((CurContext->isDependentContext() || B.builtAll()) &&
  5583. "omp for loop exprs were not built");
  5584. getCurFunction()->setHasBranchProtectedScope();
  5585. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  5586. NestedLoopCount, Clauses, AStmt, B);
  5587. }
  5588. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  5589. SourceLocation StartLoc,
  5590. SourceLocation LParenLoc,
  5591. SourceLocation EndLoc) {
  5592. OMPClause *Res = nullptr;
  5593. switch (Kind) {
  5594. case OMPC_final:
  5595. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  5596. break;
  5597. case OMPC_num_threads:
  5598. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  5599. break;
  5600. case OMPC_safelen:
  5601. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  5602. break;
  5603. case OMPC_simdlen:
  5604. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  5605. break;
  5606. case OMPC_collapse:
  5607. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  5608. break;
  5609. case OMPC_ordered:
  5610. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  5611. break;
  5612. case OMPC_device:
  5613. Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
  5614. break;
  5615. case OMPC_num_teams:
  5616. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  5617. break;
  5618. case OMPC_thread_limit:
  5619. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  5620. break;
  5621. case OMPC_priority:
  5622. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  5623. break;
  5624. case OMPC_grainsize:
  5625. Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
  5626. break;
  5627. case OMPC_num_tasks:
  5628. Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
  5629. break;
  5630. case OMPC_hint:
  5631. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  5632. break;
  5633. case OMPC_if:
  5634. case OMPC_default:
  5635. case OMPC_proc_bind:
  5636. case OMPC_schedule:
  5637. case OMPC_private:
  5638. case OMPC_firstprivate:
  5639. case OMPC_lastprivate:
  5640. case OMPC_shared:
  5641. case OMPC_reduction:
  5642. case OMPC_linear:
  5643. case OMPC_aligned:
  5644. case OMPC_copyin:
  5645. case OMPC_copyprivate:
  5646. case OMPC_nowait:
  5647. case OMPC_untied:
  5648. case OMPC_mergeable:
  5649. case OMPC_threadprivate:
  5650. case OMPC_flush:
  5651. case OMPC_read:
  5652. case OMPC_write:
  5653. case OMPC_update:
  5654. case OMPC_capture:
  5655. case OMPC_seq_cst:
  5656. case OMPC_depend:
  5657. case OMPC_threads:
  5658. case OMPC_simd:
  5659. case OMPC_map:
  5660. case OMPC_nogroup:
  5661. case OMPC_dist_schedule:
  5662. case OMPC_defaultmap:
  5663. case OMPC_unknown:
  5664. llvm_unreachable("Clause is not allowed.");
  5665. }
  5666. return Res;
  5667. }
  5668. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  5669. Expr *Condition, SourceLocation StartLoc,
  5670. SourceLocation LParenLoc,
  5671. SourceLocation NameModifierLoc,
  5672. SourceLocation ColonLoc,
  5673. SourceLocation EndLoc) {
  5674. Expr *ValExpr = Condition;
  5675. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  5676. !Condition->isInstantiationDependent() &&
  5677. !Condition->containsUnexpandedParameterPack()) {
  5678. ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
  5679. Condition->getExprLoc(), Condition);
  5680. if (Val.isInvalid())
  5681. return nullptr;
  5682. ValExpr = Val.get();
  5683. }
  5684. return new (Context) OMPIfClause(NameModifier, ValExpr, StartLoc, LParenLoc,
  5685. NameModifierLoc, ColonLoc, EndLoc);
  5686. }
  5687. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  5688. SourceLocation StartLoc,
  5689. SourceLocation LParenLoc,
  5690. SourceLocation EndLoc) {
  5691. Expr *ValExpr = Condition;
  5692. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  5693. !Condition->isInstantiationDependent() &&
  5694. !Condition->containsUnexpandedParameterPack()) {
  5695. ExprResult Val = ActOnBooleanCondition(DSAStack->getCurScope(),
  5696. Condition->getExprLoc(), Condition);
  5697. if (Val.isInvalid())
  5698. return nullptr;
  5699. ValExpr = Val.get();
  5700. }
  5701. return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  5702. }
  5703. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  5704. Expr *Op) {
  5705. if (!Op)
  5706. return ExprError();
  5707. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  5708. public:
  5709. IntConvertDiagnoser()
  5710. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  5711. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  5712. QualType T) override {
  5713. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  5714. }
  5715. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  5716. QualType T) override {
  5717. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  5718. }
  5719. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  5720. QualType T,
  5721. QualType ConvTy) override {
  5722. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  5723. }
  5724. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  5725. QualType ConvTy) override {
  5726. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  5727. << ConvTy->isEnumeralType() << ConvTy;
  5728. }
  5729. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  5730. QualType T) override {
  5731. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  5732. }
  5733. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  5734. QualType ConvTy) override {
  5735. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  5736. << ConvTy->isEnumeralType() << ConvTy;
  5737. }
  5738. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  5739. QualType) override {
  5740. llvm_unreachable("conversion functions are permitted");
  5741. }
  5742. } ConvertDiagnoser;
  5743. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  5744. }
  5745. static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
  5746. OpenMPClauseKind CKind,
  5747. bool StrictlyPositive) {
  5748. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  5749. !ValExpr->isInstantiationDependent()) {
  5750. SourceLocation Loc = ValExpr->getExprLoc();
  5751. ExprResult Value =
  5752. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  5753. if (Value.isInvalid())
  5754. return false;
  5755. ValExpr = Value.get();
  5756. // The expression must evaluate to a non-negative integer value.
  5757. llvm::APSInt Result;
  5758. if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
  5759. Result.isSigned() &&
  5760. !((!StrictlyPositive && Result.isNonNegative()) ||
  5761. (StrictlyPositive && Result.isStrictlyPositive()))) {
  5762. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  5763. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  5764. << ValExpr->getSourceRange();
  5765. return false;
  5766. }
  5767. }
  5768. return true;
  5769. }
  5770. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  5771. SourceLocation StartLoc,
  5772. SourceLocation LParenLoc,
  5773. SourceLocation EndLoc) {
  5774. Expr *ValExpr = NumThreads;
  5775. // OpenMP [2.5, Restrictions]
  5776. // The num_threads expression must evaluate to a positive integer value.
  5777. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  5778. /*StrictlyPositive=*/true))
  5779. return nullptr;
  5780. return new (Context)
  5781. OMPNumThreadsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  5782. }
  5783. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  5784. OpenMPClauseKind CKind,
  5785. bool StrictlyPositive) {
  5786. if (!E)
  5787. return ExprError();
  5788. if (E->isValueDependent() || E->isTypeDependent() ||
  5789. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  5790. return E;
  5791. llvm::APSInt Result;
  5792. ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
  5793. if (ICE.isInvalid())
  5794. return ExprError();
  5795. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  5796. (!StrictlyPositive && !Result.isNonNegative())) {
  5797. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  5798. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  5799. << E->getSourceRange();
  5800. return ExprError();
  5801. }
  5802. if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
  5803. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  5804. << E->getSourceRange();
  5805. return ExprError();
  5806. }
  5807. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  5808. DSAStack->setAssociatedLoops(Result.getExtValue());
  5809. else if (CKind == OMPC_ordered)
  5810. DSAStack->setAssociatedLoops(Result.getExtValue());
  5811. return ICE;
  5812. }
  5813. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  5814. SourceLocation LParenLoc,
  5815. SourceLocation EndLoc) {
  5816. // OpenMP [2.8.1, simd construct, Description]
  5817. // The parameter of the safelen clause must be a constant
  5818. // positive integer expression.
  5819. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  5820. if (Safelen.isInvalid())
  5821. return nullptr;
  5822. return new (Context)
  5823. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  5824. }
  5825. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  5826. SourceLocation LParenLoc,
  5827. SourceLocation EndLoc) {
  5828. // OpenMP [2.8.1, simd construct, Description]
  5829. // The parameter of the simdlen clause must be a constant
  5830. // positive integer expression.
  5831. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  5832. if (Simdlen.isInvalid())
  5833. return nullptr;
  5834. return new (Context)
  5835. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  5836. }
  5837. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  5838. SourceLocation StartLoc,
  5839. SourceLocation LParenLoc,
  5840. SourceLocation EndLoc) {
  5841. // OpenMP [2.7.1, loop construct, Description]
  5842. // OpenMP [2.8.1, simd construct, Description]
  5843. // OpenMP [2.9.6, distribute construct, Description]
  5844. // The parameter of the collapse clause must be a constant
  5845. // positive integer expression.
  5846. ExprResult NumForLoopsResult =
  5847. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  5848. if (NumForLoopsResult.isInvalid())
  5849. return nullptr;
  5850. return new (Context)
  5851. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  5852. }
  5853. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  5854. SourceLocation EndLoc,
  5855. SourceLocation LParenLoc,
  5856. Expr *NumForLoops) {
  5857. // OpenMP [2.7.1, loop construct, Description]
  5858. // OpenMP [2.8.1, simd construct, Description]
  5859. // OpenMP [2.9.6, distribute construct, Description]
  5860. // The parameter of the ordered clause must be a constant
  5861. // positive integer expression if any.
  5862. if (NumForLoops && LParenLoc.isValid()) {
  5863. ExprResult NumForLoopsResult =
  5864. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  5865. if (NumForLoopsResult.isInvalid())
  5866. return nullptr;
  5867. NumForLoops = NumForLoopsResult.get();
  5868. } else
  5869. NumForLoops = nullptr;
  5870. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
  5871. return new (Context)
  5872. OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
  5873. }
  5874. OMPClause *Sema::ActOnOpenMPSimpleClause(
  5875. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  5876. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  5877. OMPClause *Res = nullptr;
  5878. switch (Kind) {
  5879. case OMPC_default:
  5880. Res =
  5881. ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
  5882. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  5883. break;
  5884. case OMPC_proc_bind:
  5885. Res = ActOnOpenMPProcBindClause(
  5886. static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
  5887. LParenLoc, EndLoc);
  5888. break;
  5889. case OMPC_if:
  5890. case OMPC_final:
  5891. case OMPC_num_threads:
  5892. case OMPC_safelen:
  5893. case OMPC_simdlen:
  5894. case OMPC_collapse:
  5895. case OMPC_schedule:
  5896. case OMPC_private:
  5897. case OMPC_firstprivate:
  5898. case OMPC_lastprivate:
  5899. case OMPC_shared:
  5900. case OMPC_reduction:
  5901. case OMPC_linear:
  5902. case OMPC_aligned:
  5903. case OMPC_copyin:
  5904. case OMPC_copyprivate:
  5905. case OMPC_ordered:
  5906. case OMPC_nowait:
  5907. case OMPC_untied:
  5908. case OMPC_mergeable:
  5909. case OMPC_threadprivate:
  5910. case OMPC_flush:
  5911. case OMPC_read:
  5912. case OMPC_write:
  5913. case OMPC_update:
  5914. case OMPC_capture:
  5915. case OMPC_seq_cst:
  5916. case OMPC_depend:
  5917. case OMPC_device:
  5918. case OMPC_threads:
  5919. case OMPC_simd:
  5920. case OMPC_map:
  5921. case OMPC_num_teams:
  5922. case OMPC_thread_limit:
  5923. case OMPC_priority:
  5924. case OMPC_grainsize:
  5925. case OMPC_nogroup:
  5926. case OMPC_num_tasks:
  5927. case OMPC_hint:
  5928. case OMPC_dist_schedule:
  5929. case OMPC_defaultmap:
  5930. case OMPC_unknown:
  5931. llvm_unreachable("Clause is not allowed.");
  5932. }
  5933. return Res;
  5934. }
  5935. static std::string
  5936. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  5937. ArrayRef<unsigned> Exclude = llvm::None) {
  5938. std::string Values;
  5939. unsigned Bound = Last >= 2 ? Last - 2 : 0;
  5940. unsigned Skipped = Exclude.size();
  5941. auto S = Exclude.begin(), E = Exclude.end();
  5942. for (unsigned i = First; i < Last; ++i) {
  5943. if (std::find(S, E, i) != E) {
  5944. --Skipped;
  5945. continue;
  5946. }
  5947. Values += "'";
  5948. Values += getOpenMPSimpleClauseTypeName(K, i);
  5949. Values += "'";
  5950. if (i == Bound - Skipped)
  5951. Values += " or ";
  5952. else if (i != Bound + 1 - Skipped)
  5953. Values += ", ";
  5954. }
  5955. return Values;
  5956. }
  5957. OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
  5958. SourceLocation KindKwLoc,
  5959. SourceLocation StartLoc,
  5960. SourceLocation LParenLoc,
  5961. SourceLocation EndLoc) {
  5962. if (Kind == OMPC_DEFAULT_unknown) {
  5963. static_assert(OMPC_DEFAULT_unknown > 0,
  5964. "OMPC_DEFAULT_unknown not greater than 0");
  5965. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  5966. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  5967. /*Last=*/OMPC_DEFAULT_unknown)
  5968. << getOpenMPClauseName(OMPC_default);
  5969. return nullptr;
  5970. }
  5971. switch (Kind) {
  5972. case OMPC_DEFAULT_none:
  5973. DSAStack->setDefaultDSANone(KindKwLoc);
  5974. break;
  5975. case OMPC_DEFAULT_shared:
  5976. DSAStack->setDefaultDSAShared(KindKwLoc);
  5977. break;
  5978. case OMPC_DEFAULT_unknown:
  5979. llvm_unreachable("Clause kind is not allowed.");
  5980. break;
  5981. }
  5982. return new (Context)
  5983. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  5984. }
  5985. OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
  5986. SourceLocation KindKwLoc,
  5987. SourceLocation StartLoc,
  5988. SourceLocation LParenLoc,
  5989. SourceLocation EndLoc) {
  5990. if (Kind == OMPC_PROC_BIND_unknown) {
  5991. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  5992. << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
  5993. /*Last=*/OMPC_PROC_BIND_unknown)
  5994. << getOpenMPClauseName(OMPC_proc_bind);
  5995. return nullptr;
  5996. }
  5997. return new (Context)
  5998. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  5999. }
  6000. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  6001. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  6002. SourceLocation StartLoc, SourceLocation LParenLoc,
  6003. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  6004. SourceLocation EndLoc) {
  6005. OMPClause *Res = nullptr;
  6006. switch (Kind) {
  6007. case OMPC_schedule:
  6008. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  6009. assert(Argument.size() == NumberOfElements &&
  6010. ArgumentLoc.size() == NumberOfElements);
  6011. Res = ActOnOpenMPScheduleClause(
  6012. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  6013. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  6014. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  6015. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  6016. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  6017. break;
  6018. case OMPC_if:
  6019. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  6020. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  6021. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  6022. DelimLoc, EndLoc);
  6023. break;
  6024. case OMPC_dist_schedule:
  6025. Res = ActOnOpenMPDistScheduleClause(
  6026. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  6027. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  6028. break;
  6029. case OMPC_defaultmap:
  6030. enum { Modifier, DefaultmapKind };
  6031. Res = ActOnOpenMPDefaultmapClause(
  6032. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  6033. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  6034. StartLoc, LParenLoc, ArgumentLoc[Modifier],
  6035. ArgumentLoc[DefaultmapKind], EndLoc);
  6036. break;
  6037. case OMPC_final:
  6038. case OMPC_num_threads:
  6039. case OMPC_safelen:
  6040. case OMPC_simdlen:
  6041. case OMPC_collapse:
  6042. case OMPC_default:
  6043. case OMPC_proc_bind:
  6044. case OMPC_private:
  6045. case OMPC_firstprivate:
  6046. case OMPC_lastprivate:
  6047. case OMPC_shared:
  6048. case OMPC_reduction:
  6049. case OMPC_linear:
  6050. case OMPC_aligned:
  6051. case OMPC_copyin:
  6052. case OMPC_copyprivate:
  6053. case OMPC_ordered:
  6054. case OMPC_nowait:
  6055. case OMPC_untied:
  6056. case OMPC_mergeable:
  6057. case OMPC_threadprivate:
  6058. case OMPC_flush:
  6059. case OMPC_read:
  6060. case OMPC_write:
  6061. case OMPC_update:
  6062. case OMPC_capture:
  6063. case OMPC_seq_cst:
  6064. case OMPC_depend:
  6065. case OMPC_device:
  6066. case OMPC_threads:
  6067. case OMPC_simd:
  6068. case OMPC_map:
  6069. case OMPC_num_teams:
  6070. case OMPC_thread_limit:
  6071. case OMPC_priority:
  6072. case OMPC_grainsize:
  6073. case OMPC_nogroup:
  6074. case OMPC_num_tasks:
  6075. case OMPC_hint:
  6076. case OMPC_unknown:
  6077. llvm_unreachable("Clause is not allowed.");
  6078. }
  6079. return Res;
  6080. }
  6081. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  6082. OpenMPScheduleClauseModifier M2,
  6083. SourceLocation M1Loc, SourceLocation M2Loc) {
  6084. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  6085. SmallVector<unsigned, 2> Excluded;
  6086. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  6087. Excluded.push_back(M2);
  6088. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  6089. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  6090. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  6091. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  6092. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  6093. << getListOfPossibleValues(OMPC_schedule,
  6094. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  6095. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  6096. Excluded)
  6097. << getOpenMPClauseName(OMPC_schedule);
  6098. return true;
  6099. }
  6100. return false;
  6101. }
  6102. OMPClause *Sema::ActOnOpenMPScheduleClause(
  6103. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  6104. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  6105. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  6106. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  6107. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  6108. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  6109. return nullptr;
  6110. // OpenMP, 2.7.1, Loop Construct, Restrictions
  6111. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  6112. // but not both.
  6113. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  6114. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  6115. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  6116. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  6117. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  6118. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  6119. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  6120. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  6121. return nullptr;
  6122. }
  6123. if (Kind == OMPC_SCHEDULE_unknown) {
  6124. std::string Values;
  6125. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  6126. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  6127. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  6128. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  6129. Exclude);
  6130. } else {
  6131. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  6132. /*Last=*/OMPC_SCHEDULE_unknown);
  6133. }
  6134. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  6135. << Values << getOpenMPClauseName(OMPC_schedule);
  6136. return nullptr;
  6137. }
  6138. // OpenMP, 2.7.1, Loop Construct, Restrictions
  6139. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  6140. // schedule(guided).
  6141. if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  6142. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  6143. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  6144. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  6145. diag::err_omp_schedule_nonmonotonic_static);
  6146. return nullptr;
  6147. }
  6148. Expr *ValExpr = ChunkSize;
  6149. Expr *HelperValExpr = nullptr;
  6150. if (ChunkSize) {
  6151. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  6152. !ChunkSize->isInstantiationDependent() &&
  6153. !ChunkSize->containsUnexpandedParameterPack()) {
  6154. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  6155. ExprResult Val =
  6156. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  6157. if (Val.isInvalid())
  6158. return nullptr;
  6159. ValExpr = Val.get();
  6160. // OpenMP [2.7.1, Restrictions]
  6161. // chunk_size must be a loop invariant integer expression with a positive
  6162. // value.
  6163. llvm::APSInt Result;
  6164. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  6165. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  6166. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  6167. << "schedule" << 1 << ChunkSize->getSourceRange();
  6168. return nullptr;
  6169. }
  6170. } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
  6171. auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
  6172. ChunkSize->getType(), ".chunk.");
  6173. auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
  6174. ChunkSize->getExprLoc(),
  6175. /*RefersToCapture=*/true);
  6176. HelperValExpr = ImpVarRef;
  6177. }
  6178. }
  6179. }
  6180. return new (Context)
  6181. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  6182. ValExpr, HelperValExpr, M1, M1Loc, M2, M2Loc);
  6183. }
  6184. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  6185. SourceLocation StartLoc,
  6186. SourceLocation EndLoc) {
  6187. OMPClause *Res = nullptr;
  6188. switch (Kind) {
  6189. case OMPC_ordered:
  6190. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  6191. break;
  6192. case OMPC_nowait:
  6193. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  6194. break;
  6195. case OMPC_untied:
  6196. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  6197. break;
  6198. case OMPC_mergeable:
  6199. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  6200. break;
  6201. case OMPC_read:
  6202. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  6203. break;
  6204. case OMPC_write:
  6205. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  6206. break;
  6207. case OMPC_update:
  6208. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  6209. break;
  6210. case OMPC_capture:
  6211. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  6212. break;
  6213. case OMPC_seq_cst:
  6214. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  6215. break;
  6216. case OMPC_threads:
  6217. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  6218. break;
  6219. case OMPC_simd:
  6220. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  6221. break;
  6222. case OMPC_nogroup:
  6223. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  6224. break;
  6225. case OMPC_if:
  6226. case OMPC_final:
  6227. case OMPC_num_threads:
  6228. case OMPC_safelen:
  6229. case OMPC_simdlen:
  6230. case OMPC_collapse:
  6231. case OMPC_schedule:
  6232. case OMPC_private:
  6233. case OMPC_firstprivate:
  6234. case OMPC_lastprivate:
  6235. case OMPC_shared:
  6236. case OMPC_reduction:
  6237. case OMPC_linear:
  6238. case OMPC_aligned:
  6239. case OMPC_copyin:
  6240. case OMPC_copyprivate:
  6241. case OMPC_default:
  6242. case OMPC_proc_bind:
  6243. case OMPC_threadprivate:
  6244. case OMPC_flush:
  6245. case OMPC_depend:
  6246. case OMPC_device:
  6247. case OMPC_map:
  6248. case OMPC_num_teams:
  6249. case OMPC_thread_limit:
  6250. case OMPC_priority:
  6251. case OMPC_grainsize:
  6252. case OMPC_num_tasks:
  6253. case OMPC_hint:
  6254. case OMPC_dist_schedule:
  6255. case OMPC_defaultmap:
  6256. case OMPC_unknown:
  6257. llvm_unreachable("Clause is not allowed.");
  6258. }
  6259. return Res;
  6260. }
  6261. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  6262. SourceLocation EndLoc) {
  6263. DSAStack->setNowaitRegion();
  6264. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  6265. }
  6266. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  6267. SourceLocation EndLoc) {
  6268. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  6269. }
  6270. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  6271. SourceLocation EndLoc) {
  6272. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  6273. }
  6274. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  6275. SourceLocation EndLoc) {
  6276. return new (Context) OMPReadClause(StartLoc, EndLoc);
  6277. }
  6278. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  6279. SourceLocation EndLoc) {
  6280. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  6281. }
  6282. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  6283. SourceLocation EndLoc) {
  6284. return new (Context) OMPUpdateClause(StartLoc, EndLoc);
  6285. }
  6286. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  6287. SourceLocation EndLoc) {
  6288. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  6289. }
  6290. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  6291. SourceLocation EndLoc) {
  6292. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  6293. }
  6294. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  6295. SourceLocation EndLoc) {
  6296. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  6297. }
  6298. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  6299. SourceLocation EndLoc) {
  6300. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  6301. }
  6302. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  6303. SourceLocation EndLoc) {
  6304. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  6305. }
  6306. OMPClause *Sema::ActOnOpenMPVarListClause(
  6307. OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
  6308. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  6309. SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
  6310. const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
  6311. OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
  6312. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  6313. SourceLocation DepLinMapLoc) {
  6314. OMPClause *Res = nullptr;
  6315. switch (Kind) {
  6316. case OMPC_private:
  6317. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  6318. break;
  6319. case OMPC_firstprivate:
  6320. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  6321. break;
  6322. case OMPC_lastprivate:
  6323. Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  6324. break;
  6325. case OMPC_shared:
  6326. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  6327. break;
  6328. case OMPC_reduction:
  6329. Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
  6330. EndLoc, ReductionIdScopeSpec, ReductionId);
  6331. break;
  6332. case OMPC_linear:
  6333. Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
  6334. LinKind, DepLinMapLoc, ColonLoc, EndLoc);
  6335. break;
  6336. case OMPC_aligned:
  6337. Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
  6338. ColonLoc, EndLoc);
  6339. break;
  6340. case OMPC_copyin:
  6341. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  6342. break;
  6343. case OMPC_copyprivate:
  6344. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  6345. break;
  6346. case OMPC_flush:
  6347. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  6348. break;
  6349. case OMPC_depend:
  6350. Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
  6351. StartLoc, LParenLoc, EndLoc);
  6352. break;
  6353. case OMPC_map:
  6354. Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
  6355. DepLinMapLoc, ColonLoc, VarList, StartLoc,
  6356. LParenLoc, EndLoc);
  6357. break;
  6358. case OMPC_if:
  6359. case OMPC_final:
  6360. case OMPC_num_threads:
  6361. case OMPC_safelen:
  6362. case OMPC_simdlen:
  6363. case OMPC_collapse:
  6364. case OMPC_default:
  6365. case OMPC_proc_bind:
  6366. case OMPC_schedule:
  6367. case OMPC_ordered:
  6368. case OMPC_nowait:
  6369. case OMPC_untied:
  6370. case OMPC_mergeable:
  6371. case OMPC_threadprivate:
  6372. case OMPC_read:
  6373. case OMPC_write:
  6374. case OMPC_update:
  6375. case OMPC_capture:
  6376. case OMPC_seq_cst:
  6377. case OMPC_device:
  6378. case OMPC_threads:
  6379. case OMPC_simd:
  6380. case OMPC_num_teams:
  6381. case OMPC_thread_limit:
  6382. case OMPC_priority:
  6383. case OMPC_grainsize:
  6384. case OMPC_nogroup:
  6385. case OMPC_num_tasks:
  6386. case OMPC_hint:
  6387. case OMPC_dist_schedule:
  6388. case OMPC_defaultmap:
  6389. case OMPC_unknown:
  6390. llvm_unreachable("Clause is not allowed.");
  6391. }
  6392. return Res;
  6393. }
  6394. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  6395. SourceLocation StartLoc,
  6396. SourceLocation LParenLoc,
  6397. SourceLocation EndLoc) {
  6398. SmallVector<Expr *, 8> Vars;
  6399. SmallVector<Expr *, 8> PrivateCopies;
  6400. for (auto &RefExpr : VarList) {
  6401. assert(RefExpr && "NULL expr in OpenMP private clause.");
  6402. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  6403. RefExpr->containsUnexpandedParameterPack()) {
  6404. // It will be analyzed later.
  6405. Vars.push_back(RefExpr);
  6406. PrivateCopies.push_back(nullptr);
  6407. continue;
  6408. }
  6409. SourceLocation ELoc = RefExpr->getExprLoc();
  6410. // OpenMP [3.1, C/C++]
  6411. // A list item is a variable name.
  6412. // OpenMP [2.9.3.3, Restrictions, p.1]
  6413. // A variable that is part of another variable (as an array or
  6414. // structure element) cannot appear in a private clause.
  6415. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr->IgnoreParens());
  6416. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr->IgnoreParens());
  6417. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  6418. (getCurrentThisType().isNull() || !ME ||
  6419. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  6420. !isa<FieldDecl>(ME->getMemberDecl()))) {
  6421. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  6422. << (getCurrentThisType().isNull() ? 0 : 1)
  6423. << RefExpr->getSourceRange();
  6424. continue;
  6425. }
  6426. ValueDecl *D = DE ? DE->getDecl() : ME->getMemberDecl();
  6427. QualType Type = D->getType();
  6428. auto *VD = dyn_cast<VarDecl>(D);
  6429. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  6430. // A variable that appears in a private clause must not have an incomplete
  6431. // type or a reference type.
  6432. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  6433. continue;
  6434. Type = Type.getNonReferenceType();
  6435. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  6436. // in a Construct]
  6437. // Variables with the predetermined data-sharing attributes may not be
  6438. // listed in data-sharing attributes clauses, except for the cases
  6439. // listed below. For these exceptions only, listing a predetermined
  6440. // variable in a data-sharing attribute clause is allowed and overrides
  6441. // the variable's predetermined data-sharing attributes.
  6442. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
  6443. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  6444. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  6445. << getOpenMPClauseName(OMPC_private);
  6446. ReportOriginalDSA(*this, DSAStack, D, DVar);
  6447. continue;
  6448. }
  6449. // Variably modified types are not supported for tasks.
  6450. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  6451. DSAStack->getCurrentDirective() == OMPD_task) {
  6452. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  6453. << getOpenMPClauseName(OMPC_private) << Type
  6454. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  6455. bool IsDecl =
  6456. !VD ||
  6457. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6458. Diag(D->getLocation(),
  6459. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6460. << D;
  6461. continue;
  6462. }
  6463. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  6464. // A variable of class type (or array thereof) that appears in a private
  6465. // clause requires an accessible, unambiguous default constructor for the
  6466. // class type.
  6467. // Generate helper private variable and initialize it with the default
  6468. // value. The address of the original variable is replaced by the address of
  6469. // the new private variable in CodeGen. This new variable is not added to
  6470. // IdResolver, so the code in the OpenMP region uses original variable for
  6471. // proper diagnostics.
  6472. Type = Type.getUnqualifiedType();
  6473. auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
  6474. D->hasAttrs() ? &D->getAttrs() : nullptr);
  6475. ActOnUninitializedDecl(VDPrivate, /*TypeMayContainAuto=*/false);
  6476. if (VDPrivate->isInvalidDecl())
  6477. continue;
  6478. auto VDPrivateRefExpr = buildDeclRefExpr(
  6479. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  6480. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private);
  6481. Vars.push_back(RefExpr->IgnoreParens());
  6482. PrivateCopies.push_back(VDPrivateRefExpr);
  6483. }
  6484. if (Vars.empty())
  6485. return nullptr;
  6486. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  6487. PrivateCopies);
  6488. }
  6489. namespace {
  6490. class DiagsUninitializedSeveretyRAII {
  6491. private:
  6492. DiagnosticsEngine &Diags;
  6493. SourceLocation SavedLoc;
  6494. bool IsIgnored;
  6495. public:
  6496. DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
  6497. bool IsIgnored)
  6498. : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
  6499. if (!IsIgnored) {
  6500. Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
  6501. /*Map*/ diag::Severity::Ignored, Loc);
  6502. }
  6503. }
  6504. ~DiagsUninitializedSeveretyRAII() {
  6505. if (!IsIgnored)
  6506. Diags.popMappings(SavedLoc);
  6507. }
  6508. };
  6509. }
  6510. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  6511. SourceLocation StartLoc,
  6512. SourceLocation LParenLoc,
  6513. SourceLocation EndLoc) {
  6514. SmallVector<Expr *, 8> Vars;
  6515. SmallVector<Expr *, 8> PrivateCopies;
  6516. SmallVector<Expr *, 8> Inits;
  6517. bool IsImplicitClause =
  6518. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  6519. auto ImplicitClauseLoc = DSAStack->getConstructLoc();
  6520. for (auto &RefExpr : VarList) {
  6521. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  6522. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  6523. // It will be analyzed later.
  6524. Vars.push_back(RefExpr);
  6525. PrivateCopies.push_back(nullptr);
  6526. Inits.push_back(nullptr);
  6527. continue;
  6528. }
  6529. SourceLocation ELoc =
  6530. IsImplicitClause ? ImplicitClauseLoc : RefExpr->getExprLoc();
  6531. // OpenMP [2.1, C/C++]
  6532. // A list item is a variable name.
  6533. // OpenMP [2.9.3.3, Restrictions, p.1]
  6534. // A variable that is part of another variable (as an array or
  6535. // structure element) cannot appear in a private clause.
  6536. DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  6537. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  6538. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  6539. << 0 << RefExpr->getSourceRange();
  6540. continue;
  6541. }
  6542. Decl *D = DE->getDecl();
  6543. VarDecl *VD = cast<VarDecl>(D);
  6544. QualType Type = VD->getType();
  6545. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  6546. // It will be analyzed later.
  6547. Vars.push_back(DE);
  6548. PrivateCopies.push_back(nullptr);
  6549. Inits.push_back(nullptr);
  6550. continue;
  6551. }
  6552. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  6553. // A variable that appears in a private clause must not have an incomplete
  6554. // type or a reference type.
  6555. if (RequireCompleteType(ELoc, Type,
  6556. diag::err_omp_firstprivate_incomplete_type)) {
  6557. continue;
  6558. }
  6559. Type = Type.getNonReferenceType();
  6560. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  6561. // A variable of class type (or array thereof) that appears in a private
  6562. // clause requires an accessible, unambiguous copy constructor for the
  6563. // class type.
  6564. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  6565. // If an implicit firstprivate variable found it was checked already.
  6566. if (!IsImplicitClause) {
  6567. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  6568. bool IsConstant = ElemType.isConstant(Context);
  6569. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  6570. // A list item that specifies a given variable may not appear in more
  6571. // than one clause on the same directive, except that a variable may be
  6572. // specified in both firstprivate and lastprivate clauses.
  6573. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  6574. DVar.CKind != OMPC_lastprivate && DVar.RefExpr) {
  6575. Diag(ELoc, diag::err_omp_wrong_dsa)
  6576. << getOpenMPClauseName(DVar.CKind)
  6577. << getOpenMPClauseName(OMPC_firstprivate);
  6578. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6579. continue;
  6580. }
  6581. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  6582. // in a Construct]
  6583. // Variables with the predetermined data-sharing attributes may not be
  6584. // listed in data-sharing attributes clauses, except for the cases
  6585. // listed below. For these exceptions only, listing a predetermined
  6586. // variable in a data-sharing attribute clause is allowed and overrides
  6587. // the variable's predetermined data-sharing attributes.
  6588. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  6589. // in a Construct, C/C++, p.2]
  6590. // Variables with const-qualified type having no mutable member may be
  6591. // listed in a firstprivate clause, even if they are static data members.
  6592. if (!(IsConstant || VD->isStaticDataMember()) && !DVar.RefExpr &&
  6593. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  6594. Diag(ELoc, diag::err_omp_wrong_dsa)
  6595. << getOpenMPClauseName(DVar.CKind)
  6596. << getOpenMPClauseName(OMPC_firstprivate);
  6597. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6598. continue;
  6599. }
  6600. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  6601. // OpenMP [2.9.3.4, Restrictions, p.2]
  6602. // A list item that is private within a parallel region must not appear
  6603. // in a firstprivate clause on a worksharing construct if any of the
  6604. // worksharing regions arising from the worksharing construct ever bind
  6605. // to any of the parallel regions arising from the parallel construct.
  6606. if (isOpenMPWorksharingDirective(CurrDir) &&
  6607. !isOpenMPParallelDirective(CurrDir)) {
  6608. DVar = DSAStack->getImplicitDSA(VD, true);
  6609. if (DVar.CKind != OMPC_shared &&
  6610. (isOpenMPParallelDirective(DVar.DKind) ||
  6611. DVar.DKind == OMPD_unknown)) {
  6612. Diag(ELoc, diag::err_omp_required_access)
  6613. << getOpenMPClauseName(OMPC_firstprivate)
  6614. << getOpenMPClauseName(OMPC_shared);
  6615. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6616. continue;
  6617. }
  6618. }
  6619. // OpenMP [2.9.3.4, Restrictions, p.3]
  6620. // A list item that appears in a reduction clause of a parallel construct
  6621. // must not appear in a firstprivate clause on a worksharing or task
  6622. // construct if any of the worksharing or task regions arising from the
  6623. // worksharing or task construct ever bind to any of the parallel regions
  6624. // arising from the parallel construct.
  6625. // OpenMP [2.9.3.4, Restrictions, p.4]
  6626. // A list item that appears in a reduction clause in worksharing
  6627. // construct must not appear in a firstprivate clause in a task construct
  6628. // encountered during execution of any of the worksharing regions arising
  6629. // from the worksharing construct.
  6630. if (CurrDir == OMPD_task) {
  6631. DVar =
  6632. DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
  6633. [](OpenMPDirectiveKind K) -> bool {
  6634. return isOpenMPParallelDirective(K) ||
  6635. isOpenMPWorksharingDirective(K);
  6636. },
  6637. false);
  6638. if (DVar.CKind == OMPC_reduction &&
  6639. (isOpenMPParallelDirective(DVar.DKind) ||
  6640. isOpenMPWorksharingDirective(DVar.DKind))) {
  6641. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  6642. << getOpenMPDirectiveName(DVar.DKind);
  6643. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6644. continue;
  6645. }
  6646. }
  6647. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  6648. // A list item that is private within a teams region must not appear in a
  6649. // firstprivate clause on a distribute construct if any of the distribute
  6650. // regions arising from the distribute construct ever bind to any of the
  6651. // teams regions arising from the teams construct.
  6652. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  6653. // A list item that appears in a reduction clause of a teams construct
  6654. // must not appear in a firstprivate clause on a distribute construct if
  6655. // any of the distribute regions arising from the distribute construct
  6656. // ever bind to any of the teams regions arising from the teams construct.
  6657. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  6658. // A list item may appear in a firstprivate or lastprivate clause but not
  6659. // both.
  6660. if (CurrDir == OMPD_distribute) {
  6661. DVar = DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_private),
  6662. [](OpenMPDirectiveKind K) -> bool {
  6663. return isOpenMPTeamsDirective(K);
  6664. },
  6665. false);
  6666. if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) {
  6667. Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams);
  6668. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6669. continue;
  6670. }
  6671. DVar = DSAStack->hasInnermostDSA(VD, MatchesAnyClause(OMPC_reduction),
  6672. [](OpenMPDirectiveKind K) -> bool {
  6673. return isOpenMPTeamsDirective(K);
  6674. },
  6675. false);
  6676. if (DVar.CKind == OMPC_reduction &&
  6677. isOpenMPTeamsDirective(DVar.DKind)) {
  6678. Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction);
  6679. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6680. continue;
  6681. }
  6682. DVar = DSAStack->getTopDSA(VD, false);
  6683. if (DVar.CKind == OMPC_lastprivate) {
  6684. Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
  6685. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6686. continue;
  6687. }
  6688. }
  6689. }
  6690. // Variably modified types are not supported for tasks.
  6691. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  6692. DSAStack->getCurrentDirective() == OMPD_task) {
  6693. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  6694. << getOpenMPClauseName(OMPC_firstprivate) << Type
  6695. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  6696. bool IsDecl =
  6697. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  6698. Diag(VD->getLocation(),
  6699. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  6700. << VD;
  6701. continue;
  6702. }
  6703. Type = Type.getUnqualifiedType();
  6704. auto VDPrivate = buildVarDecl(*this, ELoc, Type, VD->getName(),
  6705. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  6706. // Generate helper private variable and initialize it with the value of the
  6707. // original variable. The address of the original variable is replaced by
  6708. // the address of the new private variable in the CodeGen. This new variable
  6709. // is not added to IdResolver, so the code in the OpenMP region uses
  6710. // original variable for proper diagnostics and variable capturing.
  6711. Expr *VDInitRefExpr = nullptr;
  6712. // For arrays generate initializer for single element and replace it by the
  6713. // original array element in CodeGen.
  6714. if (Type->isArrayType()) {
  6715. auto VDInit =
  6716. buildVarDecl(*this, DE->getExprLoc(), ElemType, VD->getName());
  6717. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  6718. auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
  6719. ElemType = ElemType.getUnqualifiedType();
  6720. auto *VDInitTemp = buildVarDecl(*this, DE->getLocStart(), ElemType,
  6721. ".firstprivate.temp");
  6722. InitializedEntity Entity =
  6723. InitializedEntity::InitializeVariable(VDInitTemp);
  6724. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  6725. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  6726. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  6727. if (Result.isInvalid())
  6728. VDPrivate->setInvalidDecl();
  6729. else
  6730. VDPrivate->setInit(Result.getAs<Expr>());
  6731. // Remove temp variable declaration.
  6732. Context.Deallocate(VDInitTemp);
  6733. } else {
  6734. auto *VDInit =
  6735. buildVarDecl(*this, DE->getLocStart(), Type, ".firstprivate.temp");
  6736. VDInitRefExpr =
  6737. buildDeclRefExpr(*this, VDInit, DE->getType(), DE->getExprLoc());
  6738. AddInitializerToDecl(VDPrivate,
  6739. DefaultLvalueConversion(VDInitRefExpr).get(),
  6740. /*DirectInit=*/false, /*TypeMayContainAuto=*/false);
  6741. }
  6742. if (VDPrivate->isInvalidDecl()) {
  6743. if (IsImplicitClause) {
  6744. Diag(DE->getExprLoc(),
  6745. diag::note_omp_task_predetermined_firstprivate_here);
  6746. }
  6747. continue;
  6748. }
  6749. CurContext->addDecl(VDPrivate);
  6750. auto VDPrivateRefExpr = buildDeclRefExpr(
  6751. *this, VDPrivate, DE->getType().getUnqualifiedType(), DE->getExprLoc());
  6752. DSAStack->addDSA(VD, DE, OMPC_firstprivate);
  6753. Vars.push_back(DE);
  6754. PrivateCopies.push_back(VDPrivateRefExpr);
  6755. Inits.push_back(VDInitRefExpr);
  6756. }
  6757. if (Vars.empty())
  6758. return nullptr;
  6759. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  6760. Vars, PrivateCopies, Inits);
  6761. }
  6762. OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
  6763. SourceLocation StartLoc,
  6764. SourceLocation LParenLoc,
  6765. SourceLocation EndLoc) {
  6766. SmallVector<Expr *, 8> Vars;
  6767. SmallVector<Expr *, 8> SrcExprs;
  6768. SmallVector<Expr *, 8> DstExprs;
  6769. SmallVector<Expr *, 8> AssignmentOps;
  6770. for (auto &RefExpr : VarList) {
  6771. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  6772. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  6773. // It will be analyzed later.
  6774. Vars.push_back(RefExpr);
  6775. SrcExprs.push_back(nullptr);
  6776. DstExprs.push_back(nullptr);
  6777. AssignmentOps.push_back(nullptr);
  6778. continue;
  6779. }
  6780. SourceLocation ELoc = RefExpr->getExprLoc();
  6781. // OpenMP [2.1, C/C++]
  6782. // A list item is a variable name.
  6783. // OpenMP [2.14.3.5, Restrictions, p.1]
  6784. // A variable that is part of another variable (as an array or structure
  6785. // element) cannot appear in a lastprivate clause.
  6786. DeclRefExpr *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  6787. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  6788. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  6789. << 0 << RefExpr->getSourceRange();
  6790. continue;
  6791. }
  6792. Decl *D = DE->getDecl();
  6793. VarDecl *VD = cast<VarDecl>(D);
  6794. QualType Type = VD->getType();
  6795. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  6796. // It will be analyzed later.
  6797. Vars.push_back(DE);
  6798. SrcExprs.push_back(nullptr);
  6799. DstExprs.push_back(nullptr);
  6800. AssignmentOps.push_back(nullptr);
  6801. continue;
  6802. }
  6803. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  6804. // A variable that appears in a lastprivate clause must not have an
  6805. // incomplete type or a reference type.
  6806. if (RequireCompleteType(ELoc, Type,
  6807. diag::err_omp_lastprivate_incomplete_type)) {
  6808. continue;
  6809. }
  6810. Type = Type.getNonReferenceType();
  6811. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  6812. // in a Construct]
  6813. // Variables with the predetermined data-sharing attributes may not be
  6814. // listed in data-sharing attributes clauses, except for the cases
  6815. // listed below.
  6816. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  6817. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  6818. DVar.CKind != OMPC_firstprivate &&
  6819. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  6820. Diag(ELoc, diag::err_omp_wrong_dsa)
  6821. << getOpenMPClauseName(DVar.CKind)
  6822. << getOpenMPClauseName(OMPC_lastprivate);
  6823. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6824. continue;
  6825. }
  6826. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  6827. // OpenMP [2.14.3.5, Restrictions, p.2]
  6828. // A list item that is private within a parallel region, or that appears in
  6829. // the reduction clause of a parallel construct, must not appear in a
  6830. // lastprivate clause on a worksharing construct if any of the corresponding
  6831. // worksharing regions ever binds to any of the corresponding parallel
  6832. // regions.
  6833. DSAStackTy::DSAVarData TopDVar = DVar;
  6834. if (isOpenMPWorksharingDirective(CurrDir) &&
  6835. !isOpenMPParallelDirective(CurrDir)) {
  6836. DVar = DSAStack->getImplicitDSA(VD, true);
  6837. if (DVar.CKind != OMPC_shared) {
  6838. Diag(ELoc, diag::err_omp_required_access)
  6839. << getOpenMPClauseName(OMPC_lastprivate)
  6840. << getOpenMPClauseName(OMPC_shared);
  6841. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6842. continue;
  6843. }
  6844. }
  6845. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  6846. // A variable of class type (or array thereof) that appears in a
  6847. // lastprivate clause requires an accessible, unambiguous default
  6848. // constructor for the class type, unless the list item is also specified
  6849. // in a firstprivate clause.
  6850. // A variable of class type (or array thereof) that appears in a
  6851. // lastprivate clause requires an accessible, unambiguous copy assignment
  6852. // operator for the class type.
  6853. Type = Context.getBaseElementType(Type).getNonReferenceType();
  6854. auto *SrcVD = buildVarDecl(*this, DE->getLocStart(),
  6855. Type.getUnqualifiedType(), ".lastprivate.src",
  6856. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  6857. auto *PseudoSrcExpr = buildDeclRefExpr(
  6858. *this, SrcVD, Type.getUnqualifiedType(), DE->getExprLoc());
  6859. auto *DstVD =
  6860. buildVarDecl(*this, DE->getLocStart(), Type, ".lastprivate.dst",
  6861. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  6862. auto *PseudoDstExpr =
  6863. buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
  6864. // For arrays generate assignment operation for single element and replace
  6865. // it by the original array element in CodeGen.
  6866. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
  6867. PseudoDstExpr, PseudoSrcExpr);
  6868. if (AssignmentOp.isInvalid())
  6869. continue;
  6870. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  6871. /*DiscardedValue=*/true);
  6872. if (AssignmentOp.isInvalid())
  6873. continue;
  6874. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  6875. // A list item may appear in a firstprivate or lastprivate clause but not
  6876. // both.
  6877. if (CurrDir == OMPD_distribute) {
  6878. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  6879. if (DVar.CKind == OMPC_firstprivate) {
  6880. Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute);
  6881. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6882. continue;
  6883. }
  6884. }
  6885. if (TopDVar.CKind != OMPC_firstprivate)
  6886. DSAStack->addDSA(VD, DE, OMPC_lastprivate);
  6887. Vars.push_back(DE);
  6888. SrcExprs.push_back(PseudoSrcExpr);
  6889. DstExprs.push_back(PseudoDstExpr);
  6890. AssignmentOps.push_back(AssignmentOp.get());
  6891. }
  6892. if (Vars.empty())
  6893. return nullptr;
  6894. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  6895. Vars, SrcExprs, DstExprs, AssignmentOps);
  6896. }
  6897. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  6898. SourceLocation StartLoc,
  6899. SourceLocation LParenLoc,
  6900. SourceLocation EndLoc) {
  6901. SmallVector<Expr *, 8> Vars;
  6902. for (auto &RefExpr : VarList) {
  6903. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  6904. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  6905. // It will be analyzed later.
  6906. Vars.push_back(RefExpr);
  6907. continue;
  6908. }
  6909. SourceLocation ELoc = RefExpr->getExprLoc();
  6910. // OpenMP [2.1, C/C++]
  6911. // A list item is a variable name.
  6912. // OpenMP [2.14.3.2, Restrictions, p.1]
  6913. // A variable that is part of another variable (as an array or structure
  6914. // element) cannot appear in a shared unless it is a static data member
  6915. // of a C++ class.
  6916. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  6917. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  6918. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  6919. << 0 << RefExpr->getSourceRange();
  6920. continue;
  6921. }
  6922. Decl *D = DE->getDecl();
  6923. VarDecl *VD = cast<VarDecl>(D);
  6924. QualType Type = VD->getType();
  6925. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  6926. // It will be analyzed later.
  6927. Vars.push_back(DE);
  6928. continue;
  6929. }
  6930. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  6931. // in a Construct]
  6932. // Variables with the predetermined data-sharing attributes may not be
  6933. // listed in data-sharing attributes clauses, except for the cases
  6934. // listed below. For these exceptions only, listing a predetermined
  6935. // variable in a data-sharing attribute clause is allowed and overrides
  6936. // the variable's predetermined data-sharing attributes.
  6937. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  6938. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  6939. DVar.RefExpr) {
  6940. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  6941. << getOpenMPClauseName(OMPC_shared);
  6942. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  6943. continue;
  6944. }
  6945. DSAStack->addDSA(VD, DE, OMPC_shared);
  6946. Vars.push_back(DE);
  6947. }
  6948. if (Vars.empty())
  6949. return nullptr;
  6950. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  6951. }
  6952. namespace {
  6953. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  6954. DSAStackTy *Stack;
  6955. public:
  6956. bool VisitDeclRefExpr(DeclRefExpr *E) {
  6957. if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
  6958. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
  6959. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  6960. return false;
  6961. if (DVar.CKind != OMPC_unknown)
  6962. return true;
  6963. DSAStackTy::DSAVarData DVarPrivate =
  6964. Stack->hasDSA(VD, isOpenMPPrivate, MatchesAlways(), false);
  6965. if (DVarPrivate.CKind != OMPC_unknown)
  6966. return true;
  6967. return false;
  6968. }
  6969. return false;
  6970. }
  6971. bool VisitStmt(Stmt *S) {
  6972. for (auto Child : S->children()) {
  6973. if (Child && Visit(Child))
  6974. return true;
  6975. }
  6976. return false;
  6977. }
  6978. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  6979. };
  6980. } // namespace
  6981. OMPClause *Sema::ActOnOpenMPReductionClause(
  6982. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  6983. SourceLocation ColonLoc, SourceLocation EndLoc,
  6984. CXXScopeSpec &ReductionIdScopeSpec,
  6985. const DeclarationNameInfo &ReductionId) {
  6986. // TODO: Allow scope specification search when 'declare reduction' is
  6987. // supported.
  6988. assert(ReductionIdScopeSpec.isEmpty() &&
  6989. "No support for scoped reduction identifiers yet.");
  6990. auto DN = ReductionId.getName();
  6991. auto OOK = DN.getCXXOverloadedOperator();
  6992. BinaryOperatorKind BOK = BO_Comma;
  6993. // OpenMP [2.14.3.6, reduction clause]
  6994. // C
  6995. // reduction-identifier is either an identifier or one of the following
  6996. // operators: +, -, *, &, |, ^, && and ||
  6997. // C++
  6998. // reduction-identifier is either an id-expression or one of the following
  6999. // operators: +, -, *, &, |, ^, && and ||
  7000. // FIXME: Only 'min' and 'max' identifiers are supported for now.
  7001. switch (OOK) {
  7002. case OO_Plus:
  7003. case OO_Minus:
  7004. BOK = BO_Add;
  7005. break;
  7006. case OO_Star:
  7007. BOK = BO_Mul;
  7008. break;
  7009. case OO_Amp:
  7010. BOK = BO_And;
  7011. break;
  7012. case OO_Pipe:
  7013. BOK = BO_Or;
  7014. break;
  7015. case OO_Caret:
  7016. BOK = BO_Xor;
  7017. break;
  7018. case OO_AmpAmp:
  7019. BOK = BO_LAnd;
  7020. break;
  7021. case OO_PipePipe:
  7022. BOK = BO_LOr;
  7023. break;
  7024. case OO_New:
  7025. case OO_Delete:
  7026. case OO_Array_New:
  7027. case OO_Array_Delete:
  7028. case OO_Slash:
  7029. case OO_Percent:
  7030. case OO_Tilde:
  7031. case OO_Exclaim:
  7032. case OO_Equal:
  7033. case OO_Less:
  7034. case OO_Greater:
  7035. case OO_LessEqual:
  7036. case OO_GreaterEqual:
  7037. case OO_PlusEqual:
  7038. case OO_MinusEqual:
  7039. case OO_StarEqual:
  7040. case OO_SlashEqual:
  7041. case OO_PercentEqual:
  7042. case OO_CaretEqual:
  7043. case OO_AmpEqual:
  7044. case OO_PipeEqual:
  7045. case OO_LessLess:
  7046. case OO_GreaterGreater:
  7047. case OO_LessLessEqual:
  7048. case OO_GreaterGreaterEqual:
  7049. case OO_EqualEqual:
  7050. case OO_ExclaimEqual:
  7051. case OO_PlusPlus:
  7052. case OO_MinusMinus:
  7053. case OO_Comma:
  7054. case OO_ArrowStar:
  7055. case OO_Arrow:
  7056. case OO_Call:
  7057. case OO_Subscript:
  7058. case OO_Conditional:
  7059. case OO_Coawait:
  7060. case NUM_OVERLOADED_OPERATORS:
  7061. llvm_unreachable("Unexpected reduction identifier");
  7062. case OO_None:
  7063. if (auto II = DN.getAsIdentifierInfo()) {
  7064. if (II->isStr("max"))
  7065. BOK = BO_GT;
  7066. else if (II->isStr("min"))
  7067. BOK = BO_LT;
  7068. }
  7069. break;
  7070. }
  7071. SourceRange ReductionIdRange;
  7072. if (ReductionIdScopeSpec.isValid()) {
  7073. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  7074. }
  7075. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  7076. if (BOK == BO_Comma) {
  7077. // Not allowed reduction identifier is found.
  7078. Diag(ReductionId.getLocStart(), diag::err_omp_unknown_reduction_identifier)
  7079. << ReductionIdRange;
  7080. return nullptr;
  7081. }
  7082. SmallVector<Expr *, 8> Vars;
  7083. SmallVector<Expr *, 8> Privates;
  7084. SmallVector<Expr *, 8> LHSs;
  7085. SmallVector<Expr *, 8> RHSs;
  7086. SmallVector<Expr *, 8> ReductionOps;
  7087. for (auto RefExpr : VarList) {
  7088. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  7089. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  7090. // It will be analyzed later.
  7091. Vars.push_back(RefExpr);
  7092. Privates.push_back(nullptr);
  7093. LHSs.push_back(nullptr);
  7094. RHSs.push_back(nullptr);
  7095. ReductionOps.push_back(nullptr);
  7096. continue;
  7097. }
  7098. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  7099. RefExpr->isInstantiationDependent() ||
  7100. RefExpr->containsUnexpandedParameterPack()) {
  7101. // It will be analyzed later.
  7102. Vars.push_back(RefExpr);
  7103. Privates.push_back(nullptr);
  7104. LHSs.push_back(nullptr);
  7105. RHSs.push_back(nullptr);
  7106. ReductionOps.push_back(nullptr);
  7107. continue;
  7108. }
  7109. auto ELoc = RefExpr->getExprLoc();
  7110. auto ERange = RefExpr->getSourceRange();
  7111. // OpenMP [2.1, C/C++]
  7112. // A list item is a variable or array section, subject to the restrictions
  7113. // specified in Section 2.4 on page 42 and in each of the sections
  7114. // describing clauses and directives for which a list appears.
  7115. // OpenMP [2.14.3.3, Restrictions, p.1]
  7116. // A variable that is part of another variable (as an array or
  7117. // structure element) cannot appear in a private clause.
  7118. auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
  7119. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr);
  7120. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr);
  7121. if (!ASE && !OASE && (!DE || !isa<VarDecl>(DE->getDecl()))) {
  7122. Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
  7123. << 0 << ERange;
  7124. continue;
  7125. }
  7126. QualType Type;
  7127. VarDecl *VD = nullptr;
  7128. if (DE) {
  7129. auto D = DE->getDecl();
  7130. VD = cast<VarDecl>(D);
  7131. Type = Context.getBaseElementType(VD->getType());
  7132. } else if (ASE) {
  7133. Type = ASE->getType();
  7134. auto *Base = ASE->getBase()->IgnoreParenImpCasts();
  7135. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  7136. Base = TempASE->getBase()->IgnoreParenImpCasts();
  7137. DE = dyn_cast<DeclRefExpr>(Base);
  7138. if (DE)
  7139. VD = dyn_cast<VarDecl>(DE->getDecl());
  7140. if (!VD) {
  7141. Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
  7142. << 0 << Base->getSourceRange();
  7143. continue;
  7144. }
  7145. } else if (OASE) {
  7146. auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  7147. if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
  7148. Type = ATy->getElementType();
  7149. else
  7150. Type = BaseType->getPointeeType();
  7151. auto *Base = OASE->getBase()->IgnoreParenImpCasts();
  7152. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  7153. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  7154. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  7155. Base = TempASE->getBase()->IgnoreParenImpCasts();
  7156. DE = dyn_cast<DeclRefExpr>(Base);
  7157. if (DE)
  7158. VD = dyn_cast<VarDecl>(DE->getDecl());
  7159. if (!VD) {
  7160. Diag(Base->getExprLoc(), diag::err_omp_expected_base_var_name)
  7161. << 1 << Base->getSourceRange();
  7162. continue;
  7163. }
  7164. }
  7165. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  7166. // A variable that appears in a private clause must not have an incomplete
  7167. // type or a reference type.
  7168. if (RequireCompleteType(ELoc, Type,
  7169. diag::err_omp_reduction_incomplete_type))
  7170. continue;
  7171. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  7172. // A list item that appears in a reduction clause must not be
  7173. // const-qualified.
  7174. if (Type.getNonReferenceType().isConstant(Context)) {
  7175. Diag(ELoc, diag::err_omp_const_reduction_list_item)
  7176. << getOpenMPClauseName(OMPC_reduction) << Type << ERange;
  7177. if (!ASE && !OASE) {
  7178. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  7179. VarDecl::DeclarationOnly;
  7180. Diag(VD->getLocation(),
  7181. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  7182. << VD;
  7183. }
  7184. continue;
  7185. }
  7186. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  7187. // If a list-item is a reference type then it must bind to the same object
  7188. // for all threads of the team.
  7189. if (!ASE && !OASE) {
  7190. VarDecl *VDDef = VD->getDefinition();
  7191. if (Type->isReferenceType() && VDDef) {
  7192. DSARefChecker Check(DSAStack);
  7193. if (Check.Visit(VDDef->getInit())) {
  7194. Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange;
  7195. Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  7196. continue;
  7197. }
  7198. }
  7199. }
  7200. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  7201. // The type of a list item that appears in a reduction clause must be valid
  7202. // for the reduction-identifier. For a max or min reduction in C, the type
  7203. // of the list item must be an allowed arithmetic data type: char, int,
  7204. // float, double, or _Bool, possibly modified with long, short, signed, or
  7205. // unsigned. For a max or min reduction in C++, the type of the list item
  7206. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  7207. // double, or bool, possibly modified with long, short, signed, or unsigned.
  7208. if ((BOK == BO_GT || BOK == BO_LT) &&
  7209. !(Type->isScalarType() ||
  7210. (getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  7211. Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  7212. << getLangOpts().CPlusPlus;
  7213. if (!ASE && !OASE) {
  7214. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  7215. VarDecl::DeclarationOnly;
  7216. Diag(VD->getLocation(),
  7217. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  7218. << VD;
  7219. }
  7220. continue;
  7221. }
  7222. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  7223. !getLangOpts().CPlusPlus && Type->isFloatingType()) {
  7224. Diag(ELoc, diag::err_omp_clause_floating_type_arg);
  7225. if (!ASE && !OASE) {
  7226. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  7227. VarDecl::DeclarationOnly;
  7228. Diag(VD->getLocation(),
  7229. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  7230. << VD;
  7231. }
  7232. continue;
  7233. }
  7234. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  7235. // in a Construct]
  7236. // Variables with the predetermined data-sharing attributes may not be
  7237. // listed in data-sharing attributes clauses, except for the cases
  7238. // listed below. For these exceptions only, listing a predetermined
  7239. // variable in a data-sharing attribute clause is allowed and overrides
  7240. // the variable's predetermined data-sharing attributes.
  7241. // OpenMP [2.14.3.6, Restrictions, p.3]
  7242. // Any number of reduction clauses can be specified on the directive,
  7243. // but a list item can appear only once in the reduction clauses for that
  7244. // directive.
  7245. DSAStackTy::DSAVarData DVar;
  7246. DVar = DSAStack->getTopDSA(VD, false);
  7247. if (DVar.CKind == OMPC_reduction) {
  7248. Diag(ELoc, diag::err_omp_once_referenced)
  7249. << getOpenMPClauseName(OMPC_reduction);
  7250. if (DVar.RefExpr) {
  7251. Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  7252. }
  7253. } else if (DVar.CKind != OMPC_unknown) {
  7254. Diag(ELoc, diag::err_omp_wrong_dsa)
  7255. << getOpenMPClauseName(DVar.CKind)
  7256. << getOpenMPClauseName(OMPC_reduction);
  7257. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  7258. continue;
  7259. }
  7260. // OpenMP [2.14.3.6, Restrictions, p.1]
  7261. // A list item that appears in a reduction clause of a worksharing
  7262. // construct must be shared in the parallel regions to which any of the
  7263. // worksharing regions arising from the worksharing construct bind.
  7264. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  7265. if (isOpenMPWorksharingDirective(CurrDir) &&
  7266. !isOpenMPParallelDirective(CurrDir)) {
  7267. DVar = DSAStack->getImplicitDSA(VD, true);
  7268. if (DVar.CKind != OMPC_shared) {
  7269. Diag(ELoc, diag::err_omp_required_access)
  7270. << getOpenMPClauseName(OMPC_reduction)
  7271. << getOpenMPClauseName(OMPC_shared);
  7272. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  7273. continue;
  7274. }
  7275. }
  7276. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  7277. auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs",
  7278. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  7279. auto *RHSVD = buildVarDecl(*this, ELoc, Type, VD->getName(),
  7280. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  7281. auto PrivateTy = Type;
  7282. if (OASE ||
  7283. (DE && VD->getType().getNonReferenceType()->isVariablyModifiedType())) {
  7284. // For arays/array sections only:
  7285. // Create pseudo array type for private copy. The size for this array will
  7286. // be generated during codegen.
  7287. // For array subscripts or single variables Private Ty is the same as Type
  7288. // (type of the variable or single array element).
  7289. PrivateTy = Context.getVariableArrayType(
  7290. Type, new (Context) OpaqueValueExpr(SourceLocation(),
  7291. Context.getSizeType(), VK_RValue),
  7292. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  7293. } else if (DE &&
  7294. Context.getAsArrayType(VD->getType().getNonReferenceType()))
  7295. PrivateTy = VD->getType().getNonReferenceType();
  7296. // Private copy.
  7297. auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, VD->getName(),
  7298. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  7299. // Add initializer for private variable.
  7300. Expr *Init = nullptr;
  7301. switch (BOK) {
  7302. case BO_Add:
  7303. case BO_Xor:
  7304. case BO_Or:
  7305. case BO_LOr:
  7306. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  7307. if (Type->isScalarType() || Type->isAnyComplexType()) {
  7308. Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  7309. }
  7310. break;
  7311. case BO_Mul:
  7312. case BO_LAnd:
  7313. if (Type->isScalarType() || Type->isAnyComplexType()) {
  7314. // '*' and '&&' reduction ops - initializer is '1'.
  7315. Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  7316. }
  7317. break;
  7318. case BO_And: {
  7319. // '&' reduction op - initializer is '~0'.
  7320. QualType OrigType = Type;
  7321. if (auto *ComplexTy = OrigType->getAs<ComplexType>()) {
  7322. Type = ComplexTy->getElementType();
  7323. }
  7324. if (Type->isRealFloatingType()) {
  7325. llvm::APFloat InitValue =
  7326. llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
  7327. /*isIEEE=*/true);
  7328. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  7329. Type, ELoc);
  7330. } else if (Type->isScalarType()) {
  7331. auto Size = Context.getTypeSize(Type);
  7332. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  7333. llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
  7334. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  7335. }
  7336. if (Init && OrigType->isAnyComplexType()) {
  7337. // Init = 0xFFFF + 0xFFFFi;
  7338. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  7339. Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  7340. }
  7341. Type = OrigType;
  7342. break;
  7343. }
  7344. case BO_LT:
  7345. case BO_GT: {
  7346. // 'min' reduction op - initializer is 'Largest representable number in
  7347. // the reduction list item type'.
  7348. // 'max' reduction op - initializer is 'Least representable number in
  7349. // the reduction list item type'.
  7350. if (Type->isIntegerType() || Type->isPointerType()) {
  7351. bool IsSigned = Type->hasSignedIntegerRepresentation();
  7352. auto Size = Context.getTypeSize(Type);
  7353. QualType IntTy =
  7354. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  7355. llvm::APInt InitValue =
  7356. (BOK != BO_LT)
  7357. ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  7358. : llvm::APInt::getMinValue(Size)
  7359. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  7360. : llvm::APInt::getMaxValue(Size);
  7361. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  7362. if (Type->isPointerType()) {
  7363. // Cast to pointer type.
  7364. auto CastExpr = BuildCStyleCastExpr(
  7365. SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc),
  7366. SourceLocation(), Init);
  7367. if (CastExpr.isInvalid())
  7368. continue;
  7369. Init = CastExpr.get();
  7370. }
  7371. } else if (Type->isRealFloatingType()) {
  7372. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  7373. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  7374. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  7375. Type, ELoc);
  7376. }
  7377. break;
  7378. }
  7379. case BO_PtrMemD:
  7380. case BO_PtrMemI:
  7381. case BO_MulAssign:
  7382. case BO_Div:
  7383. case BO_Rem:
  7384. case BO_Sub:
  7385. case BO_Shl:
  7386. case BO_Shr:
  7387. case BO_LE:
  7388. case BO_GE:
  7389. case BO_EQ:
  7390. case BO_NE:
  7391. case BO_AndAssign:
  7392. case BO_XorAssign:
  7393. case BO_OrAssign:
  7394. case BO_Assign:
  7395. case BO_AddAssign:
  7396. case BO_SubAssign:
  7397. case BO_DivAssign:
  7398. case BO_RemAssign:
  7399. case BO_ShlAssign:
  7400. case BO_ShrAssign:
  7401. case BO_Comma:
  7402. llvm_unreachable("Unexpected reduction operation");
  7403. }
  7404. if (Init) {
  7405. AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false,
  7406. /*TypeMayContainAuto=*/false);
  7407. } else
  7408. ActOnUninitializedDecl(RHSVD, /*TypeMayContainAuto=*/false);
  7409. if (!RHSVD->hasInit()) {
  7410. Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type
  7411. << ReductionIdRange;
  7412. if (VD) {
  7413. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  7414. VarDecl::DeclarationOnly;
  7415. Diag(VD->getLocation(),
  7416. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  7417. << VD;
  7418. }
  7419. continue;
  7420. }
  7421. // Store initializer for single element in private copy. Will be used during
  7422. // codegen.
  7423. PrivateVD->setInit(RHSVD->getInit());
  7424. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  7425. auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc);
  7426. auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc);
  7427. auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc);
  7428. ExprResult ReductionOp =
  7429. BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), BOK,
  7430. LHSDRE, RHSDRE);
  7431. if (ReductionOp.isUsable()) {
  7432. if (BOK != BO_LT && BOK != BO_GT) {
  7433. ReductionOp =
  7434. BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
  7435. BO_Assign, LHSDRE, ReductionOp.get());
  7436. } else {
  7437. auto *ConditionalOp = new (Context) ConditionalOperator(
  7438. ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(),
  7439. RHSDRE, Type, VK_LValue, OK_Ordinary);
  7440. ReductionOp =
  7441. BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(),
  7442. BO_Assign, LHSDRE, ConditionalOp);
  7443. }
  7444. ReductionOp = ActOnFinishFullExpr(ReductionOp.get());
  7445. }
  7446. if (ReductionOp.isInvalid())
  7447. continue;
  7448. DSAStack->addDSA(VD, DE, OMPC_reduction);
  7449. Vars.push_back(RefExpr);
  7450. Privates.push_back(PrivateDRE);
  7451. LHSs.push_back(LHSDRE);
  7452. RHSs.push_back(RHSDRE);
  7453. ReductionOps.push_back(ReductionOp.get());
  7454. }
  7455. if (Vars.empty())
  7456. return nullptr;
  7457. return OMPReductionClause::Create(
  7458. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars,
  7459. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates,
  7460. LHSs, RHSs, ReductionOps);
  7461. }
  7462. OMPClause *Sema::ActOnOpenMPLinearClause(
  7463. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  7464. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  7465. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  7466. SmallVector<Expr *, 8> Vars;
  7467. SmallVector<Expr *, 8> Privates;
  7468. SmallVector<Expr *, 8> Inits;
  7469. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  7470. LinKind == OMPC_LINEAR_unknown) {
  7471. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  7472. LinKind = OMPC_LINEAR_val;
  7473. }
  7474. for (auto &RefExpr : VarList) {
  7475. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  7476. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  7477. // It will be analyzed later.
  7478. Vars.push_back(RefExpr);
  7479. Privates.push_back(nullptr);
  7480. Inits.push_back(nullptr);
  7481. continue;
  7482. }
  7483. // OpenMP [2.14.3.7, linear clause]
  7484. // A list item that appears in a linear clause is subject to the private
  7485. // clause semantics described in Section 2.14.3.3 on page 159 except as
  7486. // noted. In addition, the value of the new list item on each iteration
  7487. // of the associated loop(s) corresponds to the value of the original
  7488. // list item before entering the construct plus the logical number of
  7489. // the iteration times linear-step.
  7490. SourceLocation ELoc = RefExpr->getExprLoc();
  7491. // OpenMP [2.1, C/C++]
  7492. // A list item is a variable name.
  7493. // OpenMP [2.14.3.3, Restrictions, p.1]
  7494. // A variable that is part of another variable (as an array or
  7495. // structure element) cannot appear in a private clause.
  7496. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  7497. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  7498. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  7499. << 0 << RefExpr->getSourceRange();
  7500. continue;
  7501. }
  7502. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  7503. // OpenMP [2.14.3.7, linear clause]
  7504. // A list-item cannot appear in more than one linear clause.
  7505. // A list-item that appears in a linear clause cannot appear in any
  7506. // other data-sharing attribute clause.
  7507. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, false);
  7508. if (DVar.RefExpr) {
  7509. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  7510. << getOpenMPClauseName(OMPC_linear);
  7511. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  7512. continue;
  7513. }
  7514. QualType QType = VD->getType();
  7515. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  7516. // It will be analyzed later.
  7517. Vars.push_back(DE);
  7518. Privates.push_back(nullptr);
  7519. Inits.push_back(nullptr);
  7520. continue;
  7521. }
  7522. // A variable must not have an incomplete type or a reference type.
  7523. if (RequireCompleteType(ELoc, QType,
  7524. diag::err_omp_linear_incomplete_type)) {
  7525. continue;
  7526. }
  7527. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  7528. !QType->isReferenceType()) {
  7529. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  7530. << QType << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  7531. continue;
  7532. }
  7533. QType = QType.getNonReferenceType();
  7534. // A list item must not be const-qualified.
  7535. if (QType.isConstant(Context)) {
  7536. Diag(ELoc, diag::err_omp_const_variable)
  7537. << getOpenMPClauseName(OMPC_linear);
  7538. bool IsDecl =
  7539. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  7540. Diag(VD->getLocation(),
  7541. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  7542. << VD;
  7543. continue;
  7544. }
  7545. // A list item must be of integral or pointer type.
  7546. QType = QType.getUnqualifiedType().getCanonicalType();
  7547. const Type *Ty = QType.getTypePtrOrNull();
  7548. if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
  7549. !Ty->isPointerType())) {
  7550. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << QType;
  7551. bool IsDecl =
  7552. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  7553. Diag(VD->getLocation(),
  7554. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  7555. << VD;
  7556. continue;
  7557. }
  7558. // Build private copy of original var.
  7559. auto *Private = buildVarDecl(*this, ELoc, QType, VD->getName(),
  7560. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  7561. auto *PrivateRef = buildDeclRefExpr(
  7562. *this, Private, DE->getType().getUnqualifiedType(), DE->getExprLoc());
  7563. // Build var to save initial value.
  7564. VarDecl *Init = buildVarDecl(*this, ELoc, QType, ".linear.start");
  7565. Expr *InitExpr;
  7566. if (LinKind == OMPC_LINEAR_uval)
  7567. InitExpr = VD->getInit();
  7568. else
  7569. InitExpr = DE;
  7570. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  7571. /*DirectInit*/ false, /*TypeMayContainAuto*/ false);
  7572. auto InitRef = buildDeclRefExpr(
  7573. *this, Init, DE->getType().getUnqualifiedType(), DE->getExprLoc());
  7574. DSAStack->addDSA(VD, DE, OMPC_linear);
  7575. Vars.push_back(DE);
  7576. Privates.push_back(PrivateRef);
  7577. Inits.push_back(InitRef);
  7578. }
  7579. if (Vars.empty())
  7580. return nullptr;
  7581. Expr *StepExpr = Step;
  7582. Expr *CalcStepExpr = nullptr;
  7583. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  7584. !Step->isInstantiationDependent() &&
  7585. !Step->containsUnexpandedParameterPack()) {
  7586. SourceLocation StepLoc = Step->getLocStart();
  7587. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  7588. if (Val.isInvalid())
  7589. return nullptr;
  7590. StepExpr = Val.get();
  7591. // Build var to save the step value.
  7592. VarDecl *SaveVar =
  7593. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  7594. ExprResult SaveRef =
  7595. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  7596. ExprResult CalcStep =
  7597. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  7598. CalcStep = ActOnFinishFullExpr(CalcStep.get());
  7599. // Warn about zero linear step (it would be probably better specified as
  7600. // making corresponding variables 'const').
  7601. llvm::APSInt Result;
  7602. bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
  7603. if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
  7604. Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
  7605. << (Vars.size() > 1);
  7606. if (!IsConstant && CalcStep.isUsable()) {
  7607. // Calculate the step beforehand instead of doing this on each iteration.
  7608. // (This is not used if the number of iterations may be kfold-ed).
  7609. CalcStepExpr = CalcStep.get();
  7610. }
  7611. }
  7612. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  7613. ColonLoc, EndLoc, Vars, Privates, Inits,
  7614. StepExpr, CalcStepExpr);
  7615. }
  7616. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  7617. Expr *NumIterations, Sema &SemaRef,
  7618. Scope *S) {
  7619. // Walk the vars and build update/final expressions for the CodeGen.
  7620. SmallVector<Expr *, 8> Updates;
  7621. SmallVector<Expr *, 8> Finals;
  7622. Expr *Step = Clause.getStep();
  7623. Expr *CalcStep = Clause.getCalcStep();
  7624. // OpenMP [2.14.3.7, linear clause]
  7625. // If linear-step is not specified it is assumed to be 1.
  7626. if (Step == nullptr)
  7627. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  7628. else if (CalcStep)
  7629. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  7630. bool HasErrors = false;
  7631. auto CurInit = Clause.inits().begin();
  7632. auto CurPrivate = Clause.privates().begin();
  7633. auto LinKind = Clause.getModifier();
  7634. for (auto &RefExpr : Clause.varlists()) {
  7635. Expr *InitExpr = *CurInit;
  7636. // Build privatized reference to the current linear var.
  7637. auto DE = cast<DeclRefExpr>(RefExpr);
  7638. Expr *CapturedRef;
  7639. if (LinKind == OMPC_LINEAR_uval)
  7640. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  7641. else
  7642. CapturedRef =
  7643. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  7644. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  7645. /*RefersToCapture=*/true);
  7646. // Build update: Var = InitExpr + IV * Step
  7647. ExprResult Update =
  7648. BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
  7649. InitExpr, IV, Step, /* Subtract */ false);
  7650. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
  7651. /*DiscardedValue=*/true);
  7652. // Build final: Var = InitExpr + NumIterations * Step
  7653. ExprResult Final =
  7654. BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
  7655. InitExpr, NumIterations, Step, /* Subtract */ false);
  7656. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
  7657. /*DiscardedValue=*/true);
  7658. if (!Update.isUsable() || !Final.isUsable()) {
  7659. Updates.push_back(nullptr);
  7660. Finals.push_back(nullptr);
  7661. HasErrors = true;
  7662. } else {
  7663. Updates.push_back(Update.get());
  7664. Finals.push_back(Final.get());
  7665. }
  7666. ++CurInit, ++CurPrivate;
  7667. }
  7668. Clause.setUpdates(Updates);
  7669. Clause.setFinals(Finals);
  7670. return HasErrors;
  7671. }
  7672. OMPClause *Sema::ActOnOpenMPAlignedClause(
  7673. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  7674. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  7675. SmallVector<Expr *, 8> Vars;
  7676. for (auto &RefExpr : VarList) {
  7677. assert(RefExpr && "NULL expr in OpenMP aligned clause.");
  7678. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  7679. // It will be analyzed later.
  7680. Vars.push_back(RefExpr);
  7681. continue;
  7682. }
  7683. SourceLocation ELoc = RefExpr->getExprLoc();
  7684. // OpenMP [2.1, C/C++]
  7685. // A list item is a variable name.
  7686. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  7687. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  7688. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  7689. << 0 << RefExpr->getSourceRange();
  7690. continue;
  7691. }
  7692. VarDecl *VD = cast<VarDecl>(DE->getDecl());
  7693. // OpenMP [2.8.1, simd construct, Restrictions]
  7694. // The type of list items appearing in the aligned clause must be
  7695. // array, pointer, reference to array, or reference to pointer.
  7696. QualType QType = VD->getType();
  7697. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  7698. const Type *Ty = QType.getTypePtrOrNull();
  7699. if (!Ty || (!Ty->isDependentType() && !Ty->isArrayType() &&
  7700. !Ty->isPointerType())) {
  7701. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  7702. << QType << getLangOpts().CPlusPlus << RefExpr->getSourceRange();
  7703. bool IsDecl =
  7704. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  7705. Diag(VD->getLocation(),
  7706. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  7707. << VD;
  7708. continue;
  7709. }
  7710. // OpenMP [2.8.1, simd construct, Restrictions]
  7711. // A list-item cannot appear in more than one aligned clause.
  7712. if (Expr *PrevRef = DSAStack->addUniqueAligned(VD, DE)) {
  7713. Diag(ELoc, diag::err_omp_aligned_twice) << RefExpr->getSourceRange();
  7714. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  7715. << getOpenMPClauseName(OMPC_aligned);
  7716. continue;
  7717. }
  7718. Vars.push_back(DE);
  7719. }
  7720. // OpenMP [2.8.1, simd construct, Description]
  7721. // The parameter of the aligned clause, alignment, must be a constant
  7722. // positive integer expression.
  7723. // If no optional parameter is specified, implementation-defined default
  7724. // alignments for SIMD instructions on the target platforms are assumed.
  7725. if (Alignment != nullptr) {
  7726. ExprResult AlignResult =
  7727. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  7728. if (AlignResult.isInvalid())
  7729. return nullptr;
  7730. Alignment = AlignResult.get();
  7731. }
  7732. if (Vars.empty())
  7733. return nullptr;
  7734. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  7735. EndLoc, Vars, Alignment);
  7736. }
  7737. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  7738. SourceLocation StartLoc,
  7739. SourceLocation LParenLoc,
  7740. SourceLocation EndLoc) {
  7741. SmallVector<Expr *, 8> Vars;
  7742. SmallVector<Expr *, 8> SrcExprs;
  7743. SmallVector<Expr *, 8> DstExprs;
  7744. SmallVector<Expr *, 8> AssignmentOps;
  7745. for (auto &RefExpr : VarList) {
  7746. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  7747. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  7748. // It will be analyzed later.
  7749. Vars.push_back(RefExpr);
  7750. SrcExprs.push_back(nullptr);
  7751. DstExprs.push_back(nullptr);
  7752. AssignmentOps.push_back(nullptr);
  7753. continue;
  7754. }
  7755. SourceLocation ELoc = RefExpr->getExprLoc();
  7756. // OpenMP [2.1, C/C++]
  7757. // A list item is a variable name.
  7758. // OpenMP [2.14.4.1, Restrictions, p.1]
  7759. // A list item that appears in a copyin clause must be threadprivate.
  7760. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  7761. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  7762. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  7763. << 0 << RefExpr->getSourceRange();
  7764. continue;
  7765. }
  7766. Decl *D = DE->getDecl();
  7767. VarDecl *VD = cast<VarDecl>(D);
  7768. QualType Type = VD->getType();
  7769. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  7770. // It will be analyzed later.
  7771. Vars.push_back(DE);
  7772. SrcExprs.push_back(nullptr);
  7773. DstExprs.push_back(nullptr);
  7774. AssignmentOps.push_back(nullptr);
  7775. continue;
  7776. }
  7777. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  7778. // A list item that appears in a copyin clause must be threadprivate.
  7779. if (!DSAStack->isThreadPrivate(VD)) {
  7780. Diag(ELoc, diag::err_omp_required_access)
  7781. << getOpenMPClauseName(OMPC_copyin)
  7782. << getOpenMPDirectiveName(OMPD_threadprivate);
  7783. continue;
  7784. }
  7785. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  7786. // A variable of class type (or array thereof) that appears in a
  7787. // copyin clause requires an accessible, unambiguous copy assignment
  7788. // operator for the class type.
  7789. auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  7790. auto *SrcVD =
  7791. buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
  7792. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  7793. auto *PseudoSrcExpr = buildDeclRefExpr(
  7794. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  7795. auto *DstVD =
  7796. buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
  7797. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  7798. auto *PseudoDstExpr =
  7799. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  7800. // For arrays generate assignment operation for single element and replace
  7801. // it by the original array element in CodeGen.
  7802. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
  7803. PseudoDstExpr, PseudoSrcExpr);
  7804. if (AssignmentOp.isInvalid())
  7805. continue;
  7806. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  7807. /*DiscardedValue=*/true);
  7808. if (AssignmentOp.isInvalid())
  7809. continue;
  7810. DSAStack->addDSA(VD, DE, OMPC_copyin);
  7811. Vars.push_back(DE);
  7812. SrcExprs.push_back(PseudoSrcExpr);
  7813. DstExprs.push_back(PseudoDstExpr);
  7814. AssignmentOps.push_back(AssignmentOp.get());
  7815. }
  7816. if (Vars.empty())
  7817. return nullptr;
  7818. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  7819. SrcExprs, DstExprs, AssignmentOps);
  7820. }
  7821. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  7822. SourceLocation StartLoc,
  7823. SourceLocation LParenLoc,
  7824. SourceLocation EndLoc) {
  7825. SmallVector<Expr *, 8> Vars;
  7826. SmallVector<Expr *, 8> SrcExprs;
  7827. SmallVector<Expr *, 8> DstExprs;
  7828. SmallVector<Expr *, 8> AssignmentOps;
  7829. for (auto &RefExpr : VarList) {
  7830. assert(RefExpr && "NULL expr in OpenMP copyprivate clause.");
  7831. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  7832. // It will be analyzed later.
  7833. Vars.push_back(RefExpr);
  7834. SrcExprs.push_back(nullptr);
  7835. DstExprs.push_back(nullptr);
  7836. AssignmentOps.push_back(nullptr);
  7837. continue;
  7838. }
  7839. SourceLocation ELoc = RefExpr->getExprLoc();
  7840. // OpenMP [2.1, C/C++]
  7841. // A list item is a variable name.
  7842. // OpenMP [2.14.4.1, Restrictions, p.1]
  7843. // A list item that appears in a copyin clause must be threadprivate.
  7844. DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
  7845. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  7846. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  7847. << 0 << RefExpr->getSourceRange();
  7848. continue;
  7849. }
  7850. Decl *D = DE->getDecl();
  7851. VarDecl *VD = cast<VarDecl>(D);
  7852. QualType Type = VD->getType();
  7853. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  7854. // It will be analyzed later.
  7855. Vars.push_back(DE);
  7856. SrcExprs.push_back(nullptr);
  7857. DstExprs.push_back(nullptr);
  7858. AssignmentOps.push_back(nullptr);
  7859. continue;
  7860. }
  7861. // OpenMP [2.14.4.2, Restrictions, p.2]
  7862. // A list item that appears in a copyprivate clause may not appear in a
  7863. // private or firstprivate clause on the single construct.
  7864. if (!DSAStack->isThreadPrivate(VD)) {
  7865. auto DVar = DSAStack->getTopDSA(VD, false);
  7866. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  7867. DVar.RefExpr) {
  7868. Diag(ELoc, diag::err_omp_wrong_dsa)
  7869. << getOpenMPClauseName(DVar.CKind)
  7870. << getOpenMPClauseName(OMPC_copyprivate);
  7871. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  7872. continue;
  7873. }
  7874. // OpenMP [2.11.4.2, Restrictions, p.1]
  7875. // All list items that appear in a copyprivate clause must be either
  7876. // threadprivate or private in the enclosing context.
  7877. if (DVar.CKind == OMPC_unknown) {
  7878. DVar = DSAStack->getImplicitDSA(VD, false);
  7879. if (DVar.CKind == OMPC_shared) {
  7880. Diag(ELoc, diag::err_omp_required_access)
  7881. << getOpenMPClauseName(OMPC_copyprivate)
  7882. << "threadprivate or private in the enclosing context";
  7883. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  7884. continue;
  7885. }
  7886. }
  7887. }
  7888. // Variably modified types are not supported.
  7889. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  7890. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  7891. << getOpenMPClauseName(OMPC_copyprivate) << Type
  7892. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  7893. bool IsDecl =
  7894. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  7895. Diag(VD->getLocation(),
  7896. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  7897. << VD;
  7898. continue;
  7899. }
  7900. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  7901. // A variable of class type (or array thereof) that appears in a
  7902. // copyin clause requires an accessible, unambiguous copy assignment
  7903. // operator for the class type.
  7904. Type = Context.getBaseElementType(Type.getNonReferenceType())
  7905. .getUnqualifiedType();
  7906. auto *SrcVD =
  7907. buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.src",
  7908. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  7909. auto *PseudoSrcExpr =
  7910. buildDeclRefExpr(*this, SrcVD, Type, DE->getExprLoc());
  7911. auto *DstVD =
  7912. buildVarDecl(*this, DE->getLocStart(), Type, ".copyprivate.dst",
  7913. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  7914. auto *PseudoDstExpr =
  7915. buildDeclRefExpr(*this, DstVD, Type, DE->getExprLoc());
  7916. auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
  7917. PseudoDstExpr, PseudoSrcExpr);
  7918. if (AssignmentOp.isInvalid())
  7919. continue;
  7920. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  7921. /*DiscardedValue=*/true);
  7922. if (AssignmentOp.isInvalid())
  7923. continue;
  7924. // No need to mark vars as copyprivate, they are already threadprivate or
  7925. // implicitly private.
  7926. Vars.push_back(DE);
  7927. SrcExprs.push_back(PseudoSrcExpr);
  7928. DstExprs.push_back(PseudoDstExpr);
  7929. AssignmentOps.push_back(AssignmentOp.get());
  7930. }
  7931. if (Vars.empty())
  7932. return nullptr;
  7933. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  7934. Vars, SrcExprs, DstExprs, AssignmentOps);
  7935. }
  7936. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  7937. SourceLocation StartLoc,
  7938. SourceLocation LParenLoc,
  7939. SourceLocation EndLoc) {
  7940. if (VarList.empty())
  7941. return nullptr;
  7942. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  7943. }
  7944. OMPClause *
  7945. Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
  7946. SourceLocation DepLoc, SourceLocation ColonLoc,
  7947. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  7948. SourceLocation LParenLoc, SourceLocation EndLoc) {
  7949. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  7950. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  7951. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  7952. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  7953. return nullptr;
  7954. }
  7955. if (DSAStack->getCurrentDirective() != OMPD_ordered &&
  7956. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  7957. DepKind == OMPC_DEPEND_sink)) {
  7958. unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
  7959. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  7960. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  7961. /*Last=*/OMPC_DEPEND_unknown, Except)
  7962. << getOpenMPClauseName(OMPC_depend);
  7963. return nullptr;
  7964. }
  7965. SmallVector<Expr *, 8> Vars;
  7966. llvm::APSInt DepCounter(/*BitWidth=*/32);
  7967. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  7968. if (DepKind == OMPC_DEPEND_sink) {
  7969. if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
  7970. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  7971. TotalDepCount.setIsUnsigned(/*Val=*/true);
  7972. }
  7973. }
  7974. if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
  7975. DSAStack->getParentOrderedRegionParam()) {
  7976. for (auto &RefExpr : VarList) {
  7977. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  7978. if (isa<DependentScopeDeclRefExpr>(RefExpr) ||
  7979. (DepKind == OMPC_DEPEND_sink && CurContext->isDependentContext())) {
  7980. // It will be analyzed later.
  7981. Vars.push_back(RefExpr);
  7982. continue;
  7983. }
  7984. SourceLocation ELoc = RefExpr->getExprLoc();
  7985. auto *SimpleExpr = RefExpr->IgnoreParenCasts();
  7986. if (DepKind == OMPC_DEPEND_sink) {
  7987. if (DepCounter >= TotalDepCount) {
  7988. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  7989. continue;
  7990. }
  7991. ++DepCounter;
  7992. // OpenMP [2.13.9, Summary]
  7993. // depend(dependence-type : vec), where dependence-type is:
  7994. // 'sink' and where vec is the iteration vector, which has the form:
  7995. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  7996. // where n is the value specified by the ordered clause in the loop
  7997. // directive, xi denotes the loop iteration variable of the i-th nested
  7998. // loop associated with the loop directive, and di is a constant
  7999. // non-negative integer.
  8000. SimpleExpr = SimpleExpr->IgnoreImplicit();
  8001. auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
  8002. if (!DE) {
  8003. OverloadedOperatorKind OOK = OO_None;
  8004. SourceLocation OOLoc;
  8005. Expr *LHS, *RHS;
  8006. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  8007. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  8008. OOLoc = BO->getOperatorLoc();
  8009. LHS = BO->getLHS()->IgnoreParenImpCasts();
  8010. RHS = BO->getRHS()->IgnoreParenImpCasts();
  8011. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  8012. OOK = OCE->getOperator();
  8013. OOLoc = OCE->getOperatorLoc();
  8014. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  8015. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  8016. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  8017. OOK = MCE->getMethodDecl()
  8018. ->getNameInfo()
  8019. .getName()
  8020. .getCXXOverloadedOperator();
  8021. OOLoc = MCE->getCallee()->getExprLoc();
  8022. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  8023. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  8024. } else {
  8025. Diag(ELoc, diag::err_omp_depend_sink_wrong_expr);
  8026. continue;
  8027. }
  8028. DE = dyn_cast<DeclRefExpr>(LHS);
  8029. if (!DE) {
  8030. Diag(LHS->getExprLoc(),
  8031. diag::err_omp_depend_sink_expected_loop_iteration)
  8032. << DSAStack->getParentLoopControlVariable(
  8033. DepCounter.getZExtValue());
  8034. continue;
  8035. }
  8036. if (OOK != OO_Plus && OOK != OO_Minus) {
  8037. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  8038. continue;
  8039. }
  8040. ExprResult Res = VerifyPositiveIntegerConstantInClause(
  8041. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  8042. if (Res.isInvalid())
  8043. continue;
  8044. }
  8045. auto *VD = dyn_cast<VarDecl>(DE->getDecl());
  8046. if (!CurContext->isDependentContext() &&
  8047. DSAStack->getParentOrderedRegionParam() &&
  8048. (!VD || DepCounter != DSAStack->isParentLoopControlVariable(VD))) {
  8049. Diag(DE->getExprLoc(),
  8050. diag::err_omp_depend_sink_expected_loop_iteration)
  8051. << DSAStack->getParentLoopControlVariable(
  8052. DepCounter.getZExtValue());
  8053. continue;
  8054. }
  8055. } else {
  8056. // OpenMP [2.11.1.1, Restrictions, p.3]
  8057. // A variable that is part of another variable (such as a field of a
  8058. // structure) but is not an array element or an array section cannot
  8059. // appear in a depend clause.
  8060. auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr);
  8061. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  8062. auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
  8063. if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  8064. (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) ||
  8065. (ASE && !ASE->getBase()->getType()->isAnyPointerType() &&
  8066. !ASE->getBase()->getType()->isArrayType())) {
  8067. Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item)
  8068. << 0 << RefExpr->getSourceRange();
  8069. continue;
  8070. }
  8071. }
  8072. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  8073. }
  8074. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  8075. TotalDepCount > VarList.size() &&
  8076. DSAStack->getParentOrderedRegionParam()) {
  8077. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
  8078. << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  8079. }
  8080. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  8081. Vars.empty())
  8082. return nullptr;
  8083. }
  8084. return OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, DepKind,
  8085. DepLoc, ColonLoc, Vars);
  8086. }
  8087. OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
  8088. SourceLocation LParenLoc,
  8089. SourceLocation EndLoc) {
  8090. Expr *ValExpr = Device;
  8091. // OpenMP [2.9.1, Restrictions]
  8092. // The device expression must evaluate to a non-negative integer value.
  8093. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  8094. /*StrictlyPositive=*/false))
  8095. return nullptr;
  8096. return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  8097. }
  8098. static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc,
  8099. DSAStackTy *Stack, CXXRecordDecl *RD) {
  8100. if (!RD || RD->isInvalidDecl())
  8101. return true;
  8102. if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
  8103. if (auto *CTD = CTSD->getSpecializedTemplate())
  8104. RD = CTD->getTemplatedDecl();
  8105. auto QTy = SemaRef.Context.getRecordType(RD);
  8106. if (RD->isDynamicClass()) {
  8107. SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
  8108. SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target);
  8109. return false;
  8110. }
  8111. auto *DC = RD;
  8112. bool IsCorrect = true;
  8113. for (auto *I : DC->decls()) {
  8114. if (I) {
  8115. if (auto *MD = dyn_cast<CXXMethodDecl>(I)) {
  8116. if (MD->isStatic()) {
  8117. SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
  8118. SemaRef.Diag(MD->getLocation(),
  8119. diag::note_omp_static_member_in_target);
  8120. IsCorrect = false;
  8121. }
  8122. } else if (auto *VD = dyn_cast<VarDecl>(I)) {
  8123. if (VD->isStaticDataMember()) {
  8124. SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy;
  8125. SemaRef.Diag(VD->getLocation(),
  8126. diag::note_omp_static_member_in_target);
  8127. IsCorrect = false;
  8128. }
  8129. }
  8130. }
  8131. }
  8132. for (auto &I : RD->bases()) {
  8133. if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack,
  8134. I.getType()->getAsCXXRecordDecl()))
  8135. IsCorrect = false;
  8136. }
  8137. return IsCorrect;
  8138. }
  8139. static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  8140. DSAStackTy *Stack, QualType QTy) {
  8141. NamedDecl *ND;
  8142. if (QTy->isIncompleteType(&ND)) {
  8143. SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
  8144. return false;
  8145. } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) {
  8146. if (!RD->isInvalidDecl() &&
  8147. !IsCXXRecordForMappable(SemaRef, SL, Stack, RD))
  8148. return false;
  8149. }
  8150. return true;
  8151. }
  8152. // Return the expression of the base of the map clause or null if it cannot
  8153. // be determined and do all the necessary checks to see if the expression is
  8154. // valid as a standalone map clause expression.
  8155. static Expr *CheckMapClauseExpressionBase(Sema &SemaRef, Expr *E) {
  8156. SourceLocation ELoc = E->getExprLoc();
  8157. SourceRange ERange = E->getSourceRange();
  8158. // The base of elements of list in a map clause have to be either:
  8159. // - a reference to variable or field.
  8160. // - a member expression.
  8161. // - an array expression.
  8162. //
  8163. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  8164. // reference to 'r'.
  8165. //
  8166. // If we have:
  8167. //
  8168. // struct SS {
  8169. // Bla S;
  8170. // foo() {
  8171. // #pragma omp target map (S.Arr[:12]);
  8172. // }
  8173. // }
  8174. //
  8175. // We want to retrieve the member expression 'this->S';
  8176. Expr *RelevantExpr = nullptr;
  8177. // Flags to help capture some memory
  8178. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
  8179. // If a list item is an array section, it must specify contiguous storage.
  8180. //
  8181. // For this restriction it is sufficient that we make sure only references
  8182. // to variables or fields and array expressions, and that no array sections
  8183. // exist except in the rightmost expression. E.g. these would be invalid:
  8184. //
  8185. // r.ArrS[3:5].Arr[6:7]
  8186. //
  8187. // r.ArrS[3:5].x
  8188. //
  8189. // but these would be valid:
  8190. // r.ArrS[3].Arr[6:7]
  8191. //
  8192. // r.ArrS[3].x
  8193. bool IsRightMostExpression = true;
  8194. while (!RelevantExpr) {
  8195. auto AllowArraySection = IsRightMostExpression;
  8196. IsRightMostExpression = false;
  8197. E = E->IgnoreParenImpCasts();
  8198. if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
  8199. if (!isa<VarDecl>(CurE->getDecl()))
  8200. break;
  8201. RelevantExpr = CurE;
  8202. continue;
  8203. }
  8204. if (auto *CurE = dyn_cast<MemberExpr>(E)) {
  8205. auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  8206. if (isa<CXXThisExpr>(BaseE))
  8207. // We found a base expression: this->Val.
  8208. RelevantExpr = CurE;
  8209. else
  8210. E = BaseE;
  8211. if (!isa<FieldDecl>(CurE->getMemberDecl())) {
  8212. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  8213. << CurE->getSourceRange();
  8214. break;
  8215. }
  8216. auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
  8217. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  8218. // A bit-field cannot appear in a map clause.
  8219. //
  8220. if (FD->isBitField()) {
  8221. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_map_clause)
  8222. << CurE->getSourceRange();
  8223. break;
  8224. }
  8225. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  8226. // If the type of a list item is a reference to a type T then the type
  8227. // will be considered to be T for all purposes of this clause.
  8228. QualType CurType = BaseE->getType();
  8229. if (CurType->isReferenceType())
  8230. CurType = CurType->getPointeeType();
  8231. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  8232. // A list item cannot be a variable that is a member of a structure with
  8233. // a union type.
  8234. //
  8235. if (auto *RT = CurType->getAs<RecordType>())
  8236. if (RT->isUnionType()) {
  8237. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  8238. << CurE->getSourceRange();
  8239. break;
  8240. }
  8241. continue;
  8242. }
  8243. if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
  8244. E = CurE->getBase()->IgnoreParenImpCasts();
  8245. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  8246. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  8247. << 0 << CurE->getSourceRange();
  8248. break;
  8249. }
  8250. continue;
  8251. }
  8252. if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
  8253. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  8254. // If a list item is an element of a structure, only the rightmost symbol
  8255. // of the variable reference can be an array section.
  8256. //
  8257. if (!AllowArraySection) {
  8258. SemaRef.Diag(ELoc, diag::err_omp_array_section_in_rightmost_expression)
  8259. << CurE->getSourceRange();
  8260. break;
  8261. }
  8262. E = CurE->getBase()->IgnoreParenImpCasts();
  8263. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  8264. // If the type of a list item is a reference to a type T then the type
  8265. // will be considered to be T for all purposes of this clause.
  8266. QualType CurType = E->getType();
  8267. if (CurType->isReferenceType())
  8268. CurType = CurType->getPointeeType();
  8269. if (!CurType->isAnyPointerType() && !CurType->isArrayType()) {
  8270. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  8271. << 0 << CurE->getSourceRange();
  8272. break;
  8273. }
  8274. continue;
  8275. }
  8276. // If nothing else worked, this is not a valid map clause expression.
  8277. SemaRef.Diag(ELoc,
  8278. diag::err_omp_expected_named_var_member_or_array_expression)
  8279. << ERange;
  8280. break;
  8281. }
  8282. return RelevantExpr;
  8283. }
  8284. // Return true if expression E associated with value VD has conflicts with other
  8285. // map information.
  8286. static bool CheckMapConflicts(Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD,
  8287. Expr *E, bool CurrentRegionOnly) {
  8288. assert(VD && E);
  8289. // Types used to organize the components of a valid map clause.
  8290. typedef std::pair<Expr *, ValueDecl *> MapExpressionComponent;
  8291. typedef SmallVector<MapExpressionComponent, 4> MapExpressionComponents;
  8292. // Helper to extract the components in the map clause expression E and store
  8293. // them into MEC. This assumes that E is a valid map clause expression, i.e.
  8294. // it has already passed the single clause checks.
  8295. auto ExtractMapExpressionComponents = [](Expr *TE,
  8296. MapExpressionComponents &MEC) {
  8297. while (true) {
  8298. TE = TE->IgnoreParenImpCasts();
  8299. if (auto *CurE = dyn_cast<DeclRefExpr>(TE)) {
  8300. MEC.push_back(
  8301. MapExpressionComponent(CurE, cast<VarDecl>(CurE->getDecl())));
  8302. break;
  8303. }
  8304. if (auto *CurE = dyn_cast<MemberExpr>(TE)) {
  8305. auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
  8306. MEC.push_back(MapExpressionComponent(
  8307. CurE, cast<FieldDecl>(CurE->getMemberDecl())));
  8308. if (isa<CXXThisExpr>(BaseE))
  8309. break;
  8310. TE = BaseE;
  8311. continue;
  8312. }
  8313. if (auto *CurE = dyn_cast<ArraySubscriptExpr>(TE)) {
  8314. MEC.push_back(MapExpressionComponent(CurE, nullptr));
  8315. TE = CurE->getBase()->IgnoreParenImpCasts();
  8316. continue;
  8317. }
  8318. if (auto *CurE = dyn_cast<OMPArraySectionExpr>(TE)) {
  8319. MEC.push_back(MapExpressionComponent(CurE, nullptr));
  8320. TE = CurE->getBase()->IgnoreParenImpCasts();
  8321. continue;
  8322. }
  8323. llvm_unreachable(
  8324. "Expecting only valid map clause expressions at this point!");
  8325. }
  8326. };
  8327. SourceLocation ELoc = E->getExprLoc();
  8328. SourceRange ERange = E->getSourceRange();
  8329. // In order to easily check the conflicts we need to match each component of
  8330. // the expression under test with the components of the expressions that are
  8331. // already in the stack.
  8332. MapExpressionComponents CurComponents;
  8333. ExtractMapExpressionComponents(E, CurComponents);
  8334. assert(!CurComponents.empty() && "Map clause expression with no components!");
  8335. assert(CurComponents.back().second == VD &&
  8336. "Map clause expression with unexpected base!");
  8337. // Variables to help detecting enclosing problems in data environment nests.
  8338. bool IsEnclosedByDataEnvironmentExpr = false;
  8339. Expr *EnclosingExpr = nullptr;
  8340. bool FoundError =
  8341. DSAS->checkMapInfoForVar(VD, CurrentRegionOnly, [&](Expr *RE) -> bool {
  8342. MapExpressionComponents StackComponents;
  8343. ExtractMapExpressionComponents(RE, StackComponents);
  8344. assert(!StackComponents.empty() &&
  8345. "Map clause expression with no components!");
  8346. assert(StackComponents.back().second == VD &&
  8347. "Map clause expression with unexpected base!");
  8348. // Expressions must start from the same base. Here we detect at which
  8349. // point both expressions diverge from each other and see if we can
  8350. // detect if the memory referred to both expressions is contiguous and
  8351. // do not overlap.
  8352. auto CI = CurComponents.rbegin();
  8353. auto CE = CurComponents.rend();
  8354. auto SI = StackComponents.rbegin();
  8355. auto SE = StackComponents.rend();
  8356. for (; CI != CE && SI != SE; ++CI, ++SI) {
  8357. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  8358. // At most one list item can be an array item derived from a given
  8359. // variable in map clauses of the same construct.
  8360. if (CurrentRegionOnly && (isa<ArraySubscriptExpr>(CI->first) ||
  8361. isa<OMPArraySectionExpr>(CI->first)) &&
  8362. (isa<ArraySubscriptExpr>(SI->first) ||
  8363. isa<OMPArraySectionExpr>(SI->first))) {
  8364. SemaRef.Diag(CI->first->getExprLoc(),
  8365. diag::err_omp_multiple_array_items_in_map_clause)
  8366. << CI->first->getSourceRange();
  8367. ;
  8368. SemaRef.Diag(SI->first->getExprLoc(), diag::note_used_here)
  8369. << SI->first->getSourceRange();
  8370. return true;
  8371. }
  8372. // Do both expressions have the same kind?
  8373. if (CI->first->getStmtClass() != SI->first->getStmtClass())
  8374. break;
  8375. // Are we dealing with different variables/fields?
  8376. if (CI->second != SI->second)
  8377. break;
  8378. }
  8379. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  8380. // List items of map clauses in the same construct must not share
  8381. // original storage.
  8382. //
  8383. // If the expressions are exactly the same or one is a subset of the
  8384. // other, it means they are sharing storage.
  8385. if (CI == CE && SI == SE) {
  8386. if (CurrentRegionOnly) {
  8387. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  8388. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  8389. << RE->getSourceRange();
  8390. return true;
  8391. } else {
  8392. // If we find the same expression in the enclosing data environment,
  8393. // that is legal.
  8394. IsEnclosedByDataEnvironmentExpr = true;
  8395. return false;
  8396. }
  8397. }
  8398. QualType DerivedType = std::prev(CI)->first->getType();
  8399. SourceLocation DerivedLoc = std::prev(CI)->first->getExprLoc();
  8400. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  8401. // If the type of a list item is a reference to a type T then the type
  8402. // will be considered to be T for all purposes of this clause.
  8403. if (DerivedType->isReferenceType())
  8404. DerivedType = DerivedType->getPointeeType();
  8405. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  8406. // A variable for which the type is pointer and an array section
  8407. // derived from that variable must not appear as list items of map
  8408. // clauses of the same construct.
  8409. //
  8410. // Also, cover one of the cases in:
  8411. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  8412. // If any part of the original storage of a list item has corresponding
  8413. // storage in the device data environment, all of the original storage
  8414. // must have corresponding storage in the device data environment.
  8415. //
  8416. if (DerivedType->isAnyPointerType()) {
  8417. if (CI == CE || SI == SE) {
  8418. SemaRef.Diag(
  8419. DerivedLoc,
  8420. diag::err_omp_pointer_mapped_along_with_derived_section)
  8421. << DerivedLoc;
  8422. } else {
  8423. assert(CI != CE && SI != SE);
  8424. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
  8425. << DerivedLoc;
  8426. }
  8427. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  8428. << RE->getSourceRange();
  8429. return true;
  8430. }
  8431. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  8432. // List items of map clauses in the same construct must not share
  8433. // original storage.
  8434. //
  8435. // An expression is a subset of the other.
  8436. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  8437. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  8438. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  8439. << RE->getSourceRange();
  8440. return true;
  8441. }
  8442. // The current expression uses the same base as other expression in the
  8443. // data environment but does not contain it completelly.
  8444. if (!CurrentRegionOnly && SI != SE)
  8445. EnclosingExpr = RE;
  8446. // The current expression is a subset of the expression in the data
  8447. // environment.
  8448. IsEnclosedByDataEnvironmentExpr |=
  8449. (!CurrentRegionOnly && CI != CE && SI == SE);
  8450. return false;
  8451. });
  8452. if (CurrentRegionOnly)
  8453. return FoundError;
  8454. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  8455. // If any part of the original storage of a list item has corresponding
  8456. // storage in the device data environment, all of the original storage must
  8457. // have corresponding storage in the device data environment.
  8458. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  8459. // If a list item is an element of a structure, and a different element of
  8460. // the structure has a corresponding list item in the device data environment
  8461. // prior to a task encountering the construct associated with the map clause,
  8462. // then the list item must also have a correspnding list item in the device
  8463. // data environment prior to the task encountering the construct.
  8464. //
  8465. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  8466. SemaRef.Diag(ELoc,
  8467. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  8468. << ERange;
  8469. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  8470. << EnclosingExpr->getSourceRange();
  8471. return true;
  8472. }
  8473. return FoundError;
  8474. }
  8475. OMPClause *
  8476. Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
  8477. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
  8478. SourceLocation MapLoc, SourceLocation ColonLoc,
  8479. ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  8480. SourceLocation LParenLoc, SourceLocation EndLoc) {
  8481. SmallVector<Expr *, 4> Vars;
  8482. for (auto &RE : VarList) {
  8483. assert(RE && "Null expr in omp map");
  8484. if (isa<DependentScopeDeclRefExpr>(RE)) {
  8485. // It will be analyzed later.
  8486. Vars.push_back(RE);
  8487. continue;
  8488. }
  8489. SourceLocation ELoc = RE->getExprLoc();
  8490. auto *VE = RE->IgnoreParenLValueCasts();
  8491. if (VE->isValueDependent() || VE->isTypeDependent() ||
  8492. VE->isInstantiationDependent() ||
  8493. VE->containsUnexpandedParameterPack()) {
  8494. // We can only analyze this information once the missing information is
  8495. // resolved.
  8496. Vars.push_back(RE);
  8497. continue;
  8498. }
  8499. auto *SimpleExpr = RE->IgnoreParenCasts();
  8500. if (!RE->IgnoreParenImpCasts()->isLValue()) {
  8501. Diag(ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  8502. << RE->getSourceRange();
  8503. continue;
  8504. }
  8505. // Obtain the array or member expression bases if required.
  8506. auto *BE = CheckMapClauseExpressionBase(*this, SimpleExpr);
  8507. if (!BE)
  8508. continue;
  8509. // If the base is a reference to a variable, we rely on that variable for
  8510. // the following checks. If it is a 'this' expression we rely on the field.
  8511. ValueDecl *D = nullptr;
  8512. if (auto *DRE = dyn_cast<DeclRefExpr>(BE)) {
  8513. D = DRE->getDecl();
  8514. } else {
  8515. auto *ME = cast<MemberExpr>(BE);
  8516. assert(isa<CXXThisExpr>(ME->getBase()) && "Unexpected expression!");
  8517. D = ME->getMemberDecl();
  8518. }
  8519. assert(D && "Null decl on map clause.");
  8520. auto *VD = dyn_cast<VarDecl>(D);
  8521. auto *FD = dyn_cast<FieldDecl>(D);
  8522. assert((VD || FD) && "Only variables or fields are expected here!");
  8523. (void)FD;
  8524. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  8525. // threadprivate variables cannot appear in a map clause.
  8526. if (VD && DSAStack->isThreadPrivate(VD)) {
  8527. auto DVar = DSAStack->getTopDSA(VD, false);
  8528. Diag(ELoc, diag::err_omp_threadprivate_in_map);
  8529. ReportOriginalDSA(*this, DSAStack, VD, DVar);
  8530. continue;
  8531. }
  8532. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  8533. // A list item cannot appear in both a map clause and a data-sharing
  8534. // attribute clause on the same construct.
  8535. //
  8536. // TODO: Implement this check - it cannot currently be tested because of
  8537. // missing implementation of the other data sharing clauses in target
  8538. // directives.
  8539. // Check conflicts with other map clause expressions. We check the conflicts
  8540. // with the current construct separately from the enclosing data
  8541. // environment, because the restrictions are different.
  8542. if (CheckMapConflicts(*this, DSAStack, D, SimpleExpr,
  8543. /*CurrentRegionOnly=*/true))
  8544. break;
  8545. if (CheckMapConflicts(*this, DSAStack, D, SimpleExpr,
  8546. /*CurrentRegionOnly=*/false))
  8547. break;
  8548. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  8549. // If the type of a list item is a reference to a type T then the type will
  8550. // be considered to be T for all purposes of this clause.
  8551. QualType Type = D->getType();
  8552. if (Type->isReferenceType())
  8553. Type = Type->getPointeeType();
  8554. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  8555. // A list item must have a mappable type.
  8556. if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), *this,
  8557. DSAStack, Type))
  8558. continue;
  8559. // target enter data
  8560. // OpenMP [2.10.2, Restrictions, p. 99]
  8561. // A map-type must be specified in all map clauses and must be either
  8562. // to or alloc.
  8563. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  8564. if (DKind == OMPD_target_enter_data &&
  8565. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
  8566. Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  8567. << (IsMapTypeImplicit ? 1 : 0)
  8568. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  8569. << getOpenMPDirectiveName(DKind);
  8570. continue;
  8571. }
  8572. // target exit_data
  8573. // OpenMP [2.10.3, Restrictions, p. 102]
  8574. // A map-type must be specified in all map clauses and must be either
  8575. // from, release, or delete.
  8576. DKind = DSAStack->getCurrentDirective();
  8577. if (DKind == OMPD_target_exit_data &&
  8578. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  8579. MapType == OMPC_MAP_delete)) {
  8580. Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  8581. << (IsMapTypeImplicit ? 1 : 0)
  8582. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  8583. << getOpenMPDirectiveName(DKind);
  8584. continue;
  8585. }
  8586. Vars.push_back(RE);
  8587. DSAStack->addExprToVarMapInfo(D, RE);
  8588. }
  8589. // We need to produce a map clause even if we don't have variables so that
  8590. // other diagnostics related with non-existing map clauses are accurate.
  8591. return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  8592. MapTypeModifier, MapType, IsMapTypeImplicit,
  8593. MapLoc);
  8594. }
  8595. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  8596. SourceLocation StartLoc,
  8597. SourceLocation LParenLoc,
  8598. SourceLocation EndLoc) {
  8599. Expr *ValExpr = NumTeams;
  8600. // OpenMP [teams Constrcut, Restrictions]
  8601. // The num_teams expression must evaluate to a positive integer value.
  8602. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  8603. /*StrictlyPositive=*/true))
  8604. return nullptr;
  8605. return new (Context) OMPNumTeamsClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  8606. }
  8607. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  8608. SourceLocation StartLoc,
  8609. SourceLocation LParenLoc,
  8610. SourceLocation EndLoc) {
  8611. Expr *ValExpr = ThreadLimit;
  8612. // OpenMP [teams Constrcut, Restrictions]
  8613. // The thread_limit expression must evaluate to a positive integer value.
  8614. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  8615. /*StrictlyPositive=*/true))
  8616. return nullptr;
  8617. return new (Context) OMPThreadLimitClause(ValExpr, StartLoc, LParenLoc,
  8618. EndLoc);
  8619. }
  8620. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  8621. SourceLocation StartLoc,
  8622. SourceLocation LParenLoc,
  8623. SourceLocation EndLoc) {
  8624. Expr *ValExpr = Priority;
  8625. // OpenMP [2.9.1, task Constrcut]
  8626. // The priority-value is a non-negative numerical scalar expression.
  8627. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
  8628. /*StrictlyPositive=*/false))
  8629. return nullptr;
  8630. return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  8631. }
  8632. OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
  8633. SourceLocation StartLoc,
  8634. SourceLocation LParenLoc,
  8635. SourceLocation EndLoc) {
  8636. Expr *ValExpr = Grainsize;
  8637. // OpenMP [2.9.2, taskloop Constrcut]
  8638. // The parameter of the grainsize clause must be a positive integer
  8639. // expression.
  8640. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  8641. /*StrictlyPositive=*/true))
  8642. return nullptr;
  8643. return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  8644. }
  8645. OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
  8646. SourceLocation StartLoc,
  8647. SourceLocation LParenLoc,
  8648. SourceLocation EndLoc) {
  8649. Expr *ValExpr = NumTasks;
  8650. // OpenMP [2.9.2, taskloop Constrcut]
  8651. // The parameter of the num_tasks clause must be a positive integer
  8652. // expression.
  8653. if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
  8654. /*StrictlyPositive=*/true))
  8655. return nullptr;
  8656. return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
  8657. }
  8658. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  8659. SourceLocation LParenLoc,
  8660. SourceLocation EndLoc) {
  8661. // OpenMP [2.13.2, critical construct, Description]
  8662. // ... where hint-expression is an integer constant expression that evaluates
  8663. // to a valid lock hint.
  8664. ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
  8665. if (HintExpr.isInvalid())
  8666. return nullptr;
  8667. return new (Context)
  8668. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  8669. }
  8670. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  8671. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  8672. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  8673. SourceLocation EndLoc) {
  8674. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  8675. std::string Values;
  8676. Values += "'";
  8677. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  8678. Values += "'";
  8679. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  8680. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  8681. return nullptr;
  8682. }
  8683. Expr *ValExpr = ChunkSize;
  8684. Expr *HelperValExpr = nullptr;
  8685. if (ChunkSize) {
  8686. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  8687. !ChunkSize->isInstantiationDependent() &&
  8688. !ChunkSize->containsUnexpandedParameterPack()) {
  8689. SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
  8690. ExprResult Val =
  8691. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  8692. if (Val.isInvalid())
  8693. return nullptr;
  8694. ValExpr = Val.get();
  8695. // OpenMP [2.7.1, Restrictions]
  8696. // chunk_size must be a loop invariant integer expression with a positive
  8697. // value.
  8698. llvm::APSInt Result;
  8699. if (ValExpr->isIntegerConstantExpr(Result, Context)) {
  8700. if (Result.isSigned() && !Result.isStrictlyPositive()) {
  8701. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  8702. << "dist_schedule" << ChunkSize->getSourceRange();
  8703. return nullptr;
  8704. }
  8705. } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) {
  8706. auto *ImpVar = buildVarDecl(*this, ChunkSize->getExprLoc(),
  8707. ChunkSize->getType(), ".chunk.");
  8708. auto *ImpVarRef = buildDeclRefExpr(*this, ImpVar, ChunkSize->getType(),
  8709. ChunkSize->getExprLoc(),
  8710. /*RefersToCapture=*/true);
  8711. HelperValExpr = ImpVarRef;
  8712. }
  8713. }
  8714. }
  8715. return new (Context)
  8716. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  8717. Kind, ValExpr, HelperValExpr);
  8718. }
  8719. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  8720. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  8721. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  8722. SourceLocation KindLoc, SourceLocation EndLoc) {
  8723. // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
  8724. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
  8725. Kind != OMPC_DEFAULTMAP_scalar) {
  8726. std::string Value;
  8727. SourceLocation Loc;
  8728. Value += "'";
  8729. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  8730. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  8731. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  8732. Loc = MLoc;
  8733. } else {
  8734. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  8735. OMPC_DEFAULTMAP_scalar);
  8736. Loc = KindLoc;
  8737. }
  8738. Value += "'";
  8739. Diag(Loc, diag::err_omp_unexpected_clause_value)
  8740. << Value << getOpenMPClauseName(OMPC_defaultmap);
  8741. return nullptr;
  8742. }
  8743. return new (Context)
  8744. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  8745. }