SemaOpenMP.cpp 945 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853
  1. //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. /// \file
  9. /// This file implements semantic analysis for OpenMP directives and
  10. /// clauses.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "TreeTransform.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/Decl.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/DeclOpenMP.h"
  20. #include "clang/AST/OpenMPClause.h"
  21. #include "clang/AST/StmtCXX.h"
  22. #include "clang/AST/StmtOpenMP.h"
  23. #include "clang/AST/StmtVisitor.h"
  24. #include "clang/AST/TypeOrdering.h"
  25. #include "clang/Basic/DiagnosticSema.h"
  26. #include "clang/Basic/OpenMPKinds.h"
  27. #include "clang/Basic/PartialDiagnostic.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/Sema/Initialization.h"
  30. #include "clang/Sema/Lookup.h"
  31. #include "clang/Sema/Scope.h"
  32. #include "clang/Sema/ScopeInfo.h"
  33. #include "clang/Sema/SemaInternal.h"
  34. #include "llvm/ADT/IndexedMap.h"
  35. #include "llvm/ADT/PointerEmbeddedInt.h"
  36. #include "llvm/ADT/STLExtras.h"
  37. #include "llvm/ADT/SmallSet.h"
  38. #include "llvm/ADT/StringExtras.h"
  39. #include "llvm/Frontend/OpenMP/OMPAssume.h"
  40. #include "llvm/Frontend/OpenMP/OMPConstants.h"
  41. #include <optional>
  42. #include <set>
  43. using namespace clang;
  44. using namespace llvm::omp;
  45. //===----------------------------------------------------------------------===//
  46. // Stack of data-sharing attributes for variables
  47. //===----------------------------------------------------------------------===//
  48. static const Expr *checkMapClauseExpressionBase(
  49. Sema &SemaRef, Expr *E,
  50. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  51. OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose);
  52. namespace {
  53. /// Default data sharing attributes, which can be applied to directive.
  54. enum DefaultDataSharingAttributes {
  55. DSA_unspecified = 0, /// Data sharing attribute not specified.
  56. DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
  57. DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
  58. DSA_private = 1 << 2, /// Default data sharing attribute 'private'.
  59. DSA_firstprivate = 1 << 3, /// Default data sharing attribute 'firstprivate'.
  60. };
  61. /// Stack for tracking declarations used in OpenMP directives and
  62. /// clauses and their data-sharing attributes.
  63. class DSAStackTy {
  64. public:
  65. struct DSAVarData {
  66. OpenMPDirectiveKind DKind = OMPD_unknown;
  67. OpenMPClauseKind CKind = OMPC_unknown;
  68. unsigned Modifier = 0;
  69. const Expr *RefExpr = nullptr;
  70. DeclRefExpr *PrivateCopy = nullptr;
  71. SourceLocation ImplicitDSALoc;
  72. bool AppliedToPointee = false;
  73. DSAVarData() = default;
  74. DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
  75. const Expr *RefExpr, DeclRefExpr *PrivateCopy,
  76. SourceLocation ImplicitDSALoc, unsigned Modifier,
  77. bool AppliedToPointee)
  78. : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr),
  79. PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc),
  80. AppliedToPointee(AppliedToPointee) {}
  81. };
  82. using OperatorOffsetTy =
  83. llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
  84. using DoacrossDependMapTy =
  85. llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
  86. /// Kind of the declaration used in the uses_allocators clauses.
  87. enum class UsesAllocatorsDeclKind {
  88. /// Predefined allocator
  89. PredefinedAllocator,
  90. /// User-defined allocator
  91. UserDefinedAllocator,
  92. /// The declaration that represent allocator trait
  93. AllocatorTrait,
  94. };
  95. private:
  96. struct DSAInfo {
  97. OpenMPClauseKind Attributes = OMPC_unknown;
  98. unsigned Modifier = 0;
  99. /// Pointer to a reference expression and a flag which shows that the
  100. /// variable is marked as lastprivate(true) or not (false).
  101. llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
  102. DeclRefExpr *PrivateCopy = nullptr;
  103. /// true if the attribute is applied to the pointee, not the variable
  104. /// itself.
  105. bool AppliedToPointee = false;
  106. };
  107. using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
  108. using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
  109. using LCDeclInfo = std::pair<unsigned, VarDecl *>;
  110. using LoopControlVariablesMapTy =
  111. llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
  112. /// Struct that associates a component with the clause kind where they are
  113. /// found.
  114. struct MappedExprComponentTy {
  115. OMPClauseMappableExprCommon::MappableExprComponentLists Components;
  116. OpenMPClauseKind Kind = OMPC_unknown;
  117. };
  118. using MappedExprComponentsTy =
  119. llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
  120. using CriticalsWithHintsTy =
  121. llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
  122. struct ReductionData {
  123. using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
  124. SourceRange ReductionRange;
  125. llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
  126. ReductionData() = default;
  127. void set(BinaryOperatorKind BO, SourceRange RR) {
  128. ReductionRange = RR;
  129. ReductionOp = BO;
  130. }
  131. void set(const Expr *RefExpr, SourceRange RR) {
  132. ReductionRange = RR;
  133. ReductionOp = RefExpr;
  134. }
  135. };
  136. using DeclReductionMapTy =
  137. llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
  138. struct DefaultmapInfo {
  139. OpenMPDefaultmapClauseModifier ImplicitBehavior =
  140. OMPC_DEFAULTMAP_MODIFIER_unknown;
  141. SourceLocation SLoc;
  142. DefaultmapInfo() = default;
  143. DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
  144. : ImplicitBehavior(M), SLoc(Loc) {}
  145. };
  146. struct SharingMapTy {
  147. DeclSAMapTy SharingMap;
  148. DeclReductionMapTy ReductionMap;
  149. UsedRefMapTy AlignedMap;
  150. UsedRefMapTy NontemporalMap;
  151. MappedExprComponentsTy MappedExprComponents;
  152. LoopControlVariablesMapTy LCVMap;
  153. DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
  154. SourceLocation DefaultAttrLoc;
  155. DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
  156. OpenMPDirectiveKind Directive = OMPD_unknown;
  157. DeclarationNameInfo DirectiveName;
  158. Scope *CurScope = nullptr;
  159. DeclContext *Context = nullptr;
  160. SourceLocation ConstructLoc;
  161. /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
  162. /// get the data (loop counters etc.) about enclosing loop-based construct.
  163. /// This data is required during codegen.
  164. DoacrossDependMapTy DoacrossDepends;
  165. /// First argument (Expr *) contains optional argument of the
  166. /// 'ordered' clause, the second one is true if the regions has 'ordered'
  167. /// clause, false otherwise.
  168. std::optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
  169. bool RegionHasOrderConcurrent = false;
  170. unsigned AssociatedLoops = 1;
  171. bool HasMutipleLoops = false;
  172. const Decl *PossiblyLoopCounter = nullptr;
  173. bool NowaitRegion = false;
  174. bool UntiedRegion = false;
  175. bool CancelRegion = false;
  176. bool LoopStart = false;
  177. bool BodyComplete = false;
  178. SourceLocation PrevScanLocation;
  179. SourceLocation PrevOrderedLocation;
  180. SourceLocation InnerTeamsRegionLoc;
  181. /// Reference to the taskgroup task_reduction reference expression.
  182. Expr *TaskgroupReductionRef = nullptr;
  183. llvm::DenseSet<QualType> MappedClassesQualTypes;
  184. SmallVector<Expr *, 4> InnerUsedAllocators;
  185. llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates;
  186. /// List of globals marked as declare target link in this target region
  187. /// (isOpenMPTargetExecutionDirective(Directive) == true).
  188. llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
  189. /// List of decls used in inclusive/exclusive clauses of the scan directive.
  190. llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective;
  191. llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind>
  192. UsesAllocatorsDecls;
  193. /// Data is required on creating capture fields for implicit
  194. /// default first|private clause.
  195. struct ImplicitDefaultFDInfoTy {
  196. /// Field decl.
  197. const FieldDecl *FD = nullptr;
  198. /// Nesting stack level
  199. size_t StackLevel = 0;
  200. /// Capture variable decl.
  201. VarDecl *VD = nullptr;
  202. ImplicitDefaultFDInfoTy(const FieldDecl *FD, size_t StackLevel,
  203. VarDecl *VD)
  204. : FD(FD), StackLevel(StackLevel), VD(VD) {}
  205. };
  206. /// List of captured fields
  207. llvm::SmallVector<ImplicitDefaultFDInfoTy, 8>
  208. ImplicitDefaultFirstprivateFDs;
  209. Expr *DeclareMapperVar = nullptr;
  210. SmallVector<VarDecl *, 16> IteratorVarDecls;
  211. SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
  212. Scope *CurScope, SourceLocation Loc)
  213. : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
  214. ConstructLoc(Loc) {}
  215. SharingMapTy() = default;
  216. };
  217. using StackTy = SmallVector<SharingMapTy, 4>;
  218. /// Stack of used declaration and their data-sharing attributes.
  219. DeclSAMapTy Threadprivates;
  220. const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
  221. SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
  222. /// true, if check for DSA must be from parent directive, false, if
  223. /// from current directive.
  224. OpenMPClauseKind ClauseKindMode = OMPC_unknown;
  225. Sema &SemaRef;
  226. bool ForceCapturing = false;
  227. /// true if all the variables in the target executable directives must be
  228. /// captured by reference.
  229. bool ForceCaptureByReferenceInTargetExecutable = false;
  230. CriticalsWithHintsTy Criticals;
  231. unsigned IgnoredStackElements = 0;
  232. /// Iterators over the stack iterate in order from innermost to outermost
  233. /// directive.
  234. using const_iterator = StackTy::const_reverse_iterator;
  235. const_iterator begin() const {
  236. return Stack.empty() ? const_iterator()
  237. : Stack.back().first.rbegin() + IgnoredStackElements;
  238. }
  239. const_iterator end() const {
  240. return Stack.empty() ? const_iterator() : Stack.back().first.rend();
  241. }
  242. using iterator = StackTy::reverse_iterator;
  243. iterator begin() {
  244. return Stack.empty() ? iterator()
  245. : Stack.back().first.rbegin() + IgnoredStackElements;
  246. }
  247. iterator end() {
  248. return Stack.empty() ? iterator() : Stack.back().first.rend();
  249. }
  250. // Convenience operations to get at the elements of the stack.
  251. bool isStackEmpty() const {
  252. return Stack.empty() ||
  253. Stack.back().second != CurrentNonCapturingFunctionScope ||
  254. Stack.back().first.size() <= IgnoredStackElements;
  255. }
  256. size_t getStackSize() const {
  257. return isStackEmpty() ? 0
  258. : Stack.back().first.size() - IgnoredStackElements;
  259. }
  260. SharingMapTy *getTopOfStackOrNull() {
  261. size_t Size = getStackSize();
  262. if (Size == 0)
  263. return nullptr;
  264. return &Stack.back().first[Size - 1];
  265. }
  266. const SharingMapTy *getTopOfStackOrNull() const {
  267. return const_cast<DSAStackTy &>(*this).getTopOfStackOrNull();
  268. }
  269. SharingMapTy &getTopOfStack() {
  270. assert(!isStackEmpty() && "no current directive");
  271. return *getTopOfStackOrNull();
  272. }
  273. const SharingMapTy &getTopOfStack() const {
  274. return const_cast<DSAStackTy &>(*this).getTopOfStack();
  275. }
  276. SharingMapTy *getSecondOnStackOrNull() {
  277. size_t Size = getStackSize();
  278. if (Size <= 1)
  279. return nullptr;
  280. return &Stack.back().first[Size - 2];
  281. }
  282. const SharingMapTy *getSecondOnStackOrNull() const {
  283. return const_cast<DSAStackTy &>(*this).getSecondOnStackOrNull();
  284. }
  285. /// Get the stack element at a certain level (previously returned by
  286. /// \c getNestingLevel).
  287. ///
  288. /// Note that nesting levels count from outermost to innermost, and this is
  289. /// the reverse of our iteration order where new inner levels are pushed at
  290. /// the front of the stack.
  291. SharingMapTy &getStackElemAtLevel(unsigned Level) {
  292. assert(Level < getStackSize() && "no such stack element");
  293. return Stack.back().first[Level];
  294. }
  295. const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
  296. return const_cast<DSAStackTy &>(*this).getStackElemAtLevel(Level);
  297. }
  298. DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
  299. /// Checks if the variable is a local for OpenMP region.
  300. bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
  301. /// Vector of previously declared requires directives
  302. SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
  303. /// omp_allocator_handle_t type.
  304. QualType OMPAllocatorHandleT;
  305. /// omp_depend_t type.
  306. QualType OMPDependT;
  307. /// omp_event_handle_t type.
  308. QualType OMPEventHandleT;
  309. /// omp_alloctrait_t type.
  310. QualType OMPAlloctraitT;
  311. /// Expression for the predefined allocators.
  312. Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
  313. nullptr};
  314. /// Vector of previously encountered target directives
  315. SmallVector<SourceLocation, 2> TargetLocations;
  316. SourceLocation AtomicLocation;
  317. /// Vector of declare variant construct traits.
  318. SmallVector<llvm::omp::TraitProperty, 8> ConstructTraits;
  319. public:
  320. explicit DSAStackTy(Sema &S) : SemaRef(S) {}
  321. /// Sets omp_allocator_handle_t type.
  322. void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
  323. /// Gets omp_allocator_handle_t type.
  324. QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
  325. /// Sets omp_alloctrait_t type.
  326. void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; }
  327. /// Gets omp_alloctrait_t type.
  328. QualType getOMPAlloctraitT() const { return OMPAlloctraitT; }
  329. /// Sets the given default allocator.
  330. void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
  331. Expr *Allocator) {
  332. OMPPredefinedAllocators[AllocatorKind] = Allocator;
  333. }
  334. /// Returns the specified default allocator.
  335. Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
  336. return OMPPredefinedAllocators[AllocatorKind];
  337. }
  338. /// Sets omp_depend_t type.
  339. void setOMPDependT(QualType Ty) { OMPDependT = Ty; }
  340. /// Gets omp_depend_t type.
  341. QualType getOMPDependT() const { return OMPDependT; }
  342. /// Sets omp_event_handle_t type.
  343. void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; }
  344. /// Gets omp_event_handle_t type.
  345. QualType getOMPEventHandleT() const { return OMPEventHandleT; }
  346. bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
  347. OpenMPClauseKind getClauseParsingMode() const {
  348. assert(isClauseParsingMode() && "Must be in clause parsing mode.");
  349. return ClauseKindMode;
  350. }
  351. void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
  352. bool isBodyComplete() const {
  353. const SharingMapTy *Top = getTopOfStackOrNull();
  354. return Top && Top->BodyComplete;
  355. }
  356. void setBodyComplete() { getTopOfStack().BodyComplete = true; }
  357. bool isForceVarCapturing() const { return ForceCapturing; }
  358. void setForceVarCapturing(bool V) { ForceCapturing = V; }
  359. void setForceCaptureByReferenceInTargetExecutable(bool V) {
  360. ForceCaptureByReferenceInTargetExecutable = V;
  361. }
  362. bool isForceCaptureByReferenceInTargetExecutable() const {
  363. return ForceCaptureByReferenceInTargetExecutable;
  364. }
  365. void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
  366. Scope *CurScope, SourceLocation Loc) {
  367. assert(!IgnoredStackElements &&
  368. "cannot change stack while ignoring elements");
  369. if (Stack.empty() ||
  370. Stack.back().second != CurrentNonCapturingFunctionScope)
  371. Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
  372. Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
  373. Stack.back().first.back().DefaultAttrLoc = Loc;
  374. }
  375. void pop() {
  376. assert(!IgnoredStackElements &&
  377. "cannot change stack while ignoring elements");
  378. assert(!Stack.back().first.empty() &&
  379. "Data-sharing attributes stack is empty!");
  380. Stack.back().first.pop_back();
  381. }
  382. /// RAII object to temporarily leave the scope of a directive when we want to
  383. /// logically operate in its parent.
  384. class ParentDirectiveScope {
  385. DSAStackTy &Self;
  386. bool Active;
  387. public:
  388. ParentDirectiveScope(DSAStackTy &Self, bool Activate)
  389. : Self(Self), Active(false) {
  390. if (Activate)
  391. enable();
  392. }
  393. ~ParentDirectiveScope() { disable(); }
  394. void disable() {
  395. if (Active) {
  396. --Self.IgnoredStackElements;
  397. Active = false;
  398. }
  399. }
  400. void enable() {
  401. if (!Active) {
  402. ++Self.IgnoredStackElements;
  403. Active = true;
  404. }
  405. }
  406. };
  407. /// Marks that we're started loop parsing.
  408. void loopInit() {
  409. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  410. "Expected loop-based directive.");
  411. getTopOfStack().LoopStart = true;
  412. }
  413. /// Start capturing of the variables in the loop context.
  414. void loopStart() {
  415. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  416. "Expected loop-based directive.");
  417. getTopOfStack().LoopStart = false;
  418. }
  419. /// true, if variables are captured, false otherwise.
  420. bool isLoopStarted() const {
  421. assert(isOpenMPLoopDirective(getCurrentDirective()) &&
  422. "Expected loop-based directive.");
  423. return !getTopOfStack().LoopStart;
  424. }
  425. /// Marks (or clears) declaration as possibly loop counter.
  426. void resetPossibleLoopCounter(const Decl *D = nullptr) {
  427. getTopOfStack().PossiblyLoopCounter = D ? D->getCanonicalDecl() : D;
  428. }
  429. /// Gets the possible loop counter decl.
  430. const Decl *getPossiblyLoopCunter() const {
  431. return getTopOfStack().PossiblyLoopCounter;
  432. }
  433. /// Start new OpenMP region stack in new non-capturing function.
  434. void pushFunction() {
  435. assert(!IgnoredStackElements &&
  436. "cannot change stack while ignoring elements");
  437. const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
  438. assert(!isa<CapturingScopeInfo>(CurFnScope));
  439. CurrentNonCapturingFunctionScope = CurFnScope;
  440. }
  441. /// Pop region stack for non-capturing function.
  442. void popFunction(const FunctionScopeInfo *OldFSI) {
  443. assert(!IgnoredStackElements &&
  444. "cannot change stack while ignoring elements");
  445. if (!Stack.empty() && Stack.back().second == OldFSI) {
  446. assert(Stack.back().first.empty());
  447. Stack.pop_back();
  448. }
  449. CurrentNonCapturingFunctionScope = nullptr;
  450. for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
  451. if (!isa<CapturingScopeInfo>(FSI)) {
  452. CurrentNonCapturingFunctionScope = FSI;
  453. break;
  454. }
  455. }
  456. }
  457. void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
  458. Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
  459. }
  460. const std::pair<const OMPCriticalDirective *, llvm::APSInt>
  461. getCriticalWithHint(const DeclarationNameInfo &Name) const {
  462. auto I = Criticals.find(Name.getAsString());
  463. if (I != Criticals.end())
  464. return I->second;
  465. return std::make_pair(nullptr, llvm::APSInt());
  466. }
  467. /// If 'aligned' declaration for given variable \a D was not seen yet,
  468. /// add it and return NULL; otherwise return previous occurrence's expression
  469. /// for diagnostics.
  470. const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
  471. /// If 'nontemporal' declaration for given variable \a D was not seen yet,
  472. /// add it and return NULL; otherwise return previous occurrence's expression
  473. /// for diagnostics.
  474. const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
  475. /// Register specified variable as loop control variable.
  476. void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
  477. /// Check if the specified variable is a loop control variable for
  478. /// current region.
  479. /// \return The index of the loop control variable in the list of associated
  480. /// for-loops (from outer to inner).
  481. const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
  482. /// Check if the specified variable is a loop control variable for
  483. /// parent region.
  484. /// \return The index of the loop control variable in the list of associated
  485. /// for-loops (from outer to inner).
  486. const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
  487. /// Check if the specified variable is a loop control variable for
  488. /// current region.
  489. /// \return The index of the loop control variable in the list of associated
  490. /// for-loops (from outer to inner).
  491. const LCDeclInfo isLoopControlVariable(const ValueDecl *D,
  492. unsigned Level) const;
  493. /// Get the loop control variable for the I-th loop (or nullptr) in
  494. /// parent directive.
  495. const ValueDecl *getParentLoopControlVariable(unsigned I) const;
  496. /// Marks the specified decl \p D as used in scan directive.
  497. void markDeclAsUsedInScanDirective(ValueDecl *D) {
  498. if (SharingMapTy *Stack = getSecondOnStackOrNull())
  499. Stack->UsedInScanDirective.insert(D);
  500. }
  501. /// Checks if the specified declaration was used in the inner scan directive.
  502. bool isUsedInScanDirective(ValueDecl *D) const {
  503. if (const SharingMapTy *Stack = getTopOfStackOrNull())
  504. return Stack->UsedInScanDirective.contains(D);
  505. return false;
  506. }
  507. /// Adds explicit data sharing attribute to the specified declaration.
  508. void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  509. DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0,
  510. bool AppliedToPointee = false);
  511. /// Adds additional information for the reduction items with the reduction id
  512. /// represented as an operator.
  513. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  514. BinaryOperatorKind BOK);
  515. /// Adds additional information for the reduction items with the reduction id
  516. /// represented as reduction identifier.
  517. void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  518. const Expr *ReductionRef);
  519. /// Returns the location and reduction operation from the innermost parent
  520. /// region for the given \p D.
  521. const DSAVarData
  522. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  523. BinaryOperatorKind &BOK,
  524. Expr *&TaskgroupDescriptor) const;
  525. /// Returns the location and reduction operation from the innermost parent
  526. /// region for the given \p D.
  527. const DSAVarData
  528. getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
  529. const Expr *&ReductionRef,
  530. Expr *&TaskgroupDescriptor) const;
  531. /// Return reduction reference expression for the current taskgroup or
  532. /// parallel/worksharing directives with task reductions.
  533. Expr *getTaskgroupReductionRef() const {
  534. assert((getTopOfStack().Directive == OMPD_taskgroup ||
  535. ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
  536. isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
  537. !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
  538. "taskgroup reference expression requested for non taskgroup or "
  539. "parallel/worksharing directive.");
  540. return getTopOfStack().TaskgroupReductionRef;
  541. }
  542. /// Checks if the given \p VD declaration is actually a taskgroup reduction
  543. /// descriptor variable at the \p Level of OpenMP regions.
  544. bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
  545. return getStackElemAtLevel(Level).TaskgroupReductionRef &&
  546. cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
  547. ->getDecl() == VD;
  548. }
  549. /// Returns data sharing attributes from top of the stack for the
  550. /// specified declaration.
  551. const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
  552. /// Returns data-sharing attributes for the specified declaration.
  553. const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
  554. /// Returns data-sharing attributes for the specified declaration.
  555. const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const;
  556. /// Checks if the specified variables has data-sharing attributes which
  557. /// match specified \a CPred predicate in any directive which matches \a DPred
  558. /// predicate.
  559. const DSAVarData
  560. hasDSA(ValueDecl *D,
  561. const llvm::function_ref<bool(OpenMPClauseKind, bool,
  562. DefaultDataSharingAttributes)>
  563. CPred,
  564. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  565. bool FromParent) const;
  566. /// Checks if the specified variables has data-sharing attributes which
  567. /// match specified \a CPred predicate in any innermost directive which
  568. /// matches \a DPred predicate.
  569. const DSAVarData
  570. hasInnermostDSA(ValueDecl *D,
  571. const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
  572. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  573. bool FromParent) const;
  574. /// Checks if the specified variables has explicit data-sharing
  575. /// attributes which match specified \a CPred predicate at the specified
  576. /// OpenMP region.
  577. bool
  578. hasExplicitDSA(const ValueDecl *D,
  579. const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
  580. unsigned Level, bool NotLastprivate = false) const;
  581. /// Returns true if the directive at level \Level matches in the
  582. /// specified \a DPred predicate.
  583. bool hasExplicitDirective(
  584. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  585. unsigned Level) const;
  586. /// Finds a directive which matches specified \a DPred predicate.
  587. bool hasDirective(
  588. const llvm::function_ref<bool(
  589. OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
  590. DPred,
  591. bool FromParent) const;
  592. /// Returns currently analyzed directive.
  593. OpenMPDirectiveKind getCurrentDirective() const {
  594. const SharingMapTy *Top = getTopOfStackOrNull();
  595. return Top ? Top->Directive : OMPD_unknown;
  596. }
  597. /// Returns directive kind at specified level.
  598. OpenMPDirectiveKind getDirective(unsigned Level) const {
  599. assert(!isStackEmpty() && "No directive at specified level.");
  600. return getStackElemAtLevel(Level).Directive;
  601. }
  602. /// Returns the capture region at the specified level.
  603. OpenMPDirectiveKind getCaptureRegion(unsigned Level,
  604. unsigned OpenMPCaptureLevel) const {
  605. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  606. getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
  607. return CaptureRegions[OpenMPCaptureLevel];
  608. }
  609. /// Returns parent directive.
  610. OpenMPDirectiveKind getParentDirective() const {
  611. const SharingMapTy *Parent = getSecondOnStackOrNull();
  612. return Parent ? Parent->Directive : OMPD_unknown;
  613. }
  614. /// Add requires decl to internal vector
  615. void addRequiresDecl(OMPRequiresDecl *RD) { RequiresDecls.push_back(RD); }
  616. /// Checks if the defined 'requires' directive has specified type of clause.
  617. template <typename ClauseType> bool hasRequiresDeclWithClause() const {
  618. return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
  619. return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
  620. return isa<ClauseType>(C);
  621. });
  622. });
  623. }
  624. /// Checks for a duplicate clause amongst previously declared requires
  625. /// directives
  626. bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
  627. bool IsDuplicate = false;
  628. for (OMPClause *CNew : ClauseList) {
  629. for (const OMPRequiresDecl *D : RequiresDecls) {
  630. for (const OMPClause *CPrev : D->clauselists()) {
  631. if (CNew->getClauseKind() == CPrev->getClauseKind()) {
  632. SemaRef.Diag(CNew->getBeginLoc(),
  633. diag::err_omp_requires_clause_redeclaration)
  634. << getOpenMPClauseName(CNew->getClauseKind());
  635. SemaRef.Diag(CPrev->getBeginLoc(),
  636. diag::note_omp_requires_previous_clause)
  637. << getOpenMPClauseName(CPrev->getClauseKind());
  638. IsDuplicate = true;
  639. }
  640. }
  641. }
  642. }
  643. return IsDuplicate;
  644. }
  645. /// Add location of previously encountered target to internal vector
  646. void addTargetDirLocation(SourceLocation LocStart) {
  647. TargetLocations.push_back(LocStart);
  648. }
  649. /// Add location for the first encountered atomicc directive.
  650. void addAtomicDirectiveLoc(SourceLocation Loc) {
  651. if (AtomicLocation.isInvalid())
  652. AtomicLocation = Loc;
  653. }
  654. /// Returns the location of the first encountered atomic directive in the
  655. /// module.
  656. SourceLocation getAtomicDirectiveLoc() const { return AtomicLocation; }
  657. // Return previously encountered target region locations.
  658. ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
  659. return TargetLocations;
  660. }
  661. /// Set default data sharing attribute to none.
  662. void setDefaultDSANone(SourceLocation Loc) {
  663. getTopOfStack().DefaultAttr = DSA_none;
  664. getTopOfStack().DefaultAttrLoc = Loc;
  665. }
  666. /// Set default data sharing attribute to shared.
  667. void setDefaultDSAShared(SourceLocation Loc) {
  668. getTopOfStack().DefaultAttr = DSA_shared;
  669. getTopOfStack().DefaultAttrLoc = Loc;
  670. }
  671. /// Set default data sharing attribute to private.
  672. void setDefaultDSAPrivate(SourceLocation Loc) {
  673. getTopOfStack().DefaultAttr = DSA_private;
  674. getTopOfStack().DefaultAttrLoc = Loc;
  675. }
  676. /// Set default data sharing attribute to firstprivate.
  677. void setDefaultDSAFirstPrivate(SourceLocation Loc) {
  678. getTopOfStack().DefaultAttr = DSA_firstprivate;
  679. getTopOfStack().DefaultAttrLoc = Loc;
  680. }
  681. /// Set default data mapping attribute to Modifier:Kind
  682. void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
  683. OpenMPDefaultmapClauseKind Kind, SourceLocation Loc) {
  684. DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
  685. DMI.ImplicitBehavior = M;
  686. DMI.SLoc = Loc;
  687. }
  688. /// Check whether the implicit-behavior has been set in defaultmap
  689. bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
  690. if (VariableCategory == OMPC_DEFAULTMAP_unknown)
  691. return getTopOfStack()
  692. .DefaultmapMap[OMPC_DEFAULTMAP_aggregate]
  693. .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
  694. getTopOfStack()
  695. .DefaultmapMap[OMPC_DEFAULTMAP_scalar]
  696. .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown ||
  697. getTopOfStack()
  698. .DefaultmapMap[OMPC_DEFAULTMAP_pointer]
  699. .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown;
  700. return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
  701. OMPC_DEFAULTMAP_MODIFIER_unknown;
  702. }
  703. ArrayRef<llvm::omp::TraitProperty> getConstructTraits() {
  704. return ConstructTraits;
  705. }
  706. void handleConstructTrait(ArrayRef<llvm::omp::TraitProperty> Traits,
  707. bool ScopeEntry) {
  708. if (ScopeEntry)
  709. ConstructTraits.append(Traits.begin(), Traits.end());
  710. else
  711. for (llvm::omp::TraitProperty Trait : llvm::reverse(Traits)) {
  712. llvm::omp::TraitProperty Top = ConstructTraits.pop_back_val();
  713. assert(Top == Trait && "Something left a trait on the stack!");
  714. (void)Trait;
  715. (void)Top;
  716. }
  717. }
  718. DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const {
  719. return getStackSize() <= Level ? DSA_unspecified
  720. : getStackElemAtLevel(Level).DefaultAttr;
  721. }
  722. DefaultDataSharingAttributes getDefaultDSA() const {
  723. return isStackEmpty() ? DSA_unspecified : getTopOfStack().DefaultAttr;
  724. }
  725. SourceLocation getDefaultDSALocation() const {
  726. return isStackEmpty() ? SourceLocation() : getTopOfStack().DefaultAttrLoc;
  727. }
  728. OpenMPDefaultmapClauseModifier
  729. getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
  730. return isStackEmpty()
  731. ? OMPC_DEFAULTMAP_MODIFIER_unknown
  732. : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
  733. }
  734. OpenMPDefaultmapClauseModifier
  735. getDefaultmapModifierAtLevel(unsigned Level,
  736. OpenMPDefaultmapClauseKind Kind) const {
  737. return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
  738. }
  739. bool isDefaultmapCapturedByRef(unsigned Level,
  740. OpenMPDefaultmapClauseKind Kind) const {
  741. OpenMPDefaultmapClauseModifier M =
  742. getDefaultmapModifierAtLevel(Level, Kind);
  743. if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
  744. return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
  745. (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
  746. (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
  747. (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
  748. }
  749. return true;
  750. }
  751. static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
  752. OpenMPDefaultmapClauseKind Kind) {
  753. switch (Kind) {
  754. case OMPC_DEFAULTMAP_scalar:
  755. case OMPC_DEFAULTMAP_pointer:
  756. return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
  757. (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
  758. (M == OMPC_DEFAULTMAP_MODIFIER_default);
  759. case OMPC_DEFAULTMAP_aggregate:
  760. return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
  761. default:
  762. break;
  763. }
  764. llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
  765. }
  766. bool mustBeFirstprivateAtLevel(unsigned Level,
  767. OpenMPDefaultmapClauseKind Kind) const {
  768. OpenMPDefaultmapClauseModifier M =
  769. getDefaultmapModifierAtLevel(Level, Kind);
  770. return mustBeFirstprivateBase(M, Kind);
  771. }
  772. bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
  773. OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
  774. return mustBeFirstprivateBase(M, Kind);
  775. }
  776. /// Checks if the specified variable is a threadprivate.
  777. bool isThreadPrivate(VarDecl *D) {
  778. const DSAVarData DVar = getTopDSA(D, false);
  779. return isOpenMPThreadPrivate(DVar.CKind);
  780. }
  781. /// Marks current region as ordered (it has an 'ordered' clause).
  782. void setOrderedRegion(bool IsOrdered, const Expr *Param,
  783. OMPOrderedClause *Clause) {
  784. if (IsOrdered)
  785. getTopOfStack().OrderedRegion.emplace(Param, Clause);
  786. else
  787. getTopOfStack().OrderedRegion.reset();
  788. }
  789. /// Returns true, if region is ordered (has associated 'ordered' clause),
  790. /// false - otherwise.
  791. bool isOrderedRegion() const {
  792. if (const SharingMapTy *Top = getTopOfStackOrNull())
  793. return Top->OrderedRegion.has_value();
  794. return false;
  795. }
  796. /// Returns optional parameter for the ordered region.
  797. std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
  798. if (const SharingMapTy *Top = getTopOfStackOrNull())
  799. if (Top->OrderedRegion)
  800. return *Top->OrderedRegion;
  801. return std::make_pair(nullptr, nullptr);
  802. }
  803. /// Returns true, if parent region is ordered (has associated
  804. /// 'ordered' clause), false - otherwise.
  805. bool isParentOrderedRegion() const {
  806. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  807. return Parent->OrderedRegion.has_value();
  808. return false;
  809. }
  810. /// Returns optional parameter for the ordered region.
  811. std::pair<const Expr *, OMPOrderedClause *>
  812. getParentOrderedRegionParam() const {
  813. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  814. if (Parent->OrderedRegion)
  815. return *Parent->OrderedRegion;
  816. return std::make_pair(nullptr, nullptr);
  817. }
  818. /// Marks current region as having an 'order' clause.
  819. void setRegionHasOrderConcurrent(bool HasOrderConcurrent) {
  820. getTopOfStack().RegionHasOrderConcurrent = HasOrderConcurrent;
  821. }
  822. /// Returns true, if parent region is order (has associated
  823. /// 'order' clause), false - otherwise.
  824. bool isParentOrderConcurrent() const {
  825. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  826. return Parent->RegionHasOrderConcurrent;
  827. return false;
  828. }
  829. /// Marks current region as nowait (it has a 'nowait' clause).
  830. void setNowaitRegion(bool IsNowait = true) {
  831. getTopOfStack().NowaitRegion = IsNowait;
  832. }
  833. /// Returns true, if parent region is nowait (has associated
  834. /// 'nowait' clause), false - otherwise.
  835. bool isParentNowaitRegion() const {
  836. if (const SharingMapTy *Parent = getSecondOnStackOrNull())
  837. return Parent->NowaitRegion;
  838. return false;
  839. }
  840. /// Marks current region as untied (it has a 'untied' clause).
  841. void setUntiedRegion(bool IsUntied = true) {
  842. getTopOfStack().UntiedRegion = IsUntied;
  843. }
  844. /// Return true if current region is untied.
  845. bool isUntiedRegion() const {
  846. const SharingMapTy *Top = getTopOfStackOrNull();
  847. return Top ? Top->UntiedRegion : false;
  848. }
  849. /// Marks parent region as cancel region.
  850. void setParentCancelRegion(bool Cancel = true) {
  851. if (SharingMapTy *Parent = getSecondOnStackOrNull())
  852. Parent->CancelRegion |= Cancel;
  853. }
  854. /// Return true if current region has inner cancel construct.
  855. bool isCancelRegion() const {
  856. const SharingMapTy *Top = getTopOfStackOrNull();
  857. return Top ? Top->CancelRegion : false;
  858. }
  859. /// Mark that parent region already has scan directive.
  860. void setParentHasScanDirective(SourceLocation Loc) {
  861. if (SharingMapTy *Parent = getSecondOnStackOrNull())
  862. Parent->PrevScanLocation = Loc;
  863. }
  864. /// Return true if current region has inner cancel construct.
  865. bool doesParentHasScanDirective() const {
  866. const SharingMapTy *Top = getSecondOnStackOrNull();
  867. return Top ? Top->PrevScanLocation.isValid() : false;
  868. }
  869. /// Return true if current region has inner cancel construct.
  870. SourceLocation getParentScanDirectiveLoc() const {
  871. const SharingMapTy *Top = getSecondOnStackOrNull();
  872. return Top ? Top->PrevScanLocation : SourceLocation();
  873. }
  874. /// Mark that parent region already has ordered directive.
  875. void setParentHasOrderedDirective(SourceLocation Loc) {
  876. if (SharingMapTy *Parent = getSecondOnStackOrNull())
  877. Parent->PrevOrderedLocation = Loc;
  878. }
  879. /// Return true if current region has inner ordered construct.
  880. bool doesParentHasOrderedDirective() const {
  881. const SharingMapTy *Top = getSecondOnStackOrNull();
  882. return Top ? Top->PrevOrderedLocation.isValid() : false;
  883. }
  884. /// Returns the location of the previously specified ordered directive.
  885. SourceLocation getParentOrderedDirectiveLoc() const {
  886. const SharingMapTy *Top = getSecondOnStackOrNull();
  887. return Top ? Top->PrevOrderedLocation : SourceLocation();
  888. }
  889. /// Set collapse value for the region.
  890. void setAssociatedLoops(unsigned Val) {
  891. getTopOfStack().AssociatedLoops = Val;
  892. if (Val > 1)
  893. getTopOfStack().HasMutipleLoops = true;
  894. }
  895. /// Return collapse value for region.
  896. unsigned getAssociatedLoops() const {
  897. const SharingMapTy *Top = getTopOfStackOrNull();
  898. return Top ? Top->AssociatedLoops : 0;
  899. }
  900. /// Returns true if the construct is associated with multiple loops.
  901. bool hasMutipleLoops() const {
  902. const SharingMapTy *Top = getTopOfStackOrNull();
  903. return Top ? Top->HasMutipleLoops : false;
  904. }
  905. /// Marks current target region as one with closely nested teams
  906. /// region.
  907. void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
  908. if (SharingMapTy *Parent = getSecondOnStackOrNull())
  909. Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
  910. }
  911. /// Returns true, if current region has closely nested teams region.
  912. bool hasInnerTeamsRegion() const {
  913. return getInnerTeamsRegionLoc().isValid();
  914. }
  915. /// Returns location of the nested teams region (if any).
  916. SourceLocation getInnerTeamsRegionLoc() const {
  917. const SharingMapTy *Top = getTopOfStackOrNull();
  918. return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
  919. }
  920. Scope *getCurScope() const {
  921. const SharingMapTy *Top = getTopOfStackOrNull();
  922. return Top ? Top->CurScope : nullptr;
  923. }
  924. void setContext(DeclContext *DC) { getTopOfStack().Context = DC; }
  925. SourceLocation getConstructLoc() const {
  926. const SharingMapTy *Top = getTopOfStackOrNull();
  927. return Top ? Top->ConstructLoc : SourceLocation();
  928. }
  929. /// Do the check specified in \a Check to all component lists and return true
  930. /// if any issue is found.
  931. bool checkMappableExprComponentListsForDecl(
  932. const ValueDecl *VD, bool CurrentRegionOnly,
  933. const llvm::function_ref<
  934. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  935. OpenMPClauseKind)>
  936. Check) const {
  937. if (isStackEmpty())
  938. return false;
  939. auto SI = begin();
  940. auto SE = end();
  941. if (SI == SE)
  942. return false;
  943. if (CurrentRegionOnly)
  944. SE = std::next(SI);
  945. else
  946. std::advance(SI, 1);
  947. for (; SI != SE; ++SI) {
  948. auto MI = SI->MappedExprComponents.find(VD);
  949. if (MI != SI->MappedExprComponents.end())
  950. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  951. MI->second.Components)
  952. if (Check(L, MI->second.Kind))
  953. return true;
  954. }
  955. return false;
  956. }
  957. /// Do the check specified in \a Check to all component lists at a given level
  958. /// and return true if any issue is found.
  959. bool checkMappableExprComponentListsForDeclAtLevel(
  960. const ValueDecl *VD, unsigned Level,
  961. const llvm::function_ref<
  962. bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
  963. OpenMPClauseKind)>
  964. Check) const {
  965. if (getStackSize() <= Level)
  966. return false;
  967. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  968. auto MI = StackElem.MappedExprComponents.find(VD);
  969. if (MI != StackElem.MappedExprComponents.end())
  970. for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
  971. MI->second.Components)
  972. if (Check(L, MI->second.Kind))
  973. return true;
  974. return false;
  975. }
  976. /// Create a new mappable expression component list associated with a given
  977. /// declaration and initialize it with the provided list of components.
  978. void addMappableExpressionComponents(
  979. const ValueDecl *VD,
  980. OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
  981. OpenMPClauseKind WhereFoundClauseKind) {
  982. MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
  983. // Create new entry and append the new components there.
  984. MEC.Components.resize(MEC.Components.size() + 1);
  985. MEC.Components.back().append(Components.begin(), Components.end());
  986. MEC.Kind = WhereFoundClauseKind;
  987. }
  988. unsigned getNestingLevel() const {
  989. assert(!isStackEmpty());
  990. return getStackSize() - 1;
  991. }
  992. void addDoacrossDependClause(OMPDependClause *C,
  993. const OperatorOffsetTy &OpsOffs) {
  994. SharingMapTy *Parent = getSecondOnStackOrNull();
  995. assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
  996. Parent->DoacrossDepends.try_emplace(C, OpsOffs);
  997. }
  998. llvm::iterator_range<DoacrossDependMapTy::const_iterator>
  999. getDoacrossDependClauses() const {
  1000. const SharingMapTy &StackElem = getTopOfStack();
  1001. if (isOpenMPWorksharingDirective(StackElem.Directive)) {
  1002. const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
  1003. return llvm::make_range(Ref.begin(), Ref.end());
  1004. }
  1005. return llvm::make_range(StackElem.DoacrossDepends.end(),
  1006. StackElem.DoacrossDepends.end());
  1007. }
  1008. // Store types of classes which have been explicitly mapped
  1009. void addMappedClassesQualTypes(QualType QT) {
  1010. SharingMapTy &StackElem = getTopOfStack();
  1011. StackElem.MappedClassesQualTypes.insert(QT);
  1012. }
  1013. // Return set of mapped classes types
  1014. bool isClassPreviouslyMapped(QualType QT) const {
  1015. const SharingMapTy &StackElem = getTopOfStack();
  1016. return StackElem.MappedClassesQualTypes.contains(QT);
  1017. }
  1018. /// Adds global declare target to the parent target region.
  1019. void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
  1020. assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
  1021. E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
  1022. "Expected declare target link global.");
  1023. for (auto &Elem : *this) {
  1024. if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
  1025. Elem.DeclareTargetLinkVarDecls.push_back(E);
  1026. return;
  1027. }
  1028. }
  1029. }
  1030. /// Returns the list of globals with declare target link if current directive
  1031. /// is target.
  1032. ArrayRef<DeclRefExpr *> getLinkGlobals() const {
  1033. assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
  1034. "Expected target executable directive.");
  1035. return getTopOfStack().DeclareTargetLinkVarDecls;
  1036. }
  1037. /// Adds list of allocators expressions.
  1038. void addInnerAllocatorExpr(Expr *E) {
  1039. getTopOfStack().InnerUsedAllocators.push_back(E);
  1040. }
  1041. /// Return list of used allocators.
  1042. ArrayRef<Expr *> getInnerAllocators() const {
  1043. return getTopOfStack().InnerUsedAllocators;
  1044. }
  1045. /// Marks the declaration as implicitly firstprivate nin the task-based
  1046. /// regions.
  1047. void addImplicitTaskFirstprivate(unsigned Level, Decl *D) {
  1048. getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D);
  1049. }
  1050. /// Checks if the decl is implicitly firstprivate in the task-based region.
  1051. bool isImplicitTaskFirstprivate(Decl *D) const {
  1052. return getTopOfStack().ImplicitTaskFirstprivates.contains(D);
  1053. }
  1054. /// Marks decl as used in uses_allocators clause as the allocator.
  1055. void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) {
  1056. getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind);
  1057. }
  1058. /// Checks if specified decl is used in uses allocator clause as the
  1059. /// allocator.
  1060. std::optional<UsesAllocatorsDeclKind>
  1061. isUsesAllocatorsDecl(unsigned Level, const Decl *D) const {
  1062. const SharingMapTy &StackElem = getTopOfStack();
  1063. auto I = StackElem.UsesAllocatorsDecls.find(D);
  1064. if (I == StackElem.UsesAllocatorsDecls.end())
  1065. return std::nullopt;
  1066. return I->getSecond();
  1067. }
  1068. std::optional<UsesAllocatorsDeclKind>
  1069. isUsesAllocatorsDecl(const Decl *D) const {
  1070. const SharingMapTy &StackElem = getTopOfStack();
  1071. auto I = StackElem.UsesAllocatorsDecls.find(D);
  1072. if (I == StackElem.UsesAllocatorsDecls.end())
  1073. return std::nullopt;
  1074. return I->getSecond();
  1075. }
  1076. void addDeclareMapperVarRef(Expr *Ref) {
  1077. SharingMapTy &StackElem = getTopOfStack();
  1078. StackElem.DeclareMapperVar = Ref;
  1079. }
  1080. const Expr *getDeclareMapperVarRef() const {
  1081. const SharingMapTy *Top = getTopOfStackOrNull();
  1082. return Top ? Top->DeclareMapperVar : nullptr;
  1083. }
  1084. /// Add a new iterator variable.
  1085. void addIteratorVarDecl(VarDecl *VD) {
  1086. SharingMapTy &StackElem = getTopOfStack();
  1087. StackElem.IteratorVarDecls.push_back(VD->getCanonicalDecl());
  1088. }
  1089. /// Check if variable declaration is an iterator VarDecl.
  1090. bool isIteratorVarDecl(const VarDecl *VD) const {
  1091. const SharingMapTy *Top = getTopOfStackOrNull();
  1092. if (!Top)
  1093. return false;
  1094. return llvm::any_of(Top->IteratorVarDecls, [VD](const VarDecl *IteratorVD) {
  1095. return IteratorVD == VD->getCanonicalDecl();
  1096. });
  1097. }
  1098. /// get captured field from ImplicitDefaultFirstprivateFDs
  1099. VarDecl *getImplicitFDCapExprDecl(const FieldDecl *FD) const {
  1100. const_iterator I = begin();
  1101. const_iterator EndI = end();
  1102. size_t StackLevel = getStackSize();
  1103. for (; I != EndI; ++I) {
  1104. if (I->DefaultAttr == DSA_firstprivate || I->DefaultAttr == DSA_private)
  1105. break;
  1106. StackLevel--;
  1107. }
  1108. assert((StackLevel > 0 && I != EndI) || (StackLevel == 0 && I == EndI));
  1109. if (I == EndI)
  1110. return nullptr;
  1111. for (const auto &IFD : I->ImplicitDefaultFirstprivateFDs)
  1112. if (IFD.FD == FD && IFD.StackLevel == StackLevel)
  1113. return IFD.VD;
  1114. return nullptr;
  1115. }
  1116. /// Check if capture decl is field captured in ImplicitDefaultFirstprivateFDs
  1117. bool isImplicitDefaultFirstprivateFD(VarDecl *VD) const {
  1118. const_iterator I = begin();
  1119. const_iterator EndI = end();
  1120. for (; I != EndI; ++I)
  1121. if (I->DefaultAttr == DSA_firstprivate || I->DefaultAttr == DSA_private)
  1122. break;
  1123. if (I == EndI)
  1124. return false;
  1125. for (const auto &IFD : I->ImplicitDefaultFirstprivateFDs)
  1126. if (IFD.VD == VD)
  1127. return true;
  1128. return false;
  1129. }
  1130. /// Store capture FD info in ImplicitDefaultFirstprivateFDs
  1131. void addImplicitDefaultFirstprivateFD(const FieldDecl *FD, VarDecl *VD) {
  1132. iterator I = begin();
  1133. const_iterator EndI = end();
  1134. size_t StackLevel = getStackSize();
  1135. for (; I != EndI; ++I) {
  1136. if (I->DefaultAttr == DSA_private || I->DefaultAttr == DSA_firstprivate) {
  1137. I->ImplicitDefaultFirstprivateFDs.emplace_back(FD, StackLevel, VD);
  1138. break;
  1139. }
  1140. StackLevel--;
  1141. }
  1142. assert((StackLevel > 0 && I != EndI) || (StackLevel == 0 && I == EndI));
  1143. }
  1144. };
  1145. bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  1146. return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
  1147. }
  1148. bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
  1149. return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
  1150. DKind == OMPD_unknown;
  1151. }
  1152. } // namespace
  1153. static const Expr *getExprAsWritten(const Expr *E) {
  1154. if (const auto *FE = dyn_cast<FullExpr>(E))
  1155. E = FE->getSubExpr();
  1156. if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
  1157. E = MTE->getSubExpr();
  1158. while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
  1159. E = Binder->getSubExpr();
  1160. if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
  1161. E = ICE->getSubExprAsWritten();
  1162. return E->IgnoreParens();
  1163. }
  1164. static Expr *getExprAsWritten(Expr *E) {
  1165. return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
  1166. }
  1167. static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
  1168. if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
  1169. if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  1170. D = ME->getMemberDecl();
  1171. const auto *VD = dyn_cast<VarDecl>(D);
  1172. const auto *FD = dyn_cast<FieldDecl>(D);
  1173. if (VD != nullptr) {
  1174. VD = VD->getCanonicalDecl();
  1175. D = VD;
  1176. } else {
  1177. assert(FD);
  1178. FD = FD->getCanonicalDecl();
  1179. D = FD;
  1180. }
  1181. return D;
  1182. }
  1183. static ValueDecl *getCanonicalDecl(ValueDecl *D) {
  1184. return const_cast<ValueDecl *>(
  1185. getCanonicalDecl(const_cast<const ValueDecl *>(D)));
  1186. }
  1187. DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
  1188. ValueDecl *D) const {
  1189. D = getCanonicalDecl(D);
  1190. auto *VD = dyn_cast<VarDecl>(D);
  1191. const auto *FD = dyn_cast<FieldDecl>(D);
  1192. DSAVarData DVar;
  1193. if (Iter == end()) {
  1194. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1195. // in a region but not in construct]
  1196. // File-scope or namespace-scope variables referenced in called routines
  1197. // in the region are shared unless they appear in a threadprivate
  1198. // directive.
  1199. if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
  1200. DVar.CKind = OMPC_shared;
  1201. // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
  1202. // in a region but not in construct]
  1203. // Variables with static storage duration that are declared in called
  1204. // routines in the region are shared.
  1205. if (VD && VD->hasGlobalStorage())
  1206. DVar.CKind = OMPC_shared;
  1207. // Non-static data members are shared by default.
  1208. if (FD)
  1209. DVar.CKind = OMPC_shared;
  1210. return DVar;
  1211. }
  1212. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1213. // in a Construct, C/C++, predetermined, p.1]
  1214. // Variables with automatic storage duration that are declared in a scope
  1215. // inside the construct are private.
  1216. if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
  1217. (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
  1218. DVar.CKind = OMPC_private;
  1219. return DVar;
  1220. }
  1221. DVar.DKind = Iter->Directive;
  1222. // Explicitly specified attributes and local variables with predetermined
  1223. // attributes.
  1224. if (Iter->SharingMap.count(D)) {
  1225. const DSAInfo &Data = Iter->SharingMap.lookup(D);
  1226. DVar.RefExpr = Data.RefExpr.getPointer();
  1227. DVar.PrivateCopy = Data.PrivateCopy;
  1228. DVar.CKind = Data.Attributes;
  1229. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  1230. DVar.Modifier = Data.Modifier;
  1231. DVar.AppliedToPointee = Data.AppliedToPointee;
  1232. return DVar;
  1233. }
  1234. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1235. // in a Construct, C/C++, implicitly determined, p.1]
  1236. // In a parallel or task construct, the data-sharing attributes of these
  1237. // variables are determined by the default clause, if present.
  1238. switch (Iter->DefaultAttr) {
  1239. case DSA_shared:
  1240. DVar.CKind = OMPC_shared;
  1241. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  1242. return DVar;
  1243. case DSA_none:
  1244. return DVar;
  1245. case DSA_firstprivate:
  1246. if (VD && VD->getStorageDuration() == SD_Static &&
  1247. VD->getDeclContext()->isFileContext()) {
  1248. DVar.CKind = OMPC_unknown;
  1249. } else {
  1250. DVar.CKind = OMPC_firstprivate;
  1251. }
  1252. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  1253. return DVar;
  1254. case DSA_private:
  1255. // each variable with static storage duration that is declared
  1256. // in a namespace or global scope and referenced in the construct,
  1257. // and that does not have a predetermined data-sharing attribute
  1258. if (VD && VD->getStorageDuration() == SD_Static &&
  1259. VD->getDeclContext()->isFileContext()) {
  1260. DVar.CKind = OMPC_unknown;
  1261. } else {
  1262. DVar.CKind = OMPC_private;
  1263. }
  1264. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  1265. return DVar;
  1266. case DSA_unspecified:
  1267. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1268. // in a Construct, implicitly determined, p.2]
  1269. // In a parallel construct, if no default clause is present, these
  1270. // variables are shared.
  1271. DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
  1272. if ((isOpenMPParallelDirective(DVar.DKind) &&
  1273. !isOpenMPTaskLoopDirective(DVar.DKind)) ||
  1274. isOpenMPTeamsDirective(DVar.DKind)) {
  1275. DVar.CKind = OMPC_shared;
  1276. return DVar;
  1277. }
  1278. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1279. // in a Construct, implicitly determined, p.4]
  1280. // In a task construct, if no default clause is present, a variable that in
  1281. // the enclosing context is determined to be shared by all implicit tasks
  1282. // bound to the current team is shared.
  1283. if (isOpenMPTaskingDirective(DVar.DKind)) {
  1284. DSAVarData DVarTemp;
  1285. const_iterator I = Iter, E = end();
  1286. do {
  1287. ++I;
  1288. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
  1289. // Referenced in a Construct, implicitly determined, p.6]
  1290. // In a task construct, if no default clause is present, a variable
  1291. // whose data-sharing attribute is not determined by the rules above is
  1292. // firstprivate.
  1293. DVarTemp = getDSA(I, D);
  1294. if (DVarTemp.CKind != OMPC_shared) {
  1295. DVar.RefExpr = nullptr;
  1296. DVar.CKind = OMPC_firstprivate;
  1297. return DVar;
  1298. }
  1299. } while (I != E && !isImplicitTaskingRegion(I->Directive));
  1300. DVar.CKind =
  1301. (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
  1302. return DVar;
  1303. }
  1304. }
  1305. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1306. // in a Construct, implicitly determined, p.3]
  1307. // For constructs other than task, if no default clause is present, these
  1308. // variables inherit their data-sharing attributes from the enclosing
  1309. // context.
  1310. return getDSA(++Iter, D);
  1311. }
  1312. const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
  1313. const Expr *NewDE) {
  1314. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  1315. D = getCanonicalDecl(D);
  1316. SharingMapTy &StackElem = getTopOfStack();
  1317. auto It = StackElem.AlignedMap.find(D);
  1318. if (It == StackElem.AlignedMap.end()) {
  1319. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  1320. StackElem.AlignedMap[D] = NewDE;
  1321. return nullptr;
  1322. }
  1323. assert(It->second && "Unexpected nullptr expr in the aligned map");
  1324. return It->second;
  1325. }
  1326. const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
  1327. const Expr *NewDE) {
  1328. assert(!isStackEmpty() && "Data sharing attributes stack is empty");
  1329. D = getCanonicalDecl(D);
  1330. SharingMapTy &StackElem = getTopOfStack();
  1331. auto It = StackElem.NontemporalMap.find(D);
  1332. if (It == StackElem.NontemporalMap.end()) {
  1333. assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
  1334. StackElem.NontemporalMap[D] = NewDE;
  1335. return nullptr;
  1336. }
  1337. assert(It->second && "Unexpected nullptr expr in the aligned map");
  1338. return It->second;
  1339. }
  1340. void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
  1341. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1342. D = getCanonicalDecl(D);
  1343. SharingMapTy &StackElem = getTopOfStack();
  1344. StackElem.LCVMap.try_emplace(
  1345. D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
  1346. }
  1347. const DSAStackTy::LCDeclInfo
  1348. DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
  1349. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1350. D = getCanonicalDecl(D);
  1351. const SharingMapTy &StackElem = getTopOfStack();
  1352. auto It = StackElem.LCVMap.find(D);
  1353. if (It != StackElem.LCVMap.end())
  1354. return It->second;
  1355. return {0, nullptr};
  1356. }
  1357. const DSAStackTy::LCDeclInfo
  1358. DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const {
  1359. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1360. D = getCanonicalDecl(D);
  1361. for (unsigned I = Level + 1; I > 0; --I) {
  1362. const SharingMapTy &StackElem = getStackElemAtLevel(I - 1);
  1363. auto It = StackElem.LCVMap.find(D);
  1364. if (It != StackElem.LCVMap.end())
  1365. return It->second;
  1366. }
  1367. return {0, nullptr};
  1368. }
  1369. const DSAStackTy::LCDeclInfo
  1370. DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
  1371. const SharingMapTy *Parent = getSecondOnStackOrNull();
  1372. assert(Parent && "Data-sharing attributes stack is empty");
  1373. D = getCanonicalDecl(D);
  1374. auto It = Parent->LCVMap.find(D);
  1375. if (It != Parent->LCVMap.end())
  1376. return It->second;
  1377. return {0, nullptr};
  1378. }
  1379. const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
  1380. const SharingMapTy *Parent = getSecondOnStackOrNull();
  1381. assert(Parent && "Data-sharing attributes stack is empty");
  1382. if (Parent->LCVMap.size() < I)
  1383. return nullptr;
  1384. for (const auto &Pair : Parent->LCVMap)
  1385. if (Pair.second.first == I)
  1386. return Pair.first;
  1387. return nullptr;
  1388. }
  1389. void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
  1390. DeclRefExpr *PrivateCopy, unsigned Modifier,
  1391. bool AppliedToPointee) {
  1392. D = getCanonicalDecl(D);
  1393. if (A == OMPC_threadprivate) {
  1394. DSAInfo &Data = Threadprivates[D];
  1395. Data.Attributes = A;
  1396. Data.RefExpr.setPointer(E);
  1397. Data.PrivateCopy = nullptr;
  1398. Data.Modifier = Modifier;
  1399. } else {
  1400. DSAInfo &Data = getTopOfStack().SharingMap[D];
  1401. assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
  1402. (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
  1403. (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
  1404. (isLoopControlVariable(D).first && A == OMPC_private));
  1405. Data.Modifier = Modifier;
  1406. if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
  1407. Data.RefExpr.setInt(/*IntVal=*/true);
  1408. return;
  1409. }
  1410. const bool IsLastprivate =
  1411. A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
  1412. Data.Attributes = A;
  1413. Data.RefExpr.setPointerAndInt(E, IsLastprivate);
  1414. Data.PrivateCopy = PrivateCopy;
  1415. Data.AppliedToPointee = AppliedToPointee;
  1416. if (PrivateCopy) {
  1417. DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
  1418. Data.Modifier = Modifier;
  1419. Data.Attributes = A;
  1420. Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
  1421. Data.PrivateCopy = nullptr;
  1422. Data.AppliedToPointee = AppliedToPointee;
  1423. }
  1424. }
  1425. }
  1426. /// Build a variable declaration for OpenMP loop iteration variable.
  1427. static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
  1428. StringRef Name, const AttrVec *Attrs = nullptr,
  1429. DeclRefExpr *OrigRef = nullptr) {
  1430. DeclContext *DC = SemaRef.CurContext;
  1431. IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
  1432. TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
  1433. auto *Decl =
  1434. VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
  1435. if (Attrs) {
  1436. for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
  1437. I != E; ++I)
  1438. Decl->addAttr(*I);
  1439. }
  1440. Decl->setImplicit();
  1441. if (OrigRef) {
  1442. Decl->addAttr(
  1443. OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
  1444. }
  1445. return Decl;
  1446. }
  1447. static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
  1448. SourceLocation Loc,
  1449. bool RefersToCapture = false) {
  1450. D->setReferenced();
  1451. D->markUsed(S.Context);
  1452. return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
  1453. SourceLocation(), D, RefersToCapture, Loc, Ty,
  1454. VK_LValue);
  1455. }
  1456. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  1457. BinaryOperatorKind BOK) {
  1458. D = getCanonicalDecl(D);
  1459. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1460. assert(
  1461. getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
  1462. "Additional reduction info may be specified only for reduction items.");
  1463. ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
  1464. assert(ReductionData.ReductionRange.isInvalid() &&
  1465. (getTopOfStack().Directive == OMPD_taskgroup ||
  1466. ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
  1467. isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
  1468. !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
  1469. "Additional reduction info may be specified only once for reduction "
  1470. "items.");
  1471. ReductionData.set(BOK, SR);
  1472. Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
  1473. if (!TaskgroupReductionRef) {
  1474. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  1475. SemaRef.Context.VoidPtrTy, ".task_red.");
  1476. TaskgroupReductionRef =
  1477. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  1478. }
  1479. }
  1480. void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
  1481. const Expr *ReductionRef) {
  1482. D = getCanonicalDecl(D);
  1483. assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
  1484. assert(
  1485. getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
  1486. "Additional reduction info may be specified only for reduction items.");
  1487. ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
  1488. assert(ReductionData.ReductionRange.isInvalid() &&
  1489. (getTopOfStack().Directive == OMPD_taskgroup ||
  1490. ((isOpenMPParallelDirective(getTopOfStack().Directive) ||
  1491. isOpenMPWorksharingDirective(getTopOfStack().Directive)) &&
  1492. !isOpenMPSimdDirective(getTopOfStack().Directive))) &&
  1493. "Additional reduction info may be specified only once for reduction "
  1494. "items.");
  1495. ReductionData.set(ReductionRef, SR);
  1496. Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef;
  1497. if (!TaskgroupReductionRef) {
  1498. VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
  1499. SemaRef.Context.VoidPtrTy, ".task_red.");
  1500. TaskgroupReductionRef =
  1501. buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
  1502. }
  1503. }
  1504. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  1505. const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
  1506. Expr *&TaskgroupDescriptor) const {
  1507. D = getCanonicalDecl(D);
  1508. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  1509. for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
  1510. const DSAInfo &Data = I->SharingMap.lookup(D);
  1511. if (Data.Attributes != OMPC_reduction ||
  1512. Data.Modifier != OMPC_REDUCTION_task)
  1513. continue;
  1514. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  1515. if (!ReductionData.ReductionOp ||
  1516. ReductionData.ReductionOp.is<const Expr *>())
  1517. return DSAVarData();
  1518. SR = ReductionData.ReductionRange;
  1519. BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
  1520. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  1521. "expression for the descriptor is not "
  1522. "set.");
  1523. TaskgroupDescriptor = I->TaskgroupReductionRef;
  1524. return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
  1525. Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
  1526. /*AppliedToPointee=*/false);
  1527. }
  1528. return DSAVarData();
  1529. }
  1530. const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
  1531. const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
  1532. Expr *&TaskgroupDescriptor) const {
  1533. D = getCanonicalDecl(D);
  1534. assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
  1535. for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
  1536. const DSAInfo &Data = I->SharingMap.lookup(D);
  1537. if (Data.Attributes != OMPC_reduction ||
  1538. Data.Modifier != OMPC_REDUCTION_task)
  1539. continue;
  1540. const ReductionData &ReductionData = I->ReductionMap.lookup(D);
  1541. if (!ReductionData.ReductionOp ||
  1542. !ReductionData.ReductionOp.is<const Expr *>())
  1543. return DSAVarData();
  1544. SR = ReductionData.ReductionRange;
  1545. ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
  1546. assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
  1547. "expression for the descriptor is not "
  1548. "set.");
  1549. TaskgroupDescriptor = I->TaskgroupReductionRef;
  1550. return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(),
  1551. Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task,
  1552. /*AppliedToPointee=*/false);
  1553. }
  1554. return DSAVarData();
  1555. }
  1556. bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
  1557. D = D->getCanonicalDecl();
  1558. for (const_iterator E = end(); I != E; ++I) {
  1559. if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
  1560. isOpenMPTargetExecutionDirective(I->Directive)) {
  1561. if (I->CurScope) {
  1562. Scope *TopScope = I->CurScope->getParent();
  1563. Scope *CurScope = getCurScope();
  1564. while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
  1565. CurScope = CurScope->getParent();
  1566. return CurScope != TopScope;
  1567. }
  1568. for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent())
  1569. if (I->Context == DC)
  1570. return true;
  1571. return false;
  1572. }
  1573. }
  1574. return false;
  1575. }
  1576. static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
  1577. bool AcceptIfMutable = true,
  1578. bool *IsClassType = nullptr) {
  1579. ASTContext &Context = SemaRef.getASTContext();
  1580. Type = Type.getNonReferenceType().getCanonicalType();
  1581. bool IsConstant = Type.isConstant(Context);
  1582. Type = Context.getBaseElementType(Type);
  1583. const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
  1584. ? Type->getAsCXXRecordDecl()
  1585. : nullptr;
  1586. if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
  1587. if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
  1588. RD = CTD->getTemplatedDecl();
  1589. if (IsClassType)
  1590. *IsClassType = RD;
  1591. return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
  1592. RD->hasDefinition() && RD->hasMutableFields());
  1593. }
  1594. static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
  1595. QualType Type, OpenMPClauseKind CKind,
  1596. SourceLocation ELoc,
  1597. bool AcceptIfMutable = true,
  1598. bool ListItemNotVar = false) {
  1599. ASTContext &Context = SemaRef.getASTContext();
  1600. bool IsClassType;
  1601. if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
  1602. unsigned Diag = ListItemNotVar ? diag::err_omp_const_list_item
  1603. : IsClassType ? diag::err_omp_const_not_mutable_variable
  1604. : diag::err_omp_const_variable;
  1605. SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
  1606. if (!ListItemNotVar && D) {
  1607. const VarDecl *VD = dyn_cast<VarDecl>(D);
  1608. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  1609. VarDecl::DeclarationOnly;
  1610. SemaRef.Diag(D->getLocation(),
  1611. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  1612. << D;
  1613. }
  1614. return true;
  1615. }
  1616. return false;
  1617. }
  1618. const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
  1619. bool FromParent) {
  1620. D = getCanonicalDecl(D);
  1621. DSAVarData DVar;
  1622. auto *VD = dyn_cast<VarDecl>(D);
  1623. auto TI = Threadprivates.find(D);
  1624. if (TI != Threadprivates.end()) {
  1625. DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
  1626. DVar.CKind = OMPC_threadprivate;
  1627. DVar.Modifier = TI->getSecond().Modifier;
  1628. return DVar;
  1629. }
  1630. if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  1631. DVar.RefExpr = buildDeclRefExpr(
  1632. SemaRef, VD, D->getType().getNonReferenceType(),
  1633. VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
  1634. DVar.CKind = OMPC_threadprivate;
  1635. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1636. return DVar;
  1637. }
  1638. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1639. // in a Construct, C/C++, predetermined, p.1]
  1640. // Variables appearing in threadprivate directives are threadprivate.
  1641. if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
  1642. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  1643. SemaRef.getLangOpts().OpenMPUseTLS &&
  1644. SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
  1645. (VD && VD->getStorageClass() == SC_Register &&
  1646. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
  1647. DVar.RefExpr = buildDeclRefExpr(
  1648. SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
  1649. DVar.CKind = OMPC_threadprivate;
  1650. addDSA(D, DVar.RefExpr, OMPC_threadprivate);
  1651. return DVar;
  1652. }
  1653. if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
  1654. VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
  1655. !isLoopControlVariable(D).first) {
  1656. const_iterator IterTarget =
  1657. std::find_if(begin(), end(), [](const SharingMapTy &Data) {
  1658. return isOpenMPTargetExecutionDirective(Data.Directive);
  1659. });
  1660. if (IterTarget != end()) {
  1661. const_iterator ParentIterTarget = IterTarget + 1;
  1662. for (const_iterator Iter = begin(); Iter != ParentIterTarget; ++Iter) {
  1663. if (isOpenMPLocal(VD, Iter)) {
  1664. DVar.RefExpr =
  1665. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1666. D->getLocation());
  1667. DVar.CKind = OMPC_threadprivate;
  1668. return DVar;
  1669. }
  1670. }
  1671. if (!isClauseParsingMode() || IterTarget != begin()) {
  1672. auto DSAIter = IterTarget->SharingMap.find(D);
  1673. if (DSAIter != IterTarget->SharingMap.end() &&
  1674. isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
  1675. DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
  1676. DVar.CKind = OMPC_threadprivate;
  1677. return DVar;
  1678. }
  1679. const_iterator End = end();
  1680. if (!SemaRef.isOpenMPCapturedByRef(D,
  1681. std::distance(ParentIterTarget, End),
  1682. /*OpenMPCaptureLevel=*/0)) {
  1683. DVar.RefExpr =
  1684. buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
  1685. IterTarget->ConstructLoc);
  1686. DVar.CKind = OMPC_threadprivate;
  1687. return DVar;
  1688. }
  1689. }
  1690. }
  1691. }
  1692. if (isStackEmpty())
  1693. // Not in OpenMP execution region and top scope was already checked.
  1694. return DVar;
  1695. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1696. // in a Construct, C/C++, predetermined, p.4]
  1697. // Static data members are shared.
  1698. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1699. // in a Construct, C/C++, predetermined, p.7]
  1700. // Variables with static storage duration that are declared in a scope
  1701. // inside the construct are shared.
  1702. if (VD && VD->isStaticDataMember()) {
  1703. // Check for explicitly specified attributes.
  1704. const_iterator I = begin();
  1705. const_iterator EndI = end();
  1706. if (FromParent && I != EndI)
  1707. ++I;
  1708. if (I != EndI) {
  1709. auto It = I->SharingMap.find(D);
  1710. if (It != I->SharingMap.end()) {
  1711. const DSAInfo &Data = It->getSecond();
  1712. DVar.RefExpr = Data.RefExpr.getPointer();
  1713. DVar.PrivateCopy = Data.PrivateCopy;
  1714. DVar.CKind = Data.Attributes;
  1715. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1716. DVar.DKind = I->Directive;
  1717. DVar.Modifier = Data.Modifier;
  1718. DVar.AppliedToPointee = Data.AppliedToPointee;
  1719. return DVar;
  1720. }
  1721. }
  1722. DVar.CKind = OMPC_shared;
  1723. return DVar;
  1724. }
  1725. auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
  1726. // The predetermined shared attribute for const-qualified types having no
  1727. // mutable members was removed after OpenMP 3.1.
  1728. if (SemaRef.LangOpts.OpenMP <= 31) {
  1729. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  1730. // in a Construct, C/C++, predetermined, p.6]
  1731. // Variables with const qualified type having no mutable member are
  1732. // shared.
  1733. if (isConstNotMutableType(SemaRef, D->getType())) {
  1734. // Variables with const-qualified type having no mutable member may be
  1735. // listed in a firstprivate clause, even if they are static data members.
  1736. DSAVarData DVarTemp = hasInnermostDSA(
  1737. D,
  1738. [](OpenMPClauseKind C, bool) {
  1739. return C == OMPC_firstprivate || C == OMPC_shared;
  1740. },
  1741. MatchesAlways, FromParent);
  1742. if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
  1743. return DVarTemp;
  1744. DVar.CKind = OMPC_shared;
  1745. return DVar;
  1746. }
  1747. }
  1748. // Explicitly specified attributes and local variables with predetermined
  1749. // attributes.
  1750. const_iterator I = begin();
  1751. const_iterator EndI = end();
  1752. if (FromParent && I != EndI)
  1753. ++I;
  1754. if (I == EndI)
  1755. return DVar;
  1756. auto It = I->SharingMap.find(D);
  1757. if (It != I->SharingMap.end()) {
  1758. const DSAInfo &Data = It->getSecond();
  1759. DVar.RefExpr = Data.RefExpr.getPointer();
  1760. DVar.PrivateCopy = Data.PrivateCopy;
  1761. DVar.CKind = Data.Attributes;
  1762. DVar.ImplicitDSALoc = I->DefaultAttrLoc;
  1763. DVar.DKind = I->Directive;
  1764. DVar.Modifier = Data.Modifier;
  1765. DVar.AppliedToPointee = Data.AppliedToPointee;
  1766. }
  1767. return DVar;
  1768. }
  1769. const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  1770. bool FromParent) const {
  1771. if (isStackEmpty()) {
  1772. const_iterator I;
  1773. return getDSA(I, D);
  1774. }
  1775. D = getCanonicalDecl(D);
  1776. const_iterator StartI = begin();
  1777. const_iterator EndI = end();
  1778. if (FromParent && StartI != EndI)
  1779. ++StartI;
  1780. return getDSA(StartI, D);
  1781. }
  1782. const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
  1783. unsigned Level) const {
  1784. if (getStackSize() <= Level)
  1785. return DSAVarData();
  1786. D = getCanonicalDecl(D);
  1787. const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level);
  1788. return getDSA(StartI, D);
  1789. }
  1790. const DSAStackTy::DSAVarData
  1791. DSAStackTy::hasDSA(ValueDecl *D,
  1792. const llvm::function_ref<bool(OpenMPClauseKind, bool,
  1793. DefaultDataSharingAttributes)>
  1794. CPred,
  1795. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1796. bool FromParent) const {
  1797. if (isStackEmpty())
  1798. return {};
  1799. D = getCanonicalDecl(D);
  1800. const_iterator I = begin();
  1801. const_iterator EndI = end();
  1802. if (FromParent && I != EndI)
  1803. ++I;
  1804. for (; I != EndI; ++I) {
  1805. if (!DPred(I->Directive) &&
  1806. !isImplicitOrExplicitTaskingRegion(I->Directive))
  1807. continue;
  1808. const_iterator NewI = I;
  1809. DSAVarData DVar = getDSA(NewI, D);
  1810. if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee, I->DefaultAttr))
  1811. return DVar;
  1812. }
  1813. return {};
  1814. }
  1815. const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
  1816. ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
  1817. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1818. bool FromParent) const {
  1819. if (isStackEmpty())
  1820. return {};
  1821. D = getCanonicalDecl(D);
  1822. const_iterator StartI = begin();
  1823. const_iterator EndI = end();
  1824. if (FromParent && StartI != EndI)
  1825. ++StartI;
  1826. if (StartI == EndI || !DPred(StartI->Directive))
  1827. return {};
  1828. const_iterator NewI = StartI;
  1829. DSAVarData DVar = getDSA(NewI, D);
  1830. return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee))
  1831. ? DVar
  1832. : DSAVarData();
  1833. }
  1834. bool DSAStackTy::hasExplicitDSA(
  1835. const ValueDecl *D,
  1836. const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred,
  1837. unsigned Level, bool NotLastprivate) const {
  1838. if (getStackSize() <= Level)
  1839. return false;
  1840. D = getCanonicalDecl(D);
  1841. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  1842. auto I = StackElem.SharingMap.find(D);
  1843. if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() &&
  1844. CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) &&
  1845. (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
  1846. return true;
  1847. // Check predetermined rules for the loop control variables.
  1848. auto LI = StackElem.LCVMap.find(D);
  1849. if (LI != StackElem.LCVMap.end())
  1850. return CPred(OMPC_private, /*AppliedToPointee=*/false);
  1851. return false;
  1852. }
  1853. bool DSAStackTy::hasExplicitDirective(
  1854. const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
  1855. unsigned Level) const {
  1856. if (getStackSize() <= Level)
  1857. return false;
  1858. const SharingMapTy &StackElem = getStackElemAtLevel(Level);
  1859. return DPred(StackElem.Directive);
  1860. }
  1861. bool DSAStackTy::hasDirective(
  1862. const llvm::function_ref<bool(OpenMPDirectiveKind,
  1863. const DeclarationNameInfo &, SourceLocation)>
  1864. DPred,
  1865. bool FromParent) const {
  1866. // We look only in the enclosing region.
  1867. size_t Skip = FromParent ? 2 : 1;
  1868. for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
  1869. I != E; ++I) {
  1870. if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
  1871. return true;
  1872. }
  1873. return false;
  1874. }
  1875. void Sema::InitDataSharingAttributesStack() {
  1876. VarDataSharingAttributesStack = new DSAStackTy(*this);
  1877. }
  1878. #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
  1879. void Sema::pushOpenMPFunctionRegion() { DSAStack->pushFunction(); }
  1880. void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
  1881. DSAStack->popFunction(OldFSI);
  1882. }
  1883. static bool isOpenMPDeviceDelayedContext(Sema &S) {
  1884. assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
  1885. "Expected OpenMP device compilation.");
  1886. return !S.isInOpenMPTargetExecutionDirective();
  1887. }
  1888. namespace {
  1889. /// Status of the function emission on the host/device.
  1890. enum class FunctionEmissionStatus {
  1891. Emitted,
  1892. Discarded,
  1893. Unknown,
  1894. };
  1895. } // anonymous namespace
  1896. Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
  1897. unsigned DiagID,
  1898. FunctionDecl *FD) {
  1899. assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
  1900. "Expected OpenMP device compilation.");
  1901. SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
  1902. if (FD) {
  1903. FunctionEmissionStatus FES = getEmissionStatus(FD);
  1904. switch (FES) {
  1905. case FunctionEmissionStatus::Emitted:
  1906. Kind = SemaDiagnosticBuilder::K_Immediate;
  1907. break;
  1908. case FunctionEmissionStatus::Unknown:
  1909. // TODO: We should always delay diagnostics here in case a target
  1910. // region is in a function we do not emit. However, as the
  1911. // current diagnostics are associated with the function containing
  1912. // the target region and we do not emit that one, we would miss out
  1913. // on diagnostics for the target region itself. We need to anchor
  1914. // the diagnostics with the new generated function *or* ensure we
  1915. // emit diagnostics associated with the surrounding function.
  1916. Kind = isOpenMPDeviceDelayedContext(*this)
  1917. ? SemaDiagnosticBuilder::K_Deferred
  1918. : SemaDiagnosticBuilder::K_Immediate;
  1919. break;
  1920. case FunctionEmissionStatus::TemplateDiscarded:
  1921. case FunctionEmissionStatus::OMPDiscarded:
  1922. Kind = SemaDiagnosticBuilder::K_Nop;
  1923. break;
  1924. case FunctionEmissionStatus::CUDADiscarded:
  1925. llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
  1926. break;
  1927. }
  1928. }
  1929. return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
  1930. }
  1931. Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
  1932. unsigned DiagID,
  1933. FunctionDecl *FD) {
  1934. assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
  1935. "Expected OpenMP host compilation.");
  1936. SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop;
  1937. if (FD) {
  1938. FunctionEmissionStatus FES = getEmissionStatus(FD);
  1939. switch (FES) {
  1940. case FunctionEmissionStatus::Emitted:
  1941. Kind = SemaDiagnosticBuilder::K_Immediate;
  1942. break;
  1943. case FunctionEmissionStatus::Unknown:
  1944. Kind = SemaDiagnosticBuilder::K_Deferred;
  1945. break;
  1946. case FunctionEmissionStatus::TemplateDiscarded:
  1947. case FunctionEmissionStatus::OMPDiscarded:
  1948. case FunctionEmissionStatus::CUDADiscarded:
  1949. Kind = SemaDiagnosticBuilder::K_Nop;
  1950. break;
  1951. }
  1952. }
  1953. return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this);
  1954. }
  1955. static OpenMPDefaultmapClauseKind
  1956. getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
  1957. if (LO.OpenMP <= 45) {
  1958. if (VD->getType().getNonReferenceType()->isScalarType())
  1959. return OMPC_DEFAULTMAP_scalar;
  1960. return OMPC_DEFAULTMAP_aggregate;
  1961. }
  1962. if (VD->getType().getNonReferenceType()->isAnyPointerType())
  1963. return OMPC_DEFAULTMAP_pointer;
  1964. if (VD->getType().getNonReferenceType()->isScalarType())
  1965. return OMPC_DEFAULTMAP_scalar;
  1966. return OMPC_DEFAULTMAP_aggregate;
  1967. }
  1968. bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
  1969. unsigned OpenMPCaptureLevel) const {
  1970. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  1971. ASTContext &Ctx = getASTContext();
  1972. bool IsByRef = true;
  1973. // Find the directive that is associated with the provided scope.
  1974. D = cast<ValueDecl>(D->getCanonicalDecl());
  1975. QualType Ty = D->getType();
  1976. bool IsVariableUsedInMapClause = false;
  1977. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
  1978. // This table summarizes how a given variable should be passed to the device
  1979. // given its type and the clauses where it appears. This table is based on
  1980. // the description in OpenMP 4.5 [2.10.4, target Construct] and
  1981. // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
  1982. //
  1983. // =========================================================================
  1984. // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
  1985. // | |(tofrom:scalar)| | pvt | |has_dv_adr| |
  1986. // =========================================================================
  1987. // | scl | | | | - | | bycopy|
  1988. // | scl | | - | x | - | - | bycopy|
  1989. // | scl | | x | - | - | - | null |
  1990. // | scl | x | | | - | | byref |
  1991. // | scl | x | - | x | - | - | bycopy|
  1992. // | scl | x | x | - | - | - | null |
  1993. // | scl | | - | - | - | x | byref |
  1994. // | scl | x | - | - | - | x | byref |
  1995. //
  1996. // | agg | n.a. | | | - | | byref |
  1997. // | agg | n.a. | - | x | - | - | byref |
  1998. // | agg | n.a. | x | - | - | - | null |
  1999. // | agg | n.a. | - | - | - | x | byref |
  2000. // | agg | n.a. | - | - | - | x[] | byref |
  2001. //
  2002. // | ptr | n.a. | | | - | | bycopy|
  2003. // | ptr | n.a. | - | x | - | - | bycopy|
  2004. // | ptr | n.a. | x | - | - | - | null |
  2005. // | ptr | n.a. | - | - | - | x | byref |
  2006. // | ptr | n.a. | - | - | - | x[] | bycopy|
  2007. // | ptr | n.a. | - | - | x | | bycopy|
  2008. // | ptr | n.a. | - | - | x | x | bycopy|
  2009. // | ptr | n.a. | - | - | x | x[] | bycopy|
  2010. // =========================================================================
  2011. // Legend:
  2012. // scl - scalar
  2013. // ptr - pointer
  2014. // agg - aggregate
  2015. // x - applies
  2016. // - - invalid in this combination
  2017. // [] - mapped with an array section
  2018. // byref - should be mapped by reference
  2019. // byval - should be mapped by value
  2020. // null - initialize a local variable to null on the device
  2021. //
  2022. // Observations:
  2023. // - All scalar declarations that show up in a map clause have to be passed
  2024. // by reference, because they may have been mapped in the enclosing data
  2025. // environment.
  2026. // - If the scalar value does not fit the size of uintptr, it has to be
  2027. // passed by reference, regardless the result in the table above.
  2028. // - For pointers mapped by value that have either an implicit map or an
  2029. // array section, the runtime library may pass the NULL value to the
  2030. // device instead of the value passed to it by the compiler.
  2031. if (Ty->isReferenceType())
  2032. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  2033. // Locate map clauses and see if the variable being captured is referred to
  2034. // in any of those clauses. Here we only care about variables, not fields,
  2035. // because fields are part of aggregates.
  2036. bool IsVariableAssociatedWithSection = false;
  2037. DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  2038. D, Level,
  2039. [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection,
  2040. D](OMPClauseMappableExprCommon::MappableExprComponentListRef
  2041. MapExprComponents,
  2042. OpenMPClauseKind WhereFoundClauseKind) {
  2043. // Both map and has_device_addr clauses information influences how a
  2044. // variable is captured. E.g. is_device_ptr does not require changing
  2045. // the default behavior.
  2046. if (WhereFoundClauseKind != OMPC_map &&
  2047. WhereFoundClauseKind != OMPC_has_device_addr)
  2048. return false;
  2049. auto EI = MapExprComponents.rbegin();
  2050. auto EE = MapExprComponents.rend();
  2051. assert(EI != EE && "Invalid map expression!");
  2052. if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
  2053. IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
  2054. ++EI;
  2055. if (EI == EE)
  2056. return false;
  2057. if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
  2058. isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
  2059. isa<MemberExpr>(EI->getAssociatedExpression()) ||
  2060. isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) {
  2061. IsVariableAssociatedWithSection = true;
  2062. // There is nothing more we need to know about this variable.
  2063. return true;
  2064. }
  2065. // Keep looking for more map info.
  2066. return false;
  2067. });
  2068. if (IsVariableUsedInMapClause) {
  2069. // If variable is identified in a map clause it is always captured by
  2070. // reference except if it is a pointer that is dereferenced somehow.
  2071. IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
  2072. } else {
  2073. // By default, all the data that has a scalar type is mapped by copy
  2074. // (except for reduction variables).
  2075. // Defaultmap scalar is mutual exclusive to defaultmap pointer
  2076. IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
  2077. !Ty->isAnyPointerType()) ||
  2078. !Ty->isScalarType() ||
  2079. DSAStack->isDefaultmapCapturedByRef(
  2080. Level, getVariableCategoryFromDecl(LangOpts, D)) ||
  2081. DSAStack->hasExplicitDSA(
  2082. D,
  2083. [](OpenMPClauseKind K, bool AppliedToPointee) {
  2084. return K == OMPC_reduction && !AppliedToPointee;
  2085. },
  2086. Level);
  2087. }
  2088. }
  2089. if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
  2090. IsByRef =
  2091. ((IsVariableUsedInMapClause &&
  2092. DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
  2093. OMPD_target) ||
  2094. !(DSAStack->hasExplicitDSA(
  2095. D,
  2096. [](OpenMPClauseKind K, bool AppliedToPointee) -> bool {
  2097. return K == OMPC_firstprivate ||
  2098. (K == OMPC_reduction && AppliedToPointee);
  2099. },
  2100. Level, /*NotLastprivate=*/true) ||
  2101. DSAStack->isUsesAllocatorsDecl(Level, D))) &&
  2102. // If the variable is artificial and must be captured by value - try to
  2103. // capture by value.
  2104. !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
  2105. !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) &&
  2106. // If the variable is implicitly firstprivate and scalar - capture by
  2107. // copy
  2108. !((DSAStack->getDefaultDSA() == DSA_firstprivate ||
  2109. DSAStack->getDefaultDSA() == DSA_private) &&
  2110. !DSAStack->hasExplicitDSA(
  2111. D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; },
  2112. Level) &&
  2113. !DSAStack->isLoopControlVariable(D, Level).first);
  2114. }
  2115. // When passing data by copy, we need to make sure it fits the uintptr size
  2116. // and alignment, because the runtime library only deals with uintptr types.
  2117. // If it does not fit the uintptr size, we need to pass the data by reference
  2118. // instead.
  2119. if (!IsByRef &&
  2120. (Ctx.getTypeSizeInChars(Ty) >
  2121. Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
  2122. Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
  2123. IsByRef = true;
  2124. }
  2125. return IsByRef;
  2126. }
  2127. unsigned Sema::getOpenMPNestingLevel() const {
  2128. assert(getLangOpts().OpenMP);
  2129. return DSAStack->getNestingLevel();
  2130. }
  2131. bool Sema::isInOpenMPTaskUntiedContext() const {
  2132. return isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
  2133. DSAStack->isUntiedRegion();
  2134. }
  2135. bool Sema::isInOpenMPTargetExecutionDirective() const {
  2136. return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
  2137. !DSAStack->isClauseParsingMode()) ||
  2138. DSAStack->hasDirective(
  2139. [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  2140. SourceLocation) -> bool {
  2141. return isOpenMPTargetExecutionDirective(K);
  2142. },
  2143. false);
  2144. }
  2145. bool Sema::isOpenMPRebuildMemberExpr(ValueDecl *D) {
  2146. // Only rebuild for Field.
  2147. if (!dyn_cast<FieldDecl>(D))
  2148. return false;
  2149. DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
  2150. D,
  2151. [](OpenMPClauseKind C, bool AppliedToPointee,
  2152. DefaultDataSharingAttributes DefaultAttr) {
  2153. return isOpenMPPrivate(C) && !AppliedToPointee &&
  2154. (DefaultAttr == DSA_firstprivate || DefaultAttr == DSA_private);
  2155. },
  2156. [](OpenMPDirectiveKind) { return true; },
  2157. DSAStack->isClauseParsingMode());
  2158. if (DVarPrivate.CKind != OMPC_unknown)
  2159. return true;
  2160. return false;
  2161. }
  2162. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  2163. Expr *CaptureExpr, bool WithInit,
  2164. DeclContext *CurContext,
  2165. bool AsExpression);
  2166. VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
  2167. unsigned StopAt) {
  2168. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  2169. D = getCanonicalDecl(D);
  2170. auto *VD = dyn_cast<VarDecl>(D);
  2171. // Do not capture constexpr variables.
  2172. if (VD && VD->isConstexpr())
  2173. return nullptr;
  2174. // If we want to determine whether the variable should be captured from the
  2175. // perspective of the current capturing scope, and we've already left all the
  2176. // capturing scopes of the top directive on the stack, check from the
  2177. // perspective of its parent directive (if any) instead.
  2178. DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
  2179. *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
  2180. // If we are attempting to capture a global variable in a directive with
  2181. // 'target' we return true so that this global is also mapped to the device.
  2182. //
  2183. if (VD && !VD->hasLocalStorage() &&
  2184. (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
  2185. if (isInOpenMPTargetExecutionDirective()) {
  2186. DSAStackTy::DSAVarData DVarTop =
  2187. DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  2188. if (DVarTop.CKind != OMPC_unknown && DVarTop.RefExpr)
  2189. return VD;
  2190. // If the declaration is enclosed in a 'declare target' directive,
  2191. // then it should not be captured.
  2192. //
  2193. if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  2194. return nullptr;
  2195. CapturedRegionScopeInfo *CSI = nullptr;
  2196. for (FunctionScopeInfo *FSI : llvm::drop_begin(
  2197. llvm::reverse(FunctionScopes),
  2198. CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
  2199. if (!isa<CapturingScopeInfo>(FSI))
  2200. return nullptr;
  2201. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
  2202. if (RSI->CapRegionKind == CR_OpenMP) {
  2203. CSI = RSI;
  2204. break;
  2205. }
  2206. }
  2207. assert(CSI && "Failed to find CapturedRegionScopeInfo");
  2208. SmallVector<OpenMPDirectiveKind, 4> Regions;
  2209. getOpenMPCaptureRegions(Regions,
  2210. DSAStack->getDirective(CSI->OpenMPLevel));
  2211. if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
  2212. return VD;
  2213. }
  2214. if (isInOpenMPDeclareTargetContext()) {
  2215. // Try to mark variable as declare target if it is used in capturing
  2216. // regions.
  2217. if (LangOpts.OpenMP <= 45 &&
  2218. !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  2219. checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
  2220. return nullptr;
  2221. }
  2222. }
  2223. if (CheckScopeInfo) {
  2224. bool OpenMPFound = false;
  2225. for (unsigned I = StopAt + 1; I > 0; --I) {
  2226. FunctionScopeInfo *FSI = FunctionScopes[I - 1];
  2227. if (!isa<CapturingScopeInfo>(FSI))
  2228. return nullptr;
  2229. if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
  2230. if (RSI->CapRegionKind == CR_OpenMP) {
  2231. OpenMPFound = true;
  2232. break;
  2233. }
  2234. }
  2235. if (!OpenMPFound)
  2236. return nullptr;
  2237. }
  2238. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  2239. (!DSAStack->isClauseParsingMode() ||
  2240. DSAStack->getParentDirective() != OMPD_unknown)) {
  2241. auto &&Info = DSAStack->isLoopControlVariable(D);
  2242. if (Info.first ||
  2243. (VD && VD->hasLocalStorage() &&
  2244. isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
  2245. (VD && DSAStack->isForceVarCapturing()))
  2246. return VD ? VD : Info.second;
  2247. DSAStackTy::DSAVarData DVarTop =
  2248. DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
  2249. if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) &&
  2250. (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee))
  2251. return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl());
  2252. // Threadprivate variables must not be captured.
  2253. if (isOpenMPThreadPrivate(DVarTop.CKind))
  2254. return nullptr;
  2255. // The variable is not private or it is the variable in the directive with
  2256. // default(none) clause and not used in any clause.
  2257. DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
  2258. D,
  2259. [](OpenMPClauseKind C, bool AppliedToPointee, bool) {
  2260. return isOpenMPPrivate(C) && !AppliedToPointee;
  2261. },
  2262. [](OpenMPDirectiveKind) { return true; },
  2263. DSAStack->isClauseParsingMode());
  2264. // Global shared must not be captured.
  2265. if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown &&
  2266. ((DSAStack->getDefaultDSA() != DSA_none &&
  2267. DSAStack->getDefaultDSA() != DSA_private &&
  2268. DSAStack->getDefaultDSA() != DSA_firstprivate) ||
  2269. DVarTop.CKind == OMPC_shared))
  2270. return nullptr;
  2271. auto *FD = dyn_cast<FieldDecl>(D);
  2272. if (DVarPrivate.CKind != OMPC_unknown && !VD && FD &&
  2273. !DVarPrivate.PrivateCopy) {
  2274. DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
  2275. D,
  2276. [](OpenMPClauseKind C, bool AppliedToPointee,
  2277. DefaultDataSharingAttributes DefaultAttr) {
  2278. return isOpenMPPrivate(C) && !AppliedToPointee &&
  2279. (DefaultAttr == DSA_firstprivate ||
  2280. DefaultAttr == DSA_private);
  2281. },
  2282. [](OpenMPDirectiveKind) { return true; },
  2283. DSAStack->isClauseParsingMode());
  2284. if (DVarPrivate.CKind == OMPC_unknown)
  2285. return nullptr;
  2286. VarDecl *VD = DSAStack->getImplicitFDCapExprDecl(FD);
  2287. if (VD)
  2288. return VD;
  2289. if (getCurrentThisType().isNull())
  2290. return nullptr;
  2291. Expr *ThisExpr = BuildCXXThisExpr(SourceLocation(), getCurrentThisType(),
  2292. /*IsImplicit=*/true);
  2293. const CXXScopeSpec CS = CXXScopeSpec();
  2294. Expr *ME = BuildMemberExpr(ThisExpr, /*IsArrow=*/true, SourceLocation(),
  2295. NestedNameSpecifierLoc(), SourceLocation(), FD,
  2296. DeclAccessPair::make(FD, FD->getAccess()),
  2297. /*HadMultipleCandidates=*/false,
  2298. DeclarationNameInfo(), FD->getType(),
  2299. VK_LValue, OK_Ordinary);
  2300. OMPCapturedExprDecl *CD = buildCaptureDecl(
  2301. *this, FD->getIdentifier(), ME, DVarPrivate.CKind != OMPC_private,
  2302. CurContext->getParent(), /*AsExpression=*/false);
  2303. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  2304. *this, CD, CD->getType().getNonReferenceType(), SourceLocation());
  2305. VD = cast<VarDecl>(VDPrivateRefExpr->getDecl());
  2306. DSAStack->addImplicitDefaultFirstprivateFD(FD, VD);
  2307. return VD;
  2308. }
  2309. if (DVarPrivate.CKind != OMPC_unknown ||
  2310. (VD && (DSAStack->getDefaultDSA() == DSA_none ||
  2311. DSAStack->getDefaultDSA() == DSA_private ||
  2312. DSAStack->getDefaultDSA() == DSA_firstprivate)))
  2313. return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
  2314. }
  2315. return nullptr;
  2316. }
  2317. void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
  2318. unsigned Level) const {
  2319. FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level));
  2320. }
  2321. void Sema::startOpenMPLoop() {
  2322. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  2323. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
  2324. DSAStack->loopInit();
  2325. }
  2326. void Sema::startOpenMPCXXRangeFor() {
  2327. assert(LangOpts.OpenMP && "OpenMP must be enabled.");
  2328. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  2329. DSAStack->resetPossibleLoopCounter();
  2330. DSAStack->loopStart();
  2331. }
  2332. }
  2333. OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
  2334. unsigned CapLevel) const {
  2335. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  2336. if (DSAStack->getCurrentDirective() != OMPD_unknown &&
  2337. (!DSAStack->isClauseParsingMode() ||
  2338. DSAStack->getParentDirective() != OMPD_unknown)) {
  2339. DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA(
  2340. D,
  2341. [](OpenMPClauseKind C, bool AppliedToPointee,
  2342. DefaultDataSharingAttributes DefaultAttr) {
  2343. return isOpenMPPrivate(C) && !AppliedToPointee &&
  2344. DefaultAttr == DSA_private;
  2345. },
  2346. [](OpenMPDirectiveKind) { return true; },
  2347. DSAStack->isClauseParsingMode());
  2348. if (DVarPrivate.CKind == OMPC_private && isa<OMPCapturedExprDecl>(D) &&
  2349. DSAStack->isImplicitDefaultFirstprivateFD(cast<VarDecl>(D)) &&
  2350. !DSAStack->isLoopControlVariable(D).first)
  2351. return OMPC_private;
  2352. }
  2353. if (DSAStack->hasExplicitDirective(isOpenMPTaskingDirective, Level)) {
  2354. bool IsTriviallyCopyable =
  2355. D->getType().getNonReferenceType().isTriviallyCopyableType(Context) &&
  2356. !D->getType()
  2357. .getNonReferenceType()
  2358. .getCanonicalType()
  2359. ->getAsCXXRecordDecl();
  2360. OpenMPDirectiveKind DKind = DSAStack->getDirective(Level);
  2361. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  2362. getOpenMPCaptureRegions(CaptureRegions, DKind);
  2363. if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) &&
  2364. (IsTriviallyCopyable ||
  2365. !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) {
  2366. if (DSAStack->hasExplicitDSA(
  2367. D,
  2368. [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; },
  2369. Level, /*NotLastprivate=*/true))
  2370. return OMPC_firstprivate;
  2371. DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
  2372. if (DVar.CKind != OMPC_shared &&
  2373. !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) {
  2374. DSAStack->addImplicitTaskFirstprivate(Level, D);
  2375. return OMPC_firstprivate;
  2376. }
  2377. }
  2378. }
  2379. if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  2380. if (DSAStack->getAssociatedLoops() > 0 && !DSAStack->isLoopStarted()) {
  2381. DSAStack->resetPossibleLoopCounter(D);
  2382. DSAStack->loopStart();
  2383. return OMPC_private;
  2384. }
  2385. if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
  2386. DSAStack->isLoopControlVariable(D).first) &&
  2387. !DSAStack->hasExplicitDSA(
  2388. D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; },
  2389. Level) &&
  2390. !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
  2391. return OMPC_private;
  2392. }
  2393. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  2394. if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
  2395. DSAStack->isForceVarCapturing() &&
  2396. !DSAStack->hasExplicitDSA(
  2397. D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; },
  2398. Level))
  2399. return OMPC_private;
  2400. }
  2401. // User-defined allocators are private since they must be defined in the
  2402. // context of target region.
  2403. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) &&
  2404. DSAStack->isUsesAllocatorsDecl(Level, D).value_or(
  2405. DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
  2406. DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator)
  2407. return OMPC_private;
  2408. return (DSAStack->hasExplicitDSA(
  2409. D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; },
  2410. Level) ||
  2411. (DSAStack->isClauseParsingMode() &&
  2412. DSAStack->getClauseParsingMode() == OMPC_private) ||
  2413. // Consider taskgroup reduction descriptor variable a private
  2414. // to avoid possible capture in the region.
  2415. (DSAStack->hasExplicitDirective(
  2416. [](OpenMPDirectiveKind K) {
  2417. return K == OMPD_taskgroup ||
  2418. ((isOpenMPParallelDirective(K) ||
  2419. isOpenMPWorksharingDirective(K)) &&
  2420. !isOpenMPSimdDirective(K));
  2421. },
  2422. Level) &&
  2423. DSAStack->isTaskgroupReductionRef(D, Level)))
  2424. ? OMPC_private
  2425. : OMPC_unknown;
  2426. }
  2427. void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
  2428. unsigned Level) {
  2429. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  2430. D = getCanonicalDecl(D);
  2431. OpenMPClauseKind OMPC = OMPC_unknown;
  2432. for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
  2433. const unsigned NewLevel = I - 1;
  2434. if (DSAStack->hasExplicitDSA(
  2435. D,
  2436. [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) {
  2437. if (isOpenMPPrivate(K) && !AppliedToPointee) {
  2438. OMPC = K;
  2439. return true;
  2440. }
  2441. return false;
  2442. },
  2443. NewLevel))
  2444. break;
  2445. if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
  2446. D, NewLevel,
  2447. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  2448. OpenMPClauseKind) { return true; })) {
  2449. OMPC = OMPC_map;
  2450. break;
  2451. }
  2452. if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  2453. NewLevel)) {
  2454. OMPC = OMPC_map;
  2455. if (DSAStack->mustBeFirstprivateAtLevel(
  2456. NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
  2457. OMPC = OMPC_firstprivate;
  2458. break;
  2459. }
  2460. }
  2461. if (OMPC != OMPC_unknown)
  2462. FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC)));
  2463. }
  2464. bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
  2465. unsigned CaptureLevel) const {
  2466. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  2467. // Return true if the current level is no longer enclosed in a target region.
  2468. SmallVector<OpenMPDirectiveKind, 4> Regions;
  2469. getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
  2470. const auto *VD = dyn_cast<VarDecl>(D);
  2471. return VD && !VD->hasLocalStorage() &&
  2472. DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
  2473. Level) &&
  2474. Regions[CaptureLevel] != OMPD_task;
  2475. }
  2476. bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
  2477. unsigned CaptureLevel) const {
  2478. assert(LangOpts.OpenMP && "OpenMP is not allowed");
  2479. // Return true if the current level is no longer enclosed in a target region.
  2480. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  2481. if (!VD->hasLocalStorage()) {
  2482. if (isInOpenMPTargetExecutionDirective())
  2483. return true;
  2484. DSAStackTy::DSAVarData TopDVar =
  2485. DSAStack->getTopDSA(D, /*FromParent=*/false);
  2486. unsigned NumLevels =
  2487. getOpenMPCaptureLevels(DSAStack->getDirective(Level));
  2488. if (Level == 0)
  2489. // non-file scope static variale with default(firstprivate)
  2490. // should be gloabal captured.
  2491. return (NumLevels == CaptureLevel + 1 &&
  2492. (TopDVar.CKind != OMPC_shared ||
  2493. DSAStack->getDefaultDSA() == DSA_firstprivate));
  2494. do {
  2495. --Level;
  2496. DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level);
  2497. if (DVar.CKind != OMPC_shared)
  2498. return true;
  2499. } while (Level > 0);
  2500. }
  2501. }
  2502. return true;
  2503. }
  2504. void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
  2505. void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc,
  2506. OMPTraitInfo &TI) {
  2507. OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI));
  2508. }
  2509. void Sema::ActOnOpenMPEndDeclareVariant() {
  2510. assert(isInOpenMPDeclareVariantScope() &&
  2511. "Not in OpenMP declare variant scope!");
  2512. OMPDeclareVariantScopes.pop_back();
  2513. }
  2514. void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
  2515. const FunctionDecl *Callee,
  2516. SourceLocation Loc) {
  2517. assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
  2518. std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  2519. OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl());
  2520. // Ignore host functions during device analyzis.
  2521. if (LangOpts.OpenMPIsDevice &&
  2522. (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host))
  2523. return;
  2524. // Ignore nohost functions during host analyzis.
  2525. if (!LangOpts.OpenMPIsDevice && DevTy &&
  2526. *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
  2527. return;
  2528. const FunctionDecl *FD = Callee->getMostRecentDecl();
  2529. DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD);
  2530. if (LangOpts.OpenMPIsDevice && DevTy &&
  2531. *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
  2532. // Diagnose host function called during device codegen.
  2533. StringRef HostDevTy =
  2534. getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
  2535. Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
  2536. Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
  2537. diag::note_omp_marked_device_type_here)
  2538. << HostDevTy;
  2539. return;
  2540. }
  2541. if (!LangOpts.OpenMPIsDevice && !LangOpts.OpenMPOffloadMandatory && DevTy &&
  2542. *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
  2543. // In OpenMP 5.2 or later, if the function has a host variant then allow
  2544. // that to be called instead
  2545. auto &&HasHostAttr = [](const FunctionDecl *Callee) {
  2546. for (OMPDeclareVariantAttr *A :
  2547. Callee->specific_attrs<OMPDeclareVariantAttr>()) {
  2548. auto *DeclRefVariant = cast<DeclRefExpr>(A->getVariantFuncRef());
  2549. auto *VariantFD = cast<FunctionDecl>(DeclRefVariant->getDecl());
  2550. std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  2551. OMPDeclareTargetDeclAttr::getDeviceType(
  2552. VariantFD->getMostRecentDecl());
  2553. if (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
  2554. return true;
  2555. }
  2556. return false;
  2557. };
  2558. if (getLangOpts().OpenMP >= 52 &&
  2559. Callee->hasAttr<OMPDeclareVariantAttr>() && HasHostAttr(Callee))
  2560. return;
  2561. // Diagnose nohost function called during host codegen.
  2562. StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
  2563. OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
  2564. Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
  2565. Diag(*OMPDeclareTargetDeclAttr::getLocation(FD),
  2566. diag::note_omp_marked_device_type_here)
  2567. << NoHostDevTy;
  2568. }
  2569. }
  2570. void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
  2571. const DeclarationNameInfo &DirName,
  2572. Scope *CurScope, SourceLocation Loc) {
  2573. DSAStack->push(DKind, DirName, CurScope, Loc);
  2574. PushExpressionEvaluationContext(
  2575. ExpressionEvaluationContext::PotentiallyEvaluated);
  2576. }
  2577. void Sema::StartOpenMPClause(OpenMPClauseKind K) {
  2578. DSAStack->setClauseParsingMode(K);
  2579. }
  2580. void Sema::EndOpenMPClause() {
  2581. DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
  2582. CleanupVarDeclMarking();
  2583. }
  2584. static std::pair<ValueDecl *, bool>
  2585. getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
  2586. SourceRange &ERange, bool AllowArraySection = false,
  2587. StringRef DiagType = "");
  2588. /// Check consistency of the reduction clauses.
  2589. static void checkReductionClauses(Sema &S, DSAStackTy *Stack,
  2590. ArrayRef<OMPClause *> Clauses) {
  2591. bool InscanFound = false;
  2592. SourceLocation InscanLoc;
  2593. // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions.
  2594. // A reduction clause without the inscan reduction-modifier may not appear on
  2595. // a construct on which a reduction clause with the inscan reduction-modifier
  2596. // appears.
  2597. for (OMPClause *C : Clauses) {
  2598. if (C->getClauseKind() != OMPC_reduction)
  2599. continue;
  2600. auto *RC = cast<OMPReductionClause>(C);
  2601. if (RC->getModifier() == OMPC_REDUCTION_inscan) {
  2602. InscanFound = true;
  2603. InscanLoc = RC->getModifierLoc();
  2604. continue;
  2605. }
  2606. if (RC->getModifier() == OMPC_REDUCTION_task) {
  2607. // OpenMP 5.0, 2.19.5.4 reduction Clause.
  2608. // A reduction clause with the task reduction-modifier may only appear on
  2609. // a parallel construct, a worksharing construct or a combined or
  2610. // composite construct for which any of the aforementioned constructs is a
  2611. // constituent construct and simd or loop are not constituent constructs.
  2612. OpenMPDirectiveKind CurDir = Stack->getCurrentDirective();
  2613. if (!(isOpenMPParallelDirective(CurDir) ||
  2614. isOpenMPWorksharingDirective(CurDir)) ||
  2615. isOpenMPSimdDirective(CurDir))
  2616. S.Diag(RC->getModifierLoc(),
  2617. diag::err_omp_reduction_task_not_parallel_or_worksharing);
  2618. continue;
  2619. }
  2620. }
  2621. if (InscanFound) {
  2622. for (OMPClause *C : Clauses) {
  2623. if (C->getClauseKind() != OMPC_reduction)
  2624. continue;
  2625. auto *RC = cast<OMPReductionClause>(C);
  2626. if (RC->getModifier() != OMPC_REDUCTION_inscan) {
  2627. S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown
  2628. ? RC->getBeginLoc()
  2629. : RC->getModifierLoc(),
  2630. diag::err_omp_inscan_reduction_expected);
  2631. S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction);
  2632. continue;
  2633. }
  2634. for (Expr *Ref : RC->varlists()) {
  2635. assert(Ref && "NULL expr in OpenMP nontemporal clause.");
  2636. SourceLocation ELoc;
  2637. SourceRange ERange;
  2638. Expr *SimpleRefExpr = Ref;
  2639. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  2640. /*AllowArraySection=*/true);
  2641. ValueDecl *D = Res.first;
  2642. if (!D)
  2643. continue;
  2644. if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) {
  2645. S.Diag(Ref->getExprLoc(),
  2646. diag::err_omp_reduction_not_inclusive_exclusive)
  2647. << Ref->getSourceRange();
  2648. }
  2649. }
  2650. }
  2651. }
  2652. }
  2653. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  2654. ArrayRef<OMPClause *> Clauses);
  2655. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  2656. bool WithInit);
  2657. static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
  2658. const ValueDecl *D,
  2659. const DSAStackTy::DSAVarData &DVar,
  2660. bool IsLoopIterVar = false);
  2661. void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
  2662. // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
  2663. // A variable of class type (or array thereof) that appears in a lastprivate
  2664. // clause requires an accessible, unambiguous default constructor for the
  2665. // class type, unless the list item is also specified in a firstprivate
  2666. // clause.
  2667. if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
  2668. for (OMPClause *C : D->clauses()) {
  2669. if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
  2670. SmallVector<Expr *, 8> PrivateCopies;
  2671. for (Expr *DE : Clause->varlists()) {
  2672. if (DE->isValueDependent() || DE->isTypeDependent()) {
  2673. PrivateCopies.push_back(nullptr);
  2674. continue;
  2675. }
  2676. auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
  2677. auto *VD = cast<VarDecl>(DRE->getDecl());
  2678. QualType Type = VD->getType().getNonReferenceType();
  2679. const DSAStackTy::DSAVarData DVar =
  2680. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  2681. if (DVar.CKind == OMPC_lastprivate) {
  2682. // Generate helper private variable and initialize it with the
  2683. // default value. The address of the original variable is replaced
  2684. // by the address of the new private variable in CodeGen. This new
  2685. // variable is not added to IdResolver, so the code in the OpenMP
  2686. // region uses original variable for proper diagnostics.
  2687. VarDecl *VDPrivate = buildVarDecl(
  2688. *this, DE->getExprLoc(), Type.getUnqualifiedType(),
  2689. VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
  2690. ActOnUninitializedDecl(VDPrivate);
  2691. if (VDPrivate->isInvalidDecl()) {
  2692. PrivateCopies.push_back(nullptr);
  2693. continue;
  2694. }
  2695. PrivateCopies.push_back(buildDeclRefExpr(
  2696. *this, VDPrivate, DE->getType(), DE->getExprLoc()));
  2697. } else {
  2698. // The variable is also a firstprivate, so initialization sequence
  2699. // for private copy is generated already.
  2700. PrivateCopies.push_back(nullptr);
  2701. }
  2702. }
  2703. Clause->setPrivateCopies(PrivateCopies);
  2704. continue;
  2705. }
  2706. // Finalize nontemporal clause by handling private copies, if any.
  2707. if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
  2708. SmallVector<Expr *, 8> PrivateRefs;
  2709. for (Expr *RefExpr : Clause->varlists()) {
  2710. assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
  2711. SourceLocation ELoc;
  2712. SourceRange ERange;
  2713. Expr *SimpleRefExpr = RefExpr;
  2714. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  2715. if (Res.second)
  2716. // It will be analyzed later.
  2717. PrivateRefs.push_back(RefExpr);
  2718. ValueDecl *D = Res.first;
  2719. if (!D)
  2720. continue;
  2721. const DSAStackTy::DSAVarData DVar =
  2722. DSAStack->getTopDSA(D, /*FromParent=*/false);
  2723. PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
  2724. : SimpleRefExpr);
  2725. }
  2726. Clause->setPrivateRefs(PrivateRefs);
  2727. continue;
  2728. }
  2729. if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) {
  2730. for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) {
  2731. OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I);
  2732. auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts());
  2733. if (!DRE)
  2734. continue;
  2735. ValueDecl *VD = DRE->getDecl();
  2736. if (!VD || !isa<VarDecl>(VD))
  2737. continue;
  2738. DSAStackTy::DSAVarData DVar =
  2739. DSAStack->getTopDSA(VD, /*FromParent=*/false);
  2740. // OpenMP [2.12.5, target Construct]
  2741. // Memory allocators that appear in a uses_allocators clause cannot
  2742. // appear in other data-sharing attribute clauses or data-mapping
  2743. // attribute clauses in the same construct.
  2744. Expr *MapExpr = nullptr;
  2745. if (DVar.RefExpr ||
  2746. DSAStack->checkMappableExprComponentListsForDecl(
  2747. VD, /*CurrentRegionOnly=*/true,
  2748. [VD, &MapExpr](
  2749. OMPClauseMappableExprCommon::MappableExprComponentListRef
  2750. MapExprComponents,
  2751. OpenMPClauseKind C) {
  2752. auto MI = MapExprComponents.rbegin();
  2753. auto ME = MapExprComponents.rend();
  2754. if (MI != ME &&
  2755. MI->getAssociatedDeclaration()->getCanonicalDecl() ==
  2756. VD->getCanonicalDecl()) {
  2757. MapExpr = MI->getAssociatedExpression();
  2758. return true;
  2759. }
  2760. return false;
  2761. })) {
  2762. Diag(D.Allocator->getExprLoc(),
  2763. diag::err_omp_allocator_used_in_clauses)
  2764. << D.Allocator->getSourceRange();
  2765. if (DVar.RefExpr)
  2766. reportOriginalDsa(*this, DSAStack, VD, DVar);
  2767. else
  2768. Diag(MapExpr->getExprLoc(), diag::note_used_here)
  2769. << MapExpr->getSourceRange();
  2770. }
  2771. }
  2772. continue;
  2773. }
  2774. }
  2775. // Check allocate clauses.
  2776. if (!CurContext->isDependentContext())
  2777. checkAllocateClauses(*this, DSAStack, D->clauses());
  2778. checkReductionClauses(*this, DSAStack, D->clauses());
  2779. }
  2780. DSAStack->pop();
  2781. DiscardCleanupsInEvaluationContext();
  2782. PopExpressionEvaluationContext();
  2783. }
  2784. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  2785. Expr *NumIterations, Sema &SemaRef,
  2786. Scope *S, DSAStackTy *Stack);
  2787. namespace {
  2788. class VarDeclFilterCCC final : public CorrectionCandidateCallback {
  2789. private:
  2790. Sema &SemaRef;
  2791. public:
  2792. explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
  2793. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  2794. NamedDecl *ND = Candidate.getCorrectionDecl();
  2795. if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
  2796. return VD->hasGlobalStorage() &&
  2797. SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  2798. SemaRef.getCurScope());
  2799. }
  2800. return false;
  2801. }
  2802. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2803. return std::make_unique<VarDeclFilterCCC>(*this);
  2804. }
  2805. };
  2806. class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
  2807. private:
  2808. Sema &SemaRef;
  2809. public:
  2810. explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
  2811. bool ValidateCandidate(const TypoCorrection &Candidate) override {
  2812. NamedDecl *ND = Candidate.getCorrectionDecl();
  2813. if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
  2814. isa<FunctionDecl>(ND))) {
  2815. return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
  2816. SemaRef.getCurScope());
  2817. }
  2818. return false;
  2819. }
  2820. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  2821. return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
  2822. }
  2823. };
  2824. } // namespace
  2825. ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
  2826. CXXScopeSpec &ScopeSpec,
  2827. const DeclarationNameInfo &Id,
  2828. OpenMPDirectiveKind Kind) {
  2829. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  2830. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  2831. if (Lookup.isAmbiguous())
  2832. return ExprError();
  2833. VarDecl *VD;
  2834. if (!Lookup.isSingleResult()) {
  2835. VarDeclFilterCCC CCC(*this);
  2836. if (TypoCorrection Corrected =
  2837. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  2838. CTK_ErrorRecovery)) {
  2839. diagnoseTypo(Corrected,
  2840. PDiag(Lookup.empty()
  2841. ? diag::err_undeclared_var_use_suggest
  2842. : diag::err_omp_expected_var_arg_suggest)
  2843. << Id.getName());
  2844. VD = Corrected.getCorrectionDeclAs<VarDecl>();
  2845. } else {
  2846. Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
  2847. : diag::err_omp_expected_var_arg)
  2848. << Id.getName();
  2849. return ExprError();
  2850. }
  2851. } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
  2852. Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
  2853. Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
  2854. return ExprError();
  2855. }
  2856. Lookup.suppressDiagnostics();
  2857. // OpenMP [2.9.2, Syntax, C/C++]
  2858. // Variables must be file-scope, namespace-scope, or static block-scope.
  2859. if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
  2860. Diag(Id.getLoc(), diag::err_omp_global_var_arg)
  2861. << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
  2862. bool IsDecl =
  2863. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2864. Diag(VD->getLocation(),
  2865. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2866. << VD;
  2867. return ExprError();
  2868. }
  2869. VarDecl *CanonicalVD = VD->getCanonicalDecl();
  2870. NamedDecl *ND = CanonicalVD;
  2871. // OpenMP [2.9.2, Restrictions, C/C++, p.2]
  2872. // A threadprivate directive for file-scope variables must appear outside
  2873. // any definition or declaration.
  2874. if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
  2875. !getCurLexicalContext()->isTranslationUnit()) {
  2876. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2877. << getOpenMPDirectiveName(Kind) << VD;
  2878. bool IsDecl =
  2879. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2880. Diag(VD->getLocation(),
  2881. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2882. << VD;
  2883. return ExprError();
  2884. }
  2885. // OpenMP [2.9.2, Restrictions, C/C++, p.3]
  2886. // A threadprivate directive for static class member variables must appear
  2887. // in the class definition, in the same scope in which the member
  2888. // variables are declared.
  2889. if (CanonicalVD->isStaticDataMember() &&
  2890. !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
  2891. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2892. << getOpenMPDirectiveName(Kind) << VD;
  2893. bool IsDecl =
  2894. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2895. Diag(VD->getLocation(),
  2896. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2897. << VD;
  2898. return ExprError();
  2899. }
  2900. // OpenMP [2.9.2, Restrictions, C/C++, p.4]
  2901. // A threadprivate directive for namespace-scope variables must appear
  2902. // outside any definition or declaration other than the namespace
  2903. // definition itself.
  2904. if (CanonicalVD->getDeclContext()->isNamespace() &&
  2905. (!getCurLexicalContext()->isFileContext() ||
  2906. !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
  2907. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2908. << getOpenMPDirectiveName(Kind) << VD;
  2909. bool IsDecl =
  2910. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2911. Diag(VD->getLocation(),
  2912. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2913. << VD;
  2914. return ExprError();
  2915. }
  2916. // OpenMP [2.9.2, Restrictions, C/C++, p.6]
  2917. // A threadprivate directive for static block-scope variables must appear
  2918. // in the scope of the variable and not in a nested scope.
  2919. if (CanonicalVD->isLocalVarDecl() && CurScope &&
  2920. !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
  2921. Diag(Id.getLoc(), diag::err_omp_var_scope)
  2922. << getOpenMPDirectiveName(Kind) << VD;
  2923. bool IsDecl =
  2924. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  2925. Diag(VD->getLocation(),
  2926. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  2927. << VD;
  2928. return ExprError();
  2929. }
  2930. // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
  2931. // A threadprivate directive must lexically precede all references to any
  2932. // of the variables in its list.
  2933. if (Kind == OMPD_threadprivate && VD->isUsed() &&
  2934. !DSAStack->isThreadPrivate(VD)) {
  2935. Diag(Id.getLoc(), diag::err_omp_var_used)
  2936. << getOpenMPDirectiveName(Kind) << VD;
  2937. return ExprError();
  2938. }
  2939. QualType ExprType = VD->getType().getNonReferenceType();
  2940. return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
  2941. SourceLocation(), VD,
  2942. /*RefersToEnclosingVariableOrCapture=*/false,
  2943. Id.getLoc(), ExprType, VK_LValue);
  2944. }
  2945. Sema::DeclGroupPtrTy
  2946. Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
  2947. ArrayRef<Expr *> VarList) {
  2948. if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
  2949. CurContext->addDecl(D);
  2950. return DeclGroupPtrTy::make(DeclGroupRef(D));
  2951. }
  2952. return nullptr;
  2953. }
  2954. namespace {
  2955. class LocalVarRefChecker final
  2956. : public ConstStmtVisitor<LocalVarRefChecker, bool> {
  2957. Sema &SemaRef;
  2958. public:
  2959. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  2960. if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  2961. if (VD->hasLocalStorage()) {
  2962. SemaRef.Diag(E->getBeginLoc(),
  2963. diag::err_omp_local_var_in_threadprivate_init)
  2964. << E->getSourceRange();
  2965. SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
  2966. << VD << VD->getSourceRange();
  2967. return true;
  2968. }
  2969. }
  2970. return false;
  2971. }
  2972. bool VisitStmt(const Stmt *S) {
  2973. for (const Stmt *Child : S->children()) {
  2974. if (Child && Visit(Child))
  2975. return true;
  2976. }
  2977. return false;
  2978. }
  2979. explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
  2980. };
  2981. } // namespace
  2982. OMPThreadPrivateDecl *
  2983. Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
  2984. SmallVector<Expr *, 8> Vars;
  2985. for (Expr *RefExpr : VarList) {
  2986. auto *DE = cast<DeclRefExpr>(RefExpr);
  2987. auto *VD = cast<VarDecl>(DE->getDecl());
  2988. SourceLocation ILoc = DE->getExprLoc();
  2989. // Mark variable as used.
  2990. VD->setReferenced();
  2991. VD->markUsed(Context);
  2992. QualType QType = VD->getType();
  2993. if (QType->isDependentType() || QType->isInstantiationDependentType()) {
  2994. // It will be analyzed later.
  2995. Vars.push_back(DE);
  2996. continue;
  2997. }
  2998. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  2999. // A threadprivate variable must not have an incomplete type.
  3000. if (RequireCompleteType(ILoc, VD->getType(),
  3001. diag::err_omp_threadprivate_incomplete_type)) {
  3002. continue;
  3003. }
  3004. // OpenMP [2.9.2, Restrictions, C/C++, p.10]
  3005. // A threadprivate variable must not have a reference type.
  3006. if (VD->getType()->isReferenceType()) {
  3007. Diag(ILoc, diag::err_omp_ref_type_arg)
  3008. << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
  3009. bool IsDecl =
  3010. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  3011. Diag(VD->getLocation(),
  3012. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  3013. << VD;
  3014. continue;
  3015. }
  3016. // Check if this is a TLS variable. If TLS is not being supported, produce
  3017. // the corresponding diagnostic.
  3018. if ((VD->getTLSKind() != VarDecl::TLS_None &&
  3019. !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
  3020. getLangOpts().OpenMPUseTLS &&
  3021. getASTContext().getTargetInfo().isTLSSupported())) ||
  3022. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  3023. !VD->isLocalVarDecl())) {
  3024. Diag(ILoc, diag::err_omp_var_thread_local)
  3025. << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
  3026. bool IsDecl =
  3027. VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
  3028. Diag(VD->getLocation(),
  3029. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  3030. << VD;
  3031. continue;
  3032. }
  3033. // Check if initial value of threadprivate variable reference variable with
  3034. // local storage (it is not supported by runtime).
  3035. if (const Expr *Init = VD->getAnyInitializer()) {
  3036. LocalVarRefChecker Checker(*this);
  3037. if (Checker.Visit(Init))
  3038. continue;
  3039. }
  3040. Vars.push_back(RefExpr);
  3041. DSAStack->addDSA(VD, DE, OMPC_threadprivate);
  3042. VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
  3043. Context, SourceRange(Loc, Loc)));
  3044. if (ASTMutationListener *ML = Context.getASTMutationListener())
  3045. ML->DeclarationMarkedOpenMPThreadPrivate(VD);
  3046. }
  3047. OMPThreadPrivateDecl *D = nullptr;
  3048. if (!Vars.empty()) {
  3049. D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
  3050. Vars);
  3051. D->setAccess(AS_public);
  3052. }
  3053. return D;
  3054. }
  3055. static OMPAllocateDeclAttr::AllocatorTypeTy
  3056. getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
  3057. if (!Allocator)
  3058. return OMPAllocateDeclAttr::OMPNullMemAlloc;
  3059. if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  3060. Allocator->isInstantiationDependent() ||
  3061. Allocator->containsUnexpandedParameterPack())
  3062. return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  3063. auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
  3064. llvm::FoldingSetNodeID AEId;
  3065. const Expr *AE = Allocator->IgnoreParenImpCasts();
  3066. AE->IgnoreImpCasts()->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
  3067. for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  3068. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  3069. const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
  3070. llvm::FoldingSetNodeID DAEId;
  3071. DefAllocator->IgnoreImpCasts()->Profile(DAEId, S.getASTContext(),
  3072. /*Canonical=*/true);
  3073. if (AEId == DAEId) {
  3074. AllocatorKindRes = AllocatorKind;
  3075. break;
  3076. }
  3077. }
  3078. return AllocatorKindRes;
  3079. }
  3080. static bool checkPreviousOMPAllocateAttribute(
  3081. Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
  3082. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
  3083. if (!VD->hasAttr<OMPAllocateDeclAttr>())
  3084. return false;
  3085. const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
  3086. Expr *PrevAllocator = A->getAllocator();
  3087. OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
  3088. getAllocatorKind(S, Stack, PrevAllocator);
  3089. bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
  3090. if (AllocatorsMatch &&
  3091. AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
  3092. Allocator && PrevAllocator) {
  3093. const Expr *AE = Allocator->IgnoreParenImpCasts();
  3094. const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
  3095. llvm::FoldingSetNodeID AEId, PAEId;
  3096. AE->Profile(AEId, S.Context, /*Canonical=*/true);
  3097. PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
  3098. AllocatorsMatch = AEId == PAEId;
  3099. }
  3100. if (!AllocatorsMatch) {
  3101. SmallString<256> AllocatorBuffer;
  3102. llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
  3103. if (Allocator)
  3104. Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
  3105. SmallString<256> PrevAllocatorBuffer;
  3106. llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
  3107. if (PrevAllocator)
  3108. PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
  3109. S.getPrintingPolicy());
  3110. SourceLocation AllocatorLoc =
  3111. Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
  3112. SourceRange AllocatorRange =
  3113. Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
  3114. SourceLocation PrevAllocatorLoc =
  3115. PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
  3116. SourceRange PrevAllocatorRange =
  3117. PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
  3118. S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
  3119. << (Allocator ? 1 : 0) << AllocatorStream.str()
  3120. << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
  3121. << AllocatorRange;
  3122. S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
  3123. << PrevAllocatorRange;
  3124. return true;
  3125. }
  3126. return false;
  3127. }
  3128. static void
  3129. applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
  3130. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
  3131. Expr *Allocator, Expr *Alignment, SourceRange SR) {
  3132. if (VD->hasAttr<OMPAllocateDeclAttr>())
  3133. return;
  3134. if (Alignment &&
  3135. (Alignment->isTypeDependent() || Alignment->isValueDependent() ||
  3136. Alignment->isInstantiationDependent() ||
  3137. Alignment->containsUnexpandedParameterPack()))
  3138. // Apply later when we have a usable value.
  3139. return;
  3140. if (Allocator &&
  3141. (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
  3142. Allocator->isInstantiationDependent() ||
  3143. Allocator->containsUnexpandedParameterPack()))
  3144. return;
  3145. auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
  3146. Allocator, Alignment, SR);
  3147. VD->addAttr(A);
  3148. if (ASTMutationListener *ML = S.Context.getASTMutationListener())
  3149. ML->DeclarationMarkedOpenMPAllocate(VD, A);
  3150. }
  3151. Sema::DeclGroupPtrTy
  3152. Sema::ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList,
  3153. ArrayRef<OMPClause *> Clauses,
  3154. DeclContext *Owner) {
  3155. assert(Clauses.size() <= 2 && "Expected at most two clauses.");
  3156. Expr *Alignment = nullptr;
  3157. Expr *Allocator = nullptr;
  3158. if (Clauses.empty()) {
  3159. // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
  3160. // allocate directives that appear in a target region must specify an
  3161. // allocator clause unless a requires directive with the dynamic_allocators
  3162. // clause is present in the same compilation unit.
  3163. if (LangOpts.OpenMPIsDevice &&
  3164. !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
  3165. targetDiag(Loc, diag::err_expected_allocator_clause);
  3166. } else {
  3167. for (const OMPClause *C : Clauses)
  3168. if (const auto *AC = dyn_cast<OMPAllocatorClause>(C))
  3169. Allocator = AC->getAllocator();
  3170. else if (const auto *AC = dyn_cast<OMPAlignClause>(C))
  3171. Alignment = AC->getAlignment();
  3172. else
  3173. llvm_unreachable("Unexpected clause on allocate directive");
  3174. }
  3175. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  3176. getAllocatorKind(*this, DSAStack, Allocator);
  3177. SmallVector<Expr *, 8> Vars;
  3178. for (Expr *RefExpr : VarList) {
  3179. auto *DE = cast<DeclRefExpr>(RefExpr);
  3180. auto *VD = cast<VarDecl>(DE->getDecl());
  3181. // Check if this is a TLS variable or global register.
  3182. if (VD->getTLSKind() != VarDecl::TLS_None ||
  3183. VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
  3184. (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
  3185. !VD->isLocalVarDecl()))
  3186. continue;
  3187. // If the used several times in the allocate directive, the same allocator
  3188. // must be used.
  3189. if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
  3190. AllocatorKind, Allocator))
  3191. continue;
  3192. // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
  3193. // If a list item has a static storage type, the allocator expression in the
  3194. // allocator clause must be a constant expression that evaluates to one of
  3195. // the predefined memory allocator values.
  3196. if (Allocator && VD->hasGlobalStorage()) {
  3197. if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
  3198. Diag(Allocator->getExprLoc(),
  3199. diag::err_omp_expected_predefined_allocator)
  3200. << Allocator->getSourceRange();
  3201. bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
  3202. VarDecl::DeclarationOnly;
  3203. Diag(VD->getLocation(),
  3204. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  3205. << VD;
  3206. continue;
  3207. }
  3208. }
  3209. Vars.push_back(RefExpr);
  3210. applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, Alignment,
  3211. DE->getSourceRange());
  3212. }
  3213. if (Vars.empty())
  3214. return nullptr;
  3215. if (!Owner)
  3216. Owner = getCurLexicalContext();
  3217. auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
  3218. D->setAccess(AS_public);
  3219. Owner->addDecl(D);
  3220. return DeclGroupPtrTy::make(DeclGroupRef(D));
  3221. }
  3222. Sema::DeclGroupPtrTy
  3223. Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
  3224. ArrayRef<OMPClause *> ClauseList) {
  3225. OMPRequiresDecl *D = nullptr;
  3226. if (!CurContext->isFileContext()) {
  3227. Diag(Loc, diag::err_omp_invalid_scope) << "requires";
  3228. } else {
  3229. D = CheckOMPRequiresDecl(Loc, ClauseList);
  3230. if (D) {
  3231. CurContext->addDecl(D);
  3232. DSAStack->addRequiresDecl(D);
  3233. }
  3234. }
  3235. return DeclGroupPtrTy::make(DeclGroupRef(D));
  3236. }
  3237. void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc,
  3238. OpenMPDirectiveKind DKind,
  3239. ArrayRef<std::string> Assumptions,
  3240. bool SkippedClauses) {
  3241. if (!SkippedClauses && Assumptions.empty())
  3242. Diag(Loc, diag::err_omp_no_clause_for_directive)
  3243. << llvm::omp::getAllAssumeClauseOptions()
  3244. << llvm::omp::getOpenMPDirectiveName(DKind);
  3245. auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc);
  3246. if (DKind == llvm::omp::Directive::OMPD_begin_assumes) {
  3247. OMPAssumeScoped.push_back(AA);
  3248. return;
  3249. }
  3250. // Global assumes without assumption clauses are ignored.
  3251. if (Assumptions.empty())
  3252. return;
  3253. assert(DKind == llvm::omp::Directive::OMPD_assumes &&
  3254. "Unexpected omp assumption directive!");
  3255. OMPAssumeGlobal.push_back(AA);
  3256. // The OMPAssumeGlobal scope above will take care of new declarations but
  3257. // we also want to apply the assumption to existing ones, e.g., to
  3258. // declarations in included headers. To this end, we traverse all existing
  3259. // declaration contexts and annotate function declarations here.
  3260. SmallVector<DeclContext *, 8> DeclContexts;
  3261. auto *Ctx = CurContext;
  3262. while (Ctx->getLexicalParent())
  3263. Ctx = Ctx->getLexicalParent();
  3264. DeclContexts.push_back(Ctx);
  3265. while (!DeclContexts.empty()) {
  3266. DeclContext *DC = DeclContexts.pop_back_val();
  3267. for (auto *SubDC : DC->decls()) {
  3268. if (SubDC->isInvalidDecl())
  3269. continue;
  3270. if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) {
  3271. DeclContexts.push_back(CTD->getTemplatedDecl());
  3272. llvm::append_range(DeclContexts, CTD->specializations());
  3273. continue;
  3274. }
  3275. if (auto *DC = dyn_cast<DeclContext>(SubDC))
  3276. DeclContexts.push_back(DC);
  3277. if (auto *F = dyn_cast<FunctionDecl>(SubDC)) {
  3278. F->addAttr(AA);
  3279. continue;
  3280. }
  3281. }
  3282. }
  3283. }
  3284. void Sema::ActOnOpenMPEndAssumesDirective() {
  3285. assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!");
  3286. OMPAssumeScoped.pop_back();
  3287. }
  3288. OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
  3289. ArrayRef<OMPClause *> ClauseList) {
  3290. /// For target specific clauses, the requires directive cannot be
  3291. /// specified after the handling of any of the target regions in the
  3292. /// current compilation unit.
  3293. ArrayRef<SourceLocation> TargetLocations =
  3294. DSAStack->getEncounteredTargetLocs();
  3295. SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc();
  3296. if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) {
  3297. for (const OMPClause *CNew : ClauseList) {
  3298. // Check if any of the requires clauses affect target regions.
  3299. if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
  3300. isa<OMPUnifiedAddressClause>(CNew) ||
  3301. isa<OMPReverseOffloadClause>(CNew) ||
  3302. isa<OMPDynamicAllocatorsClause>(CNew)) {
  3303. Diag(Loc, diag::err_omp_directive_before_requires)
  3304. << "target" << getOpenMPClauseName(CNew->getClauseKind());
  3305. for (SourceLocation TargetLoc : TargetLocations) {
  3306. Diag(TargetLoc, diag::note_omp_requires_encountered_directive)
  3307. << "target";
  3308. }
  3309. } else if (!AtomicLoc.isInvalid() &&
  3310. isa<OMPAtomicDefaultMemOrderClause>(CNew)) {
  3311. Diag(Loc, diag::err_omp_directive_before_requires)
  3312. << "atomic" << getOpenMPClauseName(CNew->getClauseKind());
  3313. Diag(AtomicLoc, diag::note_omp_requires_encountered_directive)
  3314. << "atomic";
  3315. }
  3316. }
  3317. }
  3318. if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
  3319. return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
  3320. ClauseList);
  3321. return nullptr;
  3322. }
  3323. static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
  3324. const ValueDecl *D,
  3325. const DSAStackTy::DSAVarData &DVar,
  3326. bool IsLoopIterVar) {
  3327. if (DVar.RefExpr) {
  3328. SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
  3329. << getOpenMPClauseName(DVar.CKind);
  3330. return;
  3331. }
  3332. enum {
  3333. PDSA_StaticMemberShared,
  3334. PDSA_StaticLocalVarShared,
  3335. PDSA_LoopIterVarPrivate,
  3336. PDSA_LoopIterVarLinear,
  3337. PDSA_LoopIterVarLastprivate,
  3338. PDSA_ConstVarShared,
  3339. PDSA_GlobalVarShared,
  3340. PDSA_TaskVarFirstprivate,
  3341. PDSA_LocalVarPrivate,
  3342. PDSA_Implicit
  3343. } Reason = PDSA_Implicit;
  3344. bool ReportHint = false;
  3345. auto ReportLoc = D->getLocation();
  3346. auto *VD = dyn_cast<VarDecl>(D);
  3347. if (IsLoopIterVar) {
  3348. if (DVar.CKind == OMPC_private)
  3349. Reason = PDSA_LoopIterVarPrivate;
  3350. else if (DVar.CKind == OMPC_lastprivate)
  3351. Reason = PDSA_LoopIterVarLastprivate;
  3352. else
  3353. Reason = PDSA_LoopIterVarLinear;
  3354. } else if (isOpenMPTaskingDirective(DVar.DKind) &&
  3355. DVar.CKind == OMPC_firstprivate) {
  3356. Reason = PDSA_TaskVarFirstprivate;
  3357. ReportLoc = DVar.ImplicitDSALoc;
  3358. } else if (VD && VD->isStaticLocal())
  3359. Reason = PDSA_StaticLocalVarShared;
  3360. else if (VD && VD->isStaticDataMember())
  3361. Reason = PDSA_StaticMemberShared;
  3362. else if (VD && VD->isFileVarDecl())
  3363. Reason = PDSA_GlobalVarShared;
  3364. else if (D->getType().isConstant(SemaRef.getASTContext()))
  3365. Reason = PDSA_ConstVarShared;
  3366. else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
  3367. ReportHint = true;
  3368. Reason = PDSA_LocalVarPrivate;
  3369. }
  3370. if (Reason != PDSA_Implicit) {
  3371. SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
  3372. << Reason << ReportHint
  3373. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  3374. } else if (DVar.ImplicitDSALoc.isValid()) {
  3375. SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
  3376. << getOpenMPClauseName(DVar.CKind);
  3377. }
  3378. }
  3379. static OpenMPMapClauseKind
  3380. getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
  3381. bool IsAggregateOrDeclareTarget) {
  3382. OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
  3383. switch (M) {
  3384. case OMPC_DEFAULTMAP_MODIFIER_alloc:
  3385. Kind = OMPC_MAP_alloc;
  3386. break;
  3387. case OMPC_DEFAULTMAP_MODIFIER_to:
  3388. Kind = OMPC_MAP_to;
  3389. break;
  3390. case OMPC_DEFAULTMAP_MODIFIER_from:
  3391. Kind = OMPC_MAP_from;
  3392. break;
  3393. case OMPC_DEFAULTMAP_MODIFIER_tofrom:
  3394. Kind = OMPC_MAP_tofrom;
  3395. break;
  3396. case OMPC_DEFAULTMAP_MODIFIER_present:
  3397. // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description]
  3398. // If implicit-behavior is present, each variable referenced in the
  3399. // construct in the category specified by variable-category is treated as if
  3400. // it had been listed in a map clause with the map-type of alloc and
  3401. // map-type-modifier of present.
  3402. Kind = OMPC_MAP_alloc;
  3403. break;
  3404. case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
  3405. case OMPC_DEFAULTMAP_MODIFIER_last:
  3406. llvm_unreachable("Unexpected defaultmap implicit behavior");
  3407. case OMPC_DEFAULTMAP_MODIFIER_none:
  3408. case OMPC_DEFAULTMAP_MODIFIER_default:
  3409. case OMPC_DEFAULTMAP_MODIFIER_unknown:
  3410. // IsAggregateOrDeclareTarget could be true if:
  3411. // 1. the implicit behavior for aggregate is tofrom
  3412. // 2. it's a declare target link
  3413. if (IsAggregateOrDeclareTarget) {
  3414. Kind = OMPC_MAP_tofrom;
  3415. break;
  3416. }
  3417. llvm_unreachable("Unexpected defaultmap implicit behavior");
  3418. }
  3419. assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
  3420. return Kind;
  3421. }
  3422. namespace {
  3423. class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
  3424. DSAStackTy *Stack;
  3425. Sema &SemaRef;
  3426. bool ErrorFound = false;
  3427. bool TryCaptureCXXThisMembers = false;
  3428. CapturedStmt *CS = nullptr;
  3429. const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
  3430. llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
  3431. llvm::SmallVector<Expr *, 4> ImplicitPrivate;
  3432. llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete];
  3433. llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
  3434. ImplicitMapModifier[DefaultmapKindNum];
  3435. Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
  3436. llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
  3437. void VisitSubCaptures(OMPExecutableDirective *S) {
  3438. // Check implicitly captured variables.
  3439. if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
  3440. return;
  3441. if (S->getDirectiveKind() == OMPD_atomic ||
  3442. S->getDirectiveKind() == OMPD_critical ||
  3443. S->getDirectiveKind() == OMPD_section ||
  3444. S->getDirectiveKind() == OMPD_master ||
  3445. S->getDirectiveKind() == OMPD_masked ||
  3446. isOpenMPLoopTransformationDirective(S->getDirectiveKind())) {
  3447. Visit(S->getAssociatedStmt());
  3448. return;
  3449. }
  3450. visitSubCaptures(S->getInnermostCapturedStmt());
  3451. // Try to capture inner this->member references to generate correct mappings
  3452. // and diagnostics.
  3453. if (TryCaptureCXXThisMembers ||
  3454. (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  3455. llvm::any_of(S->getInnermostCapturedStmt()->captures(),
  3456. [](const CapturedStmt::Capture &C) {
  3457. return C.capturesThis();
  3458. }))) {
  3459. bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
  3460. TryCaptureCXXThisMembers = true;
  3461. Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
  3462. TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
  3463. }
  3464. // In tasks firstprivates are not captured anymore, need to analyze them
  3465. // explicitly.
  3466. if (isOpenMPTaskingDirective(S->getDirectiveKind()) &&
  3467. !isOpenMPTaskLoopDirective(S->getDirectiveKind())) {
  3468. for (OMPClause *C : S->clauses())
  3469. if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) {
  3470. for (Expr *Ref : FC->varlists())
  3471. Visit(Ref);
  3472. }
  3473. }
  3474. }
  3475. public:
  3476. void VisitDeclRefExpr(DeclRefExpr *E) {
  3477. if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
  3478. E->isValueDependent() || E->containsUnexpandedParameterPack() ||
  3479. E->isInstantiationDependent())
  3480. return;
  3481. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  3482. // Check the datasharing rules for the expressions in the clauses.
  3483. if (!CS || (isa<OMPCapturedExprDecl>(VD) && !CS->capturesVariable(VD) &&
  3484. !Stack->getTopDSA(VD, /*FromParent=*/false).RefExpr &&
  3485. !Stack->isImplicitDefaultFirstprivateFD(VD))) {
  3486. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
  3487. if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
  3488. Visit(CED->getInit());
  3489. return;
  3490. }
  3491. } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
  3492. // Do not analyze internal variables and do not enclose them into
  3493. // implicit clauses.
  3494. if (!Stack->isImplicitDefaultFirstprivateFD(VD))
  3495. return;
  3496. VD = VD->getCanonicalDecl();
  3497. // Skip internally declared variables.
  3498. if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) &&
  3499. !Stack->isImplicitDefaultFirstprivateFD(VD) &&
  3500. !Stack->isImplicitTaskFirstprivate(VD))
  3501. return;
  3502. // Skip allocators in uses_allocators clauses.
  3503. if (Stack->isUsesAllocatorsDecl(VD))
  3504. return;
  3505. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  3506. // Check if the variable has explicit DSA set and stop analysis if it so.
  3507. if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
  3508. return;
  3509. // Skip internally declared static variables.
  3510. std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  3511. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  3512. if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
  3513. (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
  3514. !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) &&
  3515. !Stack->isImplicitDefaultFirstprivateFD(VD) &&
  3516. !Stack->isImplicitTaskFirstprivate(VD))
  3517. return;
  3518. SourceLocation ELoc = E->getExprLoc();
  3519. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  3520. // The default(none) clause requires that each variable that is referenced
  3521. // in the construct, and does not have a predetermined data-sharing
  3522. // attribute, must have its data-sharing attribute explicitly determined
  3523. // by being listed in a data-sharing attribute clause.
  3524. if (DVar.CKind == OMPC_unknown &&
  3525. (Stack->getDefaultDSA() == DSA_none ||
  3526. Stack->getDefaultDSA() == DSA_private ||
  3527. Stack->getDefaultDSA() == DSA_firstprivate) &&
  3528. isImplicitOrExplicitTaskingRegion(DKind) &&
  3529. VarsWithInheritedDSA.count(VD) == 0) {
  3530. bool InheritedDSA = Stack->getDefaultDSA() == DSA_none;
  3531. if (!InheritedDSA && (Stack->getDefaultDSA() == DSA_firstprivate ||
  3532. Stack->getDefaultDSA() == DSA_private)) {
  3533. DSAStackTy::DSAVarData DVar =
  3534. Stack->getImplicitDSA(VD, /*FromParent=*/false);
  3535. InheritedDSA = DVar.CKind == OMPC_unknown;
  3536. }
  3537. if (InheritedDSA)
  3538. VarsWithInheritedDSA[VD] = E;
  3539. if (Stack->getDefaultDSA() == DSA_none)
  3540. return;
  3541. }
  3542. // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
  3543. // If implicit-behavior is none, each variable referenced in the
  3544. // construct that does not have a predetermined data-sharing attribute
  3545. // and does not appear in a to or link clause on a declare target
  3546. // directive must be listed in a data-mapping attribute clause, a
  3547. // data-sharing attribute clause (including a data-sharing attribute
  3548. // clause on a combined construct where target. is one of the
  3549. // constituent constructs), or an is_device_ptr clause.
  3550. OpenMPDefaultmapClauseKind ClauseKind =
  3551. getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
  3552. if (SemaRef.getLangOpts().OpenMP >= 50) {
  3553. bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
  3554. OMPC_DEFAULTMAP_MODIFIER_none;
  3555. if (DVar.CKind == OMPC_unknown && IsModifierNone &&
  3556. VarsWithInheritedDSA.count(VD) == 0 && !Res) {
  3557. // Only check for data-mapping attribute and is_device_ptr here
  3558. // since we have already make sure that the declaration does not
  3559. // have a data-sharing attribute above
  3560. if (!Stack->checkMappableExprComponentListsForDecl(
  3561. VD, /*CurrentRegionOnly=*/true,
  3562. [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
  3563. MapExprComponents,
  3564. OpenMPClauseKind) {
  3565. auto MI = MapExprComponents.rbegin();
  3566. auto ME = MapExprComponents.rend();
  3567. return MI != ME && MI->getAssociatedDeclaration() == VD;
  3568. })) {
  3569. VarsWithInheritedDSA[VD] = E;
  3570. return;
  3571. }
  3572. }
  3573. }
  3574. if (SemaRef.getLangOpts().OpenMP > 50) {
  3575. bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) ==
  3576. OMPC_DEFAULTMAP_MODIFIER_present;
  3577. if (IsModifierPresent) {
  3578. if (!llvm::is_contained(ImplicitMapModifier[ClauseKind],
  3579. OMPC_MAP_MODIFIER_present)) {
  3580. ImplicitMapModifier[ClauseKind].push_back(
  3581. OMPC_MAP_MODIFIER_present);
  3582. }
  3583. }
  3584. }
  3585. if (isOpenMPTargetExecutionDirective(DKind) &&
  3586. !Stack->isLoopControlVariable(VD).first) {
  3587. if (!Stack->checkMappableExprComponentListsForDecl(
  3588. VD, /*CurrentRegionOnly=*/true,
  3589. [this](OMPClauseMappableExprCommon::MappableExprComponentListRef
  3590. StackComponents,
  3591. OpenMPClauseKind) {
  3592. if (SemaRef.LangOpts.OpenMP >= 50)
  3593. return !StackComponents.empty();
  3594. // Variable is used if it has been marked as an array, array
  3595. // section, array shaping or the variable iself.
  3596. return StackComponents.size() == 1 ||
  3597. llvm::all_of(
  3598. llvm::drop_begin(llvm::reverse(StackComponents)),
  3599. [](const OMPClauseMappableExprCommon::
  3600. MappableComponent &MC) {
  3601. return MC.getAssociatedDeclaration() ==
  3602. nullptr &&
  3603. (isa<OMPArraySectionExpr>(
  3604. MC.getAssociatedExpression()) ||
  3605. isa<OMPArrayShapingExpr>(
  3606. MC.getAssociatedExpression()) ||
  3607. isa<ArraySubscriptExpr>(
  3608. MC.getAssociatedExpression()));
  3609. });
  3610. })) {
  3611. bool IsFirstprivate = false;
  3612. // By default lambdas are captured as firstprivates.
  3613. if (const auto *RD =
  3614. VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
  3615. IsFirstprivate = RD->isLambda();
  3616. IsFirstprivate =
  3617. IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
  3618. if (IsFirstprivate) {
  3619. ImplicitFirstprivate.emplace_back(E);
  3620. } else {
  3621. OpenMPDefaultmapClauseModifier M =
  3622. Stack->getDefaultmapModifier(ClauseKind);
  3623. OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
  3624. M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
  3625. ImplicitMap[ClauseKind][Kind].emplace_back(E);
  3626. }
  3627. return;
  3628. }
  3629. }
  3630. // OpenMP [2.9.3.6, Restrictions, p.2]
  3631. // A list item that appears in a reduction clause of the innermost
  3632. // enclosing worksharing or parallel construct may not be accessed in an
  3633. // explicit task.
  3634. DVar = Stack->hasInnermostDSA(
  3635. VD,
  3636. [](OpenMPClauseKind C, bool AppliedToPointee) {
  3637. return C == OMPC_reduction && !AppliedToPointee;
  3638. },
  3639. [](OpenMPDirectiveKind K) {
  3640. return isOpenMPParallelDirective(K) ||
  3641. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  3642. },
  3643. /*FromParent=*/true);
  3644. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  3645. ErrorFound = true;
  3646. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  3647. reportOriginalDsa(SemaRef, Stack, VD, DVar);
  3648. return;
  3649. }
  3650. // Define implicit data-sharing attributes for task.
  3651. DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
  3652. if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) ||
  3653. (((Stack->getDefaultDSA() == DSA_firstprivate &&
  3654. DVar.CKind == OMPC_firstprivate) ||
  3655. (Stack->getDefaultDSA() == DSA_private &&
  3656. DVar.CKind == OMPC_private)) &&
  3657. !DVar.RefExpr)) &&
  3658. !Stack->isLoopControlVariable(VD).first) {
  3659. if (Stack->getDefaultDSA() == DSA_private)
  3660. ImplicitPrivate.push_back(E);
  3661. else
  3662. ImplicitFirstprivate.push_back(E);
  3663. return;
  3664. }
  3665. // Store implicitly used globals with declare target link for parent
  3666. // target.
  3667. if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
  3668. *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  3669. Stack->addToParentTargetRegionLinkGlobals(E);
  3670. return;
  3671. }
  3672. }
  3673. }
  3674. void VisitMemberExpr(MemberExpr *E) {
  3675. if (E->isTypeDependent() || E->isValueDependent() ||
  3676. E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
  3677. return;
  3678. auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
  3679. OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
  3680. if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) {
  3681. if (!FD)
  3682. return;
  3683. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
  3684. // Check if the variable has explicit DSA set and stop analysis if it
  3685. // so.
  3686. if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
  3687. return;
  3688. if (isOpenMPTargetExecutionDirective(DKind) &&
  3689. !Stack->isLoopControlVariable(FD).first &&
  3690. !Stack->checkMappableExprComponentListsForDecl(
  3691. FD, /*CurrentRegionOnly=*/true,
  3692. [](OMPClauseMappableExprCommon::MappableExprComponentListRef
  3693. StackComponents,
  3694. OpenMPClauseKind) {
  3695. return isa<CXXThisExpr>(
  3696. cast<MemberExpr>(
  3697. StackComponents.back().getAssociatedExpression())
  3698. ->getBase()
  3699. ->IgnoreParens());
  3700. })) {
  3701. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  3702. // A bit-field cannot appear in a map clause.
  3703. //
  3704. if (FD->isBitField())
  3705. return;
  3706. // Check to see if the member expression is referencing a class that
  3707. // has already been explicitly mapped
  3708. if (Stack->isClassPreviouslyMapped(TE->getType()))
  3709. return;
  3710. OpenMPDefaultmapClauseModifier Modifier =
  3711. Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
  3712. OpenMPDefaultmapClauseKind ClauseKind =
  3713. getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD);
  3714. OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
  3715. Modifier, /*IsAggregateOrDeclareTarget*/ true);
  3716. ImplicitMap[ClauseKind][Kind].emplace_back(E);
  3717. return;
  3718. }
  3719. SourceLocation ELoc = E->getExprLoc();
  3720. // OpenMP [2.9.3.6, Restrictions, p.2]
  3721. // A list item that appears in a reduction clause of the innermost
  3722. // enclosing worksharing or parallel construct may not be accessed in
  3723. // an explicit task.
  3724. DVar = Stack->hasInnermostDSA(
  3725. FD,
  3726. [](OpenMPClauseKind C, bool AppliedToPointee) {
  3727. return C == OMPC_reduction && !AppliedToPointee;
  3728. },
  3729. [](OpenMPDirectiveKind K) {
  3730. return isOpenMPParallelDirective(K) ||
  3731. isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
  3732. },
  3733. /*FromParent=*/true);
  3734. if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
  3735. ErrorFound = true;
  3736. SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
  3737. reportOriginalDsa(SemaRef, Stack, FD, DVar);
  3738. return;
  3739. }
  3740. // Define implicit data-sharing attributes for task.
  3741. DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
  3742. if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
  3743. !Stack->isLoopControlVariable(FD).first) {
  3744. // Check if there is a captured expression for the current field in the
  3745. // region. Do not mark it as firstprivate unless there is no captured
  3746. // expression.
  3747. // TODO: try to make it firstprivate.
  3748. if (DVar.CKind != OMPC_unknown)
  3749. ImplicitFirstprivate.push_back(E);
  3750. }
  3751. return;
  3752. }
  3753. if (isOpenMPTargetExecutionDirective(DKind)) {
  3754. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  3755. if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
  3756. Stack->getCurrentDirective(),
  3757. /*NoDiagnose=*/true))
  3758. return;
  3759. const auto *VD = cast<ValueDecl>(
  3760. CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
  3761. if (!Stack->checkMappableExprComponentListsForDecl(
  3762. VD, /*CurrentRegionOnly=*/true,
  3763. [&CurComponents](
  3764. OMPClauseMappableExprCommon::MappableExprComponentListRef
  3765. StackComponents,
  3766. OpenMPClauseKind) {
  3767. auto CCI = CurComponents.rbegin();
  3768. auto CCE = CurComponents.rend();
  3769. for (const auto &SC : llvm::reverse(StackComponents)) {
  3770. // Do both expressions have the same kind?
  3771. if (CCI->getAssociatedExpression()->getStmtClass() !=
  3772. SC.getAssociatedExpression()->getStmtClass())
  3773. if (!((isa<OMPArraySectionExpr>(
  3774. SC.getAssociatedExpression()) ||
  3775. isa<OMPArrayShapingExpr>(
  3776. SC.getAssociatedExpression())) &&
  3777. isa<ArraySubscriptExpr>(
  3778. CCI->getAssociatedExpression())))
  3779. return false;
  3780. const Decl *CCD = CCI->getAssociatedDeclaration();
  3781. const Decl *SCD = SC.getAssociatedDeclaration();
  3782. CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
  3783. SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
  3784. if (SCD != CCD)
  3785. return false;
  3786. std::advance(CCI, 1);
  3787. if (CCI == CCE)
  3788. break;
  3789. }
  3790. return true;
  3791. })) {
  3792. Visit(E->getBase());
  3793. }
  3794. } else if (!TryCaptureCXXThisMembers) {
  3795. Visit(E->getBase());
  3796. }
  3797. }
  3798. void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
  3799. for (OMPClause *C : S->clauses()) {
  3800. // Skip analysis of arguments of private clauses for task|target
  3801. // directives.
  3802. if (isa_and_nonnull<OMPPrivateClause>(C))
  3803. continue;
  3804. // Skip analysis of arguments of implicitly defined firstprivate clause
  3805. // for task|target directives.
  3806. // Skip analysis of arguments of implicitly defined map clause for target
  3807. // directives.
  3808. if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
  3809. C->isImplicit() &&
  3810. !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) {
  3811. for (Stmt *CC : C->children()) {
  3812. if (CC)
  3813. Visit(CC);
  3814. }
  3815. }
  3816. }
  3817. // Check implicitly captured variables.
  3818. VisitSubCaptures(S);
  3819. }
  3820. void VisitOMPLoopTransformationDirective(OMPLoopTransformationDirective *S) {
  3821. // Loop transformation directives do not introduce data sharing
  3822. VisitStmt(S);
  3823. }
  3824. void VisitCallExpr(CallExpr *S) {
  3825. for (Stmt *C : S->arguments()) {
  3826. if (C) {
  3827. // Check implicitly captured variables in the task-based directives to
  3828. // check if they must be firstprivatized.
  3829. Visit(C);
  3830. }
  3831. }
  3832. if (Expr *Callee = S->getCallee()) {
  3833. auto *CI = Callee->IgnoreParenImpCasts();
  3834. if (auto *CE = dyn_cast<MemberExpr>(CI))
  3835. Visit(CE->getBase());
  3836. else if (auto *CE = dyn_cast<DeclRefExpr>(CI))
  3837. Visit(CE);
  3838. }
  3839. }
  3840. void VisitStmt(Stmt *S) {
  3841. for (Stmt *C : S->children()) {
  3842. if (C) {
  3843. // Check implicitly captured variables in the task-based directives to
  3844. // check if they must be firstprivatized.
  3845. Visit(C);
  3846. }
  3847. }
  3848. }
  3849. void visitSubCaptures(CapturedStmt *S) {
  3850. for (const CapturedStmt::Capture &Cap : S->captures()) {
  3851. if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
  3852. continue;
  3853. VarDecl *VD = Cap.getCapturedVar();
  3854. // Do not try to map the variable if it or its sub-component was mapped
  3855. // already.
  3856. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  3857. Stack->checkMappableExprComponentListsForDecl(
  3858. VD, /*CurrentRegionOnly=*/true,
  3859. [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  3860. OpenMPClauseKind) { return true; }))
  3861. continue;
  3862. DeclRefExpr *DRE = buildDeclRefExpr(
  3863. SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
  3864. Cap.getLocation(), /*RefersToCapture=*/true);
  3865. Visit(DRE);
  3866. }
  3867. }
  3868. bool isErrorFound() const { return ErrorFound; }
  3869. ArrayRef<Expr *> getImplicitFirstprivate() const {
  3870. return ImplicitFirstprivate;
  3871. }
  3872. ArrayRef<Expr *> getImplicitPrivate() const { return ImplicitPrivate; }
  3873. ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK,
  3874. OpenMPMapClauseKind MK) const {
  3875. return ImplicitMap[DK][MK];
  3876. }
  3877. ArrayRef<OpenMPMapModifierKind>
  3878. getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const {
  3879. return ImplicitMapModifier[Kind];
  3880. }
  3881. const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
  3882. return VarsWithInheritedDSA;
  3883. }
  3884. DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
  3885. : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
  3886. // Process declare target link variables for the target directives.
  3887. if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
  3888. for (DeclRefExpr *E : Stack->getLinkGlobals())
  3889. Visit(E);
  3890. }
  3891. }
  3892. };
  3893. } // namespace
  3894. static void handleDeclareVariantConstructTrait(DSAStackTy *Stack,
  3895. OpenMPDirectiveKind DKind,
  3896. bool ScopeEntry) {
  3897. SmallVector<llvm::omp::TraitProperty, 8> Traits;
  3898. if (isOpenMPTargetExecutionDirective(DKind))
  3899. Traits.emplace_back(llvm::omp::TraitProperty::construct_target_target);
  3900. if (isOpenMPTeamsDirective(DKind))
  3901. Traits.emplace_back(llvm::omp::TraitProperty::construct_teams_teams);
  3902. if (isOpenMPParallelDirective(DKind))
  3903. Traits.emplace_back(llvm::omp::TraitProperty::construct_parallel_parallel);
  3904. if (isOpenMPWorksharingDirective(DKind))
  3905. Traits.emplace_back(llvm::omp::TraitProperty::construct_for_for);
  3906. if (isOpenMPSimdDirective(DKind))
  3907. Traits.emplace_back(llvm::omp::TraitProperty::construct_simd_simd);
  3908. Stack->handleConstructTrait(Traits, ScopeEntry);
  3909. }
  3910. void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
  3911. switch (DKind) {
  3912. case OMPD_parallel:
  3913. case OMPD_parallel_for:
  3914. case OMPD_parallel_for_simd:
  3915. case OMPD_parallel_sections:
  3916. case OMPD_parallel_master:
  3917. case OMPD_parallel_masked:
  3918. case OMPD_parallel_loop:
  3919. case OMPD_teams:
  3920. case OMPD_teams_distribute:
  3921. case OMPD_teams_distribute_simd: {
  3922. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3923. QualType KmpInt32PtrTy =
  3924. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3925. Sema::CapturedParamNameType Params[] = {
  3926. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3927. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3928. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3929. };
  3930. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3931. Params);
  3932. break;
  3933. }
  3934. case OMPD_target_teams:
  3935. case OMPD_target_parallel:
  3936. case OMPD_target_parallel_for:
  3937. case OMPD_target_parallel_for_simd:
  3938. case OMPD_target_teams_loop:
  3939. case OMPD_target_parallel_loop:
  3940. case OMPD_target_teams_distribute:
  3941. case OMPD_target_teams_distribute_simd: {
  3942. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3943. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3944. QualType KmpInt32PtrTy =
  3945. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3946. QualType Args[] = {VoidPtrTy};
  3947. FunctionProtoType::ExtProtoInfo EPI;
  3948. EPI.Variadic = true;
  3949. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3950. Sema::CapturedParamNameType Params[] = {
  3951. std::make_pair(".global_tid.", KmpInt32Ty),
  3952. std::make_pair(".part_id.", KmpInt32PtrTy),
  3953. std::make_pair(".privates.", VoidPtrTy),
  3954. std::make_pair(
  3955. ".copy_fn.",
  3956. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  3957. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  3958. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3959. };
  3960. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3961. Params, /*OpenMPCaptureLevel=*/0);
  3962. // Mark this captured region as inlined, because we don't use outlined
  3963. // function directly.
  3964. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  3965. AlwaysInlineAttr::CreateImplicit(
  3966. Context, {}, AttributeCommonInfo::AS_Keyword,
  3967. AlwaysInlineAttr::Keyword_forceinline));
  3968. Sema::CapturedParamNameType ParamsTarget[] = {
  3969. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3970. };
  3971. // Start a captured region for 'target' with no implicit parameters.
  3972. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3973. ParamsTarget, /*OpenMPCaptureLevel=*/1);
  3974. Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
  3975. std::make_pair(".global_tid.", KmpInt32PtrTy),
  3976. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  3977. std::make_pair(StringRef(), QualType()) // __context with shared vars
  3978. };
  3979. // Start a captured region for 'teams' or 'parallel'. Both regions have
  3980. // the same implicit parameters.
  3981. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  3982. ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
  3983. break;
  3984. }
  3985. case OMPD_target:
  3986. case OMPD_target_simd: {
  3987. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  3988. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  3989. QualType KmpInt32PtrTy =
  3990. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  3991. QualType Args[] = {VoidPtrTy};
  3992. FunctionProtoType::ExtProtoInfo EPI;
  3993. EPI.Variadic = true;
  3994. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  3995. Sema::CapturedParamNameType Params[] = {
  3996. std::make_pair(".global_tid.", KmpInt32Ty),
  3997. std::make_pair(".part_id.", KmpInt32PtrTy),
  3998. std::make_pair(".privates.", VoidPtrTy),
  3999. std::make_pair(
  4000. ".copy_fn.",
  4001. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  4002. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  4003. std::make_pair(StringRef(), QualType()) // __context with shared vars
  4004. };
  4005. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4006. Params, /*OpenMPCaptureLevel=*/0);
  4007. // Mark this captured region as inlined, because we don't use outlined
  4008. // function directly.
  4009. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  4010. AlwaysInlineAttr::CreateImplicit(
  4011. Context, {}, AttributeCommonInfo::AS_Keyword,
  4012. AlwaysInlineAttr::Keyword_forceinline));
  4013. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4014. std::make_pair(StringRef(), QualType()),
  4015. /*OpenMPCaptureLevel=*/1);
  4016. break;
  4017. }
  4018. case OMPD_atomic:
  4019. case OMPD_critical:
  4020. case OMPD_section:
  4021. case OMPD_master:
  4022. case OMPD_masked:
  4023. case OMPD_tile:
  4024. case OMPD_unroll:
  4025. break;
  4026. case OMPD_loop:
  4027. // TODO: 'loop' may require additional parameters depending on the binding.
  4028. // Treat similar to OMPD_simd/OMPD_for for now.
  4029. case OMPD_simd:
  4030. case OMPD_for:
  4031. case OMPD_for_simd:
  4032. case OMPD_sections:
  4033. case OMPD_single:
  4034. case OMPD_taskgroup:
  4035. case OMPD_distribute:
  4036. case OMPD_distribute_simd:
  4037. case OMPD_ordered:
  4038. case OMPD_target_data:
  4039. case OMPD_dispatch: {
  4040. Sema::CapturedParamNameType Params[] = {
  4041. std::make_pair(StringRef(), QualType()) // __context with shared vars
  4042. };
  4043. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4044. Params);
  4045. break;
  4046. }
  4047. case OMPD_task: {
  4048. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  4049. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  4050. QualType KmpInt32PtrTy =
  4051. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  4052. QualType Args[] = {VoidPtrTy};
  4053. FunctionProtoType::ExtProtoInfo EPI;
  4054. EPI.Variadic = true;
  4055. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  4056. Sema::CapturedParamNameType Params[] = {
  4057. std::make_pair(".global_tid.", KmpInt32Ty),
  4058. std::make_pair(".part_id.", KmpInt32PtrTy),
  4059. std::make_pair(".privates.", VoidPtrTy),
  4060. std::make_pair(
  4061. ".copy_fn.",
  4062. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  4063. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  4064. std::make_pair(StringRef(), QualType()) // __context with shared vars
  4065. };
  4066. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4067. Params);
  4068. // Mark this captured region as inlined, because we don't use outlined
  4069. // function directly.
  4070. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  4071. AlwaysInlineAttr::CreateImplicit(
  4072. Context, {}, AttributeCommonInfo::AS_Keyword,
  4073. AlwaysInlineAttr::Keyword_forceinline));
  4074. break;
  4075. }
  4076. case OMPD_taskloop:
  4077. case OMPD_taskloop_simd:
  4078. case OMPD_master_taskloop:
  4079. case OMPD_masked_taskloop:
  4080. case OMPD_masked_taskloop_simd:
  4081. case OMPD_master_taskloop_simd: {
  4082. QualType KmpInt32Ty =
  4083. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  4084. .withConst();
  4085. QualType KmpUInt64Ty =
  4086. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  4087. .withConst();
  4088. QualType KmpInt64Ty =
  4089. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  4090. .withConst();
  4091. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  4092. QualType KmpInt32PtrTy =
  4093. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  4094. QualType Args[] = {VoidPtrTy};
  4095. FunctionProtoType::ExtProtoInfo EPI;
  4096. EPI.Variadic = true;
  4097. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  4098. Sema::CapturedParamNameType Params[] = {
  4099. std::make_pair(".global_tid.", KmpInt32Ty),
  4100. std::make_pair(".part_id.", KmpInt32PtrTy),
  4101. std::make_pair(".privates.", VoidPtrTy),
  4102. std::make_pair(
  4103. ".copy_fn.",
  4104. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  4105. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  4106. std::make_pair(".lb.", KmpUInt64Ty),
  4107. std::make_pair(".ub.", KmpUInt64Ty),
  4108. std::make_pair(".st.", KmpInt64Ty),
  4109. std::make_pair(".liter.", KmpInt32Ty),
  4110. std::make_pair(".reductions.", VoidPtrTy),
  4111. std::make_pair(StringRef(), QualType()) // __context with shared vars
  4112. };
  4113. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4114. Params);
  4115. // Mark this captured region as inlined, because we don't use outlined
  4116. // function directly.
  4117. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  4118. AlwaysInlineAttr::CreateImplicit(
  4119. Context, {}, AttributeCommonInfo::AS_Keyword,
  4120. AlwaysInlineAttr::Keyword_forceinline));
  4121. break;
  4122. }
  4123. case OMPD_parallel_masked_taskloop:
  4124. case OMPD_parallel_masked_taskloop_simd:
  4125. case OMPD_parallel_master_taskloop:
  4126. case OMPD_parallel_master_taskloop_simd: {
  4127. QualType KmpInt32Ty =
  4128. Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
  4129. .withConst();
  4130. QualType KmpUInt64Ty =
  4131. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
  4132. .withConst();
  4133. QualType KmpInt64Ty =
  4134. Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
  4135. .withConst();
  4136. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  4137. QualType KmpInt32PtrTy =
  4138. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  4139. Sema::CapturedParamNameType ParamsParallel[] = {
  4140. std::make_pair(".global_tid.", KmpInt32PtrTy),
  4141. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  4142. std::make_pair(StringRef(), QualType()) // __context with shared vars
  4143. };
  4144. // Start a captured region for 'parallel'.
  4145. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4146. ParamsParallel, /*OpenMPCaptureLevel=*/0);
  4147. QualType Args[] = {VoidPtrTy};
  4148. FunctionProtoType::ExtProtoInfo EPI;
  4149. EPI.Variadic = true;
  4150. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  4151. Sema::CapturedParamNameType Params[] = {
  4152. std::make_pair(".global_tid.", KmpInt32Ty),
  4153. std::make_pair(".part_id.", KmpInt32PtrTy),
  4154. std::make_pair(".privates.", VoidPtrTy),
  4155. std::make_pair(
  4156. ".copy_fn.",
  4157. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  4158. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  4159. std::make_pair(".lb.", KmpUInt64Ty),
  4160. std::make_pair(".ub.", KmpUInt64Ty),
  4161. std::make_pair(".st.", KmpInt64Ty),
  4162. std::make_pair(".liter.", KmpInt32Ty),
  4163. std::make_pair(".reductions.", VoidPtrTy),
  4164. std::make_pair(StringRef(), QualType()) // __context with shared vars
  4165. };
  4166. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4167. Params, /*OpenMPCaptureLevel=*/1);
  4168. // Mark this captured region as inlined, because we don't use outlined
  4169. // function directly.
  4170. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  4171. AlwaysInlineAttr::CreateImplicit(
  4172. Context, {}, AttributeCommonInfo::AS_Keyword,
  4173. AlwaysInlineAttr::Keyword_forceinline));
  4174. break;
  4175. }
  4176. case OMPD_distribute_parallel_for_simd:
  4177. case OMPD_distribute_parallel_for: {
  4178. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  4179. QualType KmpInt32PtrTy =
  4180. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  4181. Sema::CapturedParamNameType Params[] = {
  4182. std::make_pair(".global_tid.", KmpInt32PtrTy),
  4183. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  4184. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  4185. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  4186. std::make_pair(StringRef(), QualType()) // __context with shared vars
  4187. };
  4188. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4189. Params);
  4190. break;
  4191. }
  4192. case OMPD_target_teams_distribute_parallel_for:
  4193. case OMPD_target_teams_distribute_parallel_for_simd: {
  4194. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  4195. QualType KmpInt32PtrTy =
  4196. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  4197. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  4198. QualType Args[] = {VoidPtrTy};
  4199. FunctionProtoType::ExtProtoInfo EPI;
  4200. EPI.Variadic = true;
  4201. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  4202. Sema::CapturedParamNameType Params[] = {
  4203. std::make_pair(".global_tid.", KmpInt32Ty),
  4204. std::make_pair(".part_id.", KmpInt32PtrTy),
  4205. std::make_pair(".privates.", VoidPtrTy),
  4206. std::make_pair(
  4207. ".copy_fn.",
  4208. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  4209. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  4210. std::make_pair(StringRef(), QualType()) // __context with shared vars
  4211. };
  4212. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4213. Params, /*OpenMPCaptureLevel=*/0);
  4214. // Mark this captured region as inlined, because we don't use outlined
  4215. // function directly.
  4216. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  4217. AlwaysInlineAttr::CreateImplicit(
  4218. Context, {}, AttributeCommonInfo::AS_Keyword,
  4219. AlwaysInlineAttr::Keyword_forceinline));
  4220. Sema::CapturedParamNameType ParamsTarget[] = {
  4221. std::make_pair(StringRef(), QualType()) // __context with shared vars
  4222. };
  4223. // Start a captured region for 'target' with no implicit parameters.
  4224. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4225. ParamsTarget, /*OpenMPCaptureLevel=*/1);
  4226. Sema::CapturedParamNameType ParamsTeams[] = {
  4227. std::make_pair(".global_tid.", KmpInt32PtrTy),
  4228. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  4229. std::make_pair(StringRef(), QualType()) // __context with shared vars
  4230. };
  4231. // Start a captured region for 'target' with no implicit parameters.
  4232. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4233. ParamsTeams, /*OpenMPCaptureLevel=*/2);
  4234. Sema::CapturedParamNameType ParamsParallel[] = {
  4235. std::make_pair(".global_tid.", KmpInt32PtrTy),
  4236. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  4237. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  4238. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  4239. std::make_pair(StringRef(), QualType()) // __context with shared vars
  4240. };
  4241. // Start a captured region for 'teams' or 'parallel'. Both regions have
  4242. // the same implicit parameters.
  4243. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4244. ParamsParallel, /*OpenMPCaptureLevel=*/3);
  4245. break;
  4246. }
  4247. case OMPD_teams_loop: {
  4248. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  4249. QualType KmpInt32PtrTy =
  4250. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  4251. Sema::CapturedParamNameType ParamsTeams[] = {
  4252. std::make_pair(".global_tid.", KmpInt32PtrTy),
  4253. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  4254. std::make_pair(StringRef(), QualType()) // __context with shared vars
  4255. };
  4256. // Start a captured region for 'teams'.
  4257. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4258. ParamsTeams, /*OpenMPCaptureLevel=*/0);
  4259. break;
  4260. }
  4261. case OMPD_teams_distribute_parallel_for:
  4262. case OMPD_teams_distribute_parallel_for_simd: {
  4263. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  4264. QualType KmpInt32PtrTy =
  4265. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  4266. Sema::CapturedParamNameType ParamsTeams[] = {
  4267. std::make_pair(".global_tid.", KmpInt32PtrTy),
  4268. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  4269. std::make_pair(StringRef(), QualType()) // __context with shared vars
  4270. };
  4271. // Start a captured region for 'target' with no implicit parameters.
  4272. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4273. ParamsTeams, /*OpenMPCaptureLevel=*/0);
  4274. Sema::CapturedParamNameType ParamsParallel[] = {
  4275. std::make_pair(".global_tid.", KmpInt32PtrTy),
  4276. std::make_pair(".bound_tid.", KmpInt32PtrTy),
  4277. std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
  4278. std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
  4279. std::make_pair(StringRef(), QualType()) // __context with shared vars
  4280. };
  4281. // Start a captured region for 'teams' or 'parallel'. Both regions have
  4282. // the same implicit parameters.
  4283. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4284. ParamsParallel, /*OpenMPCaptureLevel=*/1);
  4285. break;
  4286. }
  4287. case OMPD_target_update:
  4288. case OMPD_target_enter_data:
  4289. case OMPD_target_exit_data: {
  4290. QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
  4291. QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
  4292. QualType KmpInt32PtrTy =
  4293. Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
  4294. QualType Args[] = {VoidPtrTy};
  4295. FunctionProtoType::ExtProtoInfo EPI;
  4296. EPI.Variadic = true;
  4297. QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
  4298. Sema::CapturedParamNameType Params[] = {
  4299. std::make_pair(".global_tid.", KmpInt32Ty),
  4300. std::make_pair(".part_id.", KmpInt32PtrTy),
  4301. std::make_pair(".privates.", VoidPtrTy),
  4302. std::make_pair(
  4303. ".copy_fn.",
  4304. Context.getPointerType(CopyFnType).withConst().withRestrict()),
  4305. std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
  4306. std::make_pair(StringRef(), QualType()) // __context with shared vars
  4307. };
  4308. ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
  4309. Params);
  4310. // Mark this captured region as inlined, because we don't use outlined
  4311. // function directly.
  4312. getCurCapturedRegion()->TheCapturedDecl->addAttr(
  4313. AlwaysInlineAttr::CreateImplicit(
  4314. Context, {}, AttributeCommonInfo::AS_Keyword,
  4315. AlwaysInlineAttr::Keyword_forceinline));
  4316. break;
  4317. }
  4318. case OMPD_threadprivate:
  4319. case OMPD_allocate:
  4320. case OMPD_taskyield:
  4321. case OMPD_error:
  4322. case OMPD_barrier:
  4323. case OMPD_taskwait:
  4324. case OMPD_cancellation_point:
  4325. case OMPD_cancel:
  4326. case OMPD_flush:
  4327. case OMPD_depobj:
  4328. case OMPD_scan:
  4329. case OMPD_declare_reduction:
  4330. case OMPD_declare_mapper:
  4331. case OMPD_declare_simd:
  4332. case OMPD_declare_target:
  4333. case OMPD_end_declare_target:
  4334. case OMPD_requires:
  4335. case OMPD_declare_variant:
  4336. case OMPD_begin_declare_variant:
  4337. case OMPD_end_declare_variant:
  4338. case OMPD_metadirective:
  4339. llvm_unreachable("OpenMP Directive is not allowed");
  4340. case OMPD_unknown:
  4341. default:
  4342. llvm_unreachable("Unknown OpenMP directive");
  4343. }
  4344. DSAStack->setContext(CurContext);
  4345. handleDeclareVariantConstructTrait(DSAStack, DKind, /* ScopeEntry */ true);
  4346. }
  4347. int Sema::getNumberOfConstructScopes(unsigned Level) const {
  4348. return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
  4349. }
  4350. int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
  4351. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  4352. getOpenMPCaptureRegions(CaptureRegions, DKind);
  4353. return CaptureRegions.size();
  4354. }
  4355. static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
  4356. Expr *CaptureExpr, bool WithInit,
  4357. DeclContext *CurContext,
  4358. bool AsExpression) {
  4359. assert(CaptureExpr);
  4360. ASTContext &C = S.getASTContext();
  4361. Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
  4362. QualType Ty = Init->getType();
  4363. if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
  4364. if (S.getLangOpts().CPlusPlus) {
  4365. Ty = C.getLValueReferenceType(Ty);
  4366. } else {
  4367. Ty = C.getPointerType(Ty);
  4368. ExprResult Res =
  4369. S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
  4370. if (!Res.isUsable())
  4371. return nullptr;
  4372. Init = Res.get();
  4373. }
  4374. WithInit = true;
  4375. }
  4376. auto *CED = OMPCapturedExprDecl::Create(C, CurContext, Id, Ty,
  4377. CaptureExpr->getBeginLoc());
  4378. if (!WithInit)
  4379. CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
  4380. CurContext->addHiddenDecl(CED);
  4381. Sema::TentativeAnalysisScope Trap(S);
  4382. S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
  4383. return CED;
  4384. }
  4385. static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
  4386. bool WithInit) {
  4387. OMPCapturedExprDecl *CD;
  4388. if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
  4389. CD = cast<OMPCapturedExprDecl>(VD);
  4390. else
  4391. CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
  4392. S.CurContext,
  4393. /*AsExpression=*/false);
  4394. return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  4395. CaptureExpr->getExprLoc());
  4396. }
  4397. static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
  4398. CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
  4399. if (!Ref) {
  4400. OMPCapturedExprDecl *CD = buildCaptureDecl(
  4401. S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
  4402. /*WithInit=*/true, S.CurContext, /*AsExpression=*/true);
  4403. Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
  4404. CaptureExpr->getExprLoc());
  4405. }
  4406. ExprResult Res = Ref;
  4407. if (!S.getLangOpts().CPlusPlus &&
  4408. CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
  4409. Ref->getType()->isPointerType()) {
  4410. Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
  4411. if (!Res.isUsable())
  4412. return ExprError();
  4413. }
  4414. return S.DefaultLvalueConversion(Res.get());
  4415. }
  4416. namespace {
  4417. // OpenMP directives parsed in this section are represented as a
  4418. // CapturedStatement with an associated statement. If a syntax error
  4419. // is detected during the parsing of the associated statement, the
  4420. // compiler must abort processing and close the CapturedStatement.
  4421. //
  4422. // Combined directives such as 'target parallel' have more than one
  4423. // nested CapturedStatements. This RAII ensures that we unwind out
  4424. // of all the nested CapturedStatements when an error is found.
  4425. class CaptureRegionUnwinderRAII {
  4426. private:
  4427. Sema &S;
  4428. bool &ErrorFound;
  4429. OpenMPDirectiveKind DKind = OMPD_unknown;
  4430. public:
  4431. CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
  4432. OpenMPDirectiveKind DKind)
  4433. : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
  4434. ~CaptureRegionUnwinderRAII() {
  4435. if (ErrorFound) {
  4436. int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
  4437. while (--ThisCaptureLevel >= 0)
  4438. S.ActOnCapturedRegionError();
  4439. }
  4440. }
  4441. };
  4442. } // namespace
  4443. void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
  4444. // Capture variables captured by reference in lambdas for target-based
  4445. // directives.
  4446. if (!CurContext->isDependentContext() &&
  4447. (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
  4448. isOpenMPTargetDataManagementDirective(
  4449. DSAStack->getCurrentDirective()))) {
  4450. QualType Type = V->getType();
  4451. if (const auto *RD = Type.getCanonicalType()
  4452. .getNonReferenceType()
  4453. ->getAsCXXRecordDecl()) {
  4454. bool SavedForceCaptureByReferenceInTargetExecutable =
  4455. DSAStack->isForceCaptureByReferenceInTargetExecutable();
  4456. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  4457. /*V=*/true);
  4458. if (RD->isLambda()) {
  4459. llvm::DenseMap<const ValueDecl *, FieldDecl *> Captures;
  4460. FieldDecl *ThisCapture;
  4461. RD->getCaptureFields(Captures, ThisCapture);
  4462. for (const LambdaCapture &LC : RD->captures()) {
  4463. if (LC.getCaptureKind() == LCK_ByRef) {
  4464. VarDecl *VD = cast<VarDecl>(LC.getCapturedVar());
  4465. DeclContext *VDC = VD->getDeclContext();
  4466. if (!VDC->Encloses(CurContext))
  4467. continue;
  4468. MarkVariableReferenced(LC.getLocation(), VD);
  4469. } else if (LC.getCaptureKind() == LCK_This) {
  4470. QualType ThisTy = getCurrentThisType();
  4471. if (!ThisTy.isNull() &&
  4472. Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
  4473. CheckCXXThisCapture(LC.getLocation());
  4474. }
  4475. }
  4476. }
  4477. DSAStack->setForceCaptureByReferenceInTargetExecutable(
  4478. SavedForceCaptureByReferenceInTargetExecutable);
  4479. }
  4480. }
  4481. }
  4482. static bool checkOrderedOrderSpecified(Sema &S,
  4483. const ArrayRef<OMPClause *> Clauses) {
  4484. const OMPOrderedClause *Ordered = nullptr;
  4485. const OMPOrderClause *Order = nullptr;
  4486. for (const OMPClause *Clause : Clauses) {
  4487. if (Clause->getClauseKind() == OMPC_ordered)
  4488. Ordered = cast<OMPOrderedClause>(Clause);
  4489. else if (Clause->getClauseKind() == OMPC_order) {
  4490. Order = cast<OMPOrderClause>(Clause);
  4491. if (Order->getKind() != OMPC_ORDER_concurrent)
  4492. Order = nullptr;
  4493. }
  4494. if (Ordered && Order)
  4495. break;
  4496. }
  4497. if (Ordered && Order) {
  4498. S.Diag(Order->getKindKwLoc(),
  4499. diag::err_omp_simple_clause_incompatible_with_ordered)
  4500. << getOpenMPClauseName(OMPC_order)
  4501. << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
  4502. << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
  4503. S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
  4504. << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
  4505. return true;
  4506. }
  4507. return false;
  4508. }
  4509. StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
  4510. ArrayRef<OMPClause *> Clauses) {
  4511. handleDeclareVariantConstructTrait(DSAStack, DSAStack->getCurrentDirective(),
  4512. /* ScopeEntry */ false);
  4513. if (DSAStack->getCurrentDirective() == OMPD_atomic ||
  4514. DSAStack->getCurrentDirective() == OMPD_critical ||
  4515. DSAStack->getCurrentDirective() == OMPD_section ||
  4516. DSAStack->getCurrentDirective() == OMPD_master ||
  4517. DSAStack->getCurrentDirective() == OMPD_masked)
  4518. return S;
  4519. bool ErrorFound = false;
  4520. CaptureRegionUnwinderRAII CaptureRegionUnwinder(
  4521. *this, ErrorFound, DSAStack->getCurrentDirective());
  4522. if (!S.isUsable()) {
  4523. ErrorFound = true;
  4524. return StmtError();
  4525. }
  4526. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  4527. getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
  4528. OMPOrderedClause *OC = nullptr;
  4529. OMPScheduleClause *SC = nullptr;
  4530. SmallVector<const OMPLinearClause *, 4> LCs;
  4531. SmallVector<const OMPClauseWithPreInit *, 4> PICs;
  4532. // This is required for proper codegen.
  4533. for (OMPClause *Clause : Clauses) {
  4534. if (!LangOpts.OpenMPSimd &&
  4535. (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) ||
  4536. DSAStack->getCurrentDirective() == OMPD_target) &&
  4537. Clause->getClauseKind() == OMPC_in_reduction) {
  4538. // Capture taskgroup task_reduction descriptors inside the tasking regions
  4539. // with the corresponding in_reduction items.
  4540. auto *IRC = cast<OMPInReductionClause>(Clause);
  4541. for (Expr *E : IRC->taskgroup_descriptors())
  4542. if (E)
  4543. MarkDeclarationsReferencedInExpr(E);
  4544. }
  4545. if (isOpenMPPrivate(Clause->getClauseKind()) ||
  4546. Clause->getClauseKind() == OMPC_copyprivate ||
  4547. (getLangOpts().OpenMPUseTLS &&
  4548. getASTContext().getTargetInfo().isTLSSupported() &&
  4549. Clause->getClauseKind() == OMPC_copyin)) {
  4550. DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
  4551. // Mark all variables in private list clauses as used in inner region.
  4552. for (Stmt *VarRef : Clause->children()) {
  4553. if (auto *E = cast_or_null<Expr>(VarRef)) {
  4554. MarkDeclarationsReferencedInExpr(E);
  4555. }
  4556. }
  4557. DSAStack->setForceVarCapturing(/*V=*/false);
  4558. } else if (isOpenMPLoopTransformationDirective(
  4559. DSAStack->getCurrentDirective())) {
  4560. assert(CaptureRegions.empty() &&
  4561. "No captured regions in loop transformation directives.");
  4562. } else if (CaptureRegions.size() > 1 ||
  4563. CaptureRegions.back() != OMPD_unknown) {
  4564. if (auto *C = OMPClauseWithPreInit::get(Clause))
  4565. PICs.push_back(C);
  4566. if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
  4567. if (Expr *E = C->getPostUpdateExpr())
  4568. MarkDeclarationsReferencedInExpr(E);
  4569. }
  4570. }
  4571. if (Clause->getClauseKind() == OMPC_schedule)
  4572. SC = cast<OMPScheduleClause>(Clause);
  4573. else if (Clause->getClauseKind() == OMPC_ordered)
  4574. OC = cast<OMPOrderedClause>(Clause);
  4575. else if (Clause->getClauseKind() == OMPC_linear)
  4576. LCs.push_back(cast<OMPLinearClause>(Clause));
  4577. }
  4578. // Capture allocator expressions if used.
  4579. for (Expr *E : DSAStack->getInnerAllocators())
  4580. MarkDeclarationsReferencedInExpr(E);
  4581. // OpenMP, 2.7.1 Loop Construct, Restrictions
  4582. // The nonmonotonic modifier cannot be specified if an ordered clause is
  4583. // specified.
  4584. if (SC &&
  4585. (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  4586. SC->getSecondScheduleModifier() ==
  4587. OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  4588. OC) {
  4589. Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
  4590. ? SC->getFirstScheduleModifierLoc()
  4591. : SC->getSecondScheduleModifierLoc(),
  4592. diag::err_omp_simple_clause_incompatible_with_ordered)
  4593. << getOpenMPClauseName(OMPC_schedule)
  4594. << getOpenMPSimpleClauseTypeName(OMPC_schedule,
  4595. OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  4596. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  4597. ErrorFound = true;
  4598. }
  4599. // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
  4600. // If an order(concurrent) clause is present, an ordered clause may not appear
  4601. // on the same directive.
  4602. if (checkOrderedOrderSpecified(*this, Clauses))
  4603. ErrorFound = true;
  4604. if (!LCs.empty() && OC && OC->getNumForLoops()) {
  4605. for (const OMPLinearClause *C : LCs) {
  4606. Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
  4607. << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
  4608. }
  4609. ErrorFound = true;
  4610. }
  4611. if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
  4612. isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
  4613. OC->getNumForLoops()) {
  4614. Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
  4615. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  4616. ErrorFound = true;
  4617. }
  4618. if (ErrorFound) {
  4619. return StmtError();
  4620. }
  4621. StmtResult SR = S;
  4622. unsigned CompletedRegions = 0;
  4623. for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
  4624. // Mark all variables in private list clauses as used in inner region.
  4625. // Required for proper codegen of combined directives.
  4626. // TODO: add processing for other clauses.
  4627. if (ThisCaptureRegion != OMPD_unknown) {
  4628. for (const clang::OMPClauseWithPreInit *C : PICs) {
  4629. OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
  4630. // Find the particular capture region for the clause if the
  4631. // directive is a combined one with multiple capture regions.
  4632. // If the directive is not a combined one, the capture region
  4633. // associated with the clause is OMPD_unknown and is generated
  4634. // only once.
  4635. if (CaptureRegion == ThisCaptureRegion ||
  4636. CaptureRegion == OMPD_unknown) {
  4637. if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
  4638. for (Decl *D : DS->decls())
  4639. MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
  4640. }
  4641. }
  4642. }
  4643. }
  4644. if (ThisCaptureRegion == OMPD_target) {
  4645. // Capture allocator traits in the target region. They are used implicitly
  4646. // and, thus, are not captured by default.
  4647. for (OMPClause *C : Clauses) {
  4648. if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) {
  4649. for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End;
  4650. ++I) {
  4651. OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I);
  4652. if (Expr *E = D.AllocatorTraits)
  4653. MarkDeclarationsReferencedInExpr(E);
  4654. }
  4655. continue;
  4656. }
  4657. }
  4658. }
  4659. if (ThisCaptureRegion == OMPD_parallel) {
  4660. // Capture temp arrays for inscan reductions and locals in aligned
  4661. // clauses.
  4662. for (OMPClause *C : Clauses) {
  4663. if (auto *RC = dyn_cast<OMPReductionClause>(C)) {
  4664. if (RC->getModifier() != OMPC_REDUCTION_inscan)
  4665. continue;
  4666. for (Expr *E : RC->copy_array_temps())
  4667. MarkDeclarationsReferencedInExpr(E);
  4668. }
  4669. if (auto *AC = dyn_cast<OMPAlignedClause>(C)) {
  4670. for (Expr *E : AC->varlists())
  4671. MarkDeclarationsReferencedInExpr(E);
  4672. }
  4673. }
  4674. }
  4675. if (++CompletedRegions == CaptureRegions.size())
  4676. DSAStack->setBodyComplete();
  4677. SR = ActOnCapturedRegionEnd(SR.get());
  4678. }
  4679. return SR;
  4680. }
  4681. static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
  4682. OpenMPDirectiveKind CancelRegion,
  4683. SourceLocation StartLoc) {
  4684. // CancelRegion is only needed for cancel and cancellation_point.
  4685. if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
  4686. return false;
  4687. if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
  4688. CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
  4689. return false;
  4690. SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
  4691. << getOpenMPDirectiveName(CancelRegion);
  4692. return true;
  4693. }
  4694. static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
  4695. OpenMPDirectiveKind CurrentRegion,
  4696. const DeclarationNameInfo &CurrentName,
  4697. OpenMPDirectiveKind CancelRegion,
  4698. OpenMPBindClauseKind BindKind,
  4699. SourceLocation StartLoc) {
  4700. if (Stack->getCurScope()) {
  4701. OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
  4702. OpenMPDirectiveKind OffendingRegion = ParentRegion;
  4703. bool NestingProhibited = false;
  4704. bool CloseNesting = true;
  4705. bool OrphanSeen = false;
  4706. enum {
  4707. NoRecommend,
  4708. ShouldBeInParallelRegion,
  4709. ShouldBeInOrderedRegion,
  4710. ShouldBeInTargetRegion,
  4711. ShouldBeInTeamsRegion,
  4712. ShouldBeInLoopSimdRegion,
  4713. } Recommend = NoRecommend;
  4714. if (SemaRef.LangOpts.OpenMP >= 51 && Stack->isParentOrderConcurrent() &&
  4715. CurrentRegion != OMPD_simd && CurrentRegion != OMPD_loop &&
  4716. CurrentRegion != OMPD_parallel &&
  4717. !isOpenMPCombinedParallelADirective(CurrentRegion)) {
  4718. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_order)
  4719. << getOpenMPDirectiveName(CurrentRegion);
  4720. return true;
  4721. }
  4722. if (isOpenMPSimdDirective(ParentRegion) &&
  4723. ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
  4724. (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
  4725. CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic &&
  4726. CurrentRegion != OMPD_scan))) {
  4727. // OpenMP [2.16, Nesting of Regions]
  4728. // OpenMP constructs may not be nested inside a simd region.
  4729. // OpenMP [2.8.1,simd Construct, Restrictions]
  4730. // An ordered construct with the simd clause is the only OpenMP
  4731. // construct that can appear in the simd region.
  4732. // Allowing a SIMD construct nested in another SIMD construct is an
  4733. // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
  4734. // message.
  4735. // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
  4736. // The only OpenMP constructs that can be encountered during execution of
  4737. // a simd region are the atomic construct, the loop construct, the simd
  4738. // construct and the ordered construct with the simd clause.
  4739. SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
  4740. ? diag::err_omp_prohibited_region_simd
  4741. : diag::warn_omp_nesting_simd)
  4742. << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
  4743. return CurrentRegion != OMPD_simd;
  4744. }
  4745. if (ParentRegion == OMPD_atomic) {
  4746. // OpenMP [2.16, Nesting of Regions]
  4747. // OpenMP constructs may not be nested inside an atomic region.
  4748. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
  4749. return true;
  4750. }
  4751. if (CurrentRegion == OMPD_section) {
  4752. // OpenMP [2.7.2, sections Construct, Restrictions]
  4753. // Orphaned section directives are prohibited. That is, the section
  4754. // directives must appear within the sections construct and must not be
  4755. // encountered elsewhere in the sections region.
  4756. if (ParentRegion != OMPD_sections &&
  4757. ParentRegion != OMPD_parallel_sections) {
  4758. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
  4759. << (ParentRegion != OMPD_unknown)
  4760. << getOpenMPDirectiveName(ParentRegion);
  4761. return true;
  4762. }
  4763. return false;
  4764. }
  4765. // Allow some constructs (except teams and cancellation constructs) to be
  4766. // orphaned (they could be used in functions, called from OpenMP regions
  4767. // with the required preconditions).
  4768. if (ParentRegion == OMPD_unknown &&
  4769. !isOpenMPNestingTeamsDirective(CurrentRegion) &&
  4770. CurrentRegion != OMPD_cancellation_point &&
  4771. CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan)
  4772. return false;
  4773. if (CurrentRegion == OMPD_cancellation_point ||
  4774. CurrentRegion == OMPD_cancel) {
  4775. // OpenMP [2.16, Nesting of Regions]
  4776. // A cancellation point construct for which construct-type-clause is
  4777. // taskgroup must be nested inside a task construct. A cancellation
  4778. // point construct for which construct-type-clause is not taskgroup must
  4779. // be closely nested inside an OpenMP construct that matches the type
  4780. // specified in construct-type-clause.
  4781. // A cancel construct for which construct-type-clause is taskgroup must be
  4782. // nested inside a task construct. A cancel construct for which
  4783. // construct-type-clause is not taskgroup must be closely nested inside an
  4784. // OpenMP construct that matches the type specified in
  4785. // construct-type-clause.
  4786. NestingProhibited =
  4787. !((CancelRegion == OMPD_parallel &&
  4788. (ParentRegion == OMPD_parallel ||
  4789. ParentRegion == OMPD_target_parallel)) ||
  4790. (CancelRegion == OMPD_for &&
  4791. (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
  4792. ParentRegion == OMPD_target_parallel_for ||
  4793. ParentRegion == OMPD_distribute_parallel_for ||
  4794. ParentRegion == OMPD_teams_distribute_parallel_for ||
  4795. ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
  4796. (CancelRegion == OMPD_taskgroup &&
  4797. (ParentRegion == OMPD_task ||
  4798. (SemaRef.getLangOpts().OpenMP >= 50 &&
  4799. (ParentRegion == OMPD_taskloop ||
  4800. ParentRegion == OMPD_master_taskloop ||
  4801. ParentRegion == OMPD_masked_taskloop ||
  4802. ParentRegion == OMPD_parallel_masked_taskloop ||
  4803. ParentRegion == OMPD_parallel_master_taskloop)))) ||
  4804. (CancelRegion == OMPD_sections &&
  4805. (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
  4806. ParentRegion == OMPD_parallel_sections)));
  4807. OrphanSeen = ParentRegion == OMPD_unknown;
  4808. } else if (CurrentRegion == OMPD_master || CurrentRegion == OMPD_masked) {
  4809. // OpenMP 5.1 [2.22, Nesting of Regions]
  4810. // A masked region may not be closely nested inside a worksharing, loop,
  4811. // atomic, task, or taskloop region.
  4812. NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
  4813. isOpenMPGenericLoopDirective(ParentRegion) ||
  4814. isOpenMPTaskingDirective(ParentRegion);
  4815. } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
  4816. // OpenMP [2.16, Nesting of Regions]
  4817. // A critical region may not be nested (closely or otherwise) inside a
  4818. // critical region with the same name. Note that this restriction is not
  4819. // sufficient to prevent deadlock.
  4820. SourceLocation PreviousCriticalLoc;
  4821. bool DeadLock = Stack->hasDirective(
  4822. [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
  4823. const DeclarationNameInfo &DNI,
  4824. SourceLocation Loc) {
  4825. if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
  4826. PreviousCriticalLoc = Loc;
  4827. return true;
  4828. }
  4829. return false;
  4830. },
  4831. false /* skip top directive */);
  4832. if (DeadLock) {
  4833. SemaRef.Diag(StartLoc,
  4834. diag::err_omp_prohibited_region_critical_same_name)
  4835. << CurrentName.getName();
  4836. if (PreviousCriticalLoc.isValid())
  4837. SemaRef.Diag(PreviousCriticalLoc,
  4838. diag::note_omp_previous_critical_region);
  4839. return true;
  4840. }
  4841. } else if (CurrentRegion == OMPD_barrier) {
  4842. // OpenMP 5.1 [2.22, Nesting of Regions]
  4843. // A barrier region may not be closely nested inside a worksharing, loop,
  4844. // task, taskloop, critical, ordered, atomic, or masked region.
  4845. NestingProhibited =
  4846. isOpenMPWorksharingDirective(ParentRegion) ||
  4847. isOpenMPGenericLoopDirective(ParentRegion) ||
  4848. isOpenMPTaskingDirective(ParentRegion) ||
  4849. ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
  4850. ParentRegion == OMPD_parallel_master ||
  4851. ParentRegion == OMPD_parallel_masked ||
  4852. ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
  4853. } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
  4854. !isOpenMPParallelDirective(CurrentRegion) &&
  4855. !isOpenMPTeamsDirective(CurrentRegion)) {
  4856. // OpenMP 5.1 [2.22, Nesting of Regions]
  4857. // A loop region that binds to a parallel region or a worksharing region
  4858. // may not be closely nested inside a worksharing, loop, task, taskloop,
  4859. // critical, ordered, atomic, or masked region.
  4860. NestingProhibited =
  4861. isOpenMPWorksharingDirective(ParentRegion) ||
  4862. isOpenMPGenericLoopDirective(ParentRegion) ||
  4863. isOpenMPTaskingDirective(ParentRegion) ||
  4864. ParentRegion == OMPD_master || ParentRegion == OMPD_masked ||
  4865. ParentRegion == OMPD_parallel_master ||
  4866. ParentRegion == OMPD_parallel_masked ||
  4867. ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered;
  4868. Recommend = ShouldBeInParallelRegion;
  4869. } else if (CurrentRegion == OMPD_ordered) {
  4870. // OpenMP [2.16, Nesting of Regions]
  4871. // An ordered region may not be closely nested inside a critical,
  4872. // atomic, or explicit task region.
  4873. // An ordered region must be closely nested inside a loop region (or
  4874. // parallel loop region) with an ordered clause.
  4875. // OpenMP [2.8.1,simd Construct, Restrictions]
  4876. // An ordered construct with the simd clause is the only OpenMP construct
  4877. // that can appear in the simd region.
  4878. NestingProhibited = ParentRegion == OMPD_critical ||
  4879. isOpenMPTaskingDirective(ParentRegion) ||
  4880. !(isOpenMPSimdDirective(ParentRegion) ||
  4881. Stack->isParentOrderedRegion());
  4882. Recommend = ShouldBeInOrderedRegion;
  4883. } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
  4884. // OpenMP [2.16, Nesting of Regions]
  4885. // If specified, a teams construct must be contained within a target
  4886. // construct.
  4887. NestingProhibited =
  4888. (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
  4889. (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
  4890. ParentRegion != OMPD_target);
  4891. OrphanSeen = ParentRegion == OMPD_unknown;
  4892. Recommend = ShouldBeInTargetRegion;
  4893. } else if (CurrentRegion == OMPD_scan) {
  4894. // OpenMP [2.16, Nesting of Regions]
  4895. // If specified, a teams construct must be contained within a target
  4896. // construct.
  4897. NestingProhibited =
  4898. SemaRef.LangOpts.OpenMP < 50 ||
  4899. (ParentRegion != OMPD_simd && ParentRegion != OMPD_for &&
  4900. ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for &&
  4901. ParentRegion != OMPD_parallel_for_simd);
  4902. OrphanSeen = ParentRegion == OMPD_unknown;
  4903. Recommend = ShouldBeInLoopSimdRegion;
  4904. }
  4905. if (!NestingProhibited &&
  4906. !isOpenMPTargetExecutionDirective(CurrentRegion) &&
  4907. !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
  4908. (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
  4909. // OpenMP [5.1, 2.22, Nesting of Regions]
  4910. // distribute, distribute simd, distribute parallel worksharing-loop,
  4911. // distribute parallel worksharing-loop SIMD, loop, parallel regions,
  4912. // including any parallel regions arising from combined constructs,
  4913. // omp_get_num_teams() regions, and omp_get_team_num() regions are the
  4914. // only OpenMP regions that may be strictly nested inside the teams
  4915. // region.
  4916. //
  4917. // As an extension, we permit atomic within teams as well.
  4918. NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
  4919. !isOpenMPDistributeDirective(CurrentRegion) &&
  4920. CurrentRegion != OMPD_loop &&
  4921. !(SemaRef.getLangOpts().OpenMPExtensions &&
  4922. CurrentRegion == OMPD_atomic);
  4923. Recommend = ShouldBeInParallelRegion;
  4924. }
  4925. if (!NestingProhibited && CurrentRegion == OMPD_loop) {
  4926. // OpenMP [5.1, 2.11.7, loop Construct, Restrictions]
  4927. // If the bind clause is present on the loop construct and binding is
  4928. // teams then the corresponding loop region must be strictly nested inside
  4929. // a teams region.
  4930. NestingProhibited = BindKind == OMPC_BIND_teams &&
  4931. ParentRegion != OMPD_teams &&
  4932. ParentRegion != OMPD_target_teams;
  4933. Recommend = ShouldBeInTeamsRegion;
  4934. }
  4935. if (!NestingProhibited &&
  4936. isOpenMPNestingDistributeDirective(CurrentRegion)) {
  4937. // OpenMP 4.5 [2.17 Nesting of Regions]
  4938. // The region associated with the distribute construct must be strictly
  4939. // nested inside a teams region
  4940. NestingProhibited =
  4941. (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
  4942. Recommend = ShouldBeInTeamsRegion;
  4943. }
  4944. if (!NestingProhibited &&
  4945. (isOpenMPTargetExecutionDirective(CurrentRegion) ||
  4946. isOpenMPTargetDataManagementDirective(CurrentRegion))) {
  4947. // OpenMP 4.5 [2.17 Nesting of Regions]
  4948. // If a target, target update, target data, target enter data, or
  4949. // target exit data construct is encountered during execution of a
  4950. // target region, the behavior is unspecified.
  4951. NestingProhibited = Stack->hasDirective(
  4952. [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
  4953. SourceLocation) {
  4954. if (isOpenMPTargetExecutionDirective(K)) {
  4955. OffendingRegion = K;
  4956. return true;
  4957. }
  4958. return false;
  4959. },
  4960. false /* don't skip top directive */);
  4961. CloseNesting = false;
  4962. }
  4963. if (NestingProhibited) {
  4964. if (OrphanSeen) {
  4965. SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  4966. << getOpenMPDirectiveName(CurrentRegion) << Recommend;
  4967. } else {
  4968. SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
  4969. << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
  4970. << Recommend << getOpenMPDirectiveName(CurrentRegion);
  4971. }
  4972. return true;
  4973. }
  4974. }
  4975. return false;
  4976. }
  4977. struct Kind2Unsigned {
  4978. using argument_type = OpenMPDirectiveKind;
  4979. unsigned operator()(argument_type DK) { return unsigned(DK); }
  4980. };
  4981. static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
  4982. ArrayRef<OMPClause *> Clauses,
  4983. ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
  4984. bool ErrorFound = false;
  4985. unsigned NamedModifiersNumber = 0;
  4986. llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
  4987. FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1);
  4988. SmallVector<SourceLocation, 4> NameModifierLoc;
  4989. for (const OMPClause *C : Clauses) {
  4990. if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
  4991. // At most one if clause without a directive-name-modifier can appear on
  4992. // the directive.
  4993. OpenMPDirectiveKind CurNM = IC->getNameModifier();
  4994. if (FoundNameModifiers[CurNM]) {
  4995. S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  4996. << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
  4997. << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
  4998. ErrorFound = true;
  4999. } else if (CurNM != OMPD_unknown) {
  5000. NameModifierLoc.push_back(IC->getNameModifierLoc());
  5001. ++NamedModifiersNumber;
  5002. }
  5003. FoundNameModifiers[CurNM] = IC;
  5004. if (CurNM == OMPD_unknown)
  5005. continue;
  5006. // Check if the specified name modifier is allowed for the current
  5007. // directive.
  5008. // At most one if clause with the particular directive-name-modifier can
  5009. // appear on the directive.
  5010. if (!llvm::is_contained(AllowedNameModifiers, CurNM)) {
  5011. S.Diag(IC->getNameModifierLoc(),
  5012. diag::err_omp_wrong_if_directive_name_modifier)
  5013. << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
  5014. ErrorFound = true;
  5015. }
  5016. }
  5017. }
  5018. // If any if clause on the directive includes a directive-name-modifier then
  5019. // all if clauses on the directive must include a directive-name-modifier.
  5020. if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
  5021. if (NamedModifiersNumber == AllowedNameModifiers.size()) {
  5022. S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
  5023. diag::err_omp_no_more_if_clause);
  5024. } else {
  5025. std::string Values;
  5026. std::string Sep(", ");
  5027. unsigned AllowedCnt = 0;
  5028. unsigned TotalAllowedNum =
  5029. AllowedNameModifiers.size() - NamedModifiersNumber;
  5030. for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
  5031. ++Cnt) {
  5032. OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
  5033. if (!FoundNameModifiers[NM]) {
  5034. Values += "'";
  5035. Values += getOpenMPDirectiveName(NM);
  5036. Values += "'";
  5037. if (AllowedCnt + 2 == TotalAllowedNum)
  5038. Values += " or ";
  5039. else if (AllowedCnt + 1 != TotalAllowedNum)
  5040. Values += Sep;
  5041. ++AllowedCnt;
  5042. }
  5043. }
  5044. S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
  5045. diag::err_omp_unnamed_if_clause)
  5046. << (TotalAllowedNum > 1) << Values;
  5047. }
  5048. for (SourceLocation Loc : NameModifierLoc) {
  5049. S.Diag(Loc, diag::note_omp_previous_named_if_clause);
  5050. }
  5051. ErrorFound = true;
  5052. }
  5053. return ErrorFound;
  5054. }
  5055. static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
  5056. SourceLocation &ELoc,
  5057. SourceRange &ERange,
  5058. bool AllowArraySection,
  5059. StringRef DiagType) {
  5060. if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
  5061. RefExpr->containsUnexpandedParameterPack())
  5062. return std::make_pair(nullptr, true);
  5063. // OpenMP [3.1, C/C++]
  5064. // A list item is a variable name.
  5065. // OpenMP [2.9.3.3, Restrictions, p.1]
  5066. // A variable that is part of another variable (as an array or
  5067. // structure element) cannot appear in a private clause.
  5068. RefExpr = RefExpr->IgnoreParens();
  5069. enum {
  5070. NoArrayExpr = -1,
  5071. ArraySubscript = 0,
  5072. OMPArraySection = 1
  5073. } IsArrayExpr = NoArrayExpr;
  5074. if (AllowArraySection) {
  5075. if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
  5076. Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
  5077. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  5078. Base = TempASE->getBase()->IgnoreParenImpCasts();
  5079. RefExpr = Base;
  5080. IsArrayExpr = ArraySubscript;
  5081. } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
  5082. Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  5083. while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
  5084. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  5085. while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
  5086. Base = TempASE->getBase()->IgnoreParenImpCasts();
  5087. RefExpr = Base;
  5088. IsArrayExpr = OMPArraySection;
  5089. }
  5090. }
  5091. ELoc = RefExpr->getExprLoc();
  5092. ERange = RefExpr->getSourceRange();
  5093. RefExpr = RefExpr->IgnoreParenImpCasts();
  5094. auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
  5095. auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
  5096. if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
  5097. (S.getCurrentThisType().isNull() || !ME ||
  5098. !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
  5099. !isa<FieldDecl>(ME->getMemberDecl()))) {
  5100. if (IsArrayExpr != NoArrayExpr) {
  5101. S.Diag(ELoc, diag::err_omp_expected_base_var_name)
  5102. << IsArrayExpr << ERange;
  5103. } else if (!DiagType.empty()) {
  5104. unsigned DiagSelect = S.getLangOpts().CPlusPlus
  5105. ? (S.getCurrentThisType().isNull() ? 1 : 2)
  5106. : 0;
  5107. S.Diag(ELoc, diag::err_omp_expected_var_name_member_expr_with_type)
  5108. << DiagSelect << DiagType << ERange;
  5109. } else {
  5110. S.Diag(ELoc,
  5111. AllowArraySection
  5112. ? diag::err_omp_expected_var_name_member_expr_or_array_item
  5113. : diag::err_omp_expected_var_name_member_expr)
  5114. << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
  5115. }
  5116. return std::make_pair(nullptr, false);
  5117. }
  5118. return std::make_pair(
  5119. getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
  5120. }
  5121. namespace {
  5122. /// Checks if the allocator is used in uses_allocators clause to be allowed in
  5123. /// target regions.
  5124. class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> {
  5125. DSAStackTy *S = nullptr;
  5126. public:
  5127. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  5128. return S->isUsesAllocatorsDecl(E->getDecl())
  5129. .value_or(DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) ==
  5130. DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait;
  5131. }
  5132. bool VisitStmt(const Stmt *S) {
  5133. for (const Stmt *Child : S->children()) {
  5134. if (Child && Visit(Child))
  5135. return true;
  5136. }
  5137. return false;
  5138. }
  5139. explicit AllocatorChecker(DSAStackTy *S) : S(S) {}
  5140. };
  5141. } // namespace
  5142. static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
  5143. ArrayRef<OMPClause *> Clauses) {
  5144. assert(!S.CurContext->isDependentContext() &&
  5145. "Expected non-dependent context.");
  5146. auto AllocateRange =
  5147. llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
  5148. llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> DeclToCopy;
  5149. auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
  5150. return isOpenMPPrivate(C->getClauseKind());
  5151. });
  5152. for (OMPClause *Cl : PrivateRange) {
  5153. MutableArrayRef<Expr *>::iterator I, It, Et;
  5154. if (Cl->getClauseKind() == OMPC_private) {
  5155. auto *PC = cast<OMPPrivateClause>(Cl);
  5156. I = PC->private_copies().begin();
  5157. It = PC->varlist_begin();
  5158. Et = PC->varlist_end();
  5159. } else if (Cl->getClauseKind() == OMPC_firstprivate) {
  5160. auto *PC = cast<OMPFirstprivateClause>(Cl);
  5161. I = PC->private_copies().begin();
  5162. It = PC->varlist_begin();
  5163. Et = PC->varlist_end();
  5164. } else if (Cl->getClauseKind() == OMPC_lastprivate) {
  5165. auto *PC = cast<OMPLastprivateClause>(Cl);
  5166. I = PC->private_copies().begin();
  5167. It = PC->varlist_begin();
  5168. Et = PC->varlist_end();
  5169. } else if (Cl->getClauseKind() == OMPC_linear) {
  5170. auto *PC = cast<OMPLinearClause>(Cl);
  5171. I = PC->privates().begin();
  5172. It = PC->varlist_begin();
  5173. Et = PC->varlist_end();
  5174. } else if (Cl->getClauseKind() == OMPC_reduction) {
  5175. auto *PC = cast<OMPReductionClause>(Cl);
  5176. I = PC->privates().begin();
  5177. It = PC->varlist_begin();
  5178. Et = PC->varlist_end();
  5179. } else if (Cl->getClauseKind() == OMPC_task_reduction) {
  5180. auto *PC = cast<OMPTaskReductionClause>(Cl);
  5181. I = PC->privates().begin();
  5182. It = PC->varlist_begin();
  5183. Et = PC->varlist_end();
  5184. } else if (Cl->getClauseKind() == OMPC_in_reduction) {
  5185. auto *PC = cast<OMPInReductionClause>(Cl);
  5186. I = PC->privates().begin();
  5187. It = PC->varlist_begin();
  5188. Et = PC->varlist_end();
  5189. } else {
  5190. llvm_unreachable("Expected private clause.");
  5191. }
  5192. for (Expr *E : llvm::make_range(It, Et)) {
  5193. if (!*I) {
  5194. ++I;
  5195. continue;
  5196. }
  5197. SourceLocation ELoc;
  5198. SourceRange ERange;
  5199. Expr *SimpleRefExpr = E;
  5200. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  5201. /*AllowArraySection=*/true);
  5202. DeclToCopy.try_emplace(Res.first,
  5203. cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
  5204. ++I;
  5205. }
  5206. }
  5207. for (OMPClause *C : AllocateRange) {
  5208. auto *AC = cast<OMPAllocateClause>(C);
  5209. if (S.getLangOpts().OpenMP >= 50 &&
  5210. !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() &&
  5211. isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
  5212. AC->getAllocator()) {
  5213. Expr *Allocator = AC->getAllocator();
  5214. // OpenMP, 2.12.5 target Construct
  5215. // Memory allocators that do not appear in a uses_allocators clause cannot
  5216. // appear as an allocator in an allocate clause or be used in the target
  5217. // region unless a requires directive with the dynamic_allocators clause
  5218. // is present in the same compilation unit.
  5219. AllocatorChecker Checker(Stack);
  5220. if (Checker.Visit(Allocator))
  5221. S.Diag(Allocator->getExprLoc(),
  5222. diag::err_omp_allocator_not_in_uses_allocators)
  5223. << Allocator->getSourceRange();
  5224. }
  5225. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
  5226. getAllocatorKind(S, Stack, AC->getAllocator());
  5227. // OpenMP, 2.11.4 allocate Clause, Restrictions.
  5228. // For task, taskloop or target directives, allocation requests to memory
  5229. // allocators with the trait access set to thread result in unspecified
  5230. // behavior.
  5231. if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
  5232. (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  5233. isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
  5234. S.Diag(AC->getAllocator()->getExprLoc(),
  5235. diag::warn_omp_allocate_thread_on_task_target_directive)
  5236. << getOpenMPDirectiveName(Stack->getCurrentDirective());
  5237. }
  5238. for (Expr *E : AC->varlists()) {
  5239. SourceLocation ELoc;
  5240. SourceRange ERange;
  5241. Expr *SimpleRefExpr = E;
  5242. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
  5243. ValueDecl *VD = Res.first;
  5244. DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
  5245. if (!isOpenMPPrivate(Data.CKind)) {
  5246. S.Diag(E->getExprLoc(),
  5247. diag::err_omp_expected_private_copy_for_allocate);
  5248. continue;
  5249. }
  5250. VarDecl *PrivateVD = DeclToCopy[VD];
  5251. if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
  5252. AllocatorKind, AC->getAllocator()))
  5253. continue;
  5254. // Placeholder until allocate clause supports align modifier.
  5255. Expr *Alignment = nullptr;
  5256. applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
  5257. Alignment, E->getSourceRange());
  5258. }
  5259. }
  5260. }
  5261. namespace {
  5262. /// Rewrite statements and expressions for Sema \p Actions CurContext.
  5263. ///
  5264. /// Used to wrap already parsed statements/expressions into a new CapturedStmt
  5265. /// context. DeclRefExpr used inside the new context are changed to refer to the
  5266. /// captured variable instead.
  5267. class CaptureVars : public TreeTransform<CaptureVars> {
  5268. using BaseTransform = TreeTransform<CaptureVars>;
  5269. public:
  5270. CaptureVars(Sema &Actions) : BaseTransform(Actions) {}
  5271. bool AlwaysRebuild() { return true; }
  5272. };
  5273. } // namespace
  5274. static VarDecl *precomputeExpr(Sema &Actions,
  5275. SmallVectorImpl<Stmt *> &BodyStmts, Expr *E,
  5276. StringRef Name) {
  5277. Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E));
  5278. VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr,
  5279. dyn_cast<DeclRefExpr>(E->IgnoreImplicit()));
  5280. auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess(
  5281. Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {})));
  5282. Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false);
  5283. BodyStmts.push_back(NewDeclStmt);
  5284. return NewVar;
  5285. }
  5286. /// Create a closure that computes the number of iterations of a loop.
  5287. ///
  5288. /// \param Actions The Sema object.
  5289. /// \param LogicalTy Type for the logical iteration number.
  5290. /// \param Rel Comparison operator of the loop condition.
  5291. /// \param StartExpr Value of the loop counter at the first iteration.
  5292. /// \param StopExpr Expression the loop counter is compared against in the loop
  5293. /// condition. \param StepExpr Amount of increment after each iteration.
  5294. ///
  5295. /// \return Closure (CapturedStmt) of the distance calculation.
  5296. static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy,
  5297. BinaryOperator::Opcode Rel,
  5298. Expr *StartExpr, Expr *StopExpr,
  5299. Expr *StepExpr) {
  5300. ASTContext &Ctx = Actions.getASTContext();
  5301. TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy);
  5302. // Captured regions currently don't support return values, we use an
  5303. // out-parameter instead. All inputs are implicit captures.
  5304. // TODO: Instead of capturing each DeclRefExpr occurring in
  5305. // StartExpr/StopExpr/Step, these could also be passed as a value capture.
  5306. QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy);
  5307. Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy},
  5308. {StringRef(), QualType()}};
  5309. Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
  5310. Stmt *Body;
  5311. {
  5312. Sema::CompoundScopeRAII CompoundScope(Actions);
  5313. CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext);
  5314. // Get the LValue expression for the result.
  5315. ImplicitParamDecl *DistParam = CS->getParam(0);
  5316. DeclRefExpr *DistRef = Actions.BuildDeclRefExpr(
  5317. DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
  5318. SmallVector<Stmt *, 4> BodyStmts;
  5319. // Capture all referenced variable references.
  5320. // TODO: Instead of computing NewStart/NewStop/NewStep inside the
  5321. // CapturedStmt, we could compute them before and capture the result, to be
  5322. // used jointly with the LoopVar function.
  5323. VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start");
  5324. VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop");
  5325. VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step");
  5326. auto BuildVarRef = [&](VarDecl *VD) {
  5327. return buildDeclRefExpr(Actions, VD, VD->getType(), {});
  5328. };
  5329. IntegerLiteral *Zero = IntegerLiteral::Create(
  5330. Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {});
  5331. IntegerLiteral *One = IntegerLiteral::Create(
  5332. Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
  5333. Expr *Dist;
  5334. if (Rel == BO_NE) {
  5335. // When using a != comparison, the increment can be +1 or -1. This can be
  5336. // dynamic at runtime, so we need to check for the direction.
  5337. Expr *IsNegStep = AssertSuccess(
  5338. Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero));
  5339. // Positive increment.
  5340. Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp(
  5341. nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
  5342. ForwardRange = AssertSuccess(
  5343. Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange));
  5344. Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp(
  5345. nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep)));
  5346. // Negative increment.
  5347. Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp(
  5348. nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
  5349. BackwardRange = AssertSuccess(
  5350. Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange));
  5351. Expr *NegIncAmount = AssertSuccess(
  5352. Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep)));
  5353. Expr *BackwardDist = AssertSuccess(
  5354. Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount));
  5355. // Use the appropriate case.
  5356. Dist = AssertSuccess(Actions.ActOnConditionalOp(
  5357. {}, {}, IsNegStep, BackwardDist, ForwardDist));
  5358. } else {
  5359. assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) &&
  5360. "Expected one of these relational operators");
  5361. // We can derive the direction from any other comparison operator. It is
  5362. // non well-formed OpenMP if Step increments/decrements in the other
  5363. // directions. Whether at least the first iteration passes the loop
  5364. // condition.
  5365. Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp(
  5366. nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop)));
  5367. // Compute the range between first and last counter value.
  5368. Expr *Range;
  5369. if (Rel == BO_GE || Rel == BO_GT)
  5370. Range = AssertSuccess(Actions.BuildBinOp(
  5371. nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop)));
  5372. else
  5373. Range = AssertSuccess(Actions.BuildBinOp(
  5374. nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart)));
  5375. // Ensure unsigned range space.
  5376. Range =
  5377. AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range));
  5378. if (Rel == BO_LE || Rel == BO_GE) {
  5379. // Add one to the range if the relational operator is inclusive.
  5380. Range =
  5381. AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, Range, One));
  5382. }
  5383. // Divide by the absolute step amount. If the range is not a multiple of
  5384. // the step size, rounding-up the effective upper bound ensures that the
  5385. // last iteration is included.
  5386. // Note that the rounding-up may cause an overflow in a temporry that
  5387. // could be avoided, but would have occurred in a C-style for-loop as well.
  5388. Expr *Divisor = BuildVarRef(NewStep);
  5389. if (Rel == BO_GE || Rel == BO_GT)
  5390. Divisor =
  5391. AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor));
  5392. Expr *DivisorMinusOne =
  5393. AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Sub, Divisor, One));
  5394. Expr *RangeRoundUp = AssertSuccess(
  5395. Actions.BuildBinOp(nullptr, {}, BO_Add, Range, DivisorMinusOne));
  5396. Dist = AssertSuccess(
  5397. Actions.BuildBinOp(nullptr, {}, BO_Div, RangeRoundUp, Divisor));
  5398. // If there is not at least one iteration, the range contains garbage. Fix
  5399. // to zero in this case.
  5400. Dist = AssertSuccess(
  5401. Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero));
  5402. }
  5403. // Assign the result to the out-parameter.
  5404. Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp(
  5405. Actions.getCurScope(), {}, BO_Assign, DistRef, Dist));
  5406. BodyStmts.push_back(ResultAssign);
  5407. Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false));
  5408. }
  5409. return cast<CapturedStmt>(
  5410. AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
  5411. }
  5412. /// Create a closure that computes the loop variable from the logical iteration
  5413. /// number.
  5414. ///
  5415. /// \param Actions The Sema object.
  5416. /// \param LoopVarTy Type for the loop variable used for result value.
  5417. /// \param LogicalTy Type for the logical iteration number.
  5418. /// \param StartExpr Value of the loop counter at the first iteration.
  5419. /// \param Step Amount of increment after each iteration.
  5420. /// \param Deref Whether the loop variable is a dereference of the loop
  5421. /// counter variable.
  5422. ///
  5423. /// \return Closure (CapturedStmt) of the loop value calculation.
  5424. static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy,
  5425. QualType LogicalTy,
  5426. DeclRefExpr *StartExpr, Expr *Step,
  5427. bool Deref) {
  5428. ASTContext &Ctx = Actions.getASTContext();
  5429. // Pass the result as an out-parameter. Passing as return value would require
  5430. // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to
  5431. // invoke a copy constructor.
  5432. QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy);
  5433. Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy},
  5434. {"Logical", LogicalTy},
  5435. {StringRef(), QualType()}};
  5436. Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params);
  5437. // Capture the initial iterator which represents the LoopVar value at the
  5438. // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update
  5439. // it in every iteration, capture it by value before it is modified.
  5440. VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl());
  5441. bool Invalid = Actions.tryCaptureVariable(StartVar, {},
  5442. Sema::TryCapture_ExplicitByVal, {});
  5443. (void)Invalid;
  5444. assert(!Invalid && "Expecting capture-by-value to work.");
  5445. Expr *Body;
  5446. {
  5447. Sema::CompoundScopeRAII CompoundScope(Actions);
  5448. auto *CS = cast<CapturedDecl>(Actions.CurContext);
  5449. ImplicitParamDecl *TargetParam = CS->getParam(0);
  5450. DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr(
  5451. TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
  5452. ImplicitParamDecl *IndvarParam = CS->getParam(1);
  5453. DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr(
  5454. IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr);
  5455. // Capture the Start expression.
  5456. CaptureVars Recap(Actions);
  5457. Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr));
  5458. Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step));
  5459. Expr *Skip = AssertSuccess(
  5460. Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef));
  5461. // TODO: Explicitly cast to the iterator's difference_type instead of
  5462. // relying on implicit conversion.
  5463. Expr *Advanced =
  5464. AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip));
  5465. if (Deref) {
  5466. // For range-based for-loops convert the loop counter value to a concrete
  5467. // loop variable value by dereferencing the iterator.
  5468. Advanced =
  5469. AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced));
  5470. }
  5471. // Assign the result to the output parameter.
  5472. Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {},
  5473. BO_Assign, TargetRef, Advanced));
  5474. }
  5475. return cast<CapturedStmt>(
  5476. AssertSuccess(Actions.ActOnCapturedRegionEnd(Body)));
  5477. }
  5478. StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) {
  5479. ASTContext &Ctx = getASTContext();
  5480. // Extract the common elements of ForStmt and CXXForRangeStmt:
  5481. // Loop variable, repeat condition, increment
  5482. Expr *Cond, *Inc;
  5483. VarDecl *LIVDecl, *LUVDecl;
  5484. if (auto *For = dyn_cast<ForStmt>(AStmt)) {
  5485. Stmt *Init = For->getInit();
  5486. if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) {
  5487. // For statement declares loop variable.
  5488. LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl());
  5489. } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) {
  5490. // For statement reuses variable.
  5491. assert(LCAssign->getOpcode() == BO_Assign &&
  5492. "init part must be a loop variable assignment");
  5493. auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS());
  5494. LIVDecl = cast<VarDecl>(CounterRef->getDecl());
  5495. } else
  5496. llvm_unreachable("Cannot determine loop variable");
  5497. LUVDecl = LIVDecl;
  5498. Cond = For->getCond();
  5499. Inc = For->getInc();
  5500. } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) {
  5501. DeclStmt *BeginStmt = RangeFor->getBeginStmt();
  5502. LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl());
  5503. LUVDecl = RangeFor->getLoopVariable();
  5504. Cond = RangeFor->getCond();
  5505. Inc = RangeFor->getInc();
  5506. } else
  5507. llvm_unreachable("unhandled kind of loop");
  5508. QualType CounterTy = LIVDecl->getType();
  5509. QualType LVTy = LUVDecl->getType();
  5510. // Analyze the loop condition.
  5511. Expr *LHS, *RHS;
  5512. BinaryOperator::Opcode CondRel;
  5513. Cond = Cond->IgnoreImplicit();
  5514. if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) {
  5515. LHS = CondBinExpr->getLHS();
  5516. RHS = CondBinExpr->getRHS();
  5517. CondRel = CondBinExpr->getOpcode();
  5518. } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) {
  5519. assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands");
  5520. LHS = CondCXXOp->getArg(0);
  5521. RHS = CondCXXOp->getArg(1);
  5522. switch (CondCXXOp->getOperator()) {
  5523. case OO_ExclaimEqual:
  5524. CondRel = BO_NE;
  5525. break;
  5526. case OO_Less:
  5527. CondRel = BO_LT;
  5528. break;
  5529. case OO_LessEqual:
  5530. CondRel = BO_LE;
  5531. break;
  5532. case OO_Greater:
  5533. CondRel = BO_GT;
  5534. break;
  5535. case OO_GreaterEqual:
  5536. CondRel = BO_GE;
  5537. break;
  5538. default:
  5539. llvm_unreachable("unexpected iterator operator");
  5540. }
  5541. } else
  5542. llvm_unreachable("unexpected loop condition");
  5543. // Normalize such that the loop counter is on the LHS.
  5544. if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) ||
  5545. cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) {
  5546. std::swap(LHS, RHS);
  5547. CondRel = BinaryOperator::reverseComparisonOp(CondRel);
  5548. }
  5549. auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit());
  5550. // Decide the bit width for the logical iteration counter. By default use the
  5551. // unsigned ptrdiff_t integer size (for iterators and pointers).
  5552. // TODO: For iterators, use iterator::difference_type,
  5553. // std::iterator_traits<>::difference_type or decltype(it - end).
  5554. QualType LogicalTy = Ctx.getUnsignedPointerDiffType();
  5555. if (CounterTy->isIntegerType()) {
  5556. unsigned BitWidth = Ctx.getIntWidth(CounterTy);
  5557. LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false);
  5558. }
  5559. // Analyze the loop increment.
  5560. Expr *Step;
  5561. if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) {
  5562. int Direction;
  5563. switch (IncUn->getOpcode()) {
  5564. case UO_PreInc:
  5565. case UO_PostInc:
  5566. Direction = 1;
  5567. break;
  5568. case UO_PreDec:
  5569. case UO_PostDec:
  5570. Direction = -1;
  5571. break;
  5572. default:
  5573. llvm_unreachable("unhandled unary increment operator");
  5574. }
  5575. Step = IntegerLiteral::Create(
  5576. Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {});
  5577. } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) {
  5578. if (IncBin->getOpcode() == BO_AddAssign) {
  5579. Step = IncBin->getRHS();
  5580. } else if (IncBin->getOpcode() == BO_SubAssign) {
  5581. Step =
  5582. AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS()));
  5583. } else
  5584. llvm_unreachable("unhandled binary increment operator");
  5585. } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) {
  5586. switch (CondCXXOp->getOperator()) {
  5587. case OO_PlusPlus:
  5588. Step = IntegerLiteral::Create(
  5589. Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {});
  5590. break;
  5591. case OO_MinusMinus:
  5592. Step = IntegerLiteral::Create(
  5593. Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {});
  5594. break;
  5595. case OO_PlusEqual:
  5596. Step = CondCXXOp->getArg(1);
  5597. break;
  5598. case OO_MinusEqual:
  5599. Step = AssertSuccess(
  5600. BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1)));
  5601. break;
  5602. default:
  5603. llvm_unreachable("unhandled overloaded increment operator");
  5604. }
  5605. } else
  5606. llvm_unreachable("unknown increment expression");
  5607. CapturedStmt *DistanceFunc =
  5608. buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step);
  5609. CapturedStmt *LoopVarFunc = buildLoopVarFunc(
  5610. *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt));
  5611. DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue,
  5612. {}, nullptr, nullptr, {}, nullptr);
  5613. return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc,
  5614. LoopVarFunc, LVRef);
  5615. }
  5616. StmtResult Sema::ActOnOpenMPLoopnest(Stmt *AStmt) {
  5617. // Handle a literal loop.
  5618. if (isa<ForStmt>(AStmt) || isa<CXXForRangeStmt>(AStmt))
  5619. return ActOnOpenMPCanonicalLoop(AStmt);
  5620. // If not a literal loop, it must be the result of a loop transformation.
  5621. OMPExecutableDirective *LoopTransform = cast<OMPExecutableDirective>(AStmt);
  5622. assert(
  5623. isOpenMPLoopTransformationDirective(LoopTransform->getDirectiveKind()) &&
  5624. "Loop transformation directive expected");
  5625. return LoopTransform;
  5626. }
  5627. static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
  5628. CXXScopeSpec &MapperIdScopeSpec,
  5629. const DeclarationNameInfo &MapperId,
  5630. QualType Type,
  5631. Expr *UnresolvedMapper);
  5632. /// Perform DFS through the structure/class data members trying to find
  5633. /// member(s) with user-defined 'default' mapper and generate implicit map
  5634. /// clauses for such members with the found 'default' mapper.
  5635. static void
  5636. processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack,
  5637. SmallVectorImpl<OMPClause *> &Clauses) {
  5638. // Check for the deault mapper for data members.
  5639. if (S.getLangOpts().OpenMP < 50)
  5640. return;
  5641. SmallVector<OMPClause *, 4> ImplicitMaps;
  5642. for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) {
  5643. auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]);
  5644. if (!C)
  5645. continue;
  5646. SmallVector<Expr *, 4> SubExprs;
  5647. auto *MI = C->mapperlist_begin();
  5648. for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End;
  5649. ++I, ++MI) {
  5650. // Expression is mapped using mapper - skip it.
  5651. if (*MI)
  5652. continue;
  5653. Expr *E = *I;
  5654. // Expression is dependent - skip it, build the mapper when it gets
  5655. // instantiated.
  5656. if (E->isTypeDependent() || E->isValueDependent() ||
  5657. E->containsUnexpandedParameterPack())
  5658. continue;
  5659. // Array section - need to check for the mapping of the array section
  5660. // element.
  5661. QualType CanonType = E->getType().getCanonicalType();
  5662. if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) {
  5663. const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts());
  5664. QualType BaseType =
  5665. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  5666. QualType ElemType;
  5667. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  5668. ElemType = ATy->getElementType();
  5669. else
  5670. ElemType = BaseType->getPointeeType();
  5671. CanonType = ElemType;
  5672. }
  5673. // DFS over data members in structures/classes.
  5674. SmallVector<std::pair<QualType, FieldDecl *>, 4> Types(
  5675. 1, {CanonType, nullptr});
  5676. llvm::DenseMap<const Type *, Expr *> Visited;
  5677. SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain(
  5678. 1, {nullptr, 1});
  5679. while (!Types.empty()) {
  5680. QualType BaseType;
  5681. FieldDecl *CurFD;
  5682. std::tie(BaseType, CurFD) = Types.pop_back_val();
  5683. while (ParentChain.back().second == 0)
  5684. ParentChain.pop_back();
  5685. --ParentChain.back().second;
  5686. if (BaseType.isNull())
  5687. continue;
  5688. // Only structs/classes are allowed to have mappers.
  5689. const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl();
  5690. if (!RD)
  5691. continue;
  5692. auto It = Visited.find(BaseType.getTypePtr());
  5693. if (It == Visited.end()) {
  5694. // Try to find the associated user-defined mapper.
  5695. CXXScopeSpec MapperIdScopeSpec;
  5696. DeclarationNameInfo DefaultMapperId;
  5697. DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier(
  5698. &S.Context.Idents.get("default")));
  5699. DefaultMapperId.setLoc(E->getExprLoc());
  5700. ExprResult ER = buildUserDefinedMapperRef(
  5701. S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId,
  5702. BaseType, /*UnresolvedMapper=*/nullptr);
  5703. if (ER.isInvalid())
  5704. continue;
  5705. It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first;
  5706. }
  5707. // Found default mapper.
  5708. if (It->second) {
  5709. auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType,
  5710. VK_LValue, OK_Ordinary, E);
  5711. OE->setIsUnique(/*V=*/true);
  5712. Expr *BaseExpr = OE;
  5713. for (const auto &P : ParentChain) {
  5714. if (P.first) {
  5715. BaseExpr = S.BuildMemberExpr(
  5716. BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
  5717. NestedNameSpecifierLoc(), SourceLocation(), P.first,
  5718. DeclAccessPair::make(P.first, P.first->getAccess()),
  5719. /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
  5720. P.first->getType(), VK_LValue, OK_Ordinary);
  5721. BaseExpr = S.DefaultLvalueConversion(BaseExpr).get();
  5722. }
  5723. }
  5724. if (CurFD)
  5725. BaseExpr = S.BuildMemberExpr(
  5726. BaseExpr, /*IsArrow=*/false, E->getExprLoc(),
  5727. NestedNameSpecifierLoc(), SourceLocation(), CurFD,
  5728. DeclAccessPair::make(CurFD, CurFD->getAccess()),
  5729. /*HadMultipleCandidates=*/false, DeclarationNameInfo(),
  5730. CurFD->getType(), VK_LValue, OK_Ordinary);
  5731. SubExprs.push_back(BaseExpr);
  5732. continue;
  5733. }
  5734. // Check for the "default" mapper for data members.
  5735. bool FirstIter = true;
  5736. for (FieldDecl *FD : RD->fields()) {
  5737. if (!FD)
  5738. continue;
  5739. QualType FieldTy = FD->getType();
  5740. if (FieldTy.isNull() ||
  5741. !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType()))
  5742. continue;
  5743. if (FirstIter) {
  5744. FirstIter = false;
  5745. ParentChain.emplace_back(CurFD, 1);
  5746. } else {
  5747. ++ParentChain.back().second;
  5748. }
  5749. Types.emplace_back(FieldTy, FD);
  5750. }
  5751. }
  5752. }
  5753. if (SubExprs.empty())
  5754. continue;
  5755. CXXScopeSpec MapperIdScopeSpec;
  5756. DeclarationNameInfo MapperId;
  5757. if (OMPClause *NewClause = S.ActOnOpenMPMapClause(
  5758. nullptr, C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
  5759. MapperIdScopeSpec, MapperId, C->getMapType(),
  5760. /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
  5761. SubExprs, OMPVarListLocTy()))
  5762. Clauses.push_back(NewClause);
  5763. }
  5764. }
  5765. StmtResult Sema::ActOnOpenMPExecutableDirective(
  5766. OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
  5767. OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
  5768. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  5769. StmtResult Res = StmtError();
  5770. OpenMPBindClauseKind BindKind = OMPC_BIND_unknown;
  5771. if (const OMPBindClause *BC =
  5772. OMPExecutableDirective::getSingleClause<OMPBindClause>(Clauses))
  5773. BindKind = BC->getBindKind();
  5774. // First check CancelRegion which is then used in checkNestingOfRegions.
  5775. if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
  5776. checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
  5777. BindKind, StartLoc))
  5778. return StmtError();
  5779. llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
  5780. VarsWithInheritedDSAType VarsWithInheritedDSA;
  5781. bool ErrorFound = false;
  5782. ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
  5783. if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic &&
  5784. Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master &&
  5785. Kind != OMPD_masked && !isOpenMPLoopTransformationDirective(Kind)) {
  5786. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  5787. // Check default data sharing attributes for referenced variables.
  5788. DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
  5789. int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
  5790. Stmt *S = AStmt;
  5791. while (--ThisCaptureLevel >= 0)
  5792. S = cast<CapturedStmt>(S)->getCapturedStmt();
  5793. DSAChecker.Visit(S);
  5794. if (!isOpenMPTargetDataManagementDirective(Kind) &&
  5795. !isOpenMPTaskingDirective(Kind)) {
  5796. // Visit subcaptures to generate implicit clauses for captured vars.
  5797. auto *CS = cast<CapturedStmt>(AStmt);
  5798. SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
  5799. getOpenMPCaptureRegions(CaptureRegions, Kind);
  5800. // Ignore outer tasking regions for target directives.
  5801. if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
  5802. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  5803. DSAChecker.visitSubCaptures(CS);
  5804. }
  5805. if (DSAChecker.isErrorFound())
  5806. return StmtError();
  5807. // Generate list of implicitly defined firstprivate variables.
  5808. VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
  5809. SmallVector<Expr *, 4> ImplicitFirstprivates(
  5810. DSAChecker.getImplicitFirstprivate().begin(),
  5811. DSAChecker.getImplicitFirstprivate().end());
  5812. SmallVector<Expr *, 4> ImplicitPrivates(
  5813. DSAChecker.getImplicitPrivate().begin(),
  5814. DSAChecker.getImplicitPrivate().end());
  5815. const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1;
  5816. SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete];
  5817. SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
  5818. ImplicitMapModifiers[DefaultmapKindNum];
  5819. SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
  5820. ImplicitMapModifiersLoc[DefaultmapKindNum];
  5821. // Get the original location of present modifier from Defaultmap clause.
  5822. SourceLocation PresentModifierLocs[DefaultmapKindNum];
  5823. for (OMPClause *C : Clauses) {
  5824. if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C))
  5825. if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present)
  5826. PresentModifierLocs[DMC->getDefaultmapKind()] =
  5827. DMC->getDefaultmapModifierLoc();
  5828. }
  5829. for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) {
  5830. auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC);
  5831. for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
  5832. ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap(
  5833. Kind, static_cast<OpenMPMapClauseKind>(I));
  5834. ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end());
  5835. }
  5836. ArrayRef<OpenMPMapModifierKind> ImplicitModifier =
  5837. DSAChecker.getImplicitMapModifier(Kind);
  5838. ImplicitMapModifiers[VC].append(ImplicitModifier.begin(),
  5839. ImplicitModifier.end());
  5840. std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]),
  5841. ImplicitModifier.size(), PresentModifierLocs[VC]);
  5842. }
  5843. // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
  5844. for (OMPClause *C : Clauses) {
  5845. if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
  5846. for (Expr *E : IRC->taskgroup_descriptors())
  5847. if (E)
  5848. ImplicitFirstprivates.emplace_back(E);
  5849. }
  5850. // OpenMP 5.0, 2.10.1 task Construct
  5851. // [detach clause]... The event-handle will be considered as if it was
  5852. // specified on a firstprivate clause.
  5853. if (auto *DC = dyn_cast<OMPDetachClause>(C))
  5854. ImplicitFirstprivates.push_back(DC->getEventHandler());
  5855. }
  5856. if (!ImplicitFirstprivates.empty()) {
  5857. if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
  5858. ImplicitFirstprivates, SourceLocation(), SourceLocation(),
  5859. SourceLocation())) {
  5860. ClausesWithImplicit.push_back(Implicit);
  5861. ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
  5862. ImplicitFirstprivates.size();
  5863. } else {
  5864. ErrorFound = true;
  5865. }
  5866. }
  5867. if (!ImplicitPrivates.empty()) {
  5868. if (OMPClause *Implicit =
  5869. ActOnOpenMPPrivateClause(ImplicitPrivates, SourceLocation(),
  5870. SourceLocation(), SourceLocation())) {
  5871. ClausesWithImplicit.push_back(Implicit);
  5872. ErrorFound = cast<OMPPrivateClause>(Implicit)->varlist_size() !=
  5873. ImplicitPrivates.size();
  5874. } else {
  5875. ErrorFound = true;
  5876. }
  5877. }
  5878. // OpenMP 5.0 [2.19.7]
  5879. // If a list item appears in a reduction, lastprivate or linear
  5880. // clause on a combined target construct then it is treated as
  5881. // if it also appears in a map clause with a map-type of tofrom
  5882. if (getLangOpts().OpenMP >= 50 && Kind != OMPD_target &&
  5883. isOpenMPTargetExecutionDirective(Kind)) {
  5884. SmallVector<Expr *, 4> ImplicitExprs;
  5885. for (OMPClause *C : Clauses) {
  5886. if (auto *RC = dyn_cast<OMPReductionClause>(C))
  5887. for (Expr *E : RC->varlists())
  5888. if (!isa<DeclRefExpr>(E->IgnoreParenImpCasts()))
  5889. ImplicitExprs.emplace_back(E);
  5890. }
  5891. if (!ImplicitExprs.empty()) {
  5892. ArrayRef<Expr *> Exprs = ImplicitExprs;
  5893. CXXScopeSpec MapperIdScopeSpec;
  5894. DeclarationNameInfo MapperId;
  5895. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  5896. nullptr, OMPC_MAP_MODIFIER_unknown, SourceLocation(),
  5897. MapperIdScopeSpec, MapperId, OMPC_MAP_tofrom,
  5898. /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
  5899. Exprs, OMPVarListLocTy(), /*NoDiagnose=*/true))
  5900. ClausesWithImplicit.emplace_back(Implicit);
  5901. }
  5902. }
  5903. for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) {
  5904. int ClauseKindCnt = -1;
  5905. for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) {
  5906. ++ClauseKindCnt;
  5907. if (ImplicitMap.empty())
  5908. continue;
  5909. CXXScopeSpec MapperIdScopeSpec;
  5910. DeclarationNameInfo MapperId;
  5911. auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
  5912. if (OMPClause *Implicit = ActOnOpenMPMapClause(
  5913. nullptr, ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I],
  5914. MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true,
  5915. SourceLocation(), SourceLocation(), ImplicitMap,
  5916. OMPVarListLocTy())) {
  5917. ClausesWithImplicit.emplace_back(Implicit);
  5918. ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() !=
  5919. ImplicitMap.size();
  5920. } else {
  5921. ErrorFound = true;
  5922. }
  5923. }
  5924. }
  5925. // Build expressions for implicit maps of data members with 'default'
  5926. // mappers.
  5927. if (LangOpts.OpenMP >= 50)
  5928. processImplicitMapsWithDefaultMappers(*this, DSAStack,
  5929. ClausesWithImplicit);
  5930. }
  5931. llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
  5932. switch (Kind) {
  5933. case OMPD_parallel:
  5934. Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
  5935. EndLoc);
  5936. AllowedNameModifiers.push_back(OMPD_parallel);
  5937. break;
  5938. case OMPD_simd:
  5939. Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  5940. VarsWithInheritedDSA);
  5941. if (LangOpts.OpenMP >= 50)
  5942. AllowedNameModifiers.push_back(OMPD_simd);
  5943. break;
  5944. case OMPD_tile:
  5945. Res =
  5946. ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  5947. break;
  5948. case OMPD_unroll:
  5949. Res = ActOnOpenMPUnrollDirective(ClausesWithImplicit, AStmt, StartLoc,
  5950. EndLoc);
  5951. break;
  5952. case OMPD_for:
  5953. Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
  5954. VarsWithInheritedDSA);
  5955. break;
  5956. case OMPD_for_simd:
  5957. Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  5958. EndLoc, VarsWithInheritedDSA);
  5959. if (LangOpts.OpenMP >= 50)
  5960. AllowedNameModifiers.push_back(OMPD_simd);
  5961. break;
  5962. case OMPD_sections:
  5963. Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
  5964. EndLoc);
  5965. break;
  5966. case OMPD_section:
  5967. assert(ClausesWithImplicit.empty() &&
  5968. "No clauses are allowed for 'omp section' directive");
  5969. Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
  5970. break;
  5971. case OMPD_single:
  5972. Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
  5973. EndLoc);
  5974. break;
  5975. case OMPD_master:
  5976. assert(ClausesWithImplicit.empty() &&
  5977. "No clauses are allowed for 'omp master' directive");
  5978. Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
  5979. break;
  5980. case OMPD_masked:
  5981. Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc,
  5982. EndLoc);
  5983. break;
  5984. case OMPD_critical:
  5985. Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
  5986. StartLoc, EndLoc);
  5987. break;
  5988. case OMPD_parallel_for:
  5989. Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
  5990. EndLoc, VarsWithInheritedDSA);
  5991. AllowedNameModifiers.push_back(OMPD_parallel);
  5992. break;
  5993. case OMPD_parallel_for_simd:
  5994. Res = ActOnOpenMPParallelForSimdDirective(
  5995. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  5996. AllowedNameModifiers.push_back(OMPD_parallel);
  5997. if (LangOpts.OpenMP >= 50)
  5998. AllowedNameModifiers.push_back(OMPD_simd);
  5999. break;
  6000. case OMPD_parallel_master:
  6001. Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
  6002. StartLoc, EndLoc);
  6003. AllowedNameModifiers.push_back(OMPD_parallel);
  6004. break;
  6005. case OMPD_parallel_masked:
  6006. Res = ActOnOpenMPParallelMaskedDirective(ClausesWithImplicit, AStmt,
  6007. StartLoc, EndLoc);
  6008. AllowedNameModifiers.push_back(OMPD_parallel);
  6009. break;
  6010. case OMPD_parallel_sections:
  6011. Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
  6012. StartLoc, EndLoc);
  6013. AllowedNameModifiers.push_back(OMPD_parallel);
  6014. break;
  6015. case OMPD_task:
  6016. Res =
  6017. ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  6018. AllowedNameModifiers.push_back(OMPD_task);
  6019. break;
  6020. case OMPD_taskyield:
  6021. assert(ClausesWithImplicit.empty() &&
  6022. "No clauses are allowed for 'omp taskyield' directive");
  6023. assert(AStmt == nullptr &&
  6024. "No associated statement allowed for 'omp taskyield' directive");
  6025. Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
  6026. break;
  6027. case OMPD_error:
  6028. assert(AStmt == nullptr &&
  6029. "No associated statement allowed for 'omp error' directive");
  6030. Res = ActOnOpenMPErrorDirective(ClausesWithImplicit, StartLoc, EndLoc);
  6031. break;
  6032. case OMPD_barrier:
  6033. assert(ClausesWithImplicit.empty() &&
  6034. "No clauses are allowed for 'omp barrier' directive");
  6035. assert(AStmt == nullptr &&
  6036. "No associated statement allowed for 'omp barrier' directive");
  6037. Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
  6038. break;
  6039. case OMPD_taskwait:
  6040. assert(AStmt == nullptr &&
  6041. "No associated statement allowed for 'omp taskwait' directive");
  6042. Res = ActOnOpenMPTaskwaitDirective(ClausesWithImplicit, StartLoc, EndLoc);
  6043. break;
  6044. case OMPD_taskgroup:
  6045. Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
  6046. EndLoc);
  6047. break;
  6048. case OMPD_flush:
  6049. assert(AStmt == nullptr &&
  6050. "No associated statement allowed for 'omp flush' directive");
  6051. Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
  6052. break;
  6053. case OMPD_depobj:
  6054. assert(AStmt == nullptr &&
  6055. "No associated statement allowed for 'omp depobj' directive");
  6056. Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc);
  6057. break;
  6058. case OMPD_scan:
  6059. assert(AStmt == nullptr &&
  6060. "No associated statement allowed for 'omp scan' directive");
  6061. Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc);
  6062. break;
  6063. case OMPD_ordered:
  6064. Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
  6065. EndLoc);
  6066. break;
  6067. case OMPD_atomic:
  6068. Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
  6069. EndLoc);
  6070. break;
  6071. case OMPD_teams:
  6072. Res =
  6073. ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
  6074. break;
  6075. case OMPD_target:
  6076. Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
  6077. EndLoc);
  6078. AllowedNameModifiers.push_back(OMPD_target);
  6079. break;
  6080. case OMPD_target_parallel:
  6081. Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
  6082. StartLoc, EndLoc);
  6083. AllowedNameModifiers.push_back(OMPD_target);
  6084. AllowedNameModifiers.push_back(OMPD_parallel);
  6085. break;
  6086. case OMPD_target_parallel_for:
  6087. Res = ActOnOpenMPTargetParallelForDirective(
  6088. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6089. AllowedNameModifiers.push_back(OMPD_target);
  6090. AllowedNameModifiers.push_back(OMPD_parallel);
  6091. break;
  6092. case OMPD_cancellation_point:
  6093. assert(ClausesWithImplicit.empty() &&
  6094. "No clauses are allowed for 'omp cancellation point' directive");
  6095. assert(AStmt == nullptr && "No associated statement allowed for 'omp "
  6096. "cancellation point' directive");
  6097. Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
  6098. break;
  6099. case OMPD_cancel:
  6100. assert(AStmt == nullptr &&
  6101. "No associated statement allowed for 'omp cancel' directive");
  6102. Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
  6103. CancelRegion);
  6104. AllowedNameModifiers.push_back(OMPD_cancel);
  6105. break;
  6106. case OMPD_target_data:
  6107. Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
  6108. EndLoc);
  6109. AllowedNameModifiers.push_back(OMPD_target_data);
  6110. break;
  6111. case OMPD_target_enter_data:
  6112. Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
  6113. EndLoc, AStmt);
  6114. AllowedNameModifiers.push_back(OMPD_target_enter_data);
  6115. break;
  6116. case OMPD_target_exit_data:
  6117. Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
  6118. EndLoc, AStmt);
  6119. AllowedNameModifiers.push_back(OMPD_target_exit_data);
  6120. break;
  6121. case OMPD_taskloop:
  6122. Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  6123. EndLoc, VarsWithInheritedDSA);
  6124. AllowedNameModifiers.push_back(OMPD_taskloop);
  6125. break;
  6126. case OMPD_taskloop_simd:
  6127. Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  6128. EndLoc, VarsWithInheritedDSA);
  6129. AllowedNameModifiers.push_back(OMPD_taskloop);
  6130. if (LangOpts.OpenMP >= 50)
  6131. AllowedNameModifiers.push_back(OMPD_simd);
  6132. break;
  6133. case OMPD_master_taskloop:
  6134. Res = ActOnOpenMPMasterTaskLoopDirective(
  6135. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6136. AllowedNameModifiers.push_back(OMPD_taskloop);
  6137. break;
  6138. case OMPD_masked_taskloop:
  6139. Res = ActOnOpenMPMaskedTaskLoopDirective(
  6140. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6141. AllowedNameModifiers.push_back(OMPD_taskloop);
  6142. break;
  6143. case OMPD_master_taskloop_simd:
  6144. Res = ActOnOpenMPMasterTaskLoopSimdDirective(
  6145. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6146. AllowedNameModifiers.push_back(OMPD_taskloop);
  6147. if (LangOpts.OpenMP >= 50)
  6148. AllowedNameModifiers.push_back(OMPD_simd);
  6149. break;
  6150. case OMPD_masked_taskloop_simd:
  6151. Res = ActOnOpenMPMaskedTaskLoopSimdDirective(
  6152. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6153. if (LangOpts.OpenMP >= 51) {
  6154. AllowedNameModifiers.push_back(OMPD_taskloop);
  6155. AllowedNameModifiers.push_back(OMPD_simd);
  6156. }
  6157. break;
  6158. case OMPD_parallel_master_taskloop:
  6159. Res = ActOnOpenMPParallelMasterTaskLoopDirective(
  6160. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6161. AllowedNameModifiers.push_back(OMPD_taskloop);
  6162. AllowedNameModifiers.push_back(OMPD_parallel);
  6163. break;
  6164. case OMPD_parallel_masked_taskloop:
  6165. Res = ActOnOpenMPParallelMaskedTaskLoopDirective(
  6166. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6167. if (LangOpts.OpenMP >= 51) {
  6168. AllowedNameModifiers.push_back(OMPD_taskloop);
  6169. AllowedNameModifiers.push_back(OMPD_parallel);
  6170. }
  6171. break;
  6172. case OMPD_parallel_master_taskloop_simd:
  6173. Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
  6174. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6175. AllowedNameModifiers.push_back(OMPD_taskloop);
  6176. AllowedNameModifiers.push_back(OMPD_parallel);
  6177. if (LangOpts.OpenMP >= 50)
  6178. AllowedNameModifiers.push_back(OMPD_simd);
  6179. break;
  6180. case OMPD_parallel_masked_taskloop_simd:
  6181. Res = ActOnOpenMPParallelMaskedTaskLoopSimdDirective(
  6182. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6183. if (LangOpts.OpenMP >= 51) {
  6184. AllowedNameModifiers.push_back(OMPD_taskloop);
  6185. AllowedNameModifiers.push_back(OMPD_parallel);
  6186. AllowedNameModifiers.push_back(OMPD_simd);
  6187. }
  6188. break;
  6189. case OMPD_distribute:
  6190. Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
  6191. EndLoc, VarsWithInheritedDSA);
  6192. break;
  6193. case OMPD_target_update:
  6194. Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
  6195. EndLoc, AStmt);
  6196. AllowedNameModifiers.push_back(OMPD_target_update);
  6197. break;
  6198. case OMPD_distribute_parallel_for:
  6199. Res = ActOnOpenMPDistributeParallelForDirective(
  6200. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6201. AllowedNameModifiers.push_back(OMPD_parallel);
  6202. break;
  6203. case OMPD_distribute_parallel_for_simd:
  6204. Res = ActOnOpenMPDistributeParallelForSimdDirective(
  6205. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6206. AllowedNameModifiers.push_back(OMPD_parallel);
  6207. if (LangOpts.OpenMP >= 50)
  6208. AllowedNameModifiers.push_back(OMPD_simd);
  6209. break;
  6210. case OMPD_distribute_simd:
  6211. Res = ActOnOpenMPDistributeSimdDirective(
  6212. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6213. if (LangOpts.OpenMP >= 50)
  6214. AllowedNameModifiers.push_back(OMPD_simd);
  6215. break;
  6216. case OMPD_target_parallel_for_simd:
  6217. Res = ActOnOpenMPTargetParallelForSimdDirective(
  6218. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6219. AllowedNameModifiers.push_back(OMPD_target);
  6220. AllowedNameModifiers.push_back(OMPD_parallel);
  6221. if (LangOpts.OpenMP >= 50)
  6222. AllowedNameModifiers.push_back(OMPD_simd);
  6223. break;
  6224. case OMPD_target_simd:
  6225. Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
  6226. EndLoc, VarsWithInheritedDSA);
  6227. AllowedNameModifiers.push_back(OMPD_target);
  6228. if (LangOpts.OpenMP >= 50)
  6229. AllowedNameModifiers.push_back(OMPD_simd);
  6230. break;
  6231. case OMPD_teams_distribute:
  6232. Res = ActOnOpenMPTeamsDistributeDirective(
  6233. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6234. break;
  6235. case OMPD_teams_distribute_simd:
  6236. Res = ActOnOpenMPTeamsDistributeSimdDirective(
  6237. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6238. if (LangOpts.OpenMP >= 50)
  6239. AllowedNameModifiers.push_back(OMPD_simd);
  6240. break;
  6241. case OMPD_teams_distribute_parallel_for_simd:
  6242. Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  6243. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6244. AllowedNameModifiers.push_back(OMPD_parallel);
  6245. if (LangOpts.OpenMP >= 50)
  6246. AllowedNameModifiers.push_back(OMPD_simd);
  6247. break;
  6248. case OMPD_teams_distribute_parallel_for:
  6249. Res = ActOnOpenMPTeamsDistributeParallelForDirective(
  6250. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6251. AllowedNameModifiers.push_back(OMPD_parallel);
  6252. break;
  6253. case OMPD_target_teams:
  6254. Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
  6255. EndLoc);
  6256. AllowedNameModifiers.push_back(OMPD_target);
  6257. break;
  6258. case OMPD_target_teams_distribute:
  6259. Res = ActOnOpenMPTargetTeamsDistributeDirective(
  6260. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6261. AllowedNameModifiers.push_back(OMPD_target);
  6262. break;
  6263. case OMPD_target_teams_distribute_parallel_for:
  6264. Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  6265. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6266. AllowedNameModifiers.push_back(OMPD_target);
  6267. AllowedNameModifiers.push_back(OMPD_parallel);
  6268. break;
  6269. case OMPD_target_teams_distribute_parallel_for_simd:
  6270. Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  6271. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6272. AllowedNameModifiers.push_back(OMPD_target);
  6273. AllowedNameModifiers.push_back(OMPD_parallel);
  6274. if (LangOpts.OpenMP >= 50)
  6275. AllowedNameModifiers.push_back(OMPD_simd);
  6276. break;
  6277. case OMPD_target_teams_distribute_simd:
  6278. Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
  6279. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6280. AllowedNameModifiers.push_back(OMPD_target);
  6281. if (LangOpts.OpenMP >= 50)
  6282. AllowedNameModifiers.push_back(OMPD_simd);
  6283. break;
  6284. case OMPD_interop:
  6285. assert(AStmt == nullptr &&
  6286. "No associated statement allowed for 'omp interop' directive");
  6287. Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc);
  6288. break;
  6289. case OMPD_dispatch:
  6290. Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc,
  6291. EndLoc);
  6292. break;
  6293. case OMPD_loop:
  6294. Res = ActOnOpenMPGenericLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
  6295. EndLoc, VarsWithInheritedDSA);
  6296. break;
  6297. case OMPD_teams_loop:
  6298. Res = ActOnOpenMPTeamsGenericLoopDirective(
  6299. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6300. break;
  6301. case OMPD_target_teams_loop:
  6302. Res = ActOnOpenMPTargetTeamsGenericLoopDirective(
  6303. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6304. break;
  6305. case OMPD_parallel_loop:
  6306. Res = ActOnOpenMPParallelGenericLoopDirective(
  6307. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6308. break;
  6309. case OMPD_target_parallel_loop:
  6310. Res = ActOnOpenMPTargetParallelGenericLoopDirective(
  6311. ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
  6312. break;
  6313. case OMPD_declare_target:
  6314. case OMPD_end_declare_target:
  6315. case OMPD_threadprivate:
  6316. case OMPD_allocate:
  6317. case OMPD_declare_reduction:
  6318. case OMPD_declare_mapper:
  6319. case OMPD_declare_simd:
  6320. case OMPD_requires:
  6321. case OMPD_declare_variant:
  6322. case OMPD_begin_declare_variant:
  6323. case OMPD_end_declare_variant:
  6324. llvm_unreachable("OpenMP Directive is not allowed");
  6325. case OMPD_unknown:
  6326. default:
  6327. llvm_unreachable("Unknown OpenMP directive");
  6328. }
  6329. ErrorFound = Res.isInvalid() || ErrorFound;
  6330. // Check variables in the clauses if default(none) or
  6331. // default(firstprivate) was specified.
  6332. if (DSAStack->getDefaultDSA() == DSA_none ||
  6333. DSAStack->getDefaultDSA() == DSA_private ||
  6334. DSAStack->getDefaultDSA() == DSA_firstprivate) {
  6335. DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
  6336. for (OMPClause *C : Clauses) {
  6337. switch (C->getClauseKind()) {
  6338. case OMPC_num_threads:
  6339. case OMPC_dist_schedule:
  6340. // Do not analyse if no parent teams directive.
  6341. if (isOpenMPTeamsDirective(Kind))
  6342. break;
  6343. continue;
  6344. case OMPC_if:
  6345. if (isOpenMPTeamsDirective(Kind) &&
  6346. cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
  6347. break;
  6348. if (isOpenMPParallelDirective(Kind) &&
  6349. isOpenMPTaskLoopDirective(Kind) &&
  6350. cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
  6351. break;
  6352. continue;
  6353. case OMPC_schedule:
  6354. case OMPC_detach:
  6355. break;
  6356. case OMPC_grainsize:
  6357. case OMPC_num_tasks:
  6358. case OMPC_final:
  6359. case OMPC_priority:
  6360. case OMPC_novariants:
  6361. case OMPC_nocontext:
  6362. // Do not analyze if no parent parallel directive.
  6363. if (isOpenMPParallelDirective(Kind))
  6364. break;
  6365. continue;
  6366. case OMPC_ordered:
  6367. case OMPC_device:
  6368. case OMPC_num_teams:
  6369. case OMPC_thread_limit:
  6370. case OMPC_hint:
  6371. case OMPC_collapse:
  6372. case OMPC_safelen:
  6373. case OMPC_simdlen:
  6374. case OMPC_sizes:
  6375. case OMPC_default:
  6376. case OMPC_proc_bind:
  6377. case OMPC_private:
  6378. case OMPC_firstprivate:
  6379. case OMPC_lastprivate:
  6380. case OMPC_shared:
  6381. case OMPC_reduction:
  6382. case OMPC_task_reduction:
  6383. case OMPC_in_reduction:
  6384. case OMPC_linear:
  6385. case OMPC_aligned:
  6386. case OMPC_copyin:
  6387. case OMPC_copyprivate:
  6388. case OMPC_nowait:
  6389. case OMPC_untied:
  6390. case OMPC_mergeable:
  6391. case OMPC_allocate:
  6392. case OMPC_read:
  6393. case OMPC_write:
  6394. case OMPC_update:
  6395. case OMPC_capture:
  6396. case OMPC_compare:
  6397. case OMPC_seq_cst:
  6398. case OMPC_acq_rel:
  6399. case OMPC_acquire:
  6400. case OMPC_release:
  6401. case OMPC_relaxed:
  6402. case OMPC_depend:
  6403. case OMPC_threads:
  6404. case OMPC_simd:
  6405. case OMPC_map:
  6406. case OMPC_nogroup:
  6407. case OMPC_defaultmap:
  6408. case OMPC_to:
  6409. case OMPC_from:
  6410. case OMPC_use_device_ptr:
  6411. case OMPC_use_device_addr:
  6412. case OMPC_is_device_ptr:
  6413. case OMPC_has_device_addr:
  6414. case OMPC_nontemporal:
  6415. case OMPC_order:
  6416. case OMPC_destroy:
  6417. case OMPC_inclusive:
  6418. case OMPC_exclusive:
  6419. case OMPC_uses_allocators:
  6420. case OMPC_affinity:
  6421. case OMPC_bind:
  6422. case OMPC_filter:
  6423. continue;
  6424. case OMPC_allocator:
  6425. case OMPC_flush:
  6426. case OMPC_depobj:
  6427. case OMPC_threadprivate:
  6428. case OMPC_uniform:
  6429. case OMPC_unknown:
  6430. case OMPC_unified_address:
  6431. case OMPC_unified_shared_memory:
  6432. case OMPC_reverse_offload:
  6433. case OMPC_dynamic_allocators:
  6434. case OMPC_atomic_default_mem_order:
  6435. case OMPC_device_type:
  6436. case OMPC_match:
  6437. case OMPC_when:
  6438. case OMPC_at:
  6439. case OMPC_severity:
  6440. case OMPC_message:
  6441. default:
  6442. llvm_unreachable("Unexpected clause");
  6443. }
  6444. for (Stmt *CC : C->children()) {
  6445. if (CC)
  6446. DSAChecker.Visit(CC);
  6447. }
  6448. }
  6449. for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
  6450. VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
  6451. }
  6452. for (const auto &P : VarsWithInheritedDSA) {
  6453. if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
  6454. continue;
  6455. ErrorFound = true;
  6456. if (DSAStack->getDefaultDSA() == DSA_none ||
  6457. DSAStack->getDefaultDSA() == DSA_private ||
  6458. DSAStack->getDefaultDSA() == DSA_firstprivate) {
  6459. Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
  6460. << P.first << P.second->getSourceRange();
  6461. Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
  6462. } else if (getLangOpts().OpenMP >= 50) {
  6463. Diag(P.second->getExprLoc(),
  6464. diag::err_omp_defaultmap_no_attr_for_variable)
  6465. << P.first << P.second->getSourceRange();
  6466. Diag(DSAStack->getDefaultDSALocation(),
  6467. diag::note_omp_defaultmap_attr_none);
  6468. }
  6469. }
  6470. if (!AllowedNameModifiers.empty())
  6471. ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
  6472. ErrorFound;
  6473. if (ErrorFound)
  6474. return StmtError();
  6475. if (!CurContext->isDependentContext() &&
  6476. isOpenMPTargetExecutionDirective(Kind) &&
  6477. !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
  6478. DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
  6479. DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
  6480. DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
  6481. // Register target to DSA Stack.
  6482. DSAStack->addTargetDirLocation(StartLoc);
  6483. }
  6484. return Res;
  6485. }
  6486. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
  6487. DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
  6488. ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
  6489. ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
  6490. ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
  6491. assert(Aligneds.size() == Alignments.size());
  6492. assert(Linears.size() == LinModifiers.size());
  6493. assert(Linears.size() == Steps.size());
  6494. if (!DG || DG.get().isNull())
  6495. return DeclGroupPtrTy();
  6496. const int SimdId = 0;
  6497. if (!DG.get().isSingleDecl()) {
  6498. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
  6499. << SimdId;
  6500. return DG;
  6501. }
  6502. Decl *ADecl = DG.get().getSingleDecl();
  6503. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  6504. ADecl = FTD->getTemplatedDecl();
  6505. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  6506. if (!FD) {
  6507. Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
  6508. return DeclGroupPtrTy();
  6509. }
  6510. // OpenMP [2.8.2, declare simd construct, Description]
  6511. // The parameter of the simdlen clause must be a constant positive integer
  6512. // expression.
  6513. ExprResult SL;
  6514. if (Simdlen)
  6515. SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
  6516. // OpenMP [2.8.2, declare simd construct, Description]
  6517. // The special this pointer can be used as if was one of the arguments to the
  6518. // function in any of the linear, aligned, or uniform clauses.
  6519. // The uniform clause declares one or more arguments to have an invariant
  6520. // value for all concurrent invocations of the function in the execution of a
  6521. // single SIMD loop.
  6522. llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
  6523. const Expr *UniformedLinearThis = nullptr;
  6524. for (const Expr *E : Uniforms) {
  6525. E = E->IgnoreParenImpCasts();
  6526. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  6527. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
  6528. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  6529. FD->getParamDecl(PVD->getFunctionScopeIndex())
  6530. ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
  6531. UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
  6532. continue;
  6533. }
  6534. if (isa<CXXThisExpr>(E)) {
  6535. UniformedLinearThis = E;
  6536. continue;
  6537. }
  6538. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  6539. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  6540. }
  6541. // OpenMP [2.8.2, declare simd construct, Description]
  6542. // The aligned clause declares that the object to which each list item points
  6543. // is aligned to the number of bytes expressed in the optional parameter of
  6544. // the aligned clause.
  6545. // The special this pointer can be used as if was one of the arguments to the
  6546. // function in any of the linear, aligned, or uniform clauses.
  6547. // The type of list items appearing in the aligned clause must be array,
  6548. // pointer, reference to array, or reference to pointer.
  6549. llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
  6550. const Expr *AlignedThis = nullptr;
  6551. for (const Expr *E : Aligneds) {
  6552. E = E->IgnoreParenImpCasts();
  6553. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  6554. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  6555. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  6556. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  6557. FD->getParamDecl(PVD->getFunctionScopeIndex())
  6558. ->getCanonicalDecl() == CanonPVD) {
  6559. // OpenMP [2.8.1, simd construct, Restrictions]
  6560. // A list-item cannot appear in more than one aligned clause.
  6561. if (AlignedArgs.count(CanonPVD) > 0) {
  6562. Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
  6563. << 1 << getOpenMPClauseName(OMPC_aligned)
  6564. << E->getSourceRange();
  6565. Diag(AlignedArgs[CanonPVD]->getExprLoc(),
  6566. diag::note_omp_explicit_dsa)
  6567. << getOpenMPClauseName(OMPC_aligned);
  6568. continue;
  6569. }
  6570. AlignedArgs[CanonPVD] = E;
  6571. QualType QTy = PVD->getType()
  6572. .getNonReferenceType()
  6573. .getUnqualifiedType()
  6574. .getCanonicalType();
  6575. const Type *Ty = QTy.getTypePtrOrNull();
  6576. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  6577. Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
  6578. << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
  6579. Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
  6580. }
  6581. continue;
  6582. }
  6583. }
  6584. if (isa<CXXThisExpr>(E)) {
  6585. if (AlignedThis) {
  6586. Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
  6587. << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
  6588. Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
  6589. << getOpenMPClauseName(OMPC_aligned);
  6590. }
  6591. AlignedThis = E;
  6592. continue;
  6593. }
  6594. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  6595. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  6596. }
  6597. // The optional parameter of the aligned clause, alignment, must be a constant
  6598. // positive integer expression. If no optional parameter is specified,
  6599. // implementation-defined default alignments for SIMD instructions on the
  6600. // target platforms are assumed.
  6601. SmallVector<const Expr *, 4> NewAligns;
  6602. for (Expr *E : Alignments) {
  6603. ExprResult Align;
  6604. if (E)
  6605. Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
  6606. NewAligns.push_back(Align.get());
  6607. }
  6608. // OpenMP [2.8.2, declare simd construct, Description]
  6609. // The linear clause declares one or more list items to be private to a SIMD
  6610. // lane and to have a linear relationship with respect to the iteration space
  6611. // of a loop.
  6612. // The special this pointer can be used as if was one of the arguments to the
  6613. // function in any of the linear, aligned, or uniform clauses.
  6614. // When a linear-step expression is specified in a linear clause it must be
  6615. // either a constant integer expression or an integer-typed parameter that is
  6616. // specified in a uniform clause on the directive.
  6617. llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
  6618. const bool IsUniformedThis = UniformedLinearThis != nullptr;
  6619. auto MI = LinModifiers.begin();
  6620. for (const Expr *E : Linears) {
  6621. auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
  6622. ++MI;
  6623. E = E->IgnoreParenImpCasts();
  6624. if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
  6625. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  6626. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  6627. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  6628. FD->getParamDecl(PVD->getFunctionScopeIndex())
  6629. ->getCanonicalDecl() == CanonPVD) {
  6630. // OpenMP [2.15.3.7, linear Clause, Restrictions]
  6631. // A list-item cannot appear in more than one linear clause.
  6632. if (LinearArgs.count(CanonPVD) > 0) {
  6633. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  6634. << getOpenMPClauseName(OMPC_linear)
  6635. << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
  6636. Diag(LinearArgs[CanonPVD]->getExprLoc(),
  6637. diag::note_omp_explicit_dsa)
  6638. << getOpenMPClauseName(OMPC_linear);
  6639. continue;
  6640. }
  6641. // Each argument can appear in at most one uniform or linear clause.
  6642. if (UniformedArgs.count(CanonPVD) > 0) {
  6643. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  6644. << getOpenMPClauseName(OMPC_linear)
  6645. << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
  6646. Diag(UniformedArgs[CanonPVD]->getExprLoc(),
  6647. diag::note_omp_explicit_dsa)
  6648. << getOpenMPClauseName(OMPC_uniform);
  6649. continue;
  6650. }
  6651. LinearArgs[CanonPVD] = E;
  6652. if (E->isValueDependent() || E->isTypeDependent() ||
  6653. E->isInstantiationDependent() ||
  6654. E->containsUnexpandedParameterPack())
  6655. continue;
  6656. (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
  6657. PVD->getOriginalType(),
  6658. /*IsDeclareSimd=*/true);
  6659. continue;
  6660. }
  6661. }
  6662. if (isa<CXXThisExpr>(E)) {
  6663. if (UniformedLinearThis) {
  6664. Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
  6665. << getOpenMPClauseName(OMPC_linear)
  6666. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
  6667. << E->getSourceRange();
  6668. Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
  6669. << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
  6670. : OMPC_linear);
  6671. continue;
  6672. }
  6673. UniformedLinearThis = E;
  6674. if (E->isValueDependent() || E->isTypeDependent() ||
  6675. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  6676. continue;
  6677. (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
  6678. E->getType(), /*IsDeclareSimd=*/true);
  6679. continue;
  6680. }
  6681. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
  6682. << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
  6683. }
  6684. Expr *Step = nullptr;
  6685. Expr *NewStep = nullptr;
  6686. SmallVector<Expr *, 4> NewSteps;
  6687. for (Expr *E : Steps) {
  6688. // Skip the same step expression, it was checked already.
  6689. if (Step == E || !E) {
  6690. NewSteps.push_back(E ? NewStep : nullptr);
  6691. continue;
  6692. }
  6693. Step = E;
  6694. if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
  6695. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  6696. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  6697. if (UniformedArgs.count(CanonPVD) == 0) {
  6698. Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
  6699. << Step->getSourceRange();
  6700. } else if (E->isValueDependent() || E->isTypeDependent() ||
  6701. E->isInstantiationDependent() ||
  6702. E->containsUnexpandedParameterPack() ||
  6703. CanonPVD->getType()->hasIntegerRepresentation()) {
  6704. NewSteps.push_back(Step);
  6705. } else {
  6706. Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
  6707. << Step->getSourceRange();
  6708. }
  6709. continue;
  6710. }
  6711. NewStep = Step;
  6712. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  6713. !Step->isInstantiationDependent() &&
  6714. !Step->containsUnexpandedParameterPack()) {
  6715. NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
  6716. .get();
  6717. if (NewStep)
  6718. NewStep =
  6719. VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get();
  6720. }
  6721. NewSteps.push_back(NewStep);
  6722. }
  6723. auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
  6724. Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
  6725. Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
  6726. const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
  6727. const_cast<Expr **>(Linears.data()), Linears.size(),
  6728. const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
  6729. NewSteps.data(), NewSteps.size(), SR);
  6730. ADecl->addAttr(NewAttr);
  6731. return DG;
  6732. }
  6733. static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
  6734. QualType NewType) {
  6735. assert(NewType->isFunctionProtoType() &&
  6736. "Expected function type with prototype.");
  6737. assert(FD->getType()->isFunctionNoProtoType() &&
  6738. "Expected function with type with no prototype.");
  6739. assert(FDWithProto->getType()->isFunctionProtoType() &&
  6740. "Expected function with prototype.");
  6741. // Synthesize parameters with the same types.
  6742. FD->setType(NewType);
  6743. SmallVector<ParmVarDecl *, 16> Params;
  6744. for (const ParmVarDecl *P : FDWithProto->parameters()) {
  6745. auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
  6746. SourceLocation(), nullptr, P->getType(),
  6747. /*TInfo=*/nullptr, SC_None, nullptr);
  6748. Param->setScopeInfo(0, Params.size());
  6749. Param->setImplicit();
  6750. Params.push_back(Param);
  6751. }
  6752. FD->setParams(Params);
  6753. }
  6754. void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) {
  6755. if (D->isInvalidDecl())
  6756. return;
  6757. FunctionDecl *FD = nullptr;
  6758. if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
  6759. FD = UTemplDecl->getTemplatedDecl();
  6760. else
  6761. FD = cast<FunctionDecl>(D);
  6762. assert(FD && "Expected a function declaration!");
  6763. // If we are instantiating templates we do *not* apply scoped assumptions but
  6764. // only global ones. We apply scoped assumption to the template definition
  6765. // though.
  6766. if (!inTemplateInstantiation()) {
  6767. for (AssumptionAttr *AA : OMPAssumeScoped)
  6768. FD->addAttr(AA);
  6769. }
  6770. for (AssumptionAttr *AA : OMPAssumeGlobal)
  6771. FD->addAttr(AA);
  6772. }
  6773. Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI)
  6774. : TI(&TI), NameSuffix(TI.getMangledName()) {}
  6775. void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
  6776. Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists,
  6777. SmallVectorImpl<FunctionDecl *> &Bases) {
  6778. if (!D.getIdentifier())
  6779. return;
  6780. OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
  6781. // Template specialization is an extension, check if we do it.
  6782. bool IsTemplated = !TemplateParamLists.empty();
  6783. if (IsTemplated &
  6784. !DVScope.TI->isExtensionActive(
  6785. llvm::omp::TraitProperty::implementation_extension_allow_templates))
  6786. return;
  6787. IdentifierInfo *BaseII = D.getIdentifier();
  6788. LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(),
  6789. LookupOrdinaryName);
  6790. LookupParsedName(Lookup, S, &D.getCXXScopeSpec());
  6791. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  6792. QualType FType = TInfo->getType();
  6793. bool IsConstexpr =
  6794. D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr;
  6795. bool IsConsteval =
  6796. D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval;
  6797. for (auto *Candidate : Lookup) {
  6798. auto *CandidateDecl = Candidate->getUnderlyingDecl();
  6799. FunctionDecl *UDecl = nullptr;
  6800. if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl)) {
  6801. auto *FTD = cast<FunctionTemplateDecl>(CandidateDecl);
  6802. if (FTD->getTemplateParameters()->size() == TemplateParamLists.size())
  6803. UDecl = FTD->getTemplatedDecl();
  6804. } else if (!IsTemplated)
  6805. UDecl = dyn_cast<FunctionDecl>(CandidateDecl);
  6806. if (!UDecl)
  6807. continue;
  6808. // Don't specialize constexpr/consteval functions with
  6809. // non-constexpr/consteval functions.
  6810. if (UDecl->isConstexpr() && !IsConstexpr)
  6811. continue;
  6812. if (UDecl->isConsteval() && !IsConsteval)
  6813. continue;
  6814. QualType UDeclTy = UDecl->getType();
  6815. if (!UDeclTy->isDependentType()) {
  6816. QualType NewType = Context.mergeFunctionTypes(
  6817. FType, UDeclTy, /* OfBlockPointer */ false,
  6818. /* Unqualified */ false, /* AllowCXX */ true);
  6819. if (NewType.isNull())
  6820. continue;
  6821. }
  6822. // Found a base!
  6823. Bases.push_back(UDecl);
  6824. }
  6825. bool UseImplicitBase = !DVScope.TI->isExtensionActive(
  6826. llvm::omp::TraitProperty::implementation_extension_disable_implicit_base);
  6827. // If no base was found we create a declaration that we use as base.
  6828. if (Bases.empty() && UseImplicitBase) {
  6829. D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
  6830. Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists);
  6831. BaseD->setImplicit(true);
  6832. if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD))
  6833. Bases.push_back(BaseTemplD->getTemplatedDecl());
  6834. else
  6835. Bases.push_back(cast<FunctionDecl>(BaseD));
  6836. }
  6837. std::string MangledName;
  6838. MangledName += D.getIdentifier()->getName();
  6839. MangledName += getOpenMPVariantManglingSeparatorStr();
  6840. MangledName += DVScope.NameSuffix;
  6841. IdentifierInfo &VariantII = Context.Idents.get(MangledName);
  6842. VariantII.setMangledOpenMPVariantName(true);
  6843. D.SetIdentifier(&VariantII, D.getBeginLoc());
  6844. }
  6845. void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
  6846. Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) {
  6847. // Do not mark function as is used to prevent its emission if this is the
  6848. // only place where it is used.
  6849. EnterExpressionEvaluationContext Unevaluated(
  6850. *this, Sema::ExpressionEvaluationContext::Unevaluated);
  6851. FunctionDecl *FD = nullptr;
  6852. if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D))
  6853. FD = UTemplDecl->getTemplatedDecl();
  6854. else
  6855. FD = cast<FunctionDecl>(D);
  6856. auto *VariantFuncRef = DeclRefExpr::Create(
  6857. Context, NestedNameSpecifierLoc(), SourceLocation(), FD,
  6858. /* RefersToEnclosingVariableOrCapture */ false,
  6859. /* NameLoc */ FD->getLocation(), FD->getType(),
  6860. ExprValueKind::VK_PRValue);
  6861. OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back();
  6862. auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit(
  6863. Context, VariantFuncRef, DVScope.TI,
  6864. /*NothingArgs=*/nullptr, /*NothingArgsSize=*/0,
  6865. /*NeedDevicePtrArgs=*/nullptr, /*NeedDevicePtrArgsSize=*/0,
  6866. /*AppendArgs=*/nullptr, /*AppendArgsSize=*/0);
  6867. for (FunctionDecl *BaseFD : Bases)
  6868. BaseFD->addAttr(OMPDeclareVariantA);
  6869. }
  6870. ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope,
  6871. SourceLocation LParenLoc,
  6872. MultiExprArg ArgExprs,
  6873. SourceLocation RParenLoc, Expr *ExecConfig) {
  6874. // The common case is a regular call we do not want to specialize at all. Try
  6875. // to make that case fast by bailing early.
  6876. CallExpr *CE = dyn_cast<CallExpr>(Call.get());
  6877. if (!CE)
  6878. return Call;
  6879. FunctionDecl *CalleeFnDecl = CE->getDirectCallee();
  6880. if (!CalleeFnDecl)
  6881. return Call;
  6882. if (LangOpts.OpenMP >= 51 && CalleeFnDecl->getIdentifier() &&
  6883. CalleeFnDecl->getName().startswith_insensitive("omp_")) {
  6884. // checking for any calls inside an Order region
  6885. if (Scope && Scope->isOpenMPOrderClauseScope())
  6886. Diag(LParenLoc, diag::err_omp_unexpected_call_to_omp_runtime_api);
  6887. }
  6888. if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>())
  6889. return Call;
  6890. ASTContext &Context = getASTContext();
  6891. std::function<void(StringRef)> DiagUnknownTrait = [this,
  6892. CE](StringRef ISATrait) {
  6893. // TODO Track the selector locations in a way that is accessible here to
  6894. // improve the diagnostic location.
  6895. Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait)
  6896. << ISATrait;
  6897. };
  6898. TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait),
  6899. getCurFunctionDecl(), DSAStack->getConstructTraits());
  6900. QualType CalleeFnType = CalleeFnDecl->getType();
  6901. SmallVector<Expr *, 4> Exprs;
  6902. SmallVector<VariantMatchInfo, 4> VMIs;
  6903. while (CalleeFnDecl) {
  6904. for (OMPDeclareVariantAttr *A :
  6905. CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) {
  6906. Expr *VariantRef = A->getVariantFuncRef();
  6907. VariantMatchInfo VMI;
  6908. OMPTraitInfo &TI = A->getTraitInfo();
  6909. TI.getAsVariantMatchInfo(Context, VMI);
  6910. if (!isVariantApplicableInContext(VMI, OMPCtx,
  6911. /* DeviceSetOnly */ false))
  6912. continue;
  6913. VMIs.push_back(VMI);
  6914. Exprs.push_back(VariantRef);
  6915. }
  6916. CalleeFnDecl = CalleeFnDecl->getPreviousDecl();
  6917. }
  6918. ExprResult NewCall;
  6919. do {
  6920. int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
  6921. if (BestIdx < 0)
  6922. return Call;
  6923. Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]);
  6924. Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl();
  6925. {
  6926. // Try to build a (member) call expression for the current best applicable
  6927. // variant expression. We allow this to fail in which case we continue
  6928. // with the next best variant expression. The fail case is part of the
  6929. // implementation defined behavior in the OpenMP standard when it talks
  6930. // about what differences in the function prototypes: "Any differences
  6931. // that the specific OpenMP context requires in the prototype of the
  6932. // variant from the base function prototype are implementation defined."
  6933. // This wording is there to allow the specialized variant to have a
  6934. // different type than the base function. This is intended and OK but if
  6935. // we cannot create a call the difference is not in the "implementation
  6936. // defined range" we allow.
  6937. Sema::TentativeAnalysisScope Trap(*this);
  6938. if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) {
  6939. auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE);
  6940. BestExpr = MemberExpr::CreateImplicit(
  6941. Context, MemberCall->getImplicitObjectArgument(),
  6942. /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy,
  6943. MemberCall->getValueKind(), MemberCall->getObjectKind());
  6944. }
  6945. NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc,
  6946. ExecConfig);
  6947. if (NewCall.isUsable()) {
  6948. if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) {
  6949. FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee();
  6950. QualType NewType = Context.mergeFunctionTypes(
  6951. CalleeFnType, NewCalleeFnDecl->getType(),
  6952. /* OfBlockPointer */ false,
  6953. /* Unqualified */ false, /* AllowCXX */ true);
  6954. if (!NewType.isNull())
  6955. break;
  6956. // Don't use the call if the function type was not compatible.
  6957. NewCall = nullptr;
  6958. }
  6959. }
  6960. }
  6961. VMIs.erase(VMIs.begin() + BestIdx);
  6962. Exprs.erase(Exprs.begin() + BestIdx);
  6963. } while (!VMIs.empty());
  6964. if (!NewCall.isUsable())
  6965. return Call;
  6966. return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0);
  6967. }
  6968. std::optional<std::pair<FunctionDecl *, Expr *>>
  6969. Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
  6970. Expr *VariantRef, OMPTraitInfo &TI,
  6971. unsigned NumAppendArgs,
  6972. SourceRange SR) {
  6973. if (!DG || DG.get().isNull())
  6974. return std::nullopt;
  6975. const int VariantId = 1;
  6976. // Must be applied only to single decl.
  6977. if (!DG.get().isSingleDecl()) {
  6978. Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
  6979. << VariantId << SR;
  6980. return std::nullopt;
  6981. }
  6982. Decl *ADecl = DG.get().getSingleDecl();
  6983. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
  6984. ADecl = FTD->getTemplatedDecl();
  6985. // Decl must be a function.
  6986. auto *FD = dyn_cast<FunctionDecl>(ADecl);
  6987. if (!FD) {
  6988. Diag(ADecl->getLocation(), diag::err_omp_function_expected)
  6989. << VariantId << SR;
  6990. return std::nullopt;
  6991. }
  6992. auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
  6993. // The 'target' attribute needs to be separately checked because it does
  6994. // not always signify a multiversion function declaration.
  6995. return FD->isMultiVersion() || FD->hasAttr<TargetAttr>();
  6996. };
  6997. // OpenMP is not compatible with multiversion function attributes.
  6998. if (HasMultiVersionAttributes(FD)) {
  6999. Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
  7000. << SR;
  7001. return std::nullopt;
  7002. }
  7003. // Allow #pragma omp declare variant only if the function is not used.
  7004. if (FD->isUsed(false))
  7005. Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
  7006. << FD->getLocation();
  7007. // Check if the function was emitted already.
  7008. const FunctionDecl *Definition;
  7009. if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
  7010. (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
  7011. Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
  7012. << FD->getLocation();
  7013. // The VariantRef must point to function.
  7014. if (!VariantRef) {
  7015. Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
  7016. return std::nullopt;
  7017. }
  7018. auto ShouldDelayChecks = [](Expr *&E, bool) {
  7019. return E && (E->isTypeDependent() || E->isValueDependent() ||
  7020. E->containsUnexpandedParameterPack() ||
  7021. E->isInstantiationDependent());
  7022. };
  7023. // Do not check templates, wait until instantiation.
  7024. if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) ||
  7025. TI.anyScoreOrCondition(ShouldDelayChecks))
  7026. return std::make_pair(FD, VariantRef);
  7027. // Deal with non-constant score and user condition expressions.
  7028. auto HandleNonConstantScoresAndConditions = [this](Expr *&E,
  7029. bool IsScore) -> bool {
  7030. if (!E || E->isIntegerConstantExpr(Context))
  7031. return false;
  7032. if (IsScore) {
  7033. // We warn on non-constant scores and pretend they were not present.
  7034. Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant)
  7035. << E;
  7036. E = nullptr;
  7037. } else {
  7038. // We could replace a non-constant user condition with "false" but we
  7039. // will soon need to handle these anyway for the dynamic version of
  7040. // OpenMP context selectors.
  7041. Diag(E->getExprLoc(),
  7042. diag::err_omp_declare_variant_user_condition_not_constant)
  7043. << E;
  7044. }
  7045. return true;
  7046. };
  7047. if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions))
  7048. return std::nullopt;
  7049. QualType AdjustedFnType = FD->getType();
  7050. if (NumAppendArgs) {
  7051. const auto *PTy = AdjustedFnType->getAsAdjusted<FunctionProtoType>();
  7052. if (!PTy) {
  7053. Diag(FD->getLocation(), diag::err_omp_declare_variant_prototype_required)
  7054. << SR;
  7055. return std::nullopt;
  7056. }
  7057. // Adjust the function type to account for an extra omp_interop_t for each
  7058. // specified in the append_args clause.
  7059. const TypeDecl *TD = nullptr;
  7060. LookupResult Result(*this, &Context.Idents.get("omp_interop_t"),
  7061. SR.getBegin(), Sema::LookupOrdinaryName);
  7062. if (LookupName(Result, getCurScope())) {
  7063. NamedDecl *ND = Result.getFoundDecl();
  7064. TD = dyn_cast_or_null<TypeDecl>(ND);
  7065. }
  7066. if (!TD) {
  7067. Diag(SR.getBegin(), diag::err_omp_interop_type_not_found) << SR;
  7068. return std::nullopt;
  7069. }
  7070. QualType InteropType = Context.getTypeDeclType(TD);
  7071. if (PTy->isVariadic()) {
  7072. Diag(FD->getLocation(), diag::err_omp_append_args_with_varargs) << SR;
  7073. return std::nullopt;
  7074. }
  7075. llvm::SmallVector<QualType, 8> Params;
  7076. Params.append(PTy->param_type_begin(), PTy->param_type_end());
  7077. Params.insert(Params.end(), NumAppendArgs, InteropType);
  7078. AdjustedFnType = Context.getFunctionType(PTy->getReturnType(), Params,
  7079. PTy->getExtProtoInfo());
  7080. }
  7081. // Convert VariantRef expression to the type of the original function to
  7082. // resolve possible conflicts.
  7083. ExprResult VariantRefCast = VariantRef;
  7084. if (LangOpts.CPlusPlus) {
  7085. QualType FnPtrType;
  7086. auto *Method = dyn_cast<CXXMethodDecl>(FD);
  7087. if (Method && !Method->isStatic()) {
  7088. const Type *ClassType =
  7089. Context.getTypeDeclType(Method->getParent()).getTypePtr();
  7090. FnPtrType = Context.getMemberPointerType(AdjustedFnType, ClassType);
  7091. ExprResult ER;
  7092. {
  7093. // Build adrr_of unary op to correctly handle type checks for member
  7094. // functions.
  7095. Sema::TentativeAnalysisScope Trap(*this);
  7096. ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
  7097. VariantRef);
  7098. }
  7099. if (!ER.isUsable()) {
  7100. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  7101. << VariantId << VariantRef->getSourceRange();
  7102. return std::nullopt;
  7103. }
  7104. VariantRef = ER.get();
  7105. } else {
  7106. FnPtrType = Context.getPointerType(AdjustedFnType);
  7107. }
  7108. QualType VarianPtrType = Context.getPointerType(VariantRef->getType());
  7109. if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) {
  7110. ImplicitConversionSequence ICS = TryImplicitConversion(
  7111. VariantRef, FnPtrType.getUnqualifiedType(),
  7112. /*SuppressUserConversions=*/false, AllowedExplicit::None,
  7113. /*InOverloadResolution=*/false,
  7114. /*CStyle=*/false,
  7115. /*AllowObjCWritebackConversion=*/false);
  7116. if (ICS.isFailure()) {
  7117. Diag(VariantRef->getExprLoc(),
  7118. diag::err_omp_declare_variant_incompat_types)
  7119. << VariantRef->getType()
  7120. << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
  7121. << (NumAppendArgs ? 1 : 0) << VariantRef->getSourceRange();
  7122. return std::nullopt;
  7123. }
  7124. VariantRefCast = PerformImplicitConversion(
  7125. VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
  7126. if (!VariantRefCast.isUsable())
  7127. return std::nullopt;
  7128. }
  7129. // Drop previously built artificial addr_of unary op for member functions.
  7130. if (Method && !Method->isStatic()) {
  7131. Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
  7132. if (auto *UO = dyn_cast<UnaryOperator>(
  7133. PossibleAddrOfVariantRef->IgnoreImplicit()))
  7134. VariantRefCast = UO->getSubExpr();
  7135. }
  7136. }
  7137. ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
  7138. if (!ER.isUsable() ||
  7139. !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
  7140. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  7141. << VariantId << VariantRef->getSourceRange();
  7142. return std::nullopt;
  7143. }
  7144. // The VariantRef must point to function.
  7145. auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
  7146. if (!DRE) {
  7147. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  7148. << VariantId << VariantRef->getSourceRange();
  7149. return std::nullopt;
  7150. }
  7151. auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
  7152. if (!NewFD) {
  7153. Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
  7154. << VariantId << VariantRef->getSourceRange();
  7155. return std::nullopt;
  7156. }
  7157. if (FD->getCanonicalDecl() == NewFD->getCanonicalDecl()) {
  7158. Diag(VariantRef->getExprLoc(),
  7159. diag::err_omp_declare_variant_same_base_function)
  7160. << VariantRef->getSourceRange();
  7161. return std::nullopt;
  7162. }
  7163. // Check if function types are compatible in C.
  7164. if (!LangOpts.CPlusPlus) {
  7165. QualType NewType =
  7166. Context.mergeFunctionTypes(AdjustedFnType, NewFD->getType());
  7167. if (NewType.isNull()) {
  7168. Diag(VariantRef->getExprLoc(),
  7169. diag::err_omp_declare_variant_incompat_types)
  7170. << NewFD->getType() << FD->getType() << (NumAppendArgs ? 1 : 0)
  7171. << VariantRef->getSourceRange();
  7172. return std::nullopt;
  7173. }
  7174. if (NewType->isFunctionProtoType()) {
  7175. if (FD->getType()->isFunctionNoProtoType())
  7176. setPrototype(*this, FD, NewFD, NewType);
  7177. else if (NewFD->getType()->isFunctionNoProtoType())
  7178. setPrototype(*this, NewFD, FD, NewType);
  7179. }
  7180. }
  7181. // Check if variant function is not marked with declare variant directive.
  7182. if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
  7183. Diag(VariantRef->getExprLoc(),
  7184. diag::warn_omp_declare_variant_marked_as_declare_variant)
  7185. << VariantRef->getSourceRange();
  7186. SourceRange SR =
  7187. NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
  7188. Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
  7189. return std::nullopt;
  7190. }
  7191. enum DoesntSupport {
  7192. VirtFuncs = 1,
  7193. Constructors = 3,
  7194. Destructors = 4,
  7195. DeletedFuncs = 5,
  7196. DefaultedFuncs = 6,
  7197. ConstexprFuncs = 7,
  7198. ConstevalFuncs = 8,
  7199. };
  7200. if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
  7201. if (CXXFD->isVirtual()) {
  7202. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  7203. << VirtFuncs;
  7204. return std::nullopt;
  7205. }
  7206. if (isa<CXXConstructorDecl>(FD)) {
  7207. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  7208. << Constructors;
  7209. return std::nullopt;
  7210. }
  7211. if (isa<CXXDestructorDecl>(FD)) {
  7212. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  7213. << Destructors;
  7214. return std::nullopt;
  7215. }
  7216. }
  7217. if (FD->isDeleted()) {
  7218. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  7219. << DeletedFuncs;
  7220. return std::nullopt;
  7221. }
  7222. if (FD->isDefaulted()) {
  7223. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  7224. << DefaultedFuncs;
  7225. return std::nullopt;
  7226. }
  7227. if (FD->isConstexpr()) {
  7228. Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
  7229. << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
  7230. return std::nullopt;
  7231. }
  7232. // Check general compatibility.
  7233. if (areMultiversionVariantFunctionsCompatible(
  7234. FD, NewFD, PartialDiagnostic::NullDiagnostic(),
  7235. PartialDiagnosticAt(SourceLocation(),
  7236. PartialDiagnostic::NullDiagnostic()),
  7237. PartialDiagnosticAt(
  7238. VariantRef->getExprLoc(),
  7239. PDiag(diag::err_omp_declare_variant_doesnt_support)),
  7240. PartialDiagnosticAt(VariantRef->getExprLoc(),
  7241. PDiag(diag::err_omp_declare_variant_diff)
  7242. << FD->getLocation()),
  7243. /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
  7244. /*CLinkageMayDiffer=*/true))
  7245. return std::nullopt;
  7246. return std::make_pair(FD, cast<Expr>(DRE));
  7247. }
  7248. void Sema::ActOnOpenMPDeclareVariantDirective(
  7249. FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI,
  7250. ArrayRef<Expr *> AdjustArgsNothing,
  7251. ArrayRef<Expr *> AdjustArgsNeedDevicePtr,
  7252. ArrayRef<OMPInteropInfo> AppendArgs, SourceLocation AdjustArgsLoc,
  7253. SourceLocation AppendArgsLoc, SourceRange SR) {
  7254. // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions]
  7255. // An adjust_args clause or append_args clause can only be specified if the
  7256. // dispatch selector of the construct selector set appears in the match
  7257. // clause.
  7258. SmallVector<Expr *, 8> AllAdjustArgs;
  7259. llvm::append_range(AllAdjustArgs, AdjustArgsNothing);
  7260. llvm::append_range(AllAdjustArgs, AdjustArgsNeedDevicePtr);
  7261. if (!AllAdjustArgs.empty() || !AppendArgs.empty()) {
  7262. VariantMatchInfo VMI;
  7263. TI.getAsVariantMatchInfo(Context, VMI);
  7264. if (!llvm::is_contained(
  7265. VMI.ConstructTraits,
  7266. llvm::omp::TraitProperty::construct_dispatch_dispatch)) {
  7267. if (!AllAdjustArgs.empty())
  7268. Diag(AdjustArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
  7269. << getOpenMPClauseName(OMPC_adjust_args);
  7270. if (!AppendArgs.empty())
  7271. Diag(AppendArgsLoc, diag::err_omp_clause_requires_dispatch_construct)
  7272. << getOpenMPClauseName(OMPC_append_args);
  7273. return;
  7274. }
  7275. }
  7276. // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions]
  7277. // Each argument can only appear in a single adjust_args clause for each
  7278. // declare variant directive.
  7279. llvm::SmallPtrSet<const VarDecl *, 4> AdjustVars;
  7280. for (Expr *E : AllAdjustArgs) {
  7281. E = E->IgnoreParenImpCasts();
  7282. if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
  7283. if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
  7284. const VarDecl *CanonPVD = PVD->getCanonicalDecl();
  7285. if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
  7286. FD->getParamDecl(PVD->getFunctionScopeIndex())
  7287. ->getCanonicalDecl() == CanonPVD) {
  7288. // It's a parameter of the function, check duplicates.
  7289. if (!AdjustVars.insert(CanonPVD).second) {
  7290. Diag(DRE->getLocation(), diag::err_omp_adjust_arg_multiple_clauses)
  7291. << PVD;
  7292. return;
  7293. }
  7294. continue;
  7295. }
  7296. }
  7297. }
  7298. // Anything that is not a function parameter is an error.
  7299. Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD << 0;
  7300. return;
  7301. }
  7302. auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
  7303. Context, VariantRef, &TI, const_cast<Expr **>(AdjustArgsNothing.data()),
  7304. AdjustArgsNothing.size(),
  7305. const_cast<Expr **>(AdjustArgsNeedDevicePtr.data()),
  7306. AdjustArgsNeedDevicePtr.size(),
  7307. const_cast<OMPInteropInfo *>(AppendArgs.data()), AppendArgs.size(), SR);
  7308. FD->addAttr(NewAttr);
  7309. }
  7310. StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
  7311. Stmt *AStmt,
  7312. SourceLocation StartLoc,
  7313. SourceLocation EndLoc) {
  7314. if (!AStmt)
  7315. return StmtError();
  7316. auto *CS = cast<CapturedStmt>(AStmt);
  7317. // 1.2.2 OpenMP Language Terminology
  7318. // Structured block - An executable statement with a single entry at the
  7319. // top and a single exit at the bottom.
  7320. // The point of exit cannot be a branch out of the structured block.
  7321. // longjmp() and throw() must not violate the entry/exit criteria.
  7322. CS->getCapturedDecl()->setNothrow();
  7323. setFunctionHasBranchProtectedScope();
  7324. return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  7325. DSAStack->getTaskgroupReductionRef(),
  7326. DSAStack->isCancelRegion());
  7327. }
  7328. namespace {
  7329. /// Iteration space of a single for loop.
  7330. struct LoopIterationSpace final {
  7331. /// True if the condition operator is the strict compare operator (<, > or
  7332. /// !=).
  7333. bool IsStrictCompare = false;
  7334. /// Condition of the loop.
  7335. Expr *PreCond = nullptr;
  7336. /// This expression calculates the number of iterations in the loop.
  7337. /// It is always possible to calculate it before starting the loop.
  7338. Expr *NumIterations = nullptr;
  7339. /// The loop counter variable.
  7340. Expr *CounterVar = nullptr;
  7341. /// Private loop counter variable.
  7342. Expr *PrivateCounterVar = nullptr;
  7343. /// This is initializer for the initial value of #CounterVar.
  7344. Expr *CounterInit = nullptr;
  7345. /// This is step for the #CounterVar used to generate its update:
  7346. /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
  7347. Expr *CounterStep = nullptr;
  7348. /// Should step be subtracted?
  7349. bool Subtract = false;
  7350. /// Source range of the loop init.
  7351. SourceRange InitSrcRange;
  7352. /// Source range of the loop condition.
  7353. SourceRange CondSrcRange;
  7354. /// Source range of the loop increment.
  7355. SourceRange IncSrcRange;
  7356. /// Minimum value that can have the loop control variable. Used to support
  7357. /// non-rectangular loops. Applied only for LCV with the non-iterator types,
  7358. /// since only such variables can be used in non-loop invariant expressions.
  7359. Expr *MinValue = nullptr;
  7360. /// Maximum value that can have the loop control variable. Used to support
  7361. /// non-rectangular loops. Applied only for LCV with the non-iterator type,
  7362. /// since only such variables can be used in non-loop invariant expressions.
  7363. Expr *MaxValue = nullptr;
  7364. /// true, if the lower bound depends on the outer loop control var.
  7365. bool IsNonRectangularLB = false;
  7366. /// true, if the upper bound depends on the outer loop control var.
  7367. bool IsNonRectangularUB = false;
  7368. /// Index of the loop this loop depends on and forms non-rectangular loop
  7369. /// nest.
  7370. unsigned LoopDependentIdx = 0;
  7371. /// Final condition for the non-rectangular loop nest support. It is used to
  7372. /// check that the number of iterations for this particular counter must be
  7373. /// finished.
  7374. Expr *FinalCondition = nullptr;
  7375. };
  7376. /// Helper class for checking canonical form of the OpenMP loops and
  7377. /// extracting iteration space of each loop in the loop nest, that will be used
  7378. /// for IR generation.
  7379. class OpenMPIterationSpaceChecker {
  7380. /// Reference to Sema.
  7381. Sema &SemaRef;
  7382. /// Does the loop associated directive support non-rectangular loops?
  7383. bool SupportsNonRectangular;
  7384. /// Data-sharing stack.
  7385. DSAStackTy &Stack;
  7386. /// A location for diagnostics (when there is no some better location).
  7387. SourceLocation DefaultLoc;
  7388. /// A location for diagnostics (when increment is not compatible).
  7389. SourceLocation ConditionLoc;
  7390. /// A source location for referring to loop init later.
  7391. SourceRange InitSrcRange;
  7392. /// A source location for referring to condition later.
  7393. SourceRange ConditionSrcRange;
  7394. /// A source location for referring to increment later.
  7395. SourceRange IncrementSrcRange;
  7396. /// Loop variable.
  7397. ValueDecl *LCDecl = nullptr;
  7398. /// Reference to loop variable.
  7399. Expr *LCRef = nullptr;
  7400. /// Lower bound (initializer for the var).
  7401. Expr *LB = nullptr;
  7402. /// Upper bound.
  7403. Expr *UB = nullptr;
  7404. /// Loop step (increment).
  7405. Expr *Step = nullptr;
  7406. /// This flag is true when condition is one of:
  7407. /// Var < UB
  7408. /// Var <= UB
  7409. /// UB > Var
  7410. /// UB >= Var
  7411. /// This will have no value when the condition is !=
  7412. std::optional<bool> TestIsLessOp;
  7413. /// This flag is true when condition is strict ( < or > ).
  7414. bool TestIsStrictOp = false;
  7415. /// This flag is true when step is subtracted on each iteration.
  7416. bool SubtractStep = false;
  7417. /// The outer loop counter this loop depends on (if any).
  7418. const ValueDecl *DepDecl = nullptr;
  7419. /// Contains number of loop (starts from 1) on which loop counter init
  7420. /// expression of this loop depends on.
  7421. std::optional<unsigned> InitDependOnLC;
  7422. /// Contains number of loop (starts from 1) on which loop counter condition
  7423. /// expression of this loop depends on.
  7424. std::optional<unsigned> CondDependOnLC;
  7425. /// Checks if the provide statement depends on the loop counter.
  7426. std::optional<unsigned> doesDependOnLoopCounter(const Stmt *S,
  7427. bool IsInitializer);
  7428. /// Original condition required for checking of the exit condition for
  7429. /// non-rectangular loop.
  7430. Expr *Condition = nullptr;
  7431. public:
  7432. OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular,
  7433. DSAStackTy &Stack, SourceLocation DefaultLoc)
  7434. : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular),
  7435. Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
  7436. /// Check init-expr for canonical loop form and save loop counter
  7437. /// variable - #Var and its initialization value - #LB.
  7438. bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
  7439. /// Check test-expr for canonical form, save upper-bound (#UB), flags
  7440. /// for less/greater and for strict/non-strict comparison.
  7441. bool checkAndSetCond(Expr *S);
  7442. /// Check incr-expr for canonical loop form and return true if it
  7443. /// does not conform, otherwise save loop step (#Step).
  7444. bool checkAndSetInc(Expr *S);
  7445. /// Return the loop counter variable.
  7446. ValueDecl *getLoopDecl() const { return LCDecl; }
  7447. /// Return the reference expression to loop counter variable.
  7448. Expr *getLoopDeclRefExpr() const { return LCRef; }
  7449. /// Source range of the loop init.
  7450. SourceRange getInitSrcRange() const { return InitSrcRange; }
  7451. /// Source range of the loop condition.
  7452. SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
  7453. /// Source range of the loop increment.
  7454. SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
  7455. /// True if the step should be subtracted.
  7456. bool shouldSubtractStep() const { return SubtractStep; }
  7457. /// True, if the compare operator is strict (<, > or !=).
  7458. bool isStrictTestOp() const { return TestIsStrictOp; }
  7459. /// Build the expression to calculate the number of iterations.
  7460. Expr *buildNumIterations(
  7461. Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
  7462. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  7463. /// Build the precondition expression for the loops.
  7464. Expr *
  7465. buildPreCond(Scope *S, Expr *Cond,
  7466. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  7467. /// Build reference expression to the counter be used for codegen.
  7468. DeclRefExpr *
  7469. buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  7470. DSAStackTy &DSA) const;
  7471. /// Build reference expression to the private counter be used for
  7472. /// codegen.
  7473. Expr *buildPrivateCounterVar() const;
  7474. /// Build initialization of the counter be used for codegen.
  7475. Expr *buildCounterInit() const;
  7476. /// Build step of the counter be used for codegen.
  7477. Expr *buildCounterStep() const;
  7478. /// Build loop data with counter value for depend clauses in ordered
  7479. /// directives.
  7480. Expr *
  7481. buildOrderedLoopData(Scope *S, Expr *Counter,
  7482. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  7483. SourceLocation Loc, Expr *Inc = nullptr,
  7484. OverloadedOperatorKind OOK = OO_Amp);
  7485. /// Builds the minimum value for the loop counter.
  7486. std::pair<Expr *, Expr *> buildMinMaxValues(
  7487. Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
  7488. /// Builds final condition for the non-rectangular loops.
  7489. Expr *buildFinalCondition(Scope *S) const;
  7490. /// Return true if any expression is dependent.
  7491. bool dependent() const;
  7492. /// Returns true if the initializer forms non-rectangular loop.
  7493. bool doesInitDependOnLC() const { return InitDependOnLC.has_value(); }
  7494. /// Returns true if the condition forms non-rectangular loop.
  7495. bool doesCondDependOnLC() const { return CondDependOnLC.has_value(); }
  7496. /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
  7497. unsigned getLoopDependentIdx() const {
  7498. return InitDependOnLC.value_or(CondDependOnLC.value_or(0));
  7499. }
  7500. private:
  7501. /// Check the right-hand side of an assignment in the increment
  7502. /// expression.
  7503. bool checkAndSetIncRHS(Expr *RHS);
  7504. /// Helper to set loop counter variable and its initializer.
  7505. bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
  7506. bool EmitDiags);
  7507. /// Helper to set upper bound.
  7508. bool setUB(Expr *NewUB, std::optional<bool> LessOp, bool StrictOp,
  7509. SourceRange SR, SourceLocation SL);
  7510. /// Helper to set loop increment.
  7511. bool setStep(Expr *NewStep, bool Subtract);
  7512. };
  7513. bool OpenMPIterationSpaceChecker::dependent() const {
  7514. if (!LCDecl) {
  7515. assert(!LB && !UB && !Step);
  7516. return false;
  7517. }
  7518. return LCDecl->getType()->isDependentType() ||
  7519. (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
  7520. (Step && Step->isValueDependent());
  7521. }
  7522. bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
  7523. Expr *NewLCRefExpr,
  7524. Expr *NewLB, bool EmitDiags) {
  7525. // State consistency checking to ensure correct usage.
  7526. assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
  7527. UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  7528. if (!NewLCDecl || !NewLB || NewLB->containsErrors())
  7529. return true;
  7530. LCDecl = getCanonicalDecl(NewLCDecl);
  7531. LCRef = NewLCRefExpr;
  7532. if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
  7533. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  7534. if ((Ctor->isCopyOrMoveConstructor() ||
  7535. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  7536. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  7537. NewLB = CE->getArg(0)->IgnoreParenImpCasts();
  7538. LB = NewLB;
  7539. if (EmitDiags)
  7540. InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
  7541. return false;
  7542. }
  7543. bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, std::optional<bool> LessOp,
  7544. bool StrictOp, SourceRange SR,
  7545. SourceLocation SL) {
  7546. // State consistency checking to ensure correct usage.
  7547. assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
  7548. Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
  7549. if (!NewUB || NewUB->containsErrors())
  7550. return true;
  7551. UB = NewUB;
  7552. if (LessOp)
  7553. TestIsLessOp = LessOp;
  7554. TestIsStrictOp = StrictOp;
  7555. ConditionSrcRange = SR;
  7556. ConditionLoc = SL;
  7557. CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
  7558. return false;
  7559. }
  7560. bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
  7561. // State consistency checking to ensure correct usage.
  7562. assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
  7563. if (!NewStep || NewStep->containsErrors())
  7564. return true;
  7565. if (!NewStep->isValueDependent()) {
  7566. // Check that the step is integer expression.
  7567. SourceLocation StepLoc = NewStep->getBeginLoc();
  7568. ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
  7569. StepLoc, getExprAsWritten(NewStep));
  7570. if (Val.isInvalid())
  7571. return true;
  7572. NewStep = Val.get();
  7573. // OpenMP [2.6, Canonical Loop Form, Restrictions]
  7574. // If test-expr is of form var relational-op b and relational-op is < or
  7575. // <= then incr-expr must cause var to increase on each iteration of the
  7576. // loop. If test-expr is of form var relational-op b and relational-op is
  7577. // > or >= then incr-expr must cause var to decrease on each iteration of
  7578. // the loop.
  7579. // If test-expr is of form b relational-op var and relational-op is < or
  7580. // <= then incr-expr must cause var to decrease on each iteration of the
  7581. // loop. If test-expr is of form b relational-op var and relational-op is
  7582. // > or >= then incr-expr must cause var to increase on each iteration of
  7583. // the loop.
  7584. std::optional<llvm::APSInt> Result =
  7585. NewStep->getIntegerConstantExpr(SemaRef.Context);
  7586. bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
  7587. bool IsConstNeg =
  7588. Result && Result->isSigned() && (Subtract != Result->isNegative());
  7589. bool IsConstPos =
  7590. Result && Result->isSigned() && (Subtract == Result->isNegative());
  7591. bool IsConstZero = Result && !Result->getBoolValue();
  7592. // != with increment is treated as <; != with decrement is treated as >
  7593. if (!TestIsLessOp)
  7594. TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
  7595. if (UB && (IsConstZero ||
  7596. (*TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
  7597. : (IsConstPos || (IsUnsigned && !Subtract))))) {
  7598. SemaRef.Diag(NewStep->getExprLoc(),
  7599. diag::err_omp_loop_incr_not_compatible)
  7600. << LCDecl << *TestIsLessOp << NewStep->getSourceRange();
  7601. SemaRef.Diag(ConditionLoc,
  7602. diag::note_omp_loop_cond_requres_compatible_incr)
  7603. << *TestIsLessOp << ConditionSrcRange;
  7604. return true;
  7605. }
  7606. if (*TestIsLessOp == Subtract) {
  7607. NewStep =
  7608. SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
  7609. .get();
  7610. Subtract = !Subtract;
  7611. }
  7612. }
  7613. Step = NewStep;
  7614. SubtractStep = Subtract;
  7615. return false;
  7616. }
  7617. namespace {
  7618. /// Checker for the non-rectangular loops. Checks if the initializer or
  7619. /// condition expression references loop counter variable.
  7620. class LoopCounterRefChecker final
  7621. : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
  7622. Sema &SemaRef;
  7623. DSAStackTy &Stack;
  7624. const ValueDecl *CurLCDecl = nullptr;
  7625. const ValueDecl *DepDecl = nullptr;
  7626. const ValueDecl *PrevDepDecl = nullptr;
  7627. bool IsInitializer = true;
  7628. bool SupportsNonRectangular;
  7629. unsigned BaseLoopId = 0;
  7630. bool checkDecl(const Expr *E, const ValueDecl *VD) {
  7631. if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
  7632. SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
  7633. << (IsInitializer ? 0 : 1);
  7634. return false;
  7635. }
  7636. const auto &&Data = Stack.isLoopControlVariable(VD);
  7637. // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
  7638. // The type of the loop iterator on which we depend may not have a random
  7639. // access iterator type.
  7640. if (Data.first && VD->getType()->isRecordType()) {
  7641. SmallString<128> Name;
  7642. llvm::raw_svector_ostream OS(Name);
  7643. VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
  7644. /*Qualified=*/true);
  7645. SemaRef.Diag(E->getExprLoc(),
  7646. diag::err_omp_wrong_dependency_iterator_type)
  7647. << OS.str();
  7648. SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
  7649. return false;
  7650. }
  7651. if (Data.first && !SupportsNonRectangular) {
  7652. SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency);
  7653. return false;
  7654. }
  7655. if (Data.first &&
  7656. (DepDecl || (PrevDepDecl &&
  7657. getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
  7658. if (!DepDecl && PrevDepDecl)
  7659. DepDecl = PrevDepDecl;
  7660. SmallString<128> Name;
  7661. llvm::raw_svector_ostream OS(Name);
  7662. DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
  7663. /*Qualified=*/true);
  7664. SemaRef.Diag(E->getExprLoc(),
  7665. diag::err_omp_invariant_or_linear_dependency)
  7666. << OS.str();
  7667. return false;
  7668. }
  7669. if (Data.first) {
  7670. DepDecl = VD;
  7671. BaseLoopId = Data.first;
  7672. }
  7673. return Data.first;
  7674. }
  7675. public:
  7676. bool VisitDeclRefExpr(const DeclRefExpr *E) {
  7677. const ValueDecl *VD = E->getDecl();
  7678. if (isa<VarDecl>(VD))
  7679. return checkDecl(E, VD);
  7680. return false;
  7681. }
  7682. bool VisitMemberExpr(const MemberExpr *E) {
  7683. if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
  7684. const ValueDecl *VD = E->getMemberDecl();
  7685. if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
  7686. return checkDecl(E, VD);
  7687. }
  7688. return false;
  7689. }
  7690. bool VisitStmt(const Stmt *S) {
  7691. bool Res = false;
  7692. for (const Stmt *Child : S->children())
  7693. Res = (Child && Visit(Child)) || Res;
  7694. return Res;
  7695. }
  7696. explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
  7697. const ValueDecl *CurLCDecl, bool IsInitializer,
  7698. const ValueDecl *PrevDepDecl = nullptr,
  7699. bool SupportsNonRectangular = true)
  7700. : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
  7701. PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer),
  7702. SupportsNonRectangular(SupportsNonRectangular) {}
  7703. unsigned getBaseLoopId() const {
  7704. assert(CurLCDecl && "Expected loop dependency.");
  7705. return BaseLoopId;
  7706. }
  7707. const ValueDecl *getDepDecl() const {
  7708. assert(CurLCDecl && "Expected loop dependency.");
  7709. return DepDecl;
  7710. }
  7711. };
  7712. } // namespace
  7713. std::optional<unsigned>
  7714. OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
  7715. bool IsInitializer) {
  7716. // Check for the non-rectangular loops.
  7717. LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
  7718. DepDecl, SupportsNonRectangular);
  7719. if (LoopStmtChecker.Visit(S)) {
  7720. DepDecl = LoopStmtChecker.getDepDecl();
  7721. return LoopStmtChecker.getBaseLoopId();
  7722. }
  7723. return std::nullopt;
  7724. }
  7725. bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
  7726. // Check init-expr for canonical loop form and save loop counter
  7727. // variable - #Var and its initialization value - #LB.
  7728. // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
  7729. // var = lb
  7730. // integer-type var = lb
  7731. // random-access-iterator-type var = lb
  7732. // pointer-type var = lb
  7733. //
  7734. if (!S) {
  7735. if (EmitDiags) {
  7736. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
  7737. }
  7738. return true;
  7739. }
  7740. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  7741. if (!ExprTemp->cleanupsHaveSideEffects())
  7742. S = ExprTemp->getSubExpr();
  7743. InitSrcRange = S->getSourceRange();
  7744. if (Expr *E = dyn_cast<Expr>(S))
  7745. S = E->IgnoreParens();
  7746. if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  7747. if (BO->getOpcode() == BO_Assign) {
  7748. Expr *LHS = BO->getLHS()->IgnoreParens();
  7749. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  7750. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  7751. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  7752. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  7753. EmitDiags);
  7754. return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
  7755. }
  7756. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  7757. if (ME->isArrow() &&
  7758. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  7759. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  7760. EmitDiags);
  7761. }
  7762. }
  7763. } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
  7764. if (DS->isSingleDecl()) {
  7765. if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
  7766. if (Var->hasInit() && !Var->getType()->isReferenceType()) {
  7767. // Accept non-canonical init form here but emit ext. warning.
  7768. if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
  7769. SemaRef.Diag(S->getBeginLoc(),
  7770. diag::ext_omp_loop_not_canonical_init)
  7771. << S->getSourceRange();
  7772. return setLCDeclAndLB(
  7773. Var,
  7774. buildDeclRefExpr(SemaRef, Var,
  7775. Var->getType().getNonReferenceType(),
  7776. DS->getBeginLoc()),
  7777. Var->getInit(), EmitDiags);
  7778. }
  7779. }
  7780. }
  7781. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  7782. if (CE->getOperator() == OO_Equal) {
  7783. Expr *LHS = CE->getArg(0);
  7784. if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  7785. if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
  7786. if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
  7787. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  7788. EmitDiags);
  7789. return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
  7790. }
  7791. if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
  7792. if (ME->isArrow() &&
  7793. isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  7794. return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
  7795. EmitDiags);
  7796. }
  7797. }
  7798. }
  7799. if (dependent() || SemaRef.CurContext->isDependentContext())
  7800. return false;
  7801. if (EmitDiags) {
  7802. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
  7803. << S->getSourceRange();
  7804. }
  7805. return true;
  7806. }
  7807. /// Ignore parenthesizes, implicit casts, copy constructor and return the
  7808. /// variable (which may be the loop variable) if possible.
  7809. static const ValueDecl *getInitLCDecl(const Expr *E) {
  7810. if (!E)
  7811. return nullptr;
  7812. E = getExprAsWritten(E);
  7813. if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
  7814. if (const CXXConstructorDecl *Ctor = CE->getConstructor())
  7815. if ((Ctor->isCopyOrMoveConstructor() ||
  7816. Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
  7817. CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
  7818. E = CE->getArg(0)->IgnoreParenImpCasts();
  7819. if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
  7820. if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
  7821. return getCanonicalDecl(VD);
  7822. }
  7823. if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
  7824. if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
  7825. return getCanonicalDecl(ME->getMemberDecl());
  7826. return nullptr;
  7827. }
  7828. bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
  7829. // Check test-expr for canonical form, save upper-bound UB, flags for
  7830. // less/greater and for strict/non-strict comparison.
  7831. // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
  7832. // var relational-op b
  7833. // b relational-op var
  7834. //
  7835. bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
  7836. if (!S) {
  7837. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
  7838. << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
  7839. return true;
  7840. }
  7841. Condition = S;
  7842. S = getExprAsWritten(S);
  7843. SourceLocation CondLoc = S->getBeginLoc();
  7844. auto &&CheckAndSetCond =
  7845. [this, IneqCondIsCanonical](BinaryOperatorKind Opcode, const Expr *LHS,
  7846. const Expr *RHS, SourceRange SR,
  7847. SourceLocation OpLoc) -> std::optional<bool> {
  7848. if (BinaryOperator::isRelationalOp(Opcode)) {
  7849. if (getInitLCDecl(LHS) == LCDecl)
  7850. return setUB(const_cast<Expr *>(RHS),
  7851. (Opcode == BO_LT || Opcode == BO_LE),
  7852. (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
  7853. if (getInitLCDecl(RHS) == LCDecl)
  7854. return setUB(const_cast<Expr *>(LHS),
  7855. (Opcode == BO_GT || Opcode == BO_GE),
  7856. (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc);
  7857. } else if (IneqCondIsCanonical && Opcode == BO_NE) {
  7858. return setUB(const_cast<Expr *>(getInitLCDecl(LHS) == LCDecl ? RHS : LHS),
  7859. /*LessOp=*/std::nullopt,
  7860. /*StrictOp=*/true, SR, OpLoc);
  7861. }
  7862. return std::nullopt;
  7863. };
  7864. std::optional<bool> Res;
  7865. if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) {
  7866. CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm();
  7867. Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(),
  7868. RBO->getOperatorLoc());
  7869. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  7870. Res = CheckAndSetCond(BO->getOpcode(), BO->getLHS(), BO->getRHS(),
  7871. BO->getSourceRange(), BO->getOperatorLoc());
  7872. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  7873. if (CE->getNumArgs() == 2) {
  7874. Res = CheckAndSetCond(
  7875. BinaryOperator::getOverloadedOpcode(CE->getOperator()), CE->getArg(0),
  7876. CE->getArg(1), CE->getSourceRange(), CE->getOperatorLoc());
  7877. }
  7878. }
  7879. if (Res)
  7880. return *Res;
  7881. if (dependent() || SemaRef.CurContext->isDependentContext())
  7882. return false;
  7883. SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
  7884. << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
  7885. return true;
  7886. }
  7887. bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
  7888. // RHS of canonical loop form increment can be:
  7889. // var + incr
  7890. // incr + var
  7891. // var - incr
  7892. //
  7893. RHS = RHS->IgnoreParenImpCasts();
  7894. if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
  7895. if (BO->isAdditiveOp()) {
  7896. bool IsAdd = BO->getOpcode() == BO_Add;
  7897. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  7898. return setStep(BO->getRHS(), !IsAdd);
  7899. if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
  7900. return setStep(BO->getLHS(), /*Subtract=*/false);
  7901. }
  7902. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
  7903. bool IsAdd = CE->getOperator() == OO_Plus;
  7904. if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
  7905. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  7906. return setStep(CE->getArg(1), !IsAdd);
  7907. if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
  7908. return setStep(CE->getArg(0), /*Subtract=*/false);
  7909. }
  7910. }
  7911. if (dependent() || SemaRef.CurContext->isDependentContext())
  7912. return false;
  7913. SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  7914. << RHS->getSourceRange() << LCDecl;
  7915. return true;
  7916. }
  7917. bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
  7918. // Check incr-expr for canonical loop form and return true if it
  7919. // does not conform.
  7920. // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
  7921. // ++var
  7922. // var++
  7923. // --var
  7924. // var--
  7925. // var += incr
  7926. // var -= incr
  7927. // var = var + incr
  7928. // var = incr + var
  7929. // var = var - incr
  7930. //
  7931. if (!S) {
  7932. SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
  7933. return true;
  7934. }
  7935. if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
  7936. if (!ExprTemp->cleanupsHaveSideEffects())
  7937. S = ExprTemp->getSubExpr();
  7938. IncrementSrcRange = S->getSourceRange();
  7939. S = S->IgnoreParens();
  7940. if (auto *UO = dyn_cast<UnaryOperator>(S)) {
  7941. if (UO->isIncrementDecrementOp() &&
  7942. getInitLCDecl(UO->getSubExpr()) == LCDecl)
  7943. return setStep(SemaRef
  7944. .ActOnIntegerConstant(UO->getBeginLoc(),
  7945. (UO->isDecrementOp() ? -1 : 1))
  7946. .get(),
  7947. /*Subtract=*/false);
  7948. } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
  7949. switch (BO->getOpcode()) {
  7950. case BO_AddAssign:
  7951. case BO_SubAssign:
  7952. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  7953. return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
  7954. break;
  7955. case BO_Assign:
  7956. if (getInitLCDecl(BO->getLHS()) == LCDecl)
  7957. return checkAndSetIncRHS(BO->getRHS());
  7958. break;
  7959. default:
  7960. break;
  7961. }
  7962. } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
  7963. switch (CE->getOperator()) {
  7964. case OO_PlusPlus:
  7965. case OO_MinusMinus:
  7966. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  7967. return setStep(SemaRef
  7968. .ActOnIntegerConstant(
  7969. CE->getBeginLoc(),
  7970. ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
  7971. .get(),
  7972. /*Subtract=*/false);
  7973. break;
  7974. case OO_PlusEqual:
  7975. case OO_MinusEqual:
  7976. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  7977. return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
  7978. break;
  7979. case OO_Equal:
  7980. if (getInitLCDecl(CE->getArg(0)) == LCDecl)
  7981. return checkAndSetIncRHS(CE->getArg(1));
  7982. break;
  7983. default:
  7984. break;
  7985. }
  7986. }
  7987. if (dependent() || SemaRef.CurContext->isDependentContext())
  7988. return false;
  7989. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
  7990. << S->getSourceRange() << LCDecl;
  7991. return true;
  7992. }
  7993. static ExprResult
  7994. tryBuildCapture(Sema &SemaRef, Expr *Capture,
  7995. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  7996. if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors())
  7997. return Capture;
  7998. if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
  7999. return SemaRef.PerformImplicitConversion(
  8000. Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
  8001. /*AllowExplicit=*/true);
  8002. auto I = Captures.find(Capture);
  8003. if (I != Captures.end())
  8004. return buildCapture(SemaRef, Capture, I->second);
  8005. DeclRefExpr *Ref = nullptr;
  8006. ExprResult Res = buildCapture(SemaRef, Capture, Ref);
  8007. Captures[Capture] = Ref;
  8008. return Res;
  8009. }
  8010. /// Calculate number of iterations, transforming to unsigned, if number of
  8011. /// iterations may be larger than the original type.
  8012. static Expr *
  8013. calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc,
  8014. Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy,
  8015. bool TestIsStrictOp, bool RoundToStep,
  8016. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  8017. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  8018. if (!NewStep.isUsable())
  8019. return nullptr;
  8020. llvm::APSInt LRes, SRes;
  8021. bool IsLowerConst = false, IsStepConst = false;
  8022. if (std::optional<llvm::APSInt> Res =
  8023. Lower->getIntegerConstantExpr(SemaRef.Context)) {
  8024. LRes = *Res;
  8025. IsLowerConst = true;
  8026. }
  8027. if (std::optional<llvm::APSInt> Res =
  8028. Step->getIntegerConstantExpr(SemaRef.Context)) {
  8029. SRes = *Res;
  8030. IsStepConst = true;
  8031. }
  8032. bool NoNeedToConvert = IsLowerConst && !RoundToStep &&
  8033. ((!TestIsStrictOp && LRes.isNonNegative()) ||
  8034. (TestIsStrictOp && LRes.isStrictlyPositive()));
  8035. bool NeedToReorganize = false;
  8036. // Check if any subexpressions in Lower -Step [+ 1] lead to overflow.
  8037. if (!NoNeedToConvert && IsLowerConst &&
  8038. (TestIsStrictOp || (RoundToStep && IsStepConst))) {
  8039. NoNeedToConvert = true;
  8040. if (RoundToStep) {
  8041. unsigned BW = LRes.getBitWidth() > SRes.getBitWidth()
  8042. ? LRes.getBitWidth()
  8043. : SRes.getBitWidth();
  8044. LRes = LRes.extend(BW + 1);
  8045. LRes.setIsSigned(true);
  8046. SRes = SRes.extend(BW + 1);
  8047. SRes.setIsSigned(true);
  8048. LRes -= SRes;
  8049. NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes;
  8050. LRes = LRes.trunc(BW);
  8051. }
  8052. if (TestIsStrictOp) {
  8053. unsigned BW = LRes.getBitWidth();
  8054. LRes = LRes.extend(BW + 1);
  8055. LRes.setIsSigned(true);
  8056. ++LRes;
  8057. NoNeedToConvert =
  8058. NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes;
  8059. // truncate to the original bitwidth.
  8060. LRes = LRes.trunc(BW);
  8061. }
  8062. NeedToReorganize = NoNeedToConvert;
  8063. }
  8064. llvm::APSInt URes;
  8065. bool IsUpperConst = false;
  8066. if (std::optional<llvm::APSInt> Res =
  8067. Upper->getIntegerConstantExpr(SemaRef.Context)) {
  8068. URes = *Res;
  8069. IsUpperConst = true;
  8070. }
  8071. if (NoNeedToConvert && IsLowerConst && IsUpperConst &&
  8072. (!RoundToStep || IsStepConst)) {
  8073. unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth()
  8074. : URes.getBitWidth();
  8075. LRes = LRes.extend(BW + 1);
  8076. LRes.setIsSigned(true);
  8077. URes = URes.extend(BW + 1);
  8078. URes.setIsSigned(true);
  8079. URes -= LRes;
  8080. NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes;
  8081. NeedToReorganize = NoNeedToConvert;
  8082. }
  8083. // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant
  8084. // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to
  8085. // unsigned.
  8086. if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) &&
  8087. !LCTy->isDependentType() && LCTy->isIntegerType()) {
  8088. QualType LowerTy = Lower->getType();
  8089. QualType UpperTy = Upper->getType();
  8090. uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy);
  8091. uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy);
  8092. if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) ||
  8093. (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) {
  8094. QualType CastType = SemaRef.Context.getIntTypeForBitwidth(
  8095. LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0);
  8096. Upper =
  8097. SemaRef
  8098. .PerformImplicitConversion(
  8099. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
  8100. CastType, Sema::AA_Converting)
  8101. .get();
  8102. Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get();
  8103. NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get());
  8104. }
  8105. }
  8106. if (!Lower || !Upper || NewStep.isInvalid())
  8107. return nullptr;
  8108. ExprResult Diff;
  8109. // If need to reorganize, then calculate the form as Upper - (Lower - Step [+
  8110. // 1]).
  8111. if (NeedToReorganize) {
  8112. Diff = Lower;
  8113. if (RoundToStep) {
  8114. // Lower - Step
  8115. Diff =
  8116. SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get());
  8117. if (!Diff.isUsable())
  8118. return nullptr;
  8119. }
  8120. // Lower - Step [+ 1]
  8121. if (TestIsStrictOp)
  8122. Diff = SemaRef.BuildBinOp(
  8123. S, DefaultLoc, BO_Add, Diff.get(),
  8124. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  8125. if (!Diff.isUsable())
  8126. return nullptr;
  8127. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  8128. if (!Diff.isUsable())
  8129. return nullptr;
  8130. // Upper - (Lower - Step [+ 1]).
  8131. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
  8132. if (!Diff.isUsable())
  8133. return nullptr;
  8134. } else {
  8135. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
  8136. if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) {
  8137. // BuildBinOp already emitted error, this one is to point user to upper
  8138. // and lower bound, and to tell what is passed to 'operator-'.
  8139. SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
  8140. << Upper->getSourceRange() << Lower->getSourceRange();
  8141. return nullptr;
  8142. }
  8143. if (!Diff.isUsable())
  8144. return nullptr;
  8145. // Upper - Lower [- 1]
  8146. if (TestIsStrictOp)
  8147. Diff = SemaRef.BuildBinOp(
  8148. S, DefaultLoc, BO_Sub, Diff.get(),
  8149. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  8150. if (!Diff.isUsable())
  8151. return nullptr;
  8152. if (RoundToStep) {
  8153. // Upper - Lower [- 1] + Step
  8154. Diff =
  8155. SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
  8156. if (!Diff.isUsable())
  8157. return nullptr;
  8158. }
  8159. }
  8160. // Parentheses (for dumping/debugging purposes only).
  8161. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  8162. if (!Diff.isUsable())
  8163. return nullptr;
  8164. // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step
  8165. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
  8166. if (!Diff.isUsable())
  8167. return nullptr;
  8168. return Diff.get();
  8169. }
  8170. /// Build the expression to calculate the number of iterations.
  8171. Expr *OpenMPIterationSpaceChecker::buildNumIterations(
  8172. Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
  8173. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  8174. QualType VarType = LCDecl->getType().getNonReferenceType();
  8175. if (!VarType->isIntegerType() && !VarType->isPointerType() &&
  8176. !SemaRef.getLangOpts().CPlusPlus)
  8177. return nullptr;
  8178. Expr *LBVal = LB;
  8179. Expr *UBVal = UB;
  8180. // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
  8181. // max(LB(MinVal), LB(MaxVal))
  8182. if (InitDependOnLC) {
  8183. const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1];
  8184. if (!IS.MinValue || !IS.MaxValue)
  8185. return nullptr;
  8186. // OuterVar = Min
  8187. ExprResult MinValue =
  8188. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
  8189. if (!MinValue.isUsable())
  8190. return nullptr;
  8191. ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  8192. IS.CounterVar, MinValue.get());
  8193. if (!LBMinVal.isUsable())
  8194. return nullptr;
  8195. // OuterVar = Min, LBVal
  8196. LBMinVal =
  8197. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
  8198. if (!LBMinVal.isUsable())
  8199. return nullptr;
  8200. // (OuterVar = Min, LBVal)
  8201. LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
  8202. if (!LBMinVal.isUsable())
  8203. return nullptr;
  8204. // OuterVar = Max
  8205. ExprResult MaxValue =
  8206. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
  8207. if (!MaxValue.isUsable())
  8208. return nullptr;
  8209. ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  8210. IS.CounterVar, MaxValue.get());
  8211. if (!LBMaxVal.isUsable())
  8212. return nullptr;
  8213. // OuterVar = Max, LBVal
  8214. LBMaxVal =
  8215. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
  8216. if (!LBMaxVal.isUsable())
  8217. return nullptr;
  8218. // (OuterVar = Max, LBVal)
  8219. LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
  8220. if (!LBMaxVal.isUsable())
  8221. return nullptr;
  8222. Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
  8223. Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
  8224. if (!LBMin || !LBMax)
  8225. return nullptr;
  8226. // LB(MinVal) < LB(MaxVal)
  8227. ExprResult MinLessMaxRes =
  8228. SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
  8229. if (!MinLessMaxRes.isUsable())
  8230. return nullptr;
  8231. Expr *MinLessMax =
  8232. tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
  8233. if (!MinLessMax)
  8234. return nullptr;
  8235. if (*TestIsLessOp) {
  8236. // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
  8237. // LB(MaxVal))
  8238. ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
  8239. MinLessMax, LBMin, LBMax);
  8240. if (!MinLB.isUsable())
  8241. return nullptr;
  8242. LBVal = MinLB.get();
  8243. } else {
  8244. // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
  8245. // LB(MaxVal))
  8246. ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
  8247. MinLessMax, LBMax, LBMin);
  8248. if (!MaxLB.isUsable())
  8249. return nullptr;
  8250. LBVal = MaxLB.get();
  8251. }
  8252. }
  8253. // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
  8254. // min(UB(MinVal), UB(MaxVal))
  8255. if (CondDependOnLC) {
  8256. const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1];
  8257. if (!IS.MinValue || !IS.MaxValue)
  8258. return nullptr;
  8259. // OuterVar = Min
  8260. ExprResult MinValue =
  8261. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
  8262. if (!MinValue.isUsable())
  8263. return nullptr;
  8264. ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  8265. IS.CounterVar, MinValue.get());
  8266. if (!UBMinVal.isUsable())
  8267. return nullptr;
  8268. // OuterVar = Min, UBVal
  8269. UBMinVal =
  8270. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
  8271. if (!UBMinVal.isUsable())
  8272. return nullptr;
  8273. // (OuterVar = Min, UBVal)
  8274. UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
  8275. if (!UBMinVal.isUsable())
  8276. return nullptr;
  8277. // OuterVar = Max
  8278. ExprResult MaxValue =
  8279. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
  8280. if (!MaxValue.isUsable())
  8281. return nullptr;
  8282. ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
  8283. IS.CounterVar, MaxValue.get());
  8284. if (!UBMaxVal.isUsable())
  8285. return nullptr;
  8286. // OuterVar = Max, UBVal
  8287. UBMaxVal =
  8288. SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
  8289. if (!UBMaxVal.isUsable())
  8290. return nullptr;
  8291. // (OuterVar = Max, UBVal)
  8292. UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
  8293. if (!UBMaxVal.isUsable())
  8294. return nullptr;
  8295. Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
  8296. Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
  8297. if (!UBMin || !UBMax)
  8298. return nullptr;
  8299. // UB(MinVal) > UB(MaxVal)
  8300. ExprResult MinGreaterMaxRes =
  8301. SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
  8302. if (!MinGreaterMaxRes.isUsable())
  8303. return nullptr;
  8304. Expr *MinGreaterMax =
  8305. tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
  8306. if (!MinGreaterMax)
  8307. return nullptr;
  8308. if (*TestIsLessOp) {
  8309. // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
  8310. // UB(MaxVal))
  8311. ExprResult MaxUB = SemaRef.ActOnConditionalOp(
  8312. DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
  8313. if (!MaxUB.isUsable())
  8314. return nullptr;
  8315. UBVal = MaxUB.get();
  8316. } else {
  8317. // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
  8318. // UB(MaxVal))
  8319. ExprResult MinUB = SemaRef.ActOnConditionalOp(
  8320. DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
  8321. if (!MinUB.isUsable())
  8322. return nullptr;
  8323. UBVal = MinUB.get();
  8324. }
  8325. }
  8326. Expr *UBExpr = *TestIsLessOp ? UBVal : LBVal;
  8327. Expr *LBExpr = *TestIsLessOp ? LBVal : UBVal;
  8328. Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
  8329. Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
  8330. if (!Upper || !Lower)
  8331. return nullptr;
  8332. ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
  8333. Step, VarType, TestIsStrictOp,
  8334. /*RoundToStep=*/true, Captures);
  8335. if (!Diff.isUsable())
  8336. return nullptr;
  8337. // OpenMP runtime requires 32-bit or 64-bit loop variables.
  8338. QualType Type = Diff.get()->getType();
  8339. ASTContext &C = SemaRef.Context;
  8340. bool UseVarType = VarType->hasIntegerRepresentation() &&
  8341. C.getTypeSize(Type) > C.getTypeSize(VarType);
  8342. if (!Type->isIntegerType() || UseVarType) {
  8343. unsigned NewSize =
  8344. UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
  8345. bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
  8346. : Type->hasSignedIntegerRepresentation();
  8347. Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
  8348. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
  8349. Diff = SemaRef.PerformImplicitConversion(
  8350. Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
  8351. if (!Diff.isUsable())
  8352. return nullptr;
  8353. }
  8354. }
  8355. if (LimitedType) {
  8356. unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
  8357. if (NewSize != C.getTypeSize(Type)) {
  8358. if (NewSize < C.getTypeSize(Type)) {
  8359. assert(NewSize == 64 && "incorrect loop var size");
  8360. SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
  8361. << InitSrcRange << ConditionSrcRange;
  8362. }
  8363. QualType NewType = C.getIntTypeForBitwidth(
  8364. NewSize, Type->hasSignedIntegerRepresentation() ||
  8365. C.getTypeSize(Type) < NewSize);
  8366. if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
  8367. Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
  8368. Sema::AA_Converting, true);
  8369. if (!Diff.isUsable())
  8370. return nullptr;
  8371. }
  8372. }
  8373. }
  8374. return Diff.get();
  8375. }
  8376. std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
  8377. Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  8378. // Do not build for iterators, they cannot be used in non-rectangular loop
  8379. // nests.
  8380. if (LCDecl->getType()->isRecordType())
  8381. return std::make_pair(nullptr, nullptr);
  8382. // If we subtract, the min is in the condition, otherwise the min is in the
  8383. // init value.
  8384. Expr *MinExpr = nullptr;
  8385. Expr *MaxExpr = nullptr;
  8386. Expr *LBExpr = *TestIsLessOp ? LB : UB;
  8387. Expr *UBExpr = *TestIsLessOp ? UB : LB;
  8388. bool LBNonRect =
  8389. *TestIsLessOp ? InitDependOnLC.has_value() : CondDependOnLC.has_value();
  8390. bool UBNonRect =
  8391. *TestIsLessOp ? CondDependOnLC.has_value() : InitDependOnLC.has_value();
  8392. Expr *Lower =
  8393. LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
  8394. Expr *Upper =
  8395. UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
  8396. if (!Upper || !Lower)
  8397. return std::make_pair(nullptr, nullptr);
  8398. if (*TestIsLessOp)
  8399. MinExpr = Lower;
  8400. else
  8401. MaxExpr = Upper;
  8402. // Build minimum/maximum value based on number of iterations.
  8403. QualType VarType = LCDecl->getType().getNonReferenceType();
  8404. ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper,
  8405. Step, VarType, TestIsStrictOp,
  8406. /*RoundToStep=*/false, Captures);
  8407. if (!Diff.isUsable())
  8408. return std::make_pair(nullptr, nullptr);
  8409. // ((Upper - Lower [- 1]) / Step) * Step
  8410. // Parentheses (for dumping/debugging purposes only).
  8411. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  8412. if (!Diff.isUsable())
  8413. return std::make_pair(nullptr, nullptr);
  8414. ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
  8415. if (!NewStep.isUsable())
  8416. return std::make_pair(nullptr, nullptr);
  8417. Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
  8418. if (!Diff.isUsable())
  8419. return std::make_pair(nullptr, nullptr);
  8420. // Parentheses (for dumping/debugging purposes only).
  8421. Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
  8422. if (!Diff.isUsable())
  8423. return std::make_pair(nullptr, nullptr);
  8424. // Convert to the ptrdiff_t, if original type is pointer.
  8425. if (VarType->isAnyPointerType() &&
  8426. !SemaRef.Context.hasSameType(
  8427. Diff.get()->getType(),
  8428. SemaRef.Context.getUnsignedPointerDiffType())) {
  8429. Diff = SemaRef.PerformImplicitConversion(
  8430. Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
  8431. Sema::AA_Converting, /*AllowExplicit=*/true);
  8432. }
  8433. if (!Diff.isUsable())
  8434. return std::make_pair(nullptr, nullptr);
  8435. if (*TestIsLessOp) {
  8436. // MinExpr = Lower;
  8437. // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
  8438. Diff = SemaRef.BuildBinOp(
  8439. S, DefaultLoc, BO_Add,
  8440. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(),
  8441. Diff.get());
  8442. if (!Diff.isUsable())
  8443. return std::make_pair(nullptr, nullptr);
  8444. } else {
  8445. // MaxExpr = Upper;
  8446. // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
  8447. Diff = SemaRef.BuildBinOp(
  8448. S, DefaultLoc, BO_Sub,
  8449. SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(),
  8450. Diff.get());
  8451. if (!Diff.isUsable())
  8452. return std::make_pair(nullptr, nullptr);
  8453. }
  8454. // Convert to the original type.
  8455. if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType))
  8456. Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType,
  8457. Sema::AA_Converting,
  8458. /*AllowExplicit=*/true);
  8459. if (!Diff.isUsable())
  8460. return std::make_pair(nullptr, nullptr);
  8461. Sema::TentativeAnalysisScope Trap(SemaRef);
  8462. Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false);
  8463. if (!Diff.isUsable())
  8464. return std::make_pair(nullptr, nullptr);
  8465. if (*TestIsLessOp)
  8466. MaxExpr = Diff.get();
  8467. else
  8468. MinExpr = Diff.get();
  8469. return std::make_pair(MinExpr, MaxExpr);
  8470. }
  8471. Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
  8472. if (InitDependOnLC || CondDependOnLC)
  8473. return Condition;
  8474. return nullptr;
  8475. }
  8476. Expr *OpenMPIterationSpaceChecker::buildPreCond(
  8477. Scope *S, Expr *Cond,
  8478. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
  8479. // Do not build a precondition when the condition/initialization is dependent
  8480. // to prevent pessimistic early loop exit.
  8481. // TODO: this can be improved by calculating min/max values but not sure that
  8482. // it will be very effective.
  8483. if (CondDependOnLC || InitDependOnLC)
  8484. return SemaRef
  8485. .PerformImplicitConversion(
  8486. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
  8487. SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  8488. /*AllowExplicit=*/true)
  8489. .get();
  8490. // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
  8491. Sema::TentativeAnalysisScope Trap(SemaRef);
  8492. ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
  8493. ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
  8494. if (!NewLB.isUsable() || !NewUB.isUsable())
  8495. return nullptr;
  8496. ExprResult CondExpr =
  8497. SemaRef.BuildBinOp(S, DefaultLoc,
  8498. *TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
  8499. : (TestIsStrictOp ? BO_GT : BO_GE),
  8500. NewLB.get(), NewUB.get());
  8501. if (CondExpr.isUsable()) {
  8502. if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
  8503. SemaRef.Context.BoolTy))
  8504. CondExpr = SemaRef.PerformImplicitConversion(
  8505. CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
  8506. /*AllowExplicit=*/true);
  8507. }
  8508. // Otherwise use original loop condition and evaluate it in runtime.
  8509. return CondExpr.isUsable() ? CondExpr.get() : Cond;
  8510. }
  8511. /// Build reference expression to the counter be used for codegen.
  8512. DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
  8513. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
  8514. DSAStackTy &DSA) const {
  8515. auto *VD = dyn_cast<VarDecl>(LCDecl);
  8516. if (!VD) {
  8517. VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
  8518. DeclRefExpr *Ref = buildDeclRefExpr(
  8519. SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
  8520. const DSAStackTy::DSAVarData Data =
  8521. DSA.getTopDSA(LCDecl, /*FromParent=*/false);
  8522. // If the loop control decl is explicitly marked as private, do not mark it
  8523. // as captured again.
  8524. if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
  8525. Captures.insert(std::make_pair(LCRef, Ref));
  8526. return Ref;
  8527. }
  8528. return cast<DeclRefExpr>(LCRef);
  8529. }
  8530. Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
  8531. if (LCDecl && !LCDecl->isInvalidDecl()) {
  8532. QualType Type = LCDecl->getType().getNonReferenceType();
  8533. VarDecl *PrivateVar = buildVarDecl(
  8534. SemaRef, DefaultLoc, Type, LCDecl->getName(),
  8535. LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
  8536. isa<VarDecl>(LCDecl)
  8537. ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
  8538. : nullptr);
  8539. if (PrivateVar->isInvalidDecl())
  8540. return nullptr;
  8541. return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
  8542. }
  8543. return nullptr;
  8544. }
  8545. /// Build initialization of the counter to be used for codegen.
  8546. Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
  8547. /// Build step of the counter be used for codegen.
  8548. Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
  8549. Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
  8550. Scope *S, Expr *Counter,
  8551. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
  8552. Expr *Inc, OverloadedOperatorKind OOK) {
  8553. Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
  8554. if (!Cnt)
  8555. return nullptr;
  8556. if (Inc) {
  8557. assert((OOK == OO_Plus || OOK == OO_Minus) &&
  8558. "Expected only + or - operations for depend clauses.");
  8559. BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
  8560. Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
  8561. if (!Cnt)
  8562. return nullptr;
  8563. }
  8564. QualType VarType = LCDecl->getType().getNonReferenceType();
  8565. if (!VarType->isIntegerType() && !VarType->isPointerType() &&
  8566. !SemaRef.getLangOpts().CPlusPlus)
  8567. return nullptr;
  8568. // Upper - Lower
  8569. Expr *Upper =
  8570. *TestIsLessOp ? Cnt : tryBuildCapture(SemaRef, LB, Captures).get();
  8571. Expr *Lower =
  8572. *TestIsLessOp ? tryBuildCapture(SemaRef, LB, Captures).get() : Cnt;
  8573. if (!Upper || !Lower)
  8574. return nullptr;
  8575. ExprResult Diff = calculateNumIters(
  8576. SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType,
  8577. /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures);
  8578. if (!Diff.isUsable())
  8579. return nullptr;
  8580. return Diff.get();
  8581. }
  8582. } // namespace
  8583. void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
  8584. assert(getLangOpts().OpenMP && "OpenMP is not active.");
  8585. assert(Init && "Expected loop in canonical form.");
  8586. unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
  8587. if (AssociatedLoops > 0 &&
  8588. isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
  8589. DSAStack->loopStart();
  8590. OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true,
  8591. *DSAStack, ForLoc);
  8592. if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
  8593. if (ValueDecl *D = ISC.getLoopDecl()) {
  8594. auto *VD = dyn_cast<VarDecl>(D);
  8595. DeclRefExpr *PrivateRef = nullptr;
  8596. if (!VD) {
  8597. if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
  8598. VD = Private;
  8599. } else {
  8600. PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
  8601. /*WithInit=*/false);
  8602. VD = cast<VarDecl>(PrivateRef->getDecl());
  8603. }
  8604. }
  8605. DSAStack->addLoopControlVariable(D, VD);
  8606. const Decl *LD = DSAStack->getPossiblyLoopCunter();
  8607. if (LD != D->getCanonicalDecl()) {
  8608. DSAStack->resetPossibleLoopCounter();
  8609. if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
  8610. MarkDeclarationsReferencedInExpr(
  8611. buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
  8612. Var->getType().getNonLValueExprType(Context),
  8613. ForLoc, /*RefersToCapture=*/true));
  8614. }
  8615. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  8616. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
  8617. // Referenced in a Construct, C/C++]. The loop iteration variable in the
  8618. // associated for-loop of a simd construct with just one associated
  8619. // for-loop may be listed in a linear clause with a constant-linear-step
  8620. // that is the increment of the associated for-loop. The loop iteration
  8621. // variable(s) in the associated for-loop(s) of a for or parallel for
  8622. // construct may be listed in a private or lastprivate clause.
  8623. DSAStackTy::DSAVarData DVar =
  8624. DSAStack->getTopDSA(D, /*FromParent=*/false);
  8625. // If LoopVarRefExpr is nullptr it means the corresponding loop variable
  8626. // is declared in the loop and it is predetermined as a private.
  8627. Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
  8628. OpenMPClauseKind PredeterminedCKind =
  8629. isOpenMPSimdDirective(DKind)
  8630. ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
  8631. : OMPC_private;
  8632. if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  8633. DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
  8634. (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
  8635. DVar.CKind != OMPC_private))) ||
  8636. ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
  8637. DKind == OMPD_master_taskloop || DKind == OMPD_masked_taskloop ||
  8638. DKind == OMPD_parallel_master_taskloop ||
  8639. DKind == OMPD_parallel_masked_taskloop ||
  8640. isOpenMPDistributeDirective(DKind)) &&
  8641. !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
  8642. DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
  8643. (DVar.CKind != OMPC_private || DVar.RefExpr)) {
  8644. Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
  8645. << getOpenMPClauseName(DVar.CKind)
  8646. << getOpenMPDirectiveName(DKind)
  8647. << getOpenMPClauseName(PredeterminedCKind);
  8648. if (DVar.RefExpr == nullptr)
  8649. DVar.CKind = PredeterminedCKind;
  8650. reportOriginalDsa(*this, DSAStack, D, DVar,
  8651. /*IsLoopIterVar=*/true);
  8652. } else if (LoopDeclRefExpr) {
  8653. // Make the loop iteration variable private (for worksharing
  8654. // constructs), linear (for simd directives with the only one
  8655. // associated loop) or lastprivate (for simd directives with several
  8656. // collapsed or ordered loops).
  8657. if (DVar.CKind == OMPC_unknown)
  8658. DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
  8659. PrivateRef);
  8660. }
  8661. }
  8662. }
  8663. DSAStack->setAssociatedLoops(AssociatedLoops - 1);
  8664. }
  8665. }
  8666. /// Called on a for stmt to check and extract its iteration space
  8667. /// for further processing (such as collapsing).
  8668. static bool checkOpenMPIterationSpace(
  8669. OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
  8670. unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
  8671. unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
  8672. Expr *OrderedLoopCountExpr,
  8673. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  8674. llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
  8675. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  8676. bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind);
  8677. // OpenMP [2.9.1, Canonical Loop Form]
  8678. // for (init-expr; test-expr; incr-expr) structured-block
  8679. // for (range-decl: range-expr) structured-block
  8680. if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S))
  8681. S = CanonLoop->getLoopStmt();
  8682. auto *For = dyn_cast_or_null<ForStmt>(S);
  8683. auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
  8684. // Ranged for is supported only in OpenMP 5.0.
  8685. if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
  8686. SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
  8687. << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
  8688. << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
  8689. << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
  8690. if (TotalNestedLoopCount > 1) {
  8691. if (CollapseLoopCountExpr && OrderedLoopCountExpr)
  8692. SemaRef.Diag(DSA.getConstructLoc(),
  8693. diag::note_omp_collapse_ordered_expr)
  8694. << 2 << CollapseLoopCountExpr->getSourceRange()
  8695. << OrderedLoopCountExpr->getSourceRange();
  8696. else if (CollapseLoopCountExpr)
  8697. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  8698. diag::note_omp_collapse_ordered_expr)
  8699. << 0 << CollapseLoopCountExpr->getSourceRange();
  8700. else
  8701. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  8702. diag::note_omp_collapse_ordered_expr)
  8703. << 1 << OrderedLoopCountExpr->getSourceRange();
  8704. }
  8705. return true;
  8706. }
  8707. assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
  8708. "No loop body.");
  8709. // Postpone analysis in dependent contexts for ranged for loops.
  8710. if (CXXFor && SemaRef.CurContext->isDependentContext())
  8711. return false;
  8712. OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA,
  8713. For ? For->getForLoc() : CXXFor->getForLoc());
  8714. // Check init.
  8715. Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
  8716. if (ISC.checkAndSetInit(Init))
  8717. return true;
  8718. bool HasErrors = false;
  8719. // Check loop variable's type.
  8720. if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
  8721. // OpenMP [2.6, Canonical Loop Form]
  8722. // Var is one of the following:
  8723. // A variable of signed or unsigned integer type.
  8724. // For C++, a variable of a random access iterator type.
  8725. // For C, a variable of a pointer type.
  8726. QualType VarType = LCDecl->getType().getNonReferenceType();
  8727. if (!VarType->isDependentType() && !VarType->isIntegerType() &&
  8728. !VarType->isPointerType() &&
  8729. !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
  8730. SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
  8731. << SemaRef.getLangOpts().CPlusPlus;
  8732. HasErrors = true;
  8733. }
  8734. // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
  8735. // a Construct
  8736. // The loop iteration variable(s) in the associated for-loop(s) of a for or
  8737. // parallel for construct is (are) private.
  8738. // The loop iteration variable in the associated for-loop of a simd
  8739. // construct with just one associated for-loop is linear with a
  8740. // constant-linear-step that is the increment of the associated for-loop.
  8741. // Exclude loop var from the list of variables with implicitly defined data
  8742. // sharing attributes.
  8743. VarsWithImplicitDSA.erase(LCDecl);
  8744. assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
  8745. // Check test-expr.
  8746. HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
  8747. // Check incr-expr.
  8748. HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
  8749. }
  8750. if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
  8751. return HasErrors;
  8752. // Build the loop's iteration space representation.
  8753. ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
  8754. DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
  8755. ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
  8756. ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
  8757. (isOpenMPWorksharingDirective(DKind) ||
  8758. isOpenMPGenericLoopDirective(DKind) ||
  8759. isOpenMPTaskLoopDirective(DKind) ||
  8760. isOpenMPDistributeDirective(DKind) ||
  8761. isOpenMPLoopTransformationDirective(DKind)),
  8762. Captures);
  8763. ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
  8764. ISC.buildCounterVar(Captures, DSA);
  8765. ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
  8766. ISC.buildPrivateCounterVar();
  8767. ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
  8768. ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
  8769. ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
  8770. ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
  8771. ISC.getConditionSrcRange();
  8772. ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
  8773. ISC.getIncrementSrcRange();
  8774. ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
  8775. ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
  8776. ISC.isStrictTestOp();
  8777. std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
  8778. ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
  8779. ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
  8780. ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
  8781. ISC.buildFinalCondition(DSA.getCurScope());
  8782. ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
  8783. ISC.doesInitDependOnLC();
  8784. ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
  8785. ISC.doesCondDependOnLC();
  8786. ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
  8787. ISC.getLoopDependentIdx();
  8788. HasErrors |=
  8789. (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
  8790. ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
  8791. ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
  8792. ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
  8793. ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
  8794. ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
  8795. if (!HasErrors && DSA.isOrderedRegion()) {
  8796. if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
  8797. if (CurrentNestedLoopCount <
  8798. DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
  8799. DSA.getOrderedRegionParam().second->setLoopNumIterations(
  8800. CurrentNestedLoopCount,
  8801. ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
  8802. DSA.getOrderedRegionParam().second->setLoopCounter(
  8803. CurrentNestedLoopCount,
  8804. ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
  8805. }
  8806. }
  8807. for (auto &Pair : DSA.getDoacrossDependClauses()) {
  8808. if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
  8809. // Erroneous case - clause has some problems.
  8810. continue;
  8811. }
  8812. if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
  8813. Pair.second.size() <= CurrentNestedLoopCount) {
  8814. // Erroneous case - clause has some problems.
  8815. Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
  8816. continue;
  8817. }
  8818. Expr *CntValue;
  8819. if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
  8820. CntValue = ISC.buildOrderedLoopData(
  8821. DSA.getCurScope(),
  8822. ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
  8823. Pair.first->getDependencyLoc());
  8824. else
  8825. CntValue = ISC.buildOrderedLoopData(
  8826. DSA.getCurScope(),
  8827. ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
  8828. Pair.first->getDependencyLoc(),
  8829. Pair.second[CurrentNestedLoopCount].first,
  8830. Pair.second[CurrentNestedLoopCount].second);
  8831. Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
  8832. }
  8833. }
  8834. return HasErrors;
  8835. }
  8836. /// Build 'VarRef = Start.
  8837. static ExprResult
  8838. buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  8839. ExprResult Start, bool IsNonRectangularLB,
  8840. llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  8841. // Build 'VarRef = Start.
  8842. ExprResult NewStart = IsNonRectangularLB
  8843. ? Start.get()
  8844. : tryBuildCapture(SemaRef, Start.get(), Captures);
  8845. if (!NewStart.isUsable())
  8846. return ExprError();
  8847. if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
  8848. VarRef.get()->getType())) {
  8849. NewStart = SemaRef.PerformImplicitConversion(
  8850. NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
  8851. /*AllowExplicit=*/true);
  8852. if (!NewStart.isUsable())
  8853. return ExprError();
  8854. }
  8855. ExprResult Init =
  8856. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  8857. return Init;
  8858. }
  8859. /// Build 'VarRef = Start + Iter * Step'.
  8860. static ExprResult buildCounterUpdate(
  8861. Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
  8862. ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
  8863. bool IsNonRectangularLB,
  8864. llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
  8865. // Add parentheses (for debugging purposes only).
  8866. Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
  8867. if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
  8868. !Step.isUsable())
  8869. return ExprError();
  8870. ExprResult NewStep = Step;
  8871. if (Captures)
  8872. NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
  8873. if (NewStep.isInvalid())
  8874. return ExprError();
  8875. ExprResult Update =
  8876. SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
  8877. if (!Update.isUsable())
  8878. return ExprError();
  8879. // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
  8880. // 'VarRef = Start (+|-) Iter * Step'.
  8881. if (!Start.isUsable())
  8882. return ExprError();
  8883. ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
  8884. if (!NewStart.isUsable())
  8885. return ExprError();
  8886. if (Captures && !IsNonRectangularLB)
  8887. NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
  8888. if (NewStart.isInvalid())
  8889. return ExprError();
  8890. // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
  8891. ExprResult SavedUpdate = Update;
  8892. ExprResult UpdateVal;
  8893. if (VarRef.get()->getType()->isOverloadableType() ||
  8894. NewStart.get()->getType()->isOverloadableType() ||
  8895. Update.get()->getType()->isOverloadableType()) {
  8896. Sema::TentativeAnalysisScope Trap(SemaRef);
  8897. Update =
  8898. SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
  8899. if (Update.isUsable()) {
  8900. UpdateVal =
  8901. SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
  8902. VarRef.get(), SavedUpdate.get());
  8903. if (UpdateVal.isUsable()) {
  8904. Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
  8905. UpdateVal.get());
  8906. }
  8907. }
  8908. }
  8909. // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
  8910. if (!Update.isUsable() || !UpdateVal.isUsable()) {
  8911. Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
  8912. NewStart.get(), SavedUpdate.get());
  8913. if (!Update.isUsable())
  8914. return ExprError();
  8915. if (!SemaRef.Context.hasSameType(Update.get()->getType(),
  8916. VarRef.get()->getType())) {
  8917. Update = SemaRef.PerformImplicitConversion(
  8918. Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
  8919. if (!Update.isUsable())
  8920. return ExprError();
  8921. }
  8922. Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
  8923. }
  8924. return Update;
  8925. }
  8926. /// Convert integer expression \a E to make it have at least \a Bits
  8927. /// bits.
  8928. static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
  8929. if (E == nullptr)
  8930. return ExprError();
  8931. ASTContext &C = SemaRef.Context;
  8932. QualType OldType = E->getType();
  8933. unsigned HasBits = C.getTypeSize(OldType);
  8934. if (HasBits >= Bits)
  8935. return ExprResult(E);
  8936. // OK to convert to signed, because new type has more bits than old.
  8937. QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
  8938. return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
  8939. true);
  8940. }
  8941. /// Check if the given expression \a E is a constant integer that fits
  8942. /// into \a Bits bits.
  8943. static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
  8944. if (E == nullptr)
  8945. return false;
  8946. if (std::optional<llvm::APSInt> Result =
  8947. E->getIntegerConstantExpr(SemaRef.Context))
  8948. return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits);
  8949. return false;
  8950. }
  8951. /// Build preinits statement for the given declarations.
  8952. static Stmt *buildPreInits(ASTContext &Context,
  8953. MutableArrayRef<Decl *> PreInits) {
  8954. if (!PreInits.empty()) {
  8955. return new (Context) DeclStmt(
  8956. DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
  8957. SourceLocation(), SourceLocation());
  8958. }
  8959. return nullptr;
  8960. }
  8961. /// Build preinits statement for the given declarations.
  8962. static Stmt *
  8963. buildPreInits(ASTContext &Context,
  8964. const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
  8965. if (!Captures.empty()) {
  8966. SmallVector<Decl *, 16> PreInits;
  8967. for (const auto &Pair : Captures)
  8968. PreInits.push_back(Pair.second->getDecl());
  8969. return buildPreInits(Context, PreInits);
  8970. }
  8971. return nullptr;
  8972. }
  8973. /// Build postupdate expression for the given list of postupdates expressions.
  8974. static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
  8975. Expr *PostUpdate = nullptr;
  8976. if (!PostUpdates.empty()) {
  8977. for (Expr *E : PostUpdates) {
  8978. Expr *ConvE = S.BuildCStyleCastExpr(
  8979. E->getExprLoc(),
  8980. S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
  8981. E->getExprLoc(), E)
  8982. .get();
  8983. PostUpdate = PostUpdate
  8984. ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
  8985. PostUpdate, ConvE)
  8986. .get()
  8987. : ConvE;
  8988. }
  8989. }
  8990. return PostUpdate;
  8991. }
  8992. /// Called on a for stmt to check itself and nested loops (if any).
  8993. /// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
  8994. /// number of collapsed loops otherwise.
  8995. static unsigned
  8996. checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
  8997. Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
  8998. DSAStackTy &DSA,
  8999. Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
  9000. OMPLoopBasedDirective::HelperExprs &Built) {
  9001. unsigned NestedLoopCount = 1;
  9002. bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) &&
  9003. !isOpenMPLoopTransformationDirective(DKind);
  9004. if (CollapseLoopCountExpr) {
  9005. // Found 'collapse' clause - calculate collapse number.
  9006. Expr::EvalResult Result;
  9007. if (!CollapseLoopCountExpr->isValueDependent() &&
  9008. CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
  9009. NestedLoopCount = Result.Val.getInt().getLimitedValue();
  9010. } else {
  9011. Built.clear(/*Size=*/1);
  9012. return 1;
  9013. }
  9014. }
  9015. unsigned OrderedLoopCount = 1;
  9016. if (OrderedLoopCountExpr) {
  9017. // Found 'ordered' clause - calculate collapse number.
  9018. Expr::EvalResult EVResult;
  9019. if (!OrderedLoopCountExpr->isValueDependent() &&
  9020. OrderedLoopCountExpr->EvaluateAsInt(EVResult,
  9021. SemaRef.getASTContext())) {
  9022. llvm::APSInt Result = EVResult.Val.getInt();
  9023. if (Result.getLimitedValue() < NestedLoopCount) {
  9024. SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
  9025. diag::err_omp_wrong_ordered_loop_count)
  9026. << OrderedLoopCountExpr->getSourceRange();
  9027. SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
  9028. diag::note_collapse_loop_count)
  9029. << CollapseLoopCountExpr->getSourceRange();
  9030. }
  9031. OrderedLoopCount = Result.getLimitedValue();
  9032. } else {
  9033. Built.clear(/*Size=*/1);
  9034. return 1;
  9035. }
  9036. }
  9037. // This is helper routine for loop directives (e.g., 'for', 'simd',
  9038. // 'for simd', etc.).
  9039. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  9040. unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount);
  9041. SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops);
  9042. if (!OMPLoopBasedDirective::doForAllLoops(
  9043. AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)),
  9044. SupportsNonPerfectlyNested, NumLoops,
  9045. [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount,
  9046. CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA,
  9047. &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) {
  9048. if (checkOpenMPIterationSpace(
  9049. DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
  9050. NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr,
  9051. VarsWithImplicitDSA, IterSpaces, Captures))
  9052. return true;
  9053. if (Cnt > 0 && Cnt >= NestedLoopCount &&
  9054. IterSpaces[Cnt].CounterVar) {
  9055. // Handle initialization of captured loop iterator variables.
  9056. auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
  9057. if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
  9058. Captures[DRE] = DRE;
  9059. }
  9060. }
  9061. return false;
  9062. },
  9063. [&SemaRef, &Captures](OMPLoopTransformationDirective *Transform) {
  9064. Stmt *DependentPreInits = Transform->getPreInits();
  9065. if (!DependentPreInits)
  9066. return;
  9067. for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) {
  9068. auto *D = cast<VarDecl>(C);
  9069. DeclRefExpr *Ref = buildDeclRefExpr(SemaRef, D, D->getType(),
  9070. Transform->getBeginLoc());
  9071. Captures[Ref] = Ref;
  9072. }
  9073. }))
  9074. return 0;
  9075. Built.clear(/* size */ NestedLoopCount);
  9076. if (SemaRef.CurContext->isDependentContext())
  9077. return NestedLoopCount;
  9078. // An example of what is generated for the following code:
  9079. //
  9080. // #pragma omp simd collapse(2) ordered(2)
  9081. // for (i = 0; i < NI; ++i)
  9082. // for (k = 0; k < NK; ++k)
  9083. // for (j = J0; j < NJ; j+=2) {
  9084. // <loop body>
  9085. // }
  9086. //
  9087. // We generate the code below.
  9088. // Note: the loop body may be outlined in CodeGen.
  9089. // Note: some counters may be C++ classes, operator- is used to find number of
  9090. // iterations and operator+= to calculate counter value.
  9091. // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
  9092. // or i64 is currently supported).
  9093. //
  9094. // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
  9095. // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
  9096. // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
  9097. // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
  9098. // // similar updates for vars in clauses (e.g. 'linear')
  9099. // <loop body (using local i and j)>
  9100. // }
  9101. // i = NI; // assign final values of counters
  9102. // j = NJ;
  9103. //
  9104. // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
  9105. // the iteration counts of the collapsed for loops.
  9106. // Precondition tests if there is at least one iteration (all conditions are
  9107. // true).
  9108. auto PreCond = ExprResult(IterSpaces[0].PreCond);
  9109. Expr *N0 = IterSpaces[0].NumIterations;
  9110. ExprResult LastIteration32 =
  9111. widenIterationCount(/*Bits=*/32,
  9112. SemaRef
  9113. .PerformImplicitConversion(
  9114. N0->IgnoreImpCasts(), N0->getType(),
  9115. Sema::AA_Converting, /*AllowExplicit=*/true)
  9116. .get(),
  9117. SemaRef);
  9118. ExprResult LastIteration64 = widenIterationCount(
  9119. /*Bits=*/64,
  9120. SemaRef
  9121. .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
  9122. Sema::AA_Converting,
  9123. /*AllowExplicit=*/true)
  9124. .get(),
  9125. SemaRef);
  9126. if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
  9127. return NestedLoopCount;
  9128. ASTContext &C = SemaRef.Context;
  9129. bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
  9130. Scope *CurScope = DSA.getCurScope();
  9131. for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
  9132. if (PreCond.isUsable()) {
  9133. PreCond =
  9134. SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
  9135. PreCond.get(), IterSpaces[Cnt].PreCond);
  9136. }
  9137. Expr *N = IterSpaces[Cnt].NumIterations;
  9138. SourceLocation Loc = N->getExprLoc();
  9139. AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
  9140. if (LastIteration32.isUsable())
  9141. LastIteration32 = SemaRef.BuildBinOp(
  9142. CurScope, Loc, BO_Mul, LastIteration32.get(),
  9143. SemaRef
  9144. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  9145. Sema::AA_Converting,
  9146. /*AllowExplicit=*/true)
  9147. .get());
  9148. if (LastIteration64.isUsable())
  9149. LastIteration64 = SemaRef.BuildBinOp(
  9150. CurScope, Loc, BO_Mul, LastIteration64.get(),
  9151. SemaRef
  9152. .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
  9153. Sema::AA_Converting,
  9154. /*AllowExplicit=*/true)
  9155. .get());
  9156. }
  9157. // Choose either the 32-bit or 64-bit version.
  9158. ExprResult LastIteration = LastIteration64;
  9159. if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
  9160. (LastIteration32.isUsable() &&
  9161. C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
  9162. (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
  9163. fitsInto(
  9164. /*Bits=*/32,
  9165. LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
  9166. LastIteration64.get(), SemaRef))))
  9167. LastIteration = LastIteration32;
  9168. QualType VType = LastIteration.get()->getType();
  9169. QualType RealVType = VType;
  9170. QualType StrideVType = VType;
  9171. if (isOpenMPTaskLoopDirective(DKind)) {
  9172. VType =
  9173. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
  9174. StrideVType =
  9175. SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
  9176. }
  9177. if (!LastIteration.isUsable())
  9178. return 0;
  9179. // Save the number of iterations.
  9180. ExprResult NumIterations = LastIteration;
  9181. {
  9182. LastIteration = SemaRef.BuildBinOp(
  9183. CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
  9184. LastIteration.get(),
  9185. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  9186. if (!LastIteration.isUsable())
  9187. return 0;
  9188. }
  9189. // Calculate the last iteration number beforehand instead of doing this on
  9190. // each iteration. Do not do this if the number of iterations may be kfold-ed.
  9191. bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context);
  9192. ExprResult CalcLastIteration;
  9193. if (!IsConstant) {
  9194. ExprResult SaveRef =
  9195. tryBuildCapture(SemaRef, LastIteration.get(), Captures);
  9196. LastIteration = SaveRef;
  9197. // Prepare SaveRef + 1.
  9198. NumIterations = SemaRef.BuildBinOp(
  9199. CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
  9200. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
  9201. if (!NumIterations.isUsable())
  9202. return 0;
  9203. }
  9204. SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
  9205. // Build variables passed into runtime, necessary for worksharing directives.
  9206. ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
  9207. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  9208. isOpenMPDistributeDirective(DKind) ||
  9209. isOpenMPGenericLoopDirective(DKind) ||
  9210. isOpenMPLoopTransformationDirective(DKind)) {
  9211. // Lower bound variable, initialized with zero.
  9212. VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
  9213. LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
  9214. SemaRef.AddInitializerToDecl(LBDecl,
  9215. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  9216. /*DirectInit*/ false);
  9217. // Upper bound variable, initialized with last iteration number.
  9218. VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
  9219. UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
  9220. SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
  9221. /*DirectInit*/ false);
  9222. // A 32-bit variable-flag where runtime returns 1 for the last iteration.
  9223. // This will be used to implement clause 'lastprivate'.
  9224. QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
  9225. VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
  9226. IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
  9227. SemaRef.AddInitializerToDecl(ILDecl,
  9228. SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  9229. /*DirectInit*/ false);
  9230. // Stride variable returned by runtime (we initialize it to 1 by default).
  9231. VarDecl *STDecl =
  9232. buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
  9233. ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
  9234. SemaRef.AddInitializerToDecl(STDecl,
  9235. SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
  9236. /*DirectInit*/ false);
  9237. // Build expression: UB = min(UB, LastIteration)
  9238. // It is necessary for CodeGen of directives with static scheduling.
  9239. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
  9240. UB.get(), LastIteration.get());
  9241. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  9242. LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
  9243. LastIteration.get(), UB.get());
  9244. EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
  9245. CondOp.get());
  9246. EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
  9247. // If we have a combined directive that combines 'distribute', 'for' or
  9248. // 'simd' we need to be able to access the bounds of the schedule of the
  9249. // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
  9250. // by scheduling 'distribute' have to be passed to the schedule of 'for'.
  9251. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  9252. // Lower bound variable, initialized with zero.
  9253. VarDecl *CombLBDecl =
  9254. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
  9255. CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
  9256. SemaRef.AddInitializerToDecl(
  9257. CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
  9258. /*DirectInit*/ false);
  9259. // Upper bound variable, initialized with last iteration number.
  9260. VarDecl *CombUBDecl =
  9261. buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
  9262. CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
  9263. SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
  9264. /*DirectInit*/ false);
  9265. ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
  9266. CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
  9267. ExprResult CombCondOp =
  9268. SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
  9269. LastIteration.get(), CombUB.get());
  9270. CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
  9271. CombCondOp.get());
  9272. CombEUB =
  9273. SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
  9274. const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
  9275. // We expect to have at least 2 more parameters than the 'parallel'
  9276. // directive does - the lower and upper bounds of the previous schedule.
  9277. assert(CD->getNumParams() >= 4 &&
  9278. "Unexpected number of parameters in loop combined directive");
  9279. // Set the proper type for the bounds given what we learned from the
  9280. // enclosed loops.
  9281. ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
  9282. ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
  9283. // Previous lower and upper bounds are obtained from the region
  9284. // parameters.
  9285. PrevLB =
  9286. buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
  9287. PrevUB =
  9288. buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
  9289. }
  9290. }
  9291. // Build the iteration variable and its initialization before loop.
  9292. ExprResult IV;
  9293. ExprResult Init, CombInit;
  9294. {
  9295. VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
  9296. IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
  9297. Expr *RHS = (isOpenMPWorksharingDirective(DKind) ||
  9298. isOpenMPGenericLoopDirective(DKind) ||
  9299. isOpenMPTaskLoopDirective(DKind) ||
  9300. isOpenMPDistributeDirective(DKind) ||
  9301. isOpenMPLoopTransformationDirective(DKind))
  9302. ? LB.get()
  9303. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  9304. Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
  9305. Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
  9306. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  9307. Expr *CombRHS =
  9308. (isOpenMPWorksharingDirective(DKind) ||
  9309. isOpenMPGenericLoopDirective(DKind) ||
  9310. isOpenMPTaskLoopDirective(DKind) ||
  9311. isOpenMPDistributeDirective(DKind))
  9312. ? CombLB.get()
  9313. : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
  9314. CombInit =
  9315. SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
  9316. CombInit =
  9317. SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
  9318. }
  9319. }
  9320. bool UseStrictCompare =
  9321. RealVType->hasUnsignedIntegerRepresentation() &&
  9322. llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
  9323. return LIS.IsStrictCompare;
  9324. });
  9325. // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
  9326. // unsigned IV)) for worksharing loops.
  9327. SourceLocation CondLoc = AStmt->getBeginLoc();
  9328. Expr *BoundUB = UB.get();
  9329. if (UseStrictCompare) {
  9330. BoundUB =
  9331. SemaRef
  9332. .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
  9333. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  9334. .get();
  9335. BoundUB =
  9336. SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
  9337. }
  9338. ExprResult Cond =
  9339. (isOpenMPWorksharingDirective(DKind) ||
  9340. isOpenMPGenericLoopDirective(DKind) ||
  9341. isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) ||
  9342. isOpenMPLoopTransformationDirective(DKind))
  9343. ? SemaRef.BuildBinOp(CurScope, CondLoc,
  9344. UseStrictCompare ? BO_LT : BO_LE, IV.get(),
  9345. BoundUB)
  9346. : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  9347. NumIterations.get());
  9348. ExprResult CombDistCond;
  9349. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  9350. CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
  9351. NumIterations.get());
  9352. }
  9353. ExprResult CombCond;
  9354. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  9355. Expr *BoundCombUB = CombUB.get();
  9356. if (UseStrictCompare) {
  9357. BoundCombUB =
  9358. SemaRef
  9359. .BuildBinOp(
  9360. CurScope, CondLoc, BO_Add, BoundCombUB,
  9361. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  9362. .get();
  9363. BoundCombUB =
  9364. SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
  9365. .get();
  9366. }
  9367. CombCond =
  9368. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  9369. IV.get(), BoundCombUB);
  9370. }
  9371. // Loop increment (IV = IV + 1)
  9372. SourceLocation IncLoc = AStmt->getBeginLoc();
  9373. ExprResult Inc =
  9374. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
  9375. SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
  9376. if (!Inc.isUsable())
  9377. return 0;
  9378. Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
  9379. Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
  9380. if (!Inc.isUsable())
  9381. return 0;
  9382. // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
  9383. // Used for directives with static scheduling.
  9384. // In combined construct, add combined version that use CombLB and CombUB
  9385. // base variables for the update
  9386. ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
  9387. if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
  9388. isOpenMPGenericLoopDirective(DKind) ||
  9389. isOpenMPDistributeDirective(DKind) ||
  9390. isOpenMPLoopTransformationDirective(DKind)) {
  9391. // LB + ST
  9392. NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
  9393. if (!NextLB.isUsable())
  9394. return 0;
  9395. // LB = LB + ST
  9396. NextLB =
  9397. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
  9398. NextLB =
  9399. SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
  9400. if (!NextLB.isUsable())
  9401. return 0;
  9402. // UB + ST
  9403. NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
  9404. if (!NextUB.isUsable())
  9405. return 0;
  9406. // UB = UB + ST
  9407. NextUB =
  9408. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
  9409. NextUB =
  9410. SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
  9411. if (!NextUB.isUsable())
  9412. return 0;
  9413. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  9414. CombNextLB =
  9415. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
  9416. if (!NextLB.isUsable())
  9417. return 0;
  9418. // LB = LB + ST
  9419. CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
  9420. CombNextLB.get());
  9421. CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
  9422. /*DiscardedValue*/ false);
  9423. if (!CombNextLB.isUsable())
  9424. return 0;
  9425. // UB + ST
  9426. CombNextUB =
  9427. SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
  9428. if (!CombNextUB.isUsable())
  9429. return 0;
  9430. // UB = UB + ST
  9431. CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
  9432. CombNextUB.get());
  9433. CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
  9434. /*DiscardedValue*/ false);
  9435. if (!CombNextUB.isUsable())
  9436. return 0;
  9437. }
  9438. }
  9439. // Create increment expression for distribute loop when combined in a same
  9440. // directive with for as IV = IV + ST; ensure upper bound expression based
  9441. // on PrevUB instead of NumIterations - used to implement 'for' when found
  9442. // in combination with 'distribute', like in 'distribute parallel for'
  9443. SourceLocation DistIncLoc = AStmt->getBeginLoc();
  9444. ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
  9445. if (isOpenMPLoopBoundSharingDirective(DKind)) {
  9446. DistCond = SemaRef.BuildBinOp(
  9447. CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
  9448. assert(DistCond.isUsable() && "distribute cond expr was not built");
  9449. DistInc =
  9450. SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
  9451. assert(DistInc.isUsable() && "distribute inc expr was not built");
  9452. DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
  9453. DistInc.get());
  9454. DistInc =
  9455. SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
  9456. assert(DistInc.isUsable() && "distribute inc expr was not built");
  9457. // Build expression: UB = min(UB, prevUB) for #for in composite or combined
  9458. // construct
  9459. ExprResult NewPrevUB = PrevUB;
  9460. SourceLocation DistEUBLoc = AStmt->getBeginLoc();
  9461. if (!SemaRef.Context.hasSameType(UB.get()->getType(),
  9462. PrevUB.get()->getType())) {
  9463. NewPrevUB = SemaRef.BuildCStyleCastExpr(
  9464. DistEUBLoc,
  9465. SemaRef.Context.getTrivialTypeSourceInfo(UB.get()->getType()),
  9466. DistEUBLoc, NewPrevUB.get());
  9467. if (!NewPrevUB.isUsable())
  9468. return 0;
  9469. }
  9470. ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT,
  9471. UB.get(), NewPrevUB.get());
  9472. ExprResult CondOp = SemaRef.ActOnConditionalOp(
  9473. DistEUBLoc, DistEUBLoc, IsUBGreater.get(), NewPrevUB.get(), UB.get());
  9474. PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
  9475. CondOp.get());
  9476. PrevEUB =
  9477. SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
  9478. // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
  9479. // parallel for is in combination with a distribute directive with
  9480. // schedule(static, 1)
  9481. Expr *BoundPrevUB = PrevUB.get();
  9482. if (UseStrictCompare) {
  9483. BoundPrevUB =
  9484. SemaRef
  9485. .BuildBinOp(
  9486. CurScope, CondLoc, BO_Add, BoundPrevUB,
  9487. SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
  9488. .get();
  9489. BoundPrevUB =
  9490. SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
  9491. .get();
  9492. }
  9493. ParForInDistCond =
  9494. SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
  9495. IV.get(), BoundPrevUB);
  9496. }
  9497. // Build updates and final values of the loop counters.
  9498. bool HasErrors = false;
  9499. Built.Counters.resize(NestedLoopCount);
  9500. Built.Inits.resize(NestedLoopCount);
  9501. Built.Updates.resize(NestedLoopCount);
  9502. Built.Finals.resize(NestedLoopCount);
  9503. Built.DependentCounters.resize(NestedLoopCount);
  9504. Built.DependentInits.resize(NestedLoopCount);
  9505. Built.FinalsConditions.resize(NestedLoopCount);
  9506. {
  9507. // We implement the following algorithm for obtaining the
  9508. // original loop iteration variable values based on the
  9509. // value of the collapsed loop iteration variable IV.
  9510. //
  9511. // Let n+1 be the number of collapsed loops in the nest.
  9512. // Iteration variables (I0, I1, .... In)
  9513. // Iteration counts (N0, N1, ... Nn)
  9514. //
  9515. // Acc = IV;
  9516. //
  9517. // To compute Ik for loop k, 0 <= k <= n, generate:
  9518. // Prod = N(k+1) * N(k+2) * ... * Nn;
  9519. // Ik = Acc / Prod;
  9520. // Acc -= Ik * Prod;
  9521. //
  9522. ExprResult Acc = IV;
  9523. for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
  9524. LoopIterationSpace &IS = IterSpaces[Cnt];
  9525. SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
  9526. ExprResult Iter;
  9527. // Compute prod
  9528. ExprResult Prod = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  9529. for (unsigned int K = Cnt + 1; K < NestedLoopCount; ++K)
  9530. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
  9531. IterSpaces[K].NumIterations);
  9532. // Iter = Acc / Prod
  9533. // If there is at least one more inner loop to avoid
  9534. // multiplication by 1.
  9535. if (Cnt + 1 < NestedLoopCount)
  9536. Iter =
  9537. SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, Acc.get(), Prod.get());
  9538. else
  9539. Iter = Acc;
  9540. if (!Iter.isUsable()) {
  9541. HasErrors = true;
  9542. break;
  9543. }
  9544. // Update Acc:
  9545. // Acc -= Iter * Prod
  9546. // Check if there is at least one more inner loop to avoid
  9547. // multiplication by 1.
  9548. if (Cnt + 1 < NestedLoopCount)
  9549. Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Iter.get(),
  9550. Prod.get());
  9551. else
  9552. Prod = Iter;
  9553. Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, Acc.get(), Prod.get());
  9554. // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
  9555. auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
  9556. DeclRefExpr *CounterVar = buildDeclRefExpr(
  9557. SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
  9558. /*RefersToCapture=*/true);
  9559. ExprResult Init =
  9560. buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
  9561. IS.CounterInit, IS.IsNonRectangularLB, Captures);
  9562. if (!Init.isUsable()) {
  9563. HasErrors = true;
  9564. break;
  9565. }
  9566. ExprResult Update = buildCounterUpdate(
  9567. SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
  9568. IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
  9569. if (!Update.isUsable()) {
  9570. HasErrors = true;
  9571. break;
  9572. }
  9573. // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
  9574. ExprResult Final =
  9575. buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
  9576. IS.CounterInit, IS.NumIterations, IS.CounterStep,
  9577. IS.Subtract, IS.IsNonRectangularLB, &Captures);
  9578. if (!Final.isUsable()) {
  9579. HasErrors = true;
  9580. break;
  9581. }
  9582. if (!Update.isUsable() || !Final.isUsable()) {
  9583. HasErrors = true;
  9584. break;
  9585. }
  9586. // Save results
  9587. Built.Counters[Cnt] = IS.CounterVar;
  9588. Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
  9589. Built.Inits[Cnt] = Init.get();
  9590. Built.Updates[Cnt] = Update.get();
  9591. Built.Finals[Cnt] = Final.get();
  9592. Built.DependentCounters[Cnt] = nullptr;
  9593. Built.DependentInits[Cnt] = nullptr;
  9594. Built.FinalsConditions[Cnt] = nullptr;
  9595. if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
  9596. Built.DependentCounters[Cnt] =
  9597. Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
  9598. Built.DependentInits[Cnt] =
  9599. Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
  9600. Built.FinalsConditions[Cnt] = IS.FinalCondition;
  9601. }
  9602. }
  9603. }
  9604. if (HasErrors)
  9605. return 0;
  9606. // Save results
  9607. Built.IterationVarRef = IV.get();
  9608. Built.LastIteration = LastIteration.get();
  9609. Built.NumIterations = NumIterations.get();
  9610. Built.CalcLastIteration = SemaRef
  9611. .ActOnFinishFullExpr(CalcLastIteration.get(),
  9612. /*DiscardedValue=*/false)
  9613. .get();
  9614. Built.PreCond = PreCond.get();
  9615. Built.PreInits = buildPreInits(C, Captures);
  9616. Built.Cond = Cond.get();
  9617. Built.Init = Init.get();
  9618. Built.Inc = Inc.get();
  9619. Built.LB = LB.get();
  9620. Built.UB = UB.get();
  9621. Built.IL = IL.get();
  9622. Built.ST = ST.get();
  9623. Built.EUB = EUB.get();
  9624. Built.NLB = NextLB.get();
  9625. Built.NUB = NextUB.get();
  9626. Built.PrevLB = PrevLB.get();
  9627. Built.PrevUB = PrevUB.get();
  9628. Built.DistInc = DistInc.get();
  9629. Built.PrevEUB = PrevEUB.get();
  9630. Built.DistCombinedFields.LB = CombLB.get();
  9631. Built.DistCombinedFields.UB = CombUB.get();
  9632. Built.DistCombinedFields.EUB = CombEUB.get();
  9633. Built.DistCombinedFields.Init = CombInit.get();
  9634. Built.DistCombinedFields.Cond = CombCond.get();
  9635. Built.DistCombinedFields.NLB = CombNextLB.get();
  9636. Built.DistCombinedFields.NUB = CombNextUB.get();
  9637. Built.DistCombinedFields.DistCond = CombDistCond.get();
  9638. Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
  9639. return NestedLoopCount;
  9640. }
  9641. static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
  9642. auto CollapseClauses =
  9643. OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
  9644. if (CollapseClauses.begin() != CollapseClauses.end())
  9645. return (*CollapseClauses.begin())->getNumForLoops();
  9646. return nullptr;
  9647. }
  9648. static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
  9649. auto OrderedClauses =
  9650. OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
  9651. if (OrderedClauses.begin() != OrderedClauses.end())
  9652. return (*OrderedClauses.begin())->getNumForLoops();
  9653. return nullptr;
  9654. }
  9655. static bool checkSimdlenSafelenSpecified(Sema &S,
  9656. const ArrayRef<OMPClause *> Clauses) {
  9657. const OMPSafelenClause *Safelen = nullptr;
  9658. const OMPSimdlenClause *Simdlen = nullptr;
  9659. for (const OMPClause *Clause : Clauses) {
  9660. if (Clause->getClauseKind() == OMPC_safelen)
  9661. Safelen = cast<OMPSafelenClause>(Clause);
  9662. else if (Clause->getClauseKind() == OMPC_simdlen)
  9663. Simdlen = cast<OMPSimdlenClause>(Clause);
  9664. if (Safelen && Simdlen)
  9665. break;
  9666. }
  9667. if (Simdlen && Safelen) {
  9668. const Expr *SimdlenLength = Simdlen->getSimdlen();
  9669. const Expr *SafelenLength = Safelen->getSafelen();
  9670. if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
  9671. SimdlenLength->isInstantiationDependent() ||
  9672. SimdlenLength->containsUnexpandedParameterPack())
  9673. return false;
  9674. if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
  9675. SafelenLength->isInstantiationDependent() ||
  9676. SafelenLength->containsUnexpandedParameterPack())
  9677. return false;
  9678. Expr::EvalResult SimdlenResult, SafelenResult;
  9679. SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
  9680. SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
  9681. llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
  9682. llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
  9683. // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
  9684. // If both simdlen and safelen clauses are specified, the value of the
  9685. // simdlen parameter must be less than or equal to the value of the safelen
  9686. // parameter.
  9687. if (SimdlenRes > SafelenRes) {
  9688. S.Diag(SimdlenLength->getExprLoc(),
  9689. diag::err_omp_wrong_simdlen_safelen_values)
  9690. << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
  9691. return true;
  9692. }
  9693. }
  9694. return false;
  9695. }
  9696. StmtResult
  9697. Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  9698. SourceLocation StartLoc, SourceLocation EndLoc,
  9699. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9700. if (!AStmt)
  9701. return StmtError();
  9702. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  9703. OMPLoopBasedDirective::HelperExprs B;
  9704. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  9705. // define the nested loops number.
  9706. unsigned NestedLoopCount = checkOpenMPLoop(
  9707. OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  9708. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  9709. if (NestedLoopCount == 0)
  9710. return StmtError();
  9711. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9712. "omp simd loop exprs were not built");
  9713. if (!CurContext->isDependentContext()) {
  9714. // Finalize the clauses that need pre-built expressions for CodeGen.
  9715. for (OMPClause *C : Clauses) {
  9716. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9717. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9718. B.NumIterations, *this, CurScope,
  9719. DSAStack))
  9720. return StmtError();
  9721. }
  9722. }
  9723. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9724. return StmtError();
  9725. setFunctionHasBranchProtectedScope();
  9726. return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  9727. Clauses, AStmt, B);
  9728. }
  9729. StmtResult
  9730. Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
  9731. SourceLocation StartLoc, SourceLocation EndLoc,
  9732. VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9733. if (!AStmt)
  9734. return StmtError();
  9735. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  9736. OMPLoopBasedDirective::HelperExprs B;
  9737. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  9738. // define the nested loops number.
  9739. unsigned NestedLoopCount = checkOpenMPLoop(
  9740. OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  9741. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  9742. if (NestedLoopCount == 0)
  9743. return StmtError();
  9744. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9745. "omp for loop exprs were not built");
  9746. if (!CurContext->isDependentContext()) {
  9747. // Finalize the clauses that need pre-built expressions for CodeGen.
  9748. for (OMPClause *C : Clauses) {
  9749. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9750. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9751. B.NumIterations, *this, CurScope,
  9752. DSAStack))
  9753. return StmtError();
  9754. }
  9755. }
  9756. setFunctionHasBranchProtectedScope();
  9757. return OMPForDirective::Create(
  9758. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  9759. DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
  9760. }
  9761. StmtResult Sema::ActOnOpenMPForSimdDirective(
  9762. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9763. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9764. if (!AStmt)
  9765. return StmtError();
  9766. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  9767. OMPLoopBasedDirective::HelperExprs B;
  9768. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  9769. // define the nested loops number.
  9770. unsigned NestedLoopCount =
  9771. checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
  9772. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  9773. VarsWithImplicitDSA, B);
  9774. if (NestedLoopCount == 0)
  9775. return StmtError();
  9776. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9777. "omp for simd loop exprs were not built");
  9778. if (!CurContext->isDependentContext()) {
  9779. // Finalize the clauses that need pre-built expressions for CodeGen.
  9780. for (OMPClause *C : Clauses) {
  9781. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  9782. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  9783. B.NumIterations, *this, CurScope,
  9784. DSAStack))
  9785. return StmtError();
  9786. }
  9787. }
  9788. if (checkSimdlenSafelenSpecified(*this, Clauses))
  9789. return StmtError();
  9790. setFunctionHasBranchProtectedScope();
  9791. return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
  9792. Clauses, AStmt, B);
  9793. }
  9794. StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
  9795. Stmt *AStmt,
  9796. SourceLocation StartLoc,
  9797. SourceLocation EndLoc) {
  9798. if (!AStmt)
  9799. return StmtError();
  9800. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  9801. auto BaseStmt = AStmt;
  9802. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  9803. BaseStmt = CS->getCapturedStmt();
  9804. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  9805. auto S = C->children();
  9806. if (S.begin() == S.end())
  9807. return StmtError();
  9808. // All associated statements must be '#pragma omp section' except for
  9809. // the first one.
  9810. for (Stmt *SectionStmt : llvm::drop_begin(S)) {
  9811. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  9812. if (SectionStmt)
  9813. Diag(SectionStmt->getBeginLoc(),
  9814. diag::err_omp_sections_substmt_not_section);
  9815. return StmtError();
  9816. }
  9817. cast<OMPSectionDirective>(SectionStmt)
  9818. ->setHasCancel(DSAStack->isCancelRegion());
  9819. }
  9820. } else {
  9821. Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
  9822. return StmtError();
  9823. }
  9824. setFunctionHasBranchProtectedScope();
  9825. return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  9826. DSAStack->getTaskgroupReductionRef(),
  9827. DSAStack->isCancelRegion());
  9828. }
  9829. StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
  9830. SourceLocation StartLoc,
  9831. SourceLocation EndLoc) {
  9832. if (!AStmt)
  9833. return StmtError();
  9834. setFunctionHasBranchProtectedScope();
  9835. DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
  9836. return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
  9837. DSAStack->isCancelRegion());
  9838. }
  9839. static Expr *getDirectCallExpr(Expr *E) {
  9840. E = E->IgnoreParenCasts()->IgnoreImplicit();
  9841. if (auto *CE = dyn_cast<CallExpr>(E))
  9842. if (CE->getDirectCallee())
  9843. return E;
  9844. return nullptr;
  9845. }
  9846. StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
  9847. Stmt *AStmt,
  9848. SourceLocation StartLoc,
  9849. SourceLocation EndLoc) {
  9850. if (!AStmt)
  9851. return StmtError();
  9852. Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt();
  9853. // 5.1 OpenMP
  9854. // expression-stmt : an expression statement with one of the following forms:
  9855. // expression = target-call ( [expression-list] );
  9856. // target-call ( [expression-list] );
  9857. SourceLocation TargetCallLoc;
  9858. if (!CurContext->isDependentContext()) {
  9859. Expr *TargetCall = nullptr;
  9860. auto *E = dyn_cast<Expr>(S);
  9861. if (!E) {
  9862. Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call);
  9863. return StmtError();
  9864. }
  9865. E = E->IgnoreParenCasts()->IgnoreImplicit();
  9866. if (auto *BO = dyn_cast<BinaryOperator>(E)) {
  9867. if (BO->getOpcode() == BO_Assign)
  9868. TargetCall = getDirectCallExpr(BO->getRHS());
  9869. } else {
  9870. if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E))
  9871. if (COCE->getOperator() == OO_Equal)
  9872. TargetCall = getDirectCallExpr(COCE->getArg(1));
  9873. if (!TargetCall)
  9874. TargetCall = getDirectCallExpr(E);
  9875. }
  9876. if (!TargetCall) {
  9877. Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call);
  9878. return StmtError();
  9879. }
  9880. TargetCallLoc = TargetCall->getExprLoc();
  9881. }
  9882. setFunctionHasBranchProtectedScope();
  9883. return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  9884. TargetCallLoc);
  9885. }
  9886. static bool checkGenericLoopLastprivate(Sema &S, ArrayRef<OMPClause *> Clauses,
  9887. OpenMPDirectiveKind K,
  9888. DSAStackTy *Stack) {
  9889. bool ErrorFound = false;
  9890. for (OMPClause *C : Clauses) {
  9891. if (auto *LPC = dyn_cast<OMPLastprivateClause>(C)) {
  9892. for (Expr *RefExpr : LPC->varlists()) {
  9893. SourceLocation ELoc;
  9894. SourceRange ERange;
  9895. Expr *SimpleRefExpr = RefExpr;
  9896. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
  9897. if (ValueDecl *D = Res.first) {
  9898. auto &&Info = Stack->isLoopControlVariable(D);
  9899. if (!Info.first) {
  9900. S.Diag(ELoc, diag::err_omp_lastprivate_loop_var_non_loop_iteration)
  9901. << getOpenMPDirectiveName(K);
  9902. ErrorFound = true;
  9903. }
  9904. }
  9905. }
  9906. }
  9907. }
  9908. return ErrorFound;
  9909. }
  9910. StmtResult Sema::ActOnOpenMPGenericLoopDirective(
  9911. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9912. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9913. if (!AStmt)
  9914. return StmtError();
  9915. // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
  9916. // A list item may not appear in a lastprivate clause unless it is the
  9917. // loop iteration variable of a loop that is associated with the construct.
  9918. if (checkGenericLoopLastprivate(*this, Clauses, OMPD_loop, DSAStack))
  9919. return StmtError();
  9920. auto *CS = cast<CapturedStmt>(AStmt);
  9921. // 1.2.2 OpenMP Language Terminology
  9922. // Structured block - An executable statement with a single entry at the
  9923. // top and a single exit at the bottom.
  9924. // The point of exit cannot be a branch out of the structured block.
  9925. // longjmp() and throw() must not violate the entry/exit criteria.
  9926. CS->getCapturedDecl()->setNothrow();
  9927. OMPLoopDirective::HelperExprs B;
  9928. // In presence of clause 'collapse', it will define the nested loops number.
  9929. unsigned NestedLoopCount = checkOpenMPLoop(
  9930. OMPD_loop, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
  9931. AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
  9932. if (NestedLoopCount == 0)
  9933. return StmtError();
  9934. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9935. "omp loop exprs were not built");
  9936. setFunctionHasBranchProtectedScope();
  9937. return OMPGenericLoopDirective::Create(Context, StartLoc, EndLoc,
  9938. NestedLoopCount, Clauses, AStmt, B);
  9939. }
  9940. StmtResult Sema::ActOnOpenMPTeamsGenericLoopDirective(
  9941. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9942. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9943. if (!AStmt)
  9944. return StmtError();
  9945. // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
  9946. // A list item may not appear in a lastprivate clause unless it is the
  9947. // loop iteration variable of a loop that is associated with the construct.
  9948. if (checkGenericLoopLastprivate(*this, Clauses, OMPD_teams_loop, DSAStack))
  9949. return StmtError();
  9950. auto *CS = cast<CapturedStmt>(AStmt);
  9951. // 1.2.2 OpenMP Language Terminology
  9952. // Structured block - An executable statement with a single entry at the
  9953. // top and a single exit at the bottom.
  9954. // The point of exit cannot be a branch out of the structured block.
  9955. // longjmp() and throw() must not violate the entry/exit criteria.
  9956. CS->getCapturedDecl()->setNothrow();
  9957. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_loop);
  9958. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  9959. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  9960. // 1.2.2 OpenMP Language Terminology
  9961. // Structured block - An executable statement with a single entry at the
  9962. // top and a single exit at the bottom.
  9963. // The point of exit cannot be a branch out of the structured block.
  9964. // longjmp() and throw() must not violate the entry/exit criteria.
  9965. CS->getCapturedDecl()->setNothrow();
  9966. }
  9967. OMPLoopDirective::HelperExprs B;
  9968. // In presence of clause 'collapse', it will define the nested loops number.
  9969. unsigned NestedLoopCount =
  9970. checkOpenMPLoop(OMPD_teams_loop, getCollapseNumberExpr(Clauses),
  9971. /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
  9972. VarsWithImplicitDSA, B);
  9973. if (NestedLoopCount == 0)
  9974. return StmtError();
  9975. assert((CurContext->isDependentContext() || B.builtAll()) &&
  9976. "omp loop exprs were not built");
  9977. setFunctionHasBranchProtectedScope();
  9978. DSAStack->setParentTeamsRegionLoc(StartLoc);
  9979. return OMPTeamsGenericLoopDirective::Create(
  9980. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  9981. }
  9982. StmtResult Sema::ActOnOpenMPTargetTeamsGenericLoopDirective(
  9983. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  9984. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  9985. if (!AStmt)
  9986. return StmtError();
  9987. // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
  9988. // A list item may not appear in a lastprivate clause unless it is the
  9989. // loop iteration variable of a loop that is associated with the construct.
  9990. if (checkGenericLoopLastprivate(*this, Clauses, OMPD_target_teams_loop,
  9991. DSAStack))
  9992. return StmtError();
  9993. auto *CS = cast<CapturedStmt>(AStmt);
  9994. // 1.2.2 OpenMP Language Terminology
  9995. // Structured block - An executable statement with a single entry at the
  9996. // top and a single exit at the bottom.
  9997. // The point of exit cannot be a branch out of the structured block.
  9998. // longjmp() and throw() must not violate the entry/exit criteria.
  9999. CS->getCapturedDecl()->setNothrow();
  10000. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams_loop);
  10001. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  10002. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  10003. // 1.2.2 OpenMP Language Terminology
  10004. // Structured block - An executable statement with a single entry at the
  10005. // top and a single exit at the bottom.
  10006. // The point of exit cannot be a branch out of the structured block.
  10007. // longjmp() and throw() must not violate the entry/exit criteria.
  10008. CS->getCapturedDecl()->setNothrow();
  10009. }
  10010. OMPLoopDirective::HelperExprs B;
  10011. // In presence of clause 'collapse', it will define the nested loops number.
  10012. unsigned NestedLoopCount =
  10013. checkOpenMPLoop(OMPD_target_teams_loop, getCollapseNumberExpr(Clauses),
  10014. /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
  10015. VarsWithImplicitDSA, B);
  10016. if (NestedLoopCount == 0)
  10017. return StmtError();
  10018. assert((CurContext->isDependentContext() || B.builtAll()) &&
  10019. "omp loop exprs were not built");
  10020. setFunctionHasBranchProtectedScope();
  10021. return OMPTargetTeamsGenericLoopDirective::Create(
  10022. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  10023. }
  10024. StmtResult Sema::ActOnOpenMPParallelGenericLoopDirective(
  10025. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  10026. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  10027. if (!AStmt)
  10028. return StmtError();
  10029. // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
  10030. // A list item may not appear in a lastprivate clause unless it is the
  10031. // loop iteration variable of a loop that is associated with the construct.
  10032. if (checkGenericLoopLastprivate(*this, Clauses, OMPD_parallel_loop, DSAStack))
  10033. return StmtError();
  10034. auto *CS = cast<CapturedStmt>(AStmt);
  10035. // 1.2.2 OpenMP Language Terminology
  10036. // Structured block - An executable statement with a single entry at the
  10037. // top and a single exit at the bottom.
  10038. // The point of exit cannot be a branch out of the structured block.
  10039. // longjmp() and throw() must not violate the entry/exit criteria.
  10040. CS->getCapturedDecl()->setNothrow();
  10041. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_parallel_loop);
  10042. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  10043. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  10044. // 1.2.2 OpenMP Language Terminology
  10045. // Structured block - An executable statement with a single entry at the
  10046. // top and a single exit at the bottom.
  10047. // The point of exit cannot be a branch out of the structured block.
  10048. // longjmp() and throw() must not violate the entry/exit criteria.
  10049. CS->getCapturedDecl()->setNothrow();
  10050. }
  10051. OMPLoopDirective::HelperExprs B;
  10052. // In presence of clause 'collapse', it will define the nested loops number.
  10053. unsigned NestedLoopCount =
  10054. checkOpenMPLoop(OMPD_parallel_loop, getCollapseNumberExpr(Clauses),
  10055. /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
  10056. VarsWithImplicitDSA, B);
  10057. if (NestedLoopCount == 0)
  10058. return StmtError();
  10059. assert((CurContext->isDependentContext() || B.builtAll()) &&
  10060. "omp loop exprs were not built");
  10061. setFunctionHasBranchProtectedScope();
  10062. return OMPParallelGenericLoopDirective::Create(
  10063. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  10064. }
  10065. StmtResult Sema::ActOnOpenMPTargetParallelGenericLoopDirective(
  10066. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  10067. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  10068. if (!AStmt)
  10069. return StmtError();
  10070. // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
  10071. // A list item may not appear in a lastprivate clause unless it is the
  10072. // loop iteration variable of a loop that is associated with the construct.
  10073. if (checkGenericLoopLastprivate(*this, Clauses, OMPD_target_parallel_loop,
  10074. DSAStack))
  10075. return StmtError();
  10076. auto *CS = cast<CapturedStmt>(AStmt);
  10077. // 1.2.2 OpenMP Language Terminology
  10078. // Structured block - An executable statement with a single entry at the
  10079. // top and a single exit at the bottom.
  10080. // The point of exit cannot be a branch out of the structured block.
  10081. // longjmp() and throw() must not violate the entry/exit criteria.
  10082. CS->getCapturedDecl()->setNothrow();
  10083. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_loop);
  10084. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  10085. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  10086. // 1.2.2 OpenMP Language Terminology
  10087. // Structured block - An executable statement with a single entry at the
  10088. // top and a single exit at the bottom.
  10089. // The point of exit cannot be a branch out of the structured block.
  10090. // longjmp() and throw() must not violate the entry/exit criteria.
  10091. CS->getCapturedDecl()->setNothrow();
  10092. }
  10093. OMPLoopDirective::HelperExprs B;
  10094. // In presence of clause 'collapse', it will define the nested loops number.
  10095. unsigned NestedLoopCount =
  10096. checkOpenMPLoop(OMPD_target_parallel_loop, getCollapseNumberExpr(Clauses),
  10097. /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
  10098. VarsWithImplicitDSA, B);
  10099. if (NestedLoopCount == 0)
  10100. return StmtError();
  10101. assert((CurContext->isDependentContext() || B.builtAll()) &&
  10102. "omp loop exprs were not built");
  10103. setFunctionHasBranchProtectedScope();
  10104. return OMPTargetParallelGenericLoopDirective::Create(
  10105. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  10106. }
  10107. StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
  10108. Stmt *AStmt,
  10109. SourceLocation StartLoc,
  10110. SourceLocation EndLoc) {
  10111. if (!AStmt)
  10112. return StmtError();
  10113. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  10114. setFunctionHasBranchProtectedScope();
  10115. // OpenMP [2.7.3, single Construct, Restrictions]
  10116. // The copyprivate clause must not be used with the nowait clause.
  10117. const OMPClause *Nowait = nullptr;
  10118. const OMPClause *Copyprivate = nullptr;
  10119. for (const OMPClause *Clause : Clauses) {
  10120. if (Clause->getClauseKind() == OMPC_nowait)
  10121. Nowait = Clause;
  10122. else if (Clause->getClauseKind() == OMPC_copyprivate)
  10123. Copyprivate = Clause;
  10124. if (Copyprivate && Nowait) {
  10125. Diag(Copyprivate->getBeginLoc(),
  10126. diag::err_omp_single_copyprivate_with_nowait);
  10127. Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
  10128. return StmtError();
  10129. }
  10130. }
  10131. return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  10132. }
  10133. StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
  10134. SourceLocation StartLoc,
  10135. SourceLocation EndLoc) {
  10136. if (!AStmt)
  10137. return StmtError();
  10138. setFunctionHasBranchProtectedScope();
  10139. return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
  10140. }
  10141. StmtResult Sema::ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
  10142. Stmt *AStmt,
  10143. SourceLocation StartLoc,
  10144. SourceLocation EndLoc) {
  10145. if (!AStmt)
  10146. return StmtError();
  10147. setFunctionHasBranchProtectedScope();
  10148. return OMPMaskedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  10149. }
  10150. StmtResult Sema::ActOnOpenMPCriticalDirective(
  10151. const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
  10152. Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
  10153. if (!AStmt)
  10154. return StmtError();
  10155. bool ErrorFound = false;
  10156. llvm::APSInt Hint;
  10157. SourceLocation HintLoc;
  10158. bool DependentHint = false;
  10159. for (const OMPClause *C : Clauses) {
  10160. if (C->getClauseKind() == OMPC_hint) {
  10161. if (!DirName.getName()) {
  10162. Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
  10163. ErrorFound = true;
  10164. }
  10165. Expr *E = cast<OMPHintClause>(C)->getHint();
  10166. if (E->isTypeDependent() || E->isValueDependent() ||
  10167. E->isInstantiationDependent()) {
  10168. DependentHint = true;
  10169. } else {
  10170. Hint = E->EvaluateKnownConstInt(Context);
  10171. HintLoc = C->getBeginLoc();
  10172. }
  10173. }
  10174. }
  10175. if (ErrorFound)
  10176. return StmtError();
  10177. const auto Pair = DSAStack->getCriticalWithHint(DirName);
  10178. if (Pair.first && DirName.getName() && !DependentHint) {
  10179. if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
  10180. Diag(StartLoc, diag::err_omp_critical_with_hint);
  10181. if (HintLoc.isValid())
  10182. Diag(HintLoc, diag::note_omp_critical_hint_here)
  10183. << 0 << toString(Hint, /*Radix=*/10, /*Signed=*/false);
  10184. else
  10185. Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
  10186. if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
  10187. Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
  10188. << 1
  10189. << toString(C->getHint()->EvaluateKnownConstInt(Context),
  10190. /*Radix=*/10, /*Signed=*/false);
  10191. } else {
  10192. Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
  10193. }
  10194. }
  10195. }
  10196. setFunctionHasBranchProtectedScope();
  10197. auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
  10198. Clauses, AStmt);
  10199. if (!Pair.first && DirName.getName() && !DependentHint)
  10200. DSAStack->addCriticalWithHint(Dir, Hint);
  10201. return Dir;
  10202. }
  10203. StmtResult Sema::ActOnOpenMPParallelForDirective(
  10204. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  10205. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  10206. if (!AStmt)
  10207. return StmtError();
  10208. auto *CS = cast<CapturedStmt>(AStmt);
  10209. // 1.2.2 OpenMP Language Terminology
  10210. // Structured block - An executable statement with a single entry at the
  10211. // top and a single exit at the bottom.
  10212. // The point of exit cannot be a branch out of the structured block.
  10213. // longjmp() and throw() must not violate the entry/exit criteria.
  10214. CS->getCapturedDecl()->setNothrow();
  10215. OMPLoopBasedDirective::HelperExprs B;
  10216. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  10217. // define the nested loops number.
  10218. unsigned NestedLoopCount =
  10219. checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
  10220. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  10221. VarsWithImplicitDSA, B);
  10222. if (NestedLoopCount == 0)
  10223. return StmtError();
  10224. assert((CurContext->isDependentContext() || B.builtAll()) &&
  10225. "omp parallel for loop exprs were not built");
  10226. if (!CurContext->isDependentContext()) {
  10227. // Finalize the clauses that need pre-built expressions for CodeGen.
  10228. for (OMPClause *C : Clauses) {
  10229. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  10230. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  10231. B.NumIterations, *this, CurScope,
  10232. DSAStack))
  10233. return StmtError();
  10234. }
  10235. }
  10236. setFunctionHasBranchProtectedScope();
  10237. return OMPParallelForDirective::Create(
  10238. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  10239. DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
  10240. }
  10241. StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
  10242. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  10243. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  10244. if (!AStmt)
  10245. return StmtError();
  10246. auto *CS = cast<CapturedStmt>(AStmt);
  10247. // 1.2.2 OpenMP Language Terminology
  10248. // Structured block - An executable statement with a single entry at the
  10249. // top and a single exit at the bottom.
  10250. // The point of exit cannot be a branch out of the structured block.
  10251. // longjmp() and throw() must not violate the entry/exit criteria.
  10252. CS->getCapturedDecl()->setNothrow();
  10253. OMPLoopBasedDirective::HelperExprs B;
  10254. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  10255. // define the nested loops number.
  10256. unsigned NestedLoopCount =
  10257. checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
  10258. getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
  10259. VarsWithImplicitDSA, B);
  10260. if (NestedLoopCount == 0)
  10261. return StmtError();
  10262. if (!CurContext->isDependentContext()) {
  10263. // Finalize the clauses that need pre-built expressions for CodeGen.
  10264. for (OMPClause *C : Clauses) {
  10265. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  10266. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  10267. B.NumIterations, *this, CurScope,
  10268. DSAStack))
  10269. return StmtError();
  10270. }
  10271. }
  10272. if (checkSimdlenSafelenSpecified(*this, Clauses))
  10273. return StmtError();
  10274. setFunctionHasBranchProtectedScope();
  10275. return OMPParallelForSimdDirective::Create(
  10276. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  10277. }
  10278. StmtResult
  10279. Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
  10280. Stmt *AStmt, SourceLocation StartLoc,
  10281. SourceLocation EndLoc) {
  10282. if (!AStmt)
  10283. return StmtError();
  10284. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  10285. auto *CS = cast<CapturedStmt>(AStmt);
  10286. // 1.2.2 OpenMP Language Terminology
  10287. // Structured block - An executable statement with a single entry at the
  10288. // top and a single exit at the bottom.
  10289. // The point of exit cannot be a branch out of the structured block.
  10290. // longjmp() and throw() must not violate the entry/exit criteria.
  10291. CS->getCapturedDecl()->setNothrow();
  10292. setFunctionHasBranchProtectedScope();
  10293. return OMPParallelMasterDirective::Create(
  10294. Context, StartLoc, EndLoc, Clauses, AStmt,
  10295. DSAStack->getTaskgroupReductionRef());
  10296. }
  10297. StmtResult
  10298. Sema::ActOnOpenMPParallelMaskedDirective(ArrayRef<OMPClause *> Clauses,
  10299. Stmt *AStmt, SourceLocation StartLoc,
  10300. SourceLocation EndLoc) {
  10301. if (!AStmt)
  10302. return StmtError();
  10303. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  10304. auto *CS = cast<CapturedStmt>(AStmt);
  10305. // 1.2.2 OpenMP Language Terminology
  10306. // Structured block - An executable statement with a single entry at the
  10307. // top and a single exit at the bottom.
  10308. // The point of exit cannot be a branch out of the structured block.
  10309. // longjmp() and throw() must not violate the entry/exit criteria.
  10310. CS->getCapturedDecl()->setNothrow();
  10311. setFunctionHasBranchProtectedScope();
  10312. return OMPParallelMaskedDirective::Create(
  10313. Context, StartLoc, EndLoc, Clauses, AStmt,
  10314. DSAStack->getTaskgroupReductionRef());
  10315. }
  10316. StmtResult
  10317. Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
  10318. Stmt *AStmt, SourceLocation StartLoc,
  10319. SourceLocation EndLoc) {
  10320. if (!AStmt)
  10321. return StmtError();
  10322. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  10323. auto BaseStmt = AStmt;
  10324. while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
  10325. BaseStmt = CS->getCapturedStmt();
  10326. if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
  10327. auto S = C->children();
  10328. if (S.begin() == S.end())
  10329. return StmtError();
  10330. // All associated statements must be '#pragma omp section' except for
  10331. // the first one.
  10332. for (Stmt *SectionStmt : llvm::drop_begin(S)) {
  10333. if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
  10334. if (SectionStmt)
  10335. Diag(SectionStmt->getBeginLoc(),
  10336. diag::err_omp_parallel_sections_substmt_not_section);
  10337. return StmtError();
  10338. }
  10339. cast<OMPSectionDirective>(SectionStmt)
  10340. ->setHasCancel(DSAStack->isCancelRegion());
  10341. }
  10342. } else {
  10343. Diag(AStmt->getBeginLoc(),
  10344. diag::err_omp_parallel_sections_not_compound_stmt);
  10345. return StmtError();
  10346. }
  10347. setFunctionHasBranchProtectedScope();
  10348. return OMPParallelSectionsDirective::Create(
  10349. Context, StartLoc, EndLoc, Clauses, AStmt,
  10350. DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
  10351. }
  10352. /// Find and diagnose mutually exclusive clause kinds.
  10353. static bool checkMutuallyExclusiveClauses(
  10354. Sema &S, ArrayRef<OMPClause *> Clauses,
  10355. ArrayRef<OpenMPClauseKind> MutuallyExclusiveClauses) {
  10356. const OMPClause *PrevClause = nullptr;
  10357. bool ErrorFound = false;
  10358. for (const OMPClause *C : Clauses) {
  10359. if (llvm::is_contained(MutuallyExclusiveClauses, C->getClauseKind())) {
  10360. if (!PrevClause) {
  10361. PrevClause = C;
  10362. } else if (PrevClause->getClauseKind() != C->getClauseKind()) {
  10363. S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive)
  10364. << getOpenMPClauseName(C->getClauseKind())
  10365. << getOpenMPClauseName(PrevClause->getClauseKind());
  10366. S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause)
  10367. << getOpenMPClauseName(PrevClause->getClauseKind());
  10368. ErrorFound = true;
  10369. }
  10370. }
  10371. }
  10372. return ErrorFound;
  10373. }
  10374. StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
  10375. Stmt *AStmt, SourceLocation StartLoc,
  10376. SourceLocation EndLoc) {
  10377. if (!AStmt)
  10378. return StmtError();
  10379. // OpenMP 5.0, 2.10.1 task Construct
  10380. // If a detach clause appears on the directive, then a mergeable clause cannot
  10381. // appear on the same directive.
  10382. if (checkMutuallyExclusiveClauses(*this, Clauses,
  10383. {OMPC_detach, OMPC_mergeable}))
  10384. return StmtError();
  10385. auto *CS = cast<CapturedStmt>(AStmt);
  10386. // 1.2.2 OpenMP Language Terminology
  10387. // Structured block - An executable statement with a single entry at the
  10388. // top and a single exit at the bottom.
  10389. // The point of exit cannot be a branch out of the structured block.
  10390. // longjmp() and throw() must not violate the entry/exit criteria.
  10391. CS->getCapturedDecl()->setNothrow();
  10392. setFunctionHasBranchProtectedScope();
  10393. return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  10394. DSAStack->isCancelRegion());
  10395. }
  10396. StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
  10397. SourceLocation EndLoc) {
  10398. return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
  10399. }
  10400. StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
  10401. SourceLocation EndLoc) {
  10402. return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
  10403. }
  10404. StmtResult Sema::ActOnOpenMPErrorDirective(ArrayRef<OMPClause *> Clauses,
  10405. SourceLocation StartLoc,
  10406. SourceLocation EndLoc,
  10407. bool InExContext) {
  10408. const OMPAtClause *AtC =
  10409. OMPExecutableDirective::getSingleClause<OMPAtClause>(Clauses);
  10410. if (AtC && !InExContext && AtC->getAtKind() == OMPC_AT_execution) {
  10411. Diag(AtC->getAtKindKwLoc(), diag::err_omp_unexpected_execution_modifier);
  10412. return StmtError();
  10413. }
  10414. const OMPSeverityClause *SeverityC =
  10415. OMPExecutableDirective::getSingleClause<OMPSeverityClause>(Clauses);
  10416. const OMPMessageClause *MessageC =
  10417. OMPExecutableDirective::getSingleClause<OMPMessageClause>(Clauses);
  10418. Expr *ME = MessageC ? MessageC->getMessageString() : nullptr;
  10419. if (!AtC || AtC->getAtKind() == OMPC_AT_compilation) {
  10420. if (SeverityC && SeverityC->getSeverityKind() == OMPC_SEVERITY_warning)
  10421. Diag(SeverityC->getSeverityKindKwLoc(), diag::warn_diagnose_if_succeeded)
  10422. << (ME ? cast<StringLiteral>(ME)->getString() : "WARNING");
  10423. else
  10424. Diag(StartLoc, diag::err_diagnose_if_succeeded)
  10425. << (ME ? cast<StringLiteral>(ME)->getString() : "ERROR");
  10426. if (!SeverityC || SeverityC->getSeverityKind() != OMPC_SEVERITY_warning)
  10427. return StmtError();
  10428. }
  10429. return OMPErrorDirective::Create(Context, StartLoc, EndLoc, Clauses);
  10430. }
  10431. StmtResult Sema::ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses,
  10432. SourceLocation StartLoc,
  10433. SourceLocation EndLoc) {
  10434. const OMPNowaitClause *NowaitC =
  10435. OMPExecutableDirective::getSingleClause<OMPNowaitClause>(Clauses);
  10436. bool HasDependC =
  10437. !OMPExecutableDirective::getClausesOfKind<OMPDependClause>(Clauses)
  10438. .empty();
  10439. if (NowaitC && !HasDependC) {
  10440. Diag(StartLoc, diag::err_omp_nowait_clause_without_depend);
  10441. return StmtError();
  10442. }
  10443. return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc, Clauses);
  10444. }
  10445. StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
  10446. Stmt *AStmt,
  10447. SourceLocation StartLoc,
  10448. SourceLocation EndLoc) {
  10449. if (!AStmt)
  10450. return StmtError();
  10451. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  10452. setFunctionHasBranchProtectedScope();
  10453. return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
  10454. AStmt,
  10455. DSAStack->getTaskgroupReductionRef());
  10456. }
  10457. StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
  10458. SourceLocation StartLoc,
  10459. SourceLocation EndLoc) {
  10460. OMPFlushClause *FC = nullptr;
  10461. OMPClause *OrderClause = nullptr;
  10462. for (OMPClause *C : Clauses) {
  10463. if (C->getClauseKind() == OMPC_flush)
  10464. FC = cast<OMPFlushClause>(C);
  10465. else
  10466. OrderClause = C;
  10467. }
  10468. OpenMPClauseKind MemOrderKind = OMPC_unknown;
  10469. SourceLocation MemOrderLoc;
  10470. for (const OMPClause *C : Clauses) {
  10471. if (C->getClauseKind() == OMPC_acq_rel ||
  10472. C->getClauseKind() == OMPC_acquire ||
  10473. C->getClauseKind() == OMPC_release) {
  10474. if (MemOrderKind != OMPC_unknown) {
  10475. Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
  10476. << getOpenMPDirectiveName(OMPD_flush) << 1
  10477. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  10478. Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
  10479. << getOpenMPClauseName(MemOrderKind);
  10480. } else {
  10481. MemOrderKind = C->getClauseKind();
  10482. MemOrderLoc = C->getBeginLoc();
  10483. }
  10484. }
  10485. }
  10486. if (FC && OrderClause) {
  10487. Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list)
  10488. << getOpenMPClauseName(OrderClause->getClauseKind());
  10489. Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here)
  10490. << getOpenMPClauseName(OrderClause->getClauseKind());
  10491. return StmtError();
  10492. }
  10493. return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
  10494. }
  10495. StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
  10496. SourceLocation StartLoc,
  10497. SourceLocation EndLoc) {
  10498. if (Clauses.empty()) {
  10499. Diag(StartLoc, diag::err_omp_depobj_expected);
  10500. return StmtError();
  10501. } else if (Clauses[0]->getClauseKind() != OMPC_depobj) {
  10502. Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected);
  10503. return StmtError();
  10504. }
  10505. // Only depobj expression and another single clause is allowed.
  10506. if (Clauses.size() > 2) {
  10507. Diag(Clauses[2]->getBeginLoc(),
  10508. diag::err_omp_depobj_single_clause_expected);
  10509. return StmtError();
  10510. } else if (Clauses.size() < 1) {
  10511. Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected);
  10512. return StmtError();
  10513. }
  10514. return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses);
  10515. }
  10516. StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
  10517. SourceLocation StartLoc,
  10518. SourceLocation EndLoc) {
  10519. // Check that exactly one clause is specified.
  10520. if (Clauses.size() != 1) {
  10521. Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(),
  10522. diag::err_omp_scan_single_clause_expected);
  10523. return StmtError();
  10524. }
  10525. // Check that scan directive is used in the scopeof the OpenMP loop body.
  10526. if (Scope *S = DSAStack->getCurScope()) {
  10527. Scope *ParentS = S->getParent();
  10528. if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() ||
  10529. !ParentS->getBreakParent()->isOpenMPLoopScope())
  10530. return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive)
  10531. << getOpenMPDirectiveName(OMPD_scan) << 5);
  10532. }
  10533. // Check that only one instance of scan directives is used in the same outer
  10534. // region.
  10535. if (DSAStack->doesParentHasScanDirective()) {
  10536. Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan";
  10537. Diag(DSAStack->getParentScanDirectiveLoc(),
  10538. diag::note_omp_previous_directive)
  10539. << "scan";
  10540. return StmtError();
  10541. }
  10542. DSAStack->setParentHasScanDirective(StartLoc);
  10543. return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses);
  10544. }
  10545. StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
  10546. Stmt *AStmt,
  10547. SourceLocation StartLoc,
  10548. SourceLocation EndLoc) {
  10549. const OMPClause *DependFound = nullptr;
  10550. const OMPClause *DependSourceClause = nullptr;
  10551. const OMPClause *DependSinkClause = nullptr;
  10552. bool ErrorFound = false;
  10553. const OMPThreadsClause *TC = nullptr;
  10554. const OMPSIMDClause *SC = nullptr;
  10555. for (const OMPClause *C : Clauses) {
  10556. if (auto *DC = dyn_cast<OMPDependClause>(C)) {
  10557. DependFound = C;
  10558. if (DC->getDependencyKind() == OMPC_DEPEND_source) {
  10559. if (DependSourceClause) {
  10560. Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
  10561. << getOpenMPDirectiveName(OMPD_ordered)
  10562. << getOpenMPClauseName(OMPC_depend) << 2;
  10563. ErrorFound = true;
  10564. } else {
  10565. DependSourceClause = C;
  10566. }
  10567. if (DependSinkClause) {
  10568. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  10569. << 0;
  10570. ErrorFound = true;
  10571. }
  10572. } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
  10573. if (DependSourceClause) {
  10574. Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
  10575. << 1;
  10576. ErrorFound = true;
  10577. }
  10578. DependSinkClause = C;
  10579. }
  10580. } else if (C->getClauseKind() == OMPC_threads) {
  10581. TC = cast<OMPThreadsClause>(C);
  10582. } else if (C->getClauseKind() == OMPC_simd) {
  10583. SC = cast<OMPSIMDClause>(C);
  10584. }
  10585. }
  10586. if (!ErrorFound && !SC &&
  10587. isOpenMPSimdDirective(DSAStack->getParentDirective())) {
  10588. // OpenMP [2.8.1,simd Construct, Restrictions]
  10589. // An ordered construct with the simd clause is the only OpenMP construct
  10590. // that can appear in the simd region.
  10591. Diag(StartLoc, diag::err_omp_prohibited_region_simd)
  10592. << (LangOpts.OpenMP >= 50 ? 1 : 0);
  10593. ErrorFound = true;
  10594. } else if (DependFound && (TC || SC)) {
  10595. Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
  10596. << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
  10597. ErrorFound = true;
  10598. } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
  10599. Diag(DependFound->getBeginLoc(),
  10600. diag::err_omp_ordered_directive_without_param);
  10601. ErrorFound = true;
  10602. } else if (TC || Clauses.empty()) {
  10603. if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
  10604. SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
  10605. Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
  10606. << (TC != nullptr);
  10607. Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
  10608. ErrorFound = true;
  10609. }
  10610. }
  10611. if ((!AStmt && !DependFound) || ErrorFound)
  10612. return StmtError();
  10613. // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions.
  10614. // During execution of an iteration of a worksharing-loop or a loop nest
  10615. // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread
  10616. // must not execute more than one ordered region corresponding to an ordered
  10617. // construct without a depend clause.
  10618. if (!DependFound) {
  10619. if (DSAStack->doesParentHasOrderedDirective()) {
  10620. Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered";
  10621. Diag(DSAStack->getParentOrderedDirectiveLoc(),
  10622. diag::note_omp_previous_directive)
  10623. << "ordered";
  10624. return StmtError();
  10625. }
  10626. DSAStack->setParentHasOrderedDirective(StartLoc);
  10627. }
  10628. if (AStmt) {
  10629. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  10630. setFunctionHasBranchProtectedScope();
  10631. }
  10632. return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  10633. }
  10634. namespace {
  10635. /// Helper class for checking expression in 'omp atomic [update]'
  10636. /// construct.
  10637. class OpenMPAtomicUpdateChecker {
  10638. /// Error results for atomic update expressions.
  10639. enum ExprAnalysisErrorCode {
  10640. /// A statement is not an expression statement.
  10641. NotAnExpression,
  10642. /// Expression is not builtin binary or unary operation.
  10643. NotABinaryOrUnaryExpression,
  10644. /// Unary operation is not post-/pre- increment/decrement operation.
  10645. NotAnUnaryIncDecExpression,
  10646. /// An expression is not of scalar type.
  10647. NotAScalarType,
  10648. /// A binary operation is not an assignment operation.
  10649. NotAnAssignmentOp,
  10650. /// RHS part of the binary operation is not a binary expression.
  10651. NotABinaryExpression,
  10652. /// RHS part is not additive/multiplicative/shift/biwise binary
  10653. /// expression.
  10654. NotABinaryOperator,
  10655. /// RHS binary operation does not have reference to the updated LHS
  10656. /// part.
  10657. NotAnUpdateExpression,
  10658. /// No errors is found.
  10659. NoError
  10660. };
  10661. /// Reference to Sema.
  10662. Sema &SemaRef;
  10663. /// A location for note diagnostics (when error is found).
  10664. SourceLocation NoteLoc;
  10665. /// 'x' lvalue part of the source atomic expression.
  10666. Expr *X;
  10667. /// 'expr' rvalue part of the source atomic expression.
  10668. Expr *E;
  10669. /// Helper expression of the form
  10670. /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  10671. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  10672. Expr *UpdateExpr;
  10673. /// Is 'x' a LHS in a RHS part of full update expression. It is
  10674. /// important for non-associative operations.
  10675. bool IsXLHSInRHSPart;
  10676. BinaryOperatorKind Op;
  10677. SourceLocation OpLoc;
  10678. /// true if the source expression is a postfix unary operation, false
  10679. /// if it is a prefix unary operation.
  10680. bool IsPostfixUpdate;
  10681. public:
  10682. OpenMPAtomicUpdateChecker(Sema &SemaRef)
  10683. : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
  10684. IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
  10685. /// Check specified statement that it is suitable for 'atomic update'
  10686. /// constructs and extract 'x', 'expr' and Operation from the original
  10687. /// expression. If DiagId and NoteId == 0, then only check is performed
  10688. /// without error notification.
  10689. /// \param DiagId Diagnostic which should be emitted if error is found.
  10690. /// \param NoteId Diagnostic note for the main error message.
  10691. /// \return true if statement is not an update expression, false otherwise.
  10692. bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
  10693. /// Return the 'x' lvalue part of the source atomic expression.
  10694. Expr *getX() const { return X; }
  10695. /// Return the 'expr' rvalue part of the source atomic expression.
  10696. Expr *getExpr() const { return E; }
  10697. /// Return the update expression used in calculation of the updated
  10698. /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
  10699. /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
  10700. Expr *getUpdateExpr() const { return UpdateExpr; }
  10701. /// Return true if 'x' is LHS in RHS part of full update expression,
  10702. /// false otherwise.
  10703. bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
  10704. /// true if the source expression is a postfix unary operation, false
  10705. /// if it is a prefix unary operation.
  10706. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  10707. private:
  10708. bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
  10709. unsigned NoteId = 0);
  10710. };
  10711. bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
  10712. BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
  10713. ExprAnalysisErrorCode ErrorFound = NoError;
  10714. SourceLocation ErrorLoc, NoteLoc;
  10715. SourceRange ErrorRange, NoteRange;
  10716. // Allowed constructs are:
  10717. // x = x binop expr;
  10718. // x = expr binop x;
  10719. if (AtomicBinOp->getOpcode() == BO_Assign) {
  10720. X = AtomicBinOp->getLHS();
  10721. if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
  10722. AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
  10723. if (AtomicInnerBinOp->isMultiplicativeOp() ||
  10724. AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
  10725. AtomicInnerBinOp->isBitwiseOp()) {
  10726. Op = AtomicInnerBinOp->getOpcode();
  10727. OpLoc = AtomicInnerBinOp->getOperatorLoc();
  10728. Expr *LHS = AtomicInnerBinOp->getLHS();
  10729. Expr *RHS = AtomicInnerBinOp->getRHS();
  10730. llvm::FoldingSetNodeID XId, LHSId, RHSId;
  10731. X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
  10732. /*Canonical=*/true);
  10733. LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
  10734. /*Canonical=*/true);
  10735. RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
  10736. /*Canonical=*/true);
  10737. if (XId == LHSId) {
  10738. E = RHS;
  10739. IsXLHSInRHSPart = true;
  10740. } else if (XId == RHSId) {
  10741. E = LHS;
  10742. IsXLHSInRHSPart = false;
  10743. } else {
  10744. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  10745. ErrorRange = AtomicInnerBinOp->getSourceRange();
  10746. NoteLoc = X->getExprLoc();
  10747. NoteRange = X->getSourceRange();
  10748. ErrorFound = NotAnUpdateExpression;
  10749. }
  10750. } else {
  10751. ErrorLoc = AtomicInnerBinOp->getExprLoc();
  10752. ErrorRange = AtomicInnerBinOp->getSourceRange();
  10753. NoteLoc = AtomicInnerBinOp->getOperatorLoc();
  10754. NoteRange = SourceRange(NoteLoc, NoteLoc);
  10755. ErrorFound = NotABinaryOperator;
  10756. }
  10757. } else {
  10758. NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
  10759. NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
  10760. ErrorFound = NotABinaryExpression;
  10761. }
  10762. } else {
  10763. ErrorLoc = AtomicBinOp->getExprLoc();
  10764. ErrorRange = AtomicBinOp->getSourceRange();
  10765. NoteLoc = AtomicBinOp->getOperatorLoc();
  10766. NoteRange = SourceRange(NoteLoc, NoteLoc);
  10767. ErrorFound = NotAnAssignmentOp;
  10768. }
  10769. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  10770. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  10771. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  10772. return true;
  10773. }
  10774. if (SemaRef.CurContext->isDependentContext())
  10775. E = X = UpdateExpr = nullptr;
  10776. return ErrorFound != NoError;
  10777. }
  10778. bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
  10779. unsigned NoteId) {
  10780. ExprAnalysisErrorCode ErrorFound = NoError;
  10781. SourceLocation ErrorLoc, NoteLoc;
  10782. SourceRange ErrorRange, NoteRange;
  10783. // Allowed constructs are:
  10784. // x++;
  10785. // x--;
  10786. // ++x;
  10787. // --x;
  10788. // x binop= expr;
  10789. // x = x binop expr;
  10790. // x = expr binop x;
  10791. if (auto *AtomicBody = dyn_cast<Expr>(S)) {
  10792. AtomicBody = AtomicBody->IgnoreParenImpCasts();
  10793. if (AtomicBody->getType()->isScalarType() ||
  10794. AtomicBody->isInstantiationDependent()) {
  10795. if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
  10796. AtomicBody->IgnoreParenImpCasts())) {
  10797. // Check for Compound Assignment Operation
  10798. Op = BinaryOperator::getOpForCompoundAssignment(
  10799. AtomicCompAssignOp->getOpcode());
  10800. OpLoc = AtomicCompAssignOp->getOperatorLoc();
  10801. E = AtomicCompAssignOp->getRHS();
  10802. X = AtomicCompAssignOp->getLHS()->IgnoreParens();
  10803. IsXLHSInRHSPart = true;
  10804. } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
  10805. AtomicBody->IgnoreParenImpCasts())) {
  10806. // Check for Binary Operation
  10807. if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
  10808. return true;
  10809. } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
  10810. AtomicBody->IgnoreParenImpCasts())) {
  10811. // Check for Unary Operation
  10812. if (AtomicUnaryOp->isIncrementDecrementOp()) {
  10813. IsPostfixUpdate = AtomicUnaryOp->isPostfix();
  10814. Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
  10815. OpLoc = AtomicUnaryOp->getOperatorLoc();
  10816. X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
  10817. E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
  10818. IsXLHSInRHSPart = true;
  10819. } else {
  10820. ErrorFound = NotAnUnaryIncDecExpression;
  10821. ErrorLoc = AtomicUnaryOp->getExprLoc();
  10822. ErrorRange = AtomicUnaryOp->getSourceRange();
  10823. NoteLoc = AtomicUnaryOp->getOperatorLoc();
  10824. NoteRange = SourceRange(NoteLoc, NoteLoc);
  10825. }
  10826. } else if (!AtomicBody->isInstantiationDependent()) {
  10827. ErrorFound = NotABinaryOrUnaryExpression;
  10828. NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
  10829. NoteRange = ErrorRange = AtomicBody->getSourceRange();
  10830. }
  10831. } else {
  10832. ErrorFound = NotAScalarType;
  10833. NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
  10834. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  10835. }
  10836. } else {
  10837. ErrorFound = NotAnExpression;
  10838. NoteLoc = ErrorLoc = S->getBeginLoc();
  10839. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  10840. }
  10841. if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
  10842. SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
  10843. SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
  10844. return true;
  10845. }
  10846. if (SemaRef.CurContext->isDependentContext())
  10847. E = X = UpdateExpr = nullptr;
  10848. if (ErrorFound == NoError && E && X) {
  10849. // Build an update expression of form 'OpaqueValueExpr(x) binop
  10850. // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
  10851. // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
  10852. auto *OVEX = new (SemaRef.getASTContext())
  10853. OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_PRValue);
  10854. auto *OVEExpr = new (SemaRef.getASTContext())
  10855. OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_PRValue);
  10856. ExprResult Update =
  10857. SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
  10858. IsXLHSInRHSPart ? OVEExpr : OVEX);
  10859. if (Update.isInvalid())
  10860. return true;
  10861. Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
  10862. Sema::AA_Casting);
  10863. if (Update.isInvalid())
  10864. return true;
  10865. UpdateExpr = Update.get();
  10866. }
  10867. return ErrorFound != NoError;
  10868. }
  10869. /// Get the node id of the fixed point of an expression \a S.
  10870. llvm::FoldingSetNodeID getNodeId(ASTContext &Context, const Expr *S) {
  10871. llvm::FoldingSetNodeID Id;
  10872. S->IgnoreParenImpCasts()->Profile(Id, Context, true);
  10873. return Id;
  10874. }
  10875. /// Check if two expressions are same.
  10876. bool checkIfTwoExprsAreSame(ASTContext &Context, const Expr *LHS,
  10877. const Expr *RHS) {
  10878. return getNodeId(Context, LHS) == getNodeId(Context, RHS);
  10879. }
  10880. class OpenMPAtomicCompareChecker {
  10881. public:
  10882. /// All kinds of errors that can occur in `atomic compare`
  10883. enum ErrorTy {
  10884. /// Empty compound statement.
  10885. NoStmt = 0,
  10886. /// More than one statement in a compound statement.
  10887. MoreThanOneStmt,
  10888. /// Not an assignment binary operator.
  10889. NotAnAssignment,
  10890. /// Not a conditional operator.
  10891. NotCondOp,
  10892. /// Wrong false expr. According to the spec, 'x' should be at the false
  10893. /// expression of a conditional expression.
  10894. WrongFalseExpr,
  10895. /// The condition of a conditional expression is not a binary operator.
  10896. NotABinaryOp,
  10897. /// Invalid binary operator (not <, >, or ==).
  10898. InvalidBinaryOp,
  10899. /// Invalid comparison (not x == e, e == x, x ordop expr, or expr ordop x).
  10900. InvalidComparison,
  10901. /// X is not a lvalue.
  10902. XNotLValue,
  10903. /// Not a scalar.
  10904. NotScalar,
  10905. /// Not an integer.
  10906. NotInteger,
  10907. /// 'else' statement is not expected.
  10908. UnexpectedElse,
  10909. /// Not an equality operator.
  10910. NotEQ,
  10911. /// Invalid assignment (not v == x).
  10912. InvalidAssignment,
  10913. /// Not if statement
  10914. NotIfStmt,
  10915. /// More than two statements in a compund statement.
  10916. MoreThanTwoStmts,
  10917. /// Not a compound statement.
  10918. NotCompoundStmt,
  10919. /// No else statement.
  10920. NoElse,
  10921. /// Not 'if (r)'.
  10922. InvalidCondition,
  10923. /// No error.
  10924. NoError,
  10925. };
  10926. struct ErrorInfoTy {
  10927. ErrorTy Error;
  10928. SourceLocation ErrorLoc;
  10929. SourceRange ErrorRange;
  10930. SourceLocation NoteLoc;
  10931. SourceRange NoteRange;
  10932. };
  10933. OpenMPAtomicCompareChecker(Sema &S) : ContextRef(S.getASTContext()) {}
  10934. /// Check if statement \a S is valid for <tt>atomic compare</tt>.
  10935. bool checkStmt(Stmt *S, ErrorInfoTy &ErrorInfo);
  10936. Expr *getX() const { return X; }
  10937. Expr *getE() const { return E; }
  10938. Expr *getD() const { return D; }
  10939. Expr *getCond() const { return C; }
  10940. bool isXBinopExpr() const { return IsXBinopExpr; }
  10941. protected:
  10942. /// Reference to ASTContext
  10943. ASTContext &ContextRef;
  10944. /// 'x' lvalue part of the source atomic expression.
  10945. Expr *X = nullptr;
  10946. /// 'expr' or 'e' rvalue part of the source atomic expression.
  10947. Expr *E = nullptr;
  10948. /// 'd' rvalue part of the source atomic expression.
  10949. Expr *D = nullptr;
  10950. /// 'cond' part of the source atomic expression. It is in one of the following
  10951. /// forms:
  10952. /// expr ordop x
  10953. /// x ordop expr
  10954. /// x == e
  10955. /// e == x
  10956. Expr *C = nullptr;
  10957. /// True if the cond expr is in the form of 'x ordop expr'.
  10958. bool IsXBinopExpr = true;
  10959. /// Check if it is a valid conditional update statement (cond-update-stmt).
  10960. bool checkCondUpdateStmt(IfStmt *S, ErrorInfoTy &ErrorInfo);
  10961. /// Check if it is a valid conditional expression statement (cond-expr-stmt).
  10962. bool checkCondExprStmt(Stmt *S, ErrorInfoTy &ErrorInfo);
  10963. /// Check if all captured values have right type.
  10964. bool checkType(ErrorInfoTy &ErrorInfo) const;
  10965. static bool CheckValue(const Expr *E, ErrorInfoTy &ErrorInfo,
  10966. bool ShouldBeLValue, bool ShouldBeInteger = false) {
  10967. if (E->isInstantiationDependent())
  10968. return true;
  10969. if (ShouldBeLValue && !E->isLValue()) {
  10970. ErrorInfo.Error = ErrorTy::XNotLValue;
  10971. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc();
  10972. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange();
  10973. return false;
  10974. }
  10975. QualType QTy = E->getType();
  10976. if (!QTy->isScalarType()) {
  10977. ErrorInfo.Error = ErrorTy::NotScalar;
  10978. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc();
  10979. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange();
  10980. return false;
  10981. }
  10982. if (ShouldBeInteger && !QTy->isIntegerType()) {
  10983. ErrorInfo.Error = ErrorTy::NotInteger;
  10984. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc();
  10985. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange();
  10986. return false;
  10987. }
  10988. return true;
  10989. }
  10990. };
  10991. bool OpenMPAtomicCompareChecker::checkCondUpdateStmt(IfStmt *S,
  10992. ErrorInfoTy &ErrorInfo) {
  10993. auto *Then = S->getThen();
  10994. if (auto *CS = dyn_cast<CompoundStmt>(Then)) {
  10995. if (CS->body_empty()) {
  10996. ErrorInfo.Error = ErrorTy::NoStmt;
  10997. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
  10998. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
  10999. return false;
  11000. }
  11001. if (CS->size() > 1) {
  11002. ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
  11003. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
  11004. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
  11005. return false;
  11006. }
  11007. Then = CS->body_front();
  11008. }
  11009. auto *BO = dyn_cast<BinaryOperator>(Then);
  11010. if (!BO) {
  11011. ErrorInfo.Error = ErrorTy::NotAnAssignment;
  11012. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Then->getBeginLoc();
  11013. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Then->getSourceRange();
  11014. return false;
  11015. }
  11016. if (BO->getOpcode() != BO_Assign) {
  11017. ErrorInfo.Error = ErrorTy::NotAnAssignment;
  11018. ErrorInfo.ErrorLoc = BO->getExprLoc();
  11019. ErrorInfo.NoteLoc = BO->getOperatorLoc();
  11020. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
  11021. return false;
  11022. }
  11023. X = BO->getLHS();
  11024. auto *Cond = dyn_cast<BinaryOperator>(S->getCond());
  11025. if (!Cond) {
  11026. ErrorInfo.Error = ErrorTy::NotABinaryOp;
  11027. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc();
  11028. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getCond()->getSourceRange();
  11029. return false;
  11030. }
  11031. switch (Cond->getOpcode()) {
  11032. case BO_EQ: {
  11033. C = Cond;
  11034. D = BO->getRHS();
  11035. if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) {
  11036. E = Cond->getRHS();
  11037. } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
  11038. E = Cond->getLHS();
  11039. } else {
  11040. ErrorInfo.Error = ErrorTy::InvalidComparison;
  11041. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
  11042. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
  11043. return false;
  11044. }
  11045. break;
  11046. }
  11047. case BO_LT:
  11048. case BO_GT: {
  11049. E = BO->getRHS();
  11050. if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS()) &&
  11051. checkIfTwoExprsAreSame(ContextRef, E, Cond->getRHS())) {
  11052. C = Cond;
  11053. } else if (checkIfTwoExprsAreSame(ContextRef, E, Cond->getLHS()) &&
  11054. checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
  11055. C = Cond;
  11056. IsXBinopExpr = false;
  11057. } else {
  11058. ErrorInfo.Error = ErrorTy::InvalidComparison;
  11059. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
  11060. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
  11061. return false;
  11062. }
  11063. break;
  11064. }
  11065. default:
  11066. ErrorInfo.Error = ErrorTy::InvalidBinaryOp;
  11067. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
  11068. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
  11069. return false;
  11070. }
  11071. if (S->getElse()) {
  11072. ErrorInfo.Error = ErrorTy::UnexpectedElse;
  11073. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getElse()->getBeginLoc();
  11074. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getElse()->getSourceRange();
  11075. return false;
  11076. }
  11077. return true;
  11078. }
  11079. bool OpenMPAtomicCompareChecker::checkCondExprStmt(Stmt *S,
  11080. ErrorInfoTy &ErrorInfo) {
  11081. auto *BO = dyn_cast<BinaryOperator>(S);
  11082. if (!BO) {
  11083. ErrorInfo.Error = ErrorTy::NotAnAssignment;
  11084. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc();
  11085. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
  11086. return false;
  11087. }
  11088. if (BO->getOpcode() != BO_Assign) {
  11089. ErrorInfo.Error = ErrorTy::NotAnAssignment;
  11090. ErrorInfo.ErrorLoc = BO->getExprLoc();
  11091. ErrorInfo.NoteLoc = BO->getOperatorLoc();
  11092. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
  11093. return false;
  11094. }
  11095. X = BO->getLHS();
  11096. auto *CO = dyn_cast<ConditionalOperator>(BO->getRHS()->IgnoreParenImpCasts());
  11097. if (!CO) {
  11098. ErrorInfo.Error = ErrorTy::NotCondOp;
  11099. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = BO->getRHS()->getExprLoc();
  11100. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getRHS()->getSourceRange();
  11101. return false;
  11102. }
  11103. if (!checkIfTwoExprsAreSame(ContextRef, X, CO->getFalseExpr())) {
  11104. ErrorInfo.Error = ErrorTy::WrongFalseExpr;
  11105. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getFalseExpr()->getExprLoc();
  11106. ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
  11107. CO->getFalseExpr()->getSourceRange();
  11108. return false;
  11109. }
  11110. auto *Cond = dyn_cast<BinaryOperator>(CO->getCond());
  11111. if (!Cond) {
  11112. ErrorInfo.Error = ErrorTy::NotABinaryOp;
  11113. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getCond()->getExprLoc();
  11114. ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
  11115. CO->getCond()->getSourceRange();
  11116. return false;
  11117. }
  11118. switch (Cond->getOpcode()) {
  11119. case BO_EQ: {
  11120. C = Cond;
  11121. D = CO->getTrueExpr();
  11122. if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) {
  11123. E = Cond->getRHS();
  11124. } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
  11125. E = Cond->getLHS();
  11126. } else {
  11127. ErrorInfo.Error = ErrorTy::InvalidComparison;
  11128. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
  11129. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
  11130. return false;
  11131. }
  11132. break;
  11133. }
  11134. case BO_LT:
  11135. case BO_GT: {
  11136. E = CO->getTrueExpr();
  11137. if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS()) &&
  11138. checkIfTwoExprsAreSame(ContextRef, E, Cond->getRHS())) {
  11139. C = Cond;
  11140. } else if (checkIfTwoExprsAreSame(ContextRef, E, Cond->getLHS()) &&
  11141. checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
  11142. C = Cond;
  11143. IsXBinopExpr = false;
  11144. } else {
  11145. ErrorInfo.Error = ErrorTy::InvalidComparison;
  11146. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
  11147. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
  11148. return false;
  11149. }
  11150. break;
  11151. }
  11152. default:
  11153. ErrorInfo.Error = ErrorTy::InvalidBinaryOp;
  11154. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
  11155. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
  11156. return false;
  11157. }
  11158. return true;
  11159. }
  11160. bool OpenMPAtomicCompareChecker::checkType(ErrorInfoTy &ErrorInfo) const {
  11161. // 'x' and 'e' cannot be nullptr
  11162. assert(X && E && "X and E cannot be nullptr");
  11163. if (!CheckValue(X, ErrorInfo, true))
  11164. return false;
  11165. if (!CheckValue(E, ErrorInfo, false))
  11166. return false;
  11167. if (D && !CheckValue(D, ErrorInfo, false))
  11168. return false;
  11169. return true;
  11170. }
  11171. bool OpenMPAtomicCompareChecker::checkStmt(
  11172. Stmt *S, OpenMPAtomicCompareChecker::ErrorInfoTy &ErrorInfo) {
  11173. auto *CS = dyn_cast<CompoundStmt>(S);
  11174. if (CS) {
  11175. if (CS->body_empty()) {
  11176. ErrorInfo.Error = ErrorTy::NoStmt;
  11177. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
  11178. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
  11179. return false;
  11180. }
  11181. if (CS->size() != 1) {
  11182. ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
  11183. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
  11184. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
  11185. return false;
  11186. }
  11187. S = CS->body_front();
  11188. }
  11189. auto Res = false;
  11190. if (auto *IS = dyn_cast<IfStmt>(S)) {
  11191. // Check if the statement is in one of the following forms
  11192. // (cond-update-stmt):
  11193. // if (expr ordop x) { x = expr; }
  11194. // if (x ordop expr) { x = expr; }
  11195. // if (x == e) { x = d; }
  11196. Res = checkCondUpdateStmt(IS, ErrorInfo);
  11197. } else {
  11198. // Check if the statement is in one of the following forms (cond-expr-stmt):
  11199. // x = expr ordop x ? expr : x;
  11200. // x = x ordop expr ? expr : x;
  11201. // x = x == e ? d : x;
  11202. Res = checkCondExprStmt(S, ErrorInfo);
  11203. }
  11204. if (!Res)
  11205. return false;
  11206. return checkType(ErrorInfo);
  11207. }
  11208. class OpenMPAtomicCompareCaptureChecker final
  11209. : public OpenMPAtomicCompareChecker {
  11210. public:
  11211. OpenMPAtomicCompareCaptureChecker(Sema &S) : OpenMPAtomicCompareChecker(S) {}
  11212. Expr *getV() const { return V; }
  11213. Expr *getR() const { return R; }
  11214. bool isFailOnly() const { return IsFailOnly; }
  11215. bool isPostfixUpdate() const { return IsPostfixUpdate; }
  11216. /// Check if statement \a S is valid for <tt>atomic compare capture</tt>.
  11217. bool checkStmt(Stmt *S, ErrorInfoTy &ErrorInfo);
  11218. private:
  11219. bool checkType(ErrorInfoTy &ErrorInfo);
  11220. // NOTE: Form 3, 4, 5 in the following comments mean the 3rd, 4th, and 5th
  11221. // form of 'conditional-update-capture-atomic' structured block on the v5.2
  11222. // spec p.p. 82:
  11223. // (1) { v = x; cond-update-stmt }
  11224. // (2) { cond-update-stmt v = x; }
  11225. // (3) if(x == e) { x = d; } else { v = x; }
  11226. // (4) { r = x == e; if(r) { x = d; } }
  11227. // (5) { r = x == e; if(r) { x = d; } else { v = x; } }
  11228. /// Check if it is valid 'if(x == e) { x = d; } else { v = x; }' (form 3)
  11229. bool checkForm3(IfStmt *S, ErrorInfoTy &ErrorInfo);
  11230. /// Check if it is valid '{ r = x == e; if(r) { x = d; } }',
  11231. /// or '{ r = x == e; if(r) { x = d; } else { v = x; } }' (form 4 and 5)
  11232. bool checkForm45(Stmt *S, ErrorInfoTy &ErrorInfo);
  11233. /// 'v' lvalue part of the source atomic expression.
  11234. Expr *V = nullptr;
  11235. /// 'r' lvalue part of the source atomic expression.
  11236. Expr *R = nullptr;
  11237. /// If 'v' is only updated when the comparison fails.
  11238. bool IsFailOnly = false;
  11239. /// If original value of 'x' must be stored in 'v', not an updated one.
  11240. bool IsPostfixUpdate = false;
  11241. };
  11242. bool OpenMPAtomicCompareCaptureChecker::checkType(ErrorInfoTy &ErrorInfo) {
  11243. if (!OpenMPAtomicCompareChecker::checkType(ErrorInfo))
  11244. return false;
  11245. if (V && !CheckValue(V, ErrorInfo, true))
  11246. return false;
  11247. if (R && !CheckValue(R, ErrorInfo, true, true))
  11248. return false;
  11249. return true;
  11250. }
  11251. bool OpenMPAtomicCompareCaptureChecker::checkForm3(IfStmt *S,
  11252. ErrorInfoTy &ErrorInfo) {
  11253. IsFailOnly = true;
  11254. auto *Then = S->getThen();
  11255. if (auto *CS = dyn_cast<CompoundStmt>(Then)) {
  11256. if (CS->body_empty()) {
  11257. ErrorInfo.Error = ErrorTy::NoStmt;
  11258. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
  11259. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
  11260. return false;
  11261. }
  11262. if (CS->size() > 1) {
  11263. ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
  11264. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
  11265. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
  11266. return false;
  11267. }
  11268. Then = CS->body_front();
  11269. }
  11270. auto *BO = dyn_cast<BinaryOperator>(Then);
  11271. if (!BO) {
  11272. ErrorInfo.Error = ErrorTy::NotAnAssignment;
  11273. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Then->getBeginLoc();
  11274. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Then->getSourceRange();
  11275. return false;
  11276. }
  11277. if (BO->getOpcode() != BO_Assign) {
  11278. ErrorInfo.Error = ErrorTy::NotAnAssignment;
  11279. ErrorInfo.ErrorLoc = BO->getExprLoc();
  11280. ErrorInfo.NoteLoc = BO->getOperatorLoc();
  11281. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
  11282. return false;
  11283. }
  11284. X = BO->getLHS();
  11285. D = BO->getRHS();
  11286. auto *Cond = dyn_cast<BinaryOperator>(S->getCond());
  11287. if (!Cond) {
  11288. ErrorInfo.Error = ErrorTy::NotABinaryOp;
  11289. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc();
  11290. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getCond()->getSourceRange();
  11291. return false;
  11292. }
  11293. if (Cond->getOpcode() != BO_EQ) {
  11294. ErrorInfo.Error = ErrorTy::NotEQ;
  11295. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
  11296. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
  11297. return false;
  11298. }
  11299. if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) {
  11300. E = Cond->getRHS();
  11301. } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) {
  11302. E = Cond->getLHS();
  11303. } else {
  11304. ErrorInfo.Error = ErrorTy::InvalidComparison;
  11305. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc();
  11306. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange();
  11307. return false;
  11308. }
  11309. C = Cond;
  11310. if (!S->getElse()) {
  11311. ErrorInfo.Error = ErrorTy::NoElse;
  11312. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc();
  11313. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
  11314. return false;
  11315. }
  11316. auto *Else = S->getElse();
  11317. if (auto *CS = dyn_cast<CompoundStmt>(Else)) {
  11318. if (CS->body_empty()) {
  11319. ErrorInfo.Error = ErrorTy::NoStmt;
  11320. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
  11321. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
  11322. return false;
  11323. }
  11324. if (CS->size() > 1) {
  11325. ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
  11326. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
  11327. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
  11328. return false;
  11329. }
  11330. Else = CS->body_front();
  11331. }
  11332. auto *ElseBO = dyn_cast<BinaryOperator>(Else);
  11333. if (!ElseBO) {
  11334. ErrorInfo.Error = ErrorTy::NotAnAssignment;
  11335. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Else->getBeginLoc();
  11336. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Else->getSourceRange();
  11337. return false;
  11338. }
  11339. if (ElseBO->getOpcode() != BO_Assign) {
  11340. ErrorInfo.Error = ErrorTy::NotAnAssignment;
  11341. ErrorInfo.ErrorLoc = ElseBO->getExprLoc();
  11342. ErrorInfo.NoteLoc = ElseBO->getOperatorLoc();
  11343. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseBO->getSourceRange();
  11344. return false;
  11345. }
  11346. if (!checkIfTwoExprsAreSame(ContextRef, X, ElseBO->getRHS())) {
  11347. ErrorInfo.Error = ErrorTy::InvalidAssignment;
  11348. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ElseBO->getRHS()->getExprLoc();
  11349. ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
  11350. ElseBO->getRHS()->getSourceRange();
  11351. return false;
  11352. }
  11353. V = ElseBO->getLHS();
  11354. return checkType(ErrorInfo);
  11355. }
  11356. bool OpenMPAtomicCompareCaptureChecker::checkForm45(Stmt *S,
  11357. ErrorInfoTy &ErrorInfo) {
  11358. // We don't check here as they should be already done before call this
  11359. // function.
  11360. auto *CS = cast<CompoundStmt>(S);
  11361. assert(CS->size() == 2 && "CompoundStmt size is not expected");
  11362. auto *S1 = cast<BinaryOperator>(CS->body_front());
  11363. auto *S2 = cast<IfStmt>(CS->body_back());
  11364. assert(S1->getOpcode() == BO_Assign && "unexpected binary operator");
  11365. if (!checkIfTwoExprsAreSame(ContextRef, S1->getLHS(), S2->getCond())) {
  11366. ErrorInfo.Error = ErrorTy::InvalidCondition;
  11367. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S2->getCond()->getExprLoc();
  11368. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S1->getLHS()->getSourceRange();
  11369. return false;
  11370. }
  11371. R = S1->getLHS();
  11372. auto *Then = S2->getThen();
  11373. if (auto *ThenCS = dyn_cast<CompoundStmt>(Then)) {
  11374. if (ThenCS->body_empty()) {
  11375. ErrorInfo.Error = ErrorTy::NoStmt;
  11376. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ThenCS->getBeginLoc();
  11377. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ThenCS->getSourceRange();
  11378. return false;
  11379. }
  11380. if (ThenCS->size() > 1) {
  11381. ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
  11382. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ThenCS->getBeginLoc();
  11383. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ThenCS->getSourceRange();
  11384. return false;
  11385. }
  11386. Then = ThenCS->body_front();
  11387. }
  11388. auto *ThenBO = dyn_cast<BinaryOperator>(Then);
  11389. if (!ThenBO) {
  11390. ErrorInfo.Error = ErrorTy::NotAnAssignment;
  11391. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S2->getBeginLoc();
  11392. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S2->getSourceRange();
  11393. return false;
  11394. }
  11395. if (ThenBO->getOpcode() != BO_Assign) {
  11396. ErrorInfo.Error = ErrorTy::NotAnAssignment;
  11397. ErrorInfo.ErrorLoc = ThenBO->getExprLoc();
  11398. ErrorInfo.NoteLoc = ThenBO->getOperatorLoc();
  11399. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ThenBO->getSourceRange();
  11400. return false;
  11401. }
  11402. X = ThenBO->getLHS();
  11403. D = ThenBO->getRHS();
  11404. auto *BO = cast<BinaryOperator>(S1->getRHS()->IgnoreImpCasts());
  11405. if (BO->getOpcode() != BO_EQ) {
  11406. ErrorInfo.Error = ErrorTy::NotEQ;
  11407. ErrorInfo.ErrorLoc = BO->getExprLoc();
  11408. ErrorInfo.NoteLoc = BO->getOperatorLoc();
  11409. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
  11410. return false;
  11411. }
  11412. C = BO;
  11413. if (checkIfTwoExprsAreSame(ContextRef, X, BO->getLHS())) {
  11414. E = BO->getRHS();
  11415. } else if (checkIfTwoExprsAreSame(ContextRef, X, BO->getRHS())) {
  11416. E = BO->getLHS();
  11417. } else {
  11418. ErrorInfo.Error = ErrorTy::InvalidComparison;
  11419. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = BO->getExprLoc();
  11420. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
  11421. return false;
  11422. }
  11423. if (S2->getElse()) {
  11424. IsFailOnly = true;
  11425. auto *Else = S2->getElse();
  11426. if (auto *ElseCS = dyn_cast<CompoundStmt>(Else)) {
  11427. if (ElseCS->body_empty()) {
  11428. ErrorInfo.Error = ErrorTy::NoStmt;
  11429. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ElseCS->getBeginLoc();
  11430. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseCS->getSourceRange();
  11431. return false;
  11432. }
  11433. if (ElseCS->size() > 1) {
  11434. ErrorInfo.Error = ErrorTy::MoreThanOneStmt;
  11435. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ElseCS->getBeginLoc();
  11436. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseCS->getSourceRange();
  11437. return false;
  11438. }
  11439. Else = ElseCS->body_front();
  11440. }
  11441. auto *ElseBO = dyn_cast<BinaryOperator>(Else);
  11442. if (!ElseBO) {
  11443. ErrorInfo.Error = ErrorTy::NotAnAssignment;
  11444. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Else->getBeginLoc();
  11445. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Else->getSourceRange();
  11446. return false;
  11447. }
  11448. if (ElseBO->getOpcode() != BO_Assign) {
  11449. ErrorInfo.Error = ErrorTy::NotAnAssignment;
  11450. ErrorInfo.ErrorLoc = ElseBO->getExprLoc();
  11451. ErrorInfo.NoteLoc = ElseBO->getOperatorLoc();
  11452. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseBO->getSourceRange();
  11453. return false;
  11454. }
  11455. if (!checkIfTwoExprsAreSame(ContextRef, X, ElseBO->getRHS())) {
  11456. ErrorInfo.Error = ErrorTy::InvalidAssignment;
  11457. ErrorInfo.ErrorLoc = ElseBO->getRHS()->getExprLoc();
  11458. ErrorInfo.NoteLoc = X->getExprLoc();
  11459. ErrorInfo.ErrorRange = ElseBO->getRHS()->getSourceRange();
  11460. ErrorInfo.NoteRange = X->getSourceRange();
  11461. return false;
  11462. }
  11463. V = ElseBO->getLHS();
  11464. }
  11465. return checkType(ErrorInfo);
  11466. }
  11467. bool OpenMPAtomicCompareCaptureChecker::checkStmt(Stmt *S,
  11468. ErrorInfoTy &ErrorInfo) {
  11469. // if(x == e) { x = d; } else { v = x; }
  11470. if (auto *IS = dyn_cast<IfStmt>(S))
  11471. return checkForm3(IS, ErrorInfo);
  11472. auto *CS = dyn_cast<CompoundStmt>(S);
  11473. if (!CS) {
  11474. ErrorInfo.Error = ErrorTy::NotCompoundStmt;
  11475. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc();
  11476. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange();
  11477. return false;
  11478. }
  11479. if (CS->body_empty()) {
  11480. ErrorInfo.Error = ErrorTy::NoStmt;
  11481. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
  11482. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
  11483. return false;
  11484. }
  11485. // { if(x == e) { x = d; } else { v = x; } }
  11486. if (CS->size() == 1) {
  11487. auto *IS = dyn_cast<IfStmt>(CS->body_front());
  11488. if (!IS) {
  11489. ErrorInfo.Error = ErrorTy::NotIfStmt;
  11490. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->body_front()->getBeginLoc();
  11491. ErrorInfo.ErrorRange = ErrorInfo.NoteRange =
  11492. CS->body_front()->getSourceRange();
  11493. return false;
  11494. }
  11495. return checkForm3(IS, ErrorInfo);
  11496. } else if (CS->size() == 2) {
  11497. auto *S1 = CS->body_front();
  11498. auto *S2 = CS->body_back();
  11499. Stmt *UpdateStmt = nullptr;
  11500. Stmt *CondUpdateStmt = nullptr;
  11501. Stmt *CondExprStmt = nullptr;
  11502. if (auto *BO = dyn_cast<BinaryOperator>(S1)) {
  11503. // It could be one of the following cases:
  11504. // { v = x; cond-update-stmt }
  11505. // { v = x; cond-expr-stmt }
  11506. // { cond-expr-stmt; v = x; }
  11507. // form 45
  11508. if (isa<BinaryOperator>(BO->getRHS()->IgnoreImpCasts()) ||
  11509. isa<ConditionalOperator>(BO->getRHS()->IgnoreImpCasts())) {
  11510. // check if form 45
  11511. if (isa<IfStmt>(S2))
  11512. return checkForm45(CS, ErrorInfo);
  11513. // { cond-expr-stmt; v = x; }
  11514. CondExprStmt = S1;
  11515. UpdateStmt = S2;
  11516. } else {
  11517. IsPostfixUpdate = true;
  11518. UpdateStmt = S1;
  11519. if (isa<IfStmt>(S2)) {
  11520. // { v = x; cond-update-stmt }
  11521. CondUpdateStmt = S2;
  11522. } else {
  11523. // { v = x; cond-expr-stmt }
  11524. CondExprStmt = S2;
  11525. }
  11526. }
  11527. } else {
  11528. // { cond-update-stmt v = x; }
  11529. UpdateStmt = S2;
  11530. CondUpdateStmt = S1;
  11531. }
  11532. auto CheckCondUpdateStmt = [this, &ErrorInfo](Stmt *CUS) {
  11533. auto *IS = dyn_cast<IfStmt>(CUS);
  11534. if (!IS) {
  11535. ErrorInfo.Error = ErrorTy::NotIfStmt;
  11536. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CUS->getBeginLoc();
  11537. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CUS->getSourceRange();
  11538. return false;
  11539. }
  11540. return checkCondUpdateStmt(IS, ErrorInfo);
  11541. };
  11542. // CheckUpdateStmt has to be called *after* CheckCondUpdateStmt.
  11543. auto CheckUpdateStmt = [this, &ErrorInfo](Stmt *US) {
  11544. auto *BO = dyn_cast<BinaryOperator>(US);
  11545. if (!BO) {
  11546. ErrorInfo.Error = ErrorTy::NotAnAssignment;
  11547. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = US->getBeginLoc();
  11548. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = US->getSourceRange();
  11549. return false;
  11550. }
  11551. if (BO->getOpcode() != BO_Assign) {
  11552. ErrorInfo.Error = ErrorTy::NotAnAssignment;
  11553. ErrorInfo.ErrorLoc = BO->getExprLoc();
  11554. ErrorInfo.NoteLoc = BO->getOperatorLoc();
  11555. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange();
  11556. return false;
  11557. }
  11558. if (!checkIfTwoExprsAreSame(ContextRef, this->X, BO->getRHS())) {
  11559. ErrorInfo.Error = ErrorTy::InvalidAssignment;
  11560. ErrorInfo.ErrorLoc = BO->getRHS()->getExprLoc();
  11561. ErrorInfo.NoteLoc = this->X->getExprLoc();
  11562. ErrorInfo.ErrorRange = BO->getRHS()->getSourceRange();
  11563. ErrorInfo.NoteRange = this->X->getSourceRange();
  11564. return false;
  11565. }
  11566. this->V = BO->getLHS();
  11567. return true;
  11568. };
  11569. if (CondUpdateStmt && !CheckCondUpdateStmt(CondUpdateStmt))
  11570. return false;
  11571. if (CondExprStmt && !checkCondExprStmt(CondExprStmt, ErrorInfo))
  11572. return false;
  11573. if (!CheckUpdateStmt(UpdateStmt))
  11574. return false;
  11575. } else {
  11576. ErrorInfo.Error = ErrorTy::MoreThanTwoStmts;
  11577. ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc();
  11578. ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange();
  11579. return false;
  11580. }
  11581. return checkType(ErrorInfo);
  11582. }
  11583. } // namespace
  11584. StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
  11585. Stmt *AStmt,
  11586. SourceLocation StartLoc,
  11587. SourceLocation EndLoc) {
  11588. // Register location of the first atomic directive.
  11589. DSAStack->addAtomicDirectiveLoc(StartLoc);
  11590. if (!AStmt)
  11591. return StmtError();
  11592. // 1.2.2 OpenMP Language Terminology
  11593. // Structured block - An executable statement with a single entry at the
  11594. // top and a single exit at the bottom.
  11595. // The point of exit cannot be a branch out of the structured block.
  11596. // longjmp() and throw() must not violate the entry/exit criteria.
  11597. OpenMPClauseKind AtomicKind = OMPC_unknown;
  11598. SourceLocation AtomicKindLoc;
  11599. OpenMPClauseKind MemOrderKind = OMPC_unknown;
  11600. SourceLocation MemOrderLoc;
  11601. bool MutexClauseEncountered = false;
  11602. llvm::SmallSet<OpenMPClauseKind, 2> EncounteredAtomicKinds;
  11603. for (const OMPClause *C : Clauses) {
  11604. switch (C->getClauseKind()) {
  11605. case OMPC_read:
  11606. case OMPC_write:
  11607. case OMPC_update:
  11608. MutexClauseEncountered = true;
  11609. [[fallthrough]];
  11610. case OMPC_capture:
  11611. case OMPC_compare: {
  11612. if (AtomicKind != OMPC_unknown && MutexClauseEncountered) {
  11613. Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
  11614. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  11615. Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
  11616. << getOpenMPClauseName(AtomicKind);
  11617. } else {
  11618. AtomicKind = C->getClauseKind();
  11619. AtomicKindLoc = C->getBeginLoc();
  11620. if (!EncounteredAtomicKinds.insert(C->getClauseKind()).second) {
  11621. Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
  11622. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  11623. Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause)
  11624. << getOpenMPClauseName(AtomicKind);
  11625. }
  11626. }
  11627. break;
  11628. }
  11629. case OMPC_seq_cst:
  11630. case OMPC_acq_rel:
  11631. case OMPC_acquire:
  11632. case OMPC_release:
  11633. case OMPC_relaxed: {
  11634. if (MemOrderKind != OMPC_unknown) {
  11635. Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses)
  11636. << getOpenMPDirectiveName(OMPD_atomic) << 0
  11637. << SourceRange(C->getBeginLoc(), C->getEndLoc());
  11638. Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
  11639. << getOpenMPClauseName(MemOrderKind);
  11640. } else {
  11641. MemOrderKind = C->getClauseKind();
  11642. MemOrderLoc = C->getBeginLoc();
  11643. }
  11644. break;
  11645. }
  11646. // The following clauses are allowed, but we don't need to do anything here.
  11647. case OMPC_hint:
  11648. break;
  11649. default:
  11650. llvm_unreachable("unknown clause is encountered");
  11651. }
  11652. }
  11653. bool IsCompareCapture = false;
  11654. if (EncounteredAtomicKinds.contains(OMPC_compare) &&
  11655. EncounteredAtomicKinds.contains(OMPC_capture)) {
  11656. IsCompareCapture = true;
  11657. AtomicKind = OMPC_compare;
  11658. }
  11659. // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions
  11660. // If atomic-clause is read then memory-order-clause must not be acq_rel or
  11661. // release.
  11662. // If atomic-clause is write then memory-order-clause must not be acq_rel or
  11663. // acquire.
  11664. // If atomic-clause is update or not present then memory-order-clause must not
  11665. // be acq_rel or acquire.
  11666. if ((AtomicKind == OMPC_read &&
  11667. (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) ||
  11668. ((AtomicKind == OMPC_write || AtomicKind == OMPC_update ||
  11669. AtomicKind == OMPC_unknown) &&
  11670. (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) {
  11671. SourceLocation Loc = AtomicKindLoc;
  11672. if (AtomicKind == OMPC_unknown)
  11673. Loc = StartLoc;
  11674. Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause)
  11675. << getOpenMPClauseName(AtomicKind)
  11676. << (AtomicKind == OMPC_unknown ? 1 : 0)
  11677. << getOpenMPClauseName(MemOrderKind);
  11678. Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause)
  11679. << getOpenMPClauseName(MemOrderKind);
  11680. }
  11681. Stmt *Body = AStmt;
  11682. if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
  11683. Body = EWC->getSubExpr();
  11684. Expr *X = nullptr;
  11685. Expr *V = nullptr;
  11686. Expr *E = nullptr;
  11687. Expr *UE = nullptr;
  11688. Expr *D = nullptr;
  11689. Expr *CE = nullptr;
  11690. Expr *R = nullptr;
  11691. bool IsXLHSInRHSPart = false;
  11692. bool IsPostfixUpdate = false;
  11693. bool IsFailOnly = false;
  11694. // OpenMP [2.12.6, atomic Construct]
  11695. // In the next expressions:
  11696. // * x and v (as applicable) are both l-value expressions with scalar type.
  11697. // * During the execution of an atomic region, multiple syntactic
  11698. // occurrences of x must designate the same storage location.
  11699. // * Neither of v and expr (as applicable) may access the storage location
  11700. // designated by x.
  11701. // * Neither of x and expr (as applicable) may access the storage location
  11702. // designated by v.
  11703. // * expr is an expression with scalar type.
  11704. // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
  11705. // * binop, binop=, ++, and -- are not overloaded operators.
  11706. // * The expression x binop expr must be numerically equivalent to x binop
  11707. // (expr). This requirement is satisfied if the operators in expr have
  11708. // precedence greater than binop, or by using parentheses around expr or
  11709. // subexpressions of expr.
  11710. // * The expression expr binop x must be numerically equivalent to (expr)
  11711. // binop x. This requirement is satisfied if the operators in expr have
  11712. // precedence equal to or greater than binop, or by using parentheses around
  11713. // expr or subexpressions of expr.
  11714. // * For forms that allow multiple occurrences of x, the number of times
  11715. // that x is evaluated is unspecified.
  11716. if (AtomicKind == OMPC_read) {
  11717. enum {
  11718. NotAnExpression,
  11719. NotAnAssignmentOp,
  11720. NotAScalarType,
  11721. NotAnLValue,
  11722. NoError
  11723. } ErrorFound = NoError;
  11724. SourceLocation ErrorLoc, NoteLoc;
  11725. SourceRange ErrorRange, NoteRange;
  11726. // If clause is read:
  11727. // v = x;
  11728. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  11729. const auto *AtomicBinOp =
  11730. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  11731. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  11732. X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  11733. V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
  11734. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  11735. (V->isInstantiationDependent() || V->getType()->isScalarType())) {
  11736. if (!X->isLValue() || !V->isLValue()) {
  11737. const Expr *NotLValueExpr = X->isLValue() ? V : X;
  11738. ErrorFound = NotAnLValue;
  11739. ErrorLoc = AtomicBinOp->getExprLoc();
  11740. ErrorRange = AtomicBinOp->getSourceRange();
  11741. NoteLoc = NotLValueExpr->getExprLoc();
  11742. NoteRange = NotLValueExpr->getSourceRange();
  11743. }
  11744. } else if (!X->isInstantiationDependent() ||
  11745. !V->isInstantiationDependent()) {
  11746. const Expr *NotScalarExpr =
  11747. (X->isInstantiationDependent() || X->getType()->isScalarType())
  11748. ? V
  11749. : X;
  11750. ErrorFound = NotAScalarType;
  11751. ErrorLoc = AtomicBinOp->getExprLoc();
  11752. ErrorRange = AtomicBinOp->getSourceRange();
  11753. NoteLoc = NotScalarExpr->getExprLoc();
  11754. NoteRange = NotScalarExpr->getSourceRange();
  11755. }
  11756. } else if (!AtomicBody->isInstantiationDependent()) {
  11757. ErrorFound = NotAnAssignmentOp;
  11758. ErrorLoc = AtomicBody->getExprLoc();
  11759. ErrorRange = AtomicBody->getSourceRange();
  11760. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  11761. : AtomicBody->getExprLoc();
  11762. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  11763. : AtomicBody->getSourceRange();
  11764. }
  11765. } else {
  11766. ErrorFound = NotAnExpression;
  11767. NoteLoc = ErrorLoc = Body->getBeginLoc();
  11768. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  11769. }
  11770. if (ErrorFound != NoError) {
  11771. Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
  11772. << ErrorRange;
  11773. Diag(NoteLoc, diag::note_omp_atomic_read_write)
  11774. << ErrorFound << NoteRange;
  11775. return StmtError();
  11776. }
  11777. if (CurContext->isDependentContext())
  11778. V = X = nullptr;
  11779. } else if (AtomicKind == OMPC_write) {
  11780. enum {
  11781. NotAnExpression,
  11782. NotAnAssignmentOp,
  11783. NotAScalarType,
  11784. NotAnLValue,
  11785. NoError
  11786. } ErrorFound = NoError;
  11787. SourceLocation ErrorLoc, NoteLoc;
  11788. SourceRange ErrorRange, NoteRange;
  11789. // If clause is write:
  11790. // x = expr;
  11791. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  11792. const auto *AtomicBinOp =
  11793. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  11794. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  11795. X = AtomicBinOp->getLHS();
  11796. E = AtomicBinOp->getRHS();
  11797. if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
  11798. (E->isInstantiationDependent() || E->getType()->isScalarType())) {
  11799. if (!X->isLValue()) {
  11800. ErrorFound = NotAnLValue;
  11801. ErrorLoc = AtomicBinOp->getExprLoc();
  11802. ErrorRange = AtomicBinOp->getSourceRange();
  11803. NoteLoc = X->getExprLoc();
  11804. NoteRange = X->getSourceRange();
  11805. }
  11806. } else if (!X->isInstantiationDependent() ||
  11807. !E->isInstantiationDependent()) {
  11808. const Expr *NotScalarExpr =
  11809. (X->isInstantiationDependent() || X->getType()->isScalarType())
  11810. ? E
  11811. : X;
  11812. ErrorFound = NotAScalarType;
  11813. ErrorLoc = AtomicBinOp->getExprLoc();
  11814. ErrorRange = AtomicBinOp->getSourceRange();
  11815. NoteLoc = NotScalarExpr->getExprLoc();
  11816. NoteRange = NotScalarExpr->getSourceRange();
  11817. }
  11818. } else if (!AtomicBody->isInstantiationDependent()) {
  11819. ErrorFound = NotAnAssignmentOp;
  11820. ErrorLoc = AtomicBody->getExprLoc();
  11821. ErrorRange = AtomicBody->getSourceRange();
  11822. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  11823. : AtomicBody->getExprLoc();
  11824. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  11825. : AtomicBody->getSourceRange();
  11826. }
  11827. } else {
  11828. ErrorFound = NotAnExpression;
  11829. NoteLoc = ErrorLoc = Body->getBeginLoc();
  11830. NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
  11831. }
  11832. if (ErrorFound != NoError) {
  11833. Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
  11834. << ErrorRange;
  11835. Diag(NoteLoc, diag::note_omp_atomic_read_write)
  11836. << ErrorFound << NoteRange;
  11837. return StmtError();
  11838. }
  11839. if (CurContext->isDependentContext())
  11840. E = X = nullptr;
  11841. } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
  11842. // If clause is update:
  11843. // x++;
  11844. // x--;
  11845. // ++x;
  11846. // --x;
  11847. // x binop= expr;
  11848. // x = x binop expr;
  11849. // x = expr binop x;
  11850. OpenMPAtomicUpdateChecker Checker(*this);
  11851. if (Checker.checkStatement(
  11852. Body,
  11853. (AtomicKind == OMPC_update)
  11854. ? diag::err_omp_atomic_update_not_expression_statement
  11855. : diag::err_omp_atomic_not_expression_statement,
  11856. diag::note_omp_atomic_update))
  11857. return StmtError();
  11858. if (!CurContext->isDependentContext()) {
  11859. E = Checker.getExpr();
  11860. X = Checker.getX();
  11861. UE = Checker.getUpdateExpr();
  11862. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  11863. }
  11864. } else if (AtomicKind == OMPC_capture) {
  11865. enum {
  11866. NotAnAssignmentOp,
  11867. NotACompoundStatement,
  11868. NotTwoSubstatements,
  11869. NotASpecificExpression,
  11870. NoError
  11871. } ErrorFound = NoError;
  11872. SourceLocation ErrorLoc, NoteLoc;
  11873. SourceRange ErrorRange, NoteRange;
  11874. if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
  11875. // If clause is a capture:
  11876. // v = x++;
  11877. // v = x--;
  11878. // v = ++x;
  11879. // v = --x;
  11880. // v = x binop= expr;
  11881. // v = x = x binop expr;
  11882. // v = x = expr binop x;
  11883. const auto *AtomicBinOp =
  11884. dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
  11885. if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
  11886. V = AtomicBinOp->getLHS();
  11887. Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
  11888. OpenMPAtomicUpdateChecker Checker(*this);
  11889. if (Checker.checkStatement(
  11890. Body, diag::err_omp_atomic_capture_not_expression_statement,
  11891. diag::note_omp_atomic_update))
  11892. return StmtError();
  11893. E = Checker.getExpr();
  11894. X = Checker.getX();
  11895. UE = Checker.getUpdateExpr();
  11896. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  11897. IsPostfixUpdate = Checker.isPostfixUpdate();
  11898. } else if (!AtomicBody->isInstantiationDependent()) {
  11899. ErrorLoc = AtomicBody->getExprLoc();
  11900. ErrorRange = AtomicBody->getSourceRange();
  11901. NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
  11902. : AtomicBody->getExprLoc();
  11903. NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
  11904. : AtomicBody->getSourceRange();
  11905. ErrorFound = NotAnAssignmentOp;
  11906. }
  11907. if (ErrorFound != NoError) {
  11908. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
  11909. << ErrorRange;
  11910. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  11911. return StmtError();
  11912. }
  11913. if (CurContext->isDependentContext())
  11914. UE = V = E = X = nullptr;
  11915. } else {
  11916. // If clause is a capture:
  11917. // { v = x; x = expr; }
  11918. // { v = x; x++; }
  11919. // { v = x; x--; }
  11920. // { v = x; ++x; }
  11921. // { v = x; --x; }
  11922. // { v = x; x binop= expr; }
  11923. // { v = x; x = x binop expr; }
  11924. // { v = x; x = expr binop x; }
  11925. // { x++; v = x; }
  11926. // { x--; v = x; }
  11927. // { ++x; v = x; }
  11928. // { --x; v = x; }
  11929. // { x binop= expr; v = x; }
  11930. // { x = x binop expr; v = x; }
  11931. // { x = expr binop x; v = x; }
  11932. if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
  11933. // Check that this is { expr1; expr2; }
  11934. if (CS->size() == 2) {
  11935. Stmt *First = CS->body_front();
  11936. Stmt *Second = CS->body_back();
  11937. if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
  11938. First = EWC->getSubExpr()->IgnoreParenImpCasts();
  11939. if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
  11940. Second = EWC->getSubExpr()->IgnoreParenImpCasts();
  11941. // Need to find what subexpression is 'v' and what is 'x'.
  11942. OpenMPAtomicUpdateChecker Checker(*this);
  11943. bool IsUpdateExprFound = !Checker.checkStatement(Second);
  11944. BinaryOperator *BinOp = nullptr;
  11945. if (IsUpdateExprFound) {
  11946. BinOp = dyn_cast<BinaryOperator>(First);
  11947. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  11948. }
  11949. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  11950. // { v = x; x++; }
  11951. // { v = x; x--; }
  11952. // { v = x; ++x; }
  11953. // { v = x; --x; }
  11954. // { v = x; x binop= expr; }
  11955. // { v = x; x = x binop expr; }
  11956. // { v = x; x = expr binop x; }
  11957. // Check that the first expression has form v = x.
  11958. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  11959. llvm::FoldingSetNodeID XId, PossibleXId;
  11960. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  11961. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  11962. IsUpdateExprFound = XId == PossibleXId;
  11963. if (IsUpdateExprFound) {
  11964. V = BinOp->getLHS();
  11965. X = Checker.getX();
  11966. E = Checker.getExpr();
  11967. UE = Checker.getUpdateExpr();
  11968. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  11969. IsPostfixUpdate = true;
  11970. }
  11971. }
  11972. if (!IsUpdateExprFound) {
  11973. IsUpdateExprFound = !Checker.checkStatement(First);
  11974. BinOp = nullptr;
  11975. if (IsUpdateExprFound) {
  11976. BinOp = dyn_cast<BinaryOperator>(Second);
  11977. IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
  11978. }
  11979. if (IsUpdateExprFound && !CurContext->isDependentContext()) {
  11980. // { x++; v = x; }
  11981. // { x--; v = x; }
  11982. // { ++x; v = x; }
  11983. // { --x; v = x; }
  11984. // { x binop= expr; v = x; }
  11985. // { x = x binop expr; v = x; }
  11986. // { x = expr binop x; v = x; }
  11987. // Check that the second expression has form v = x.
  11988. Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
  11989. llvm::FoldingSetNodeID XId, PossibleXId;
  11990. Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
  11991. PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
  11992. IsUpdateExprFound = XId == PossibleXId;
  11993. if (IsUpdateExprFound) {
  11994. V = BinOp->getLHS();
  11995. X = Checker.getX();
  11996. E = Checker.getExpr();
  11997. UE = Checker.getUpdateExpr();
  11998. IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
  11999. IsPostfixUpdate = false;
  12000. }
  12001. }
  12002. }
  12003. if (!IsUpdateExprFound) {
  12004. // { v = x; x = expr; }
  12005. auto *FirstExpr = dyn_cast<Expr>(First);
  12006. auto *SecondExpr = dyn_cast<Expr>(Second);
  12007. if (!FirstExpr || !SecondExpr ||
  12008. !(FirstExpr->isInstantiationDependent() ||
  12009. SecondExpr->isInstantiationDependent())) {
  12010. auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
  12011. if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
  12012. ErrorFound = NotAnAssignmentOp;
  12013. NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
  12014. : First->getBeginLoc();
  12015. NoteRange = ErrorRange = FirstBinOp
  12016. ? FirstBinOp->getSourceRange()
  12017. : SourceRange(ErrorLoc, ErrorLoc);
  12018. } else {
  12019. auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
  12020. if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
  12021. ErrorFound = NotAnAssignmentOp;
  12022. NoteLoc = ErrorLoc = SecondBinOp
  12023. ? SecondBinOp->getOperatorLoc()
  12024. : Second->getBeginLoc();
  12025. NoteRange = ErrorRange =
  12026. SecondBinOp ? SecondBinOp->getSourceRange()
  12027. : SourceRange(ErrorLoc, ErrorLoc);
  12028. } else {
  12029. Expr *PossibleXRHSInFirst =
  12030. FirstBinOp->getRHS()->IgnoreParenImpCasts();
  12031. Expr *PossibleXLHSInSecond =
  12032. SecondBinOp->getLHS()->IgnoreParenImpCasts();
  12033. llvm::FoldingSetNodeID X1Id, X2Id;
  12034. PossibleXRHSInFirst->Profile(X1Id, Context,
  12035. /*Canonical=*/true);
  12036. PossibleXLHSInSecond->Profile(X2Id, Context,
  12037. /*Canonical=*/true);
  12038. IsUpdateExprFound = X1Id == X2Id;
  12039. if (IsUpdateExprFound) {
  12040. V = FirstBinOp->getLHS();
  12041. X = SecondBinOp->getLHS();
  12042. E = SecondBinOp->getRHS();
  12043. UE = nullptr;
  12044. IsXLHSInRHSPart = false;
  12045. IsPostfixUpdate = true;
  12046. } else {
  12047. ErrorFound = NotASpecificExpression;
  12048. ErrorLoc = FirstBinOp->getExprLoc();
  12049. ErrorRange = FirstBinOp->getSourceRange();
  12050. NoteLoc = SecondBinOp->getLHS()->getExprLoc();
  12051. NoteRange = SecondBinOp->getRHS()->getSourceRange();
  12052. }
  12053. }
  12054. }
  12055. }
  12056. }
  12057. } else {
  12058. NoteLoc = ErrorLoc = Body->getBeginLoc();
  12059. NoteRange = ErrorRange =
  12060. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  12061. ErrorFound = NotTwoSubstatements;
  12062. }
  12063. } else {
  12064. NoteLoc = ErrorLoc = Body->getBeginLoc();
  12065. NoteRange = ErrorRange =
  12066. SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
  12067. ErrorFound = NotACompoundStatement;
  12068. }
  12069. }
  12070. if (ErrorFound != NoError) {
  12071. Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
  12072. << ErrorRange;
  12073. Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
  12074. return StmtError();
  12075. }
  12076. if (CurContext->isDependentContext())
  12077. UE = V = E = X = nullptr;
  12078. } else if (AtomicKind == OMPC_compare) {
  12079. if (IsCompareCapture) {
  12080. OpenMPAtomicCompareCaptureChecker::ErrorInfoTy ErrorInfo;
  12081. OpenMPAtomicCompareCaptureChecker Checker(*this);
  12082. if (!Checker.checkStmt(Body, ErrorInfo)) {
  12083. Diag(ErrorInfo.ErrorLoc, diag::err_omp_atomic_compare_capture)
  12084. << ErrorInfo.ErrorRange;
  12085. Diag(ErrorInfo.NoteLoc, diag::note_omp_atomic_compare)
  12086. << ErrorInfo.Error << ErrorInfo.NoteRange;
  12087. return StmtError();
  12088. }
  12089. X = Checker.getX();
  12090. E = Checker.getE();
  12091. D = Checker.getD();
  12092. CE = Checker.getCond();
  12093. V = Checker.getV();
  12094. R = Checker.getR();
  12095. // We reuse IsXLHSInRHSPart to tell if it is in the form 'x ordop expr'.
  12096. IsXLHSInRHSPart = Checker.isXBinopExpr();
  12097. IsFailOnly = Checker.isFailOnly();
  12098. IsPostfixUpdate = Checker.isPostfixUpdate();
  12099. } else {
  12100. OpenMPAtomicCompareChecker::ErrorInfoTy ErrorInfo;
  12101. OpenMPAtomicCompareChecker Checker(*this);
  12102. if (!Checker.checkStmt(Body, ErrorInfo)) {
  12103. Diag(ErrorInfo.ErrorLoc, diag::err_omp_atomic_compare)
  12104. << ErrorInfo.ErrorRange;
  12105. Diag(ErrorInfo.NoteLoc, diag::note_omp_atomic_compare)
  12106. << ErrorInfo.Error << ErrorInfo.NoteRange;
  12107. return StmtError();
  12108. }
  12109. X = Checker.getX();
  12110. E = Checker.getE();
  12111. D = Checker.getD();
  12112. CE = Checker.getCond();
  12113. // We reuse IsXLHSInRHSPart to tell if it is in the form 'x ordop expr'.
  12114. IsXLHSInRHSPart = Checker.isXBinopExpr();
  12115. }
  12116. }
  12117. setFunctionHasBranchProtectedScope();
  12118. return OMPAtomicDirective::Create(
  12119. Context, StartLoc, EndLoc, Clauses, AStmt,
  12120. {X, V, R, E, UE, D, CE, IsXLHSInRHSPart, IsPostfixUpdate, IsFailOnly});
  12121. }
  12122. StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
  12123. Stmt *AStmt,
  12124. SourceLocation StartLoc,
  12125. SourceLocation EndLoc) {
  12126. if (!AStmt)
  12127. return StmtError();
  12128. auto *CS = cast<CapturedStmt>(AStmt);
  12129. // 1.2.2 OpenMP Language Terminology
  12130. // Structured block - An executable statement with a single entry at the
  12131. // top and a single exit at the bottom.
  12132. // The point of exit cannot be a branch out of the structured block.
  12133. // longjmp() and throw() must not violate the entry/exit criteria.
  12134. CS->getCapturedDecl()->setNothrow();
  12135. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
  12136. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  12137. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  12138. // 1.2.2 OpenMP Language Terminology
  12139. // Structured block - An executable statement with a single entry at the
  12140. // top and a single exit at the bottom.
  12141. // The point of exit cannot be a branch out of the structured block.
  12142. // longjmp() and throw() must not violate the entry/exit criteria.
  12143. CS->getCapturedDecl()->setNothrow();
  12144. }
  12145. // OpenMP [2.16, Nesting of Regions]
  12146. // If specified, a teams construct must be contained within a target
  12147. // construct. That target construct must contain no statements or directives
  12148. // outside of the teams construct.
  12149. if (DSAStack->hasInnerTeamsRegion()) {
  12150. const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
  12151. bool OMPTeamsFound = true;
  12152. if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
  12153. auto I = CS->body_begin();
  12154. while (I != CS->body_end()) {
  12155. const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
  12156. if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
  12157. OMPTeamsFound) {
  12158. OMPTeamsFound = false;
  12159. break;
  12160. }
  12161. ++I;
  12162. }
  12163. assert(I != CS->body_end() && "Not found statement");
  12164. S = *I;
  12165. } else {
  12166. const auto *OED = dyn_cast<OMPExecutableDirective>(S);
  12167. OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
  12168. }
  12169. if (!OMPTeamsFound) {
  12170. Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
  12171. Diag(DSAStack->getInnerTeamsRegionLoc(),
  12172. diag::note_omp_nested_teams_construct_here);
  12173. Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
  12174. << isa<OMPExecutableDirective>(S);
  12175. return StmtError();
  12176. }
  12177. }
  12178. setFunctionHasBranchProtectedScope();
  12179. return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  12180. }
  12181. StmtResult
  12182. Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
  12183. Stmt *AStmt, SourceLocation StartLoc,
  12184. SourceLocation EndLoc) {
  12185. if (!AStmt)
  12186. return StmtError();
  12187. auto *CS = cast<CapturedStmt>(AStmt);
  12188. // 1.2.2 OpenMP Language Terminology
  12189. // Structured block - An executable statement with a single entry at the
  12190. // top and a single exit at the bottom.
  12191. // The point of exit cannot be a branch out of the structured block.
  12192. // longjmp() and throw() must not violate the entry/exit criteria.
  12193. CS->getCapturedDecl()->setNothrow();
  12194. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
  12195. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  12196. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  12197. // 1.2.2 OpenMP Language Terminology
  12198. // Structured block - An executable statement with a single entry at the
  12199. // top and a single exit at the bottom.
  12200. // The point of exit cannot be a branch out of the structured block.
  12201. // longjmp() and throw() must not violate the entry/exit criteria.
  12202. CS->getCapturedDecl()->setNothrow();
  12203. }
  12204. setFunctionHasBranchProtectedScope();
  12205. return OMPTargetParallelDirective::Create(
  12206. Context, StartLoc, EndLoc, Clauses, AStmt,
  12207. DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
  12208. }
  12209. StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
  12210. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  12211. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  12212. if (!AStmt)
  12213. return StmtError();
  12214. auto *CS = cast<CapturedStmt>(AStmt);
  12215. // 1.2.2 OpenMP Language Terminology
  12216. // Structured block - An executable statement with a single entry at the
  12217. // top and a single exit at the bottom.
  12218. // The point of exit cannot be a branch out of the structured block.
  12219. // longjmp() and throw() must not violate the entry/exit criteria.
  12220. CS->getCapturedDecl()->setNothrow();
  12221. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  12222. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  12223. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  12224. // 1.2.2 OpenMP Language Terminology
  12225. // Structured block - An executable statement with a single entry at the
  12226. // top and a single exit at the bottom.
  12227. // The point of exit cannot be a branch out of the structured block.
  12228. // longjmp() and throw() must not violate the entry/exit criteria.
  12229. CS->getCapturedDecl()->setNothrow();
  12230. }
  12231. OMPLoopBasedDirective::HelperExprs B;
  12232. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  12233. // define the nested loops number.
  12234. unsigned NestedLoopCount =
  12235. checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
  12236. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  12237. VarsWithImplicitDSA, B);
  12238. if (NestedLoopCount == 0)
  12239. return StmtError();
  12240. assert((CurContext->isDependentContext() || B.builtAll()) &&
  12241. "omp target parallel for loop exprs were not built");
  12242. if (!CurContext->isDependentContext()) {
  12243. // Finalize the clauses that need pre-built expressions for CodeGen.
  12244. for (OMPClause *C : Clauses) {
  12245. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  12246. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  12247. B.NumIterations, *this, CurScope,
  12248. DSAStack))
  12249. return StmtError();
  12250. }
  12251. }
  12252. setFunctionHasBranchProtectedScope();
  12253. return OMPTargetParallelForDirective::Create(
  12254. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  12255. DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
  12256. }
  12257. /// Check for existence of a map clause in the list of clauses.
  12258. static bool hasClauses(ArrayRef<OMPClause *> Clauses,
  12259. const OpenMPClauseKind K) {
  12260. return llvm::any_of(
  12261. Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
  12262. }
  12263. template <typename... Params>
  12264. static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
  12265. const Params... ClauseTypes) {
  12266. return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
  12267. }
  12268. /// Check if the variables in the mapping clause are externally visible.
  12269. static bool isClauseMappable(ArrayRef<OMPClause *> Clauses) {
  12270. for (const OMPClause *C : Clauses) {
  12271. if (auto *TC = dyn_cast<OMPToClause>(C))
  12272. return llvm::all_of(TC->all_decls(), [](ValueDecl *VD) {
  12273. return !VD || !VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
  12274. (VD->isExternallyVisible() &&
  12275. VD->getVisibility() != HiddenVisibility);
  12276. });
  12277. else if (auto *FC = dyn_cast<OMPFromClause>(C))
  12278. return llvm::all_of(FC->all_decls(), [](ValueDecl *VD) {
  12279. return !VD || !VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
  12280. (VD->isExternallyVisible() &&
  12281. VD->getVisibility() != HiddenVisibility);
  12282. });
  12283. }
  12284. return true;
  12285. }
  12286. StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
  12287. Stmt *AStmt,
  12288. SourceLocation StartLoc,
  12289. SourceLocation EndLoc) {
  12290. if (!AStmt)
  12291. return StmtError();
  12292. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  12293. // OpenMP [2.12.2, target data Construct, Restrictions]
  12294. // At least one map, use_device_addr or use_device_ptr clause must appear on
  12295. // the directive.
  12296. if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) &&
  12297. (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) {
  12298. StringRef Expected;
  12299. if (LangOpts.OpenMP < 50)
  12300. Expected = "'map' or 'use_device_ptr'";
  12301. else
  12302. Expected = "'map', 'use_device_ptr', or 'use_device_addr'";
  12303. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  12304. << Expected << getOpenMPDirectiveName(OMPD_target_data);
  12305. return StmtError();
  12306. }
  12307. setFunctionHasBranchProtectedScope();
  12308. return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  12309. AStmt);
  12310. }
  12311. StmtResult
  12312. Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
  12313. SourceLocation StartLoc,
  12314. SourceLocation EndLoc, Stmt *AStmt) {
  12315. if (!AStmt)
  12316. return StmtError();
  12317. auto *CS = cast<CapturedStmt>(AStmt);
  12318. // 1.2.2 OpenMP Language Terminology
  12319. // Structured block - An executable statement with a single entry at the
  12320. // top and a single exit at the bottom.
  12321. // The point of exit cannot be a branch out of the structured block.
  12322. // longjmp() and throw() must not violate the entry/exit criteria.
  12323. CS->getCapturedDecl()->setNothrow();
  12324. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
  12325. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  12326. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  12327. // 1.2.2 OpenMP Language Terminology
  12328. // Structured block - An executable statement with a single entry at the
  12329. // top and a single exit at the bottom.
  12330. // The point of exit cannot be a branch out of the structured block.
  12331. // longjmp() and throw() must not violate the entry/exit criteria.
  12332. CS->getCapturedDecl()->setNothrow();
  12333. }
  12334. // OpenMP [2.10.2, Restrictions, p. 99]
  12335. // At least one map clause must appear on the directive.
  12336. if (!hasClauses(Clauses, OMPC_map)) {
  12337. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  12338. << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
  12339. return StmtError();
  12340. }
  12341. return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  12342. AStmt);
  12343. }
  12344. StmtResult
  12345. Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
  12346. SourceLocation StartLoc,
  12347. SourceLocation EndLoc, Stmt *AStmt) {
  12348. if (!AStmt)
  12349. return StmtError();
  12350. auto *CS = cast<CapturedStmt>(AStmt);
  12351. // 1.2.2 OpenMP Language Terminology
  12352. // Structured block - An executable statement with a single entry at the
  12353. // top and a single exit at the bottom.
  12354. // The point of exit cannot be a branch out of the structured block.
  12355. // longjmp() and throw() must not violate the entry/exit criteria.
  12356. CS->getCapturedDecl()->setNothrow();
  12357. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
  12358. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  12359. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  12360. // 1.2.2 OpenMP Language Terminology
  12361. // Structured block - An executable statement with a single entry at the
  12362. // top and a single exit at the bottom.
  12363. // The point of exit cannot be a branch out of the structured block.
  12364. // longjmp() and throw() must not violate the entry/exit criteria.
  12365. CS->getCapturedDecl()->setNothrow();
  12366. }
  12367. // OpenMP [2.10.3, Restrictions, p. 102]
  12368. // At least one map clause must appear on the directive.
  12369. if (!hasClauses(Clauses, OMPC_map)) {
  12370. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  12371. << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
  12372. return StmtError();
  12373. }
  12374. return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
  12375. AStmt);
  12376. }
  12377. StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
  12378. SourceLocation StartLoc,
  12379. SourceLocation EndLoc,
  12380. Stmt *AStmt) {
  12381. if (!AStmt)
  12382. return StmtError();
  12383. auto *CS = cast<CapturedStmt>(AStmt);
  12384. // 1.2.2 OpenMP Language Terminology
  12385. // Structured block - An executable statement with a single entry at the
  12386. // top and a single exit at the bottom.
  12387. // The point of exit cannot be a branch out of the structured block.
  12388. // longjmp() and throw() must not violate the entry/exit criteria.
  12389. CS->getCapturedDecl()->setNothrow();
  12390. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
  12391. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  12392. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  12393. // 1.2.2 OpenMP Language Terminology
  12394. // Structured block - An executable statement with a single entry at the
  12395. // top and a single exit at the bottom.
  12396. // The point of exit cannot be a branch out of the structured block.
  12397. // longjmp() and throw() must not violate the entry/exit criteria.
  12398. CS->getCapturedDecl()->setNothrow();
  12399. }
  12400. if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
  12401. Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
  12402. return StmtError();
  12403. }
  12404. if (!isClauseMappable(Clauses)) {
  12405. Diag(StartLoc, diag::err_omp_cannot_update_with_internal_linkage);
  12406. return StmtError();
  12407. }
  12408. return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
  12409. AStmt);
  12410. }
  12411. StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
  12412. Stmt *AStmt, SourceLocation StartLoc,
  12413. SourceLocation EndLoc) {
  12414. if (!AStmt)
  12415. return StmtError();
  12416. auto *CS = cast<CapturedStmt>(AStmt);
  12417. // 1.2.2 OpenMP Language Terminology
  12418. // Structured block - An executable statement with a single entry at the
  12419. // top and a single exit at the bottom.
  12420. // The point of exit cannot be a branch out of the structured block.
  12421. // longjmp() and throw() must not violate the entry/exit criteria.
  12422. CS->getCapturedDecl()->setNothrow();
  12423. setFunctionHasBranchProtectedScope();
  12424. DSAStack->setParentTeamsRegionLoc(StartLoc);
  12425. return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
  12426. }
  12427. StmtResult
  12428. Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
  12429. SourceLocation EndLoc,
  12430. OpenMPDirectiveKind CancelRegion) {
  12431. if (DSAStack->isParentNowaitRegion()) {
  12432. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
  12433. return StmtError();
  12434. }
  12435. if (DSAStack->isParentOrderedRegion()) {
  12436. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
  12437. return StmtError();
  12438. }
  12439. return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
  12440. CancelRegion);
  12441. }
  12442. StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
  12443. SourceLocation StartLoc,
  12444. SourceLocation EndLoc,
  12445. OpenMPDirectiveKind CancelRegion) {
  12446. if (DSAStack->isParentNowaitRegion()) {
  12447. Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
  12448. return StmtError();
  12449. }
  12450. if (DSAStack->isParentOrderedRegion()) {
  12451. Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
  12452. return StmtError();
  12453. }
  12454. DSAStack->setParentCancelRegion(/*Cancel=*/true);
  12455. return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
  12456. CancelRegion);
  12457. }
  12458. static bool checkReductionClauseWithNogroup(Sema &S,
  12459. ArrayRef<OMPClause *> Clauses) {
  12460. const OMPClause *ReductionClause = nullptr;
  12461. const OMPClause *NogroupClause = nullptr;
  12462. for (const OMPClause *C : Clauses) {
  12463. if (C->getClauseKind() == OMPC_reduction) {
  12464. ReductionClause = C;
  12465. if (NogroupClause)
  12466. break;
  12467. continue;
  12468. }
  12469. if (C->getClauseKind() == OMPC_nogroup) {
  12470. NogroupClause = C;
  12471. if (ReductionClause)
  12472. break;
  12473. continue;
  12474. }
  12475. }
  12476. if (ReductionClause && NogroupClause) {
  12477. S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
  12478. << SourceRange(NogroupClause->getBeginLoc(),
  12479. NogroupClause->getEndLoc());
  12480. return true;
  12481. }
  12482. return false;
  12483. }
  12484. StmtResult Sema::ActOnOpenMPTaskLoopDirective(
  12485. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  12486. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  12487. if (!AStmt)
  12488. return StmtError();
  12489. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  12490. OMPLoopBasedDirective::HelperExprs B;
  12491. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  12492. // define the nested loops number.
  12493. unsigned NestedLoopCount =
  12494. checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
  12495. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  12496. VarsWithImplicitDSA, B);
  12497. if (NestedLoopCount == 0)
  12498. return StmtError();
  12499. assert((CurContext->isDependentContext() || B.builtAll()) &&
  12500. "omp for loop exprs were not built");
  12501. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12502. // The grainsize clause and num_tasks clause are mutually exclusive and may
  12503. // not appear on the same taskloop directive.
  12504. if (checkMutuallyExclusiveClauses(*this, Clauses,
  12505. {OMPC_grainsize, OMPC_num_tasks}))
  12506. return StmtError();
  12507. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12508. // If a reduction clause is present on the taskloop directive, the nogroup
  12509. // clause must not be specified.
  12510. if (checkReductionClauseWithNogroup(*this, Clauses))
  12511. return StmtError();
  12512. setFunctionHasBranchProtectedScope();
  12513. return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  12514. NestedLoopCount, Clauses, AStmt, B,
  12515. DSAStack->isCancelRegion());
  12516. }
  12517. StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
  12518. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  12519. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  12520. if (!AStmt)
  12521. return StmtError();
  12522. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  12523. OMPLoopBasedDirective::HelperExprs B;
  12524. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  12525. // define the nested loops number.
  12526. unsigned NestedLoopCount =
  12527. checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
  12528. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  12529. VarsWithImplicitDSA, B);
  12530. if (NestedLoopCount == 0)
  12531. return StmtError();
  12532. assert((CurContext->isDependentContext() || B.builtAll()) &&
  12533. "omp for loop exprs were not built");
  12534. if (!CurContext->isDependentContext()) {
  12535. // Finalize the clauses that need pre-built expressions for CodeGen.
  12536. for (OMPClause *C : Clauses) {
  12537. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  12538. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  12539. B.NumIterations, *this, CurScope,
  12540. DSAStack))
  12541. return StmtError();
  12542. }
  12543. }
  12544. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12545. // The grainsize clause and num_tasks clause are mutually exclusive and may
  12546. // not appear on the same taskloop directive.
  12547. if (checkMutuallyExclusiveClauses(*this, Clauses,
  12548. {OMPC_grainsize, OMPC_num_tasks}))
  12549. return StmtError();
  12550. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12551. // If a reduction clause is present on the taskloop directive, the nogroup
  12552. // clause must not be specified.
  12553. if (checkReductionClauseWithNogroup(*this, Clauses))
  12554. return StmtError();
  12555. if (checkSimdlenSafelenSpecified(*this, Clauses))
  12556. return StmtError();
  12557. setFunctionHasBranchProtectedScope();
  12558. return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
  12559. NestedLoopCount, Clauses, AStmt, B);
  12560. }
  12561. StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
  12562. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  12563. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  12564. if (!AStmt)
  12565. return StmtError();
  12566. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  12567. OMPLoopBasedDirective::HelperExprs B;
  12568. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  12569. // define the nested loops number.
  12570. unsigned NestedLoopCount =
  12571. checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
  12572. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  12573. VarsWithImplicitDSA, B);
  12574. if (NestedLoopCount == 0)
  12575. return StmtError();
  12576. assert((CurContext->isDependentContext() || B.builtAll()) &&
  12577. "omp for loop exprs were not built");
  12578. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12579. // The grainsize clause and num_tasks clause are mutually exclusive and may
  12580. // not appear on the same taskloop directive.
  12581. if (checkMutuallyExclusiveClauses(*this, Clauses,
  12582. {OMPC_grainsize, OMPC_num_tasks}))
  12583. return StmtError();
  12584. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12585. // If a reduction clause is present on the taskloop directive, the nogroup
  12586. // clause must not be specified.
  12587. if (checkReductionClauseWithNogroup(*this, Clauses))
  12588. return StmtError();
  12589. setFunctionHasBranchProtectedScope();
  12590. return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  12591. NestedLoopCount, Clauses, AStmt, B,
  12592. DSAStack->isCancelRegion());
  12593. }
  12594. StmtResult Sema::ActOnOpenMPMaskedTaskLoopDirective(
  12595. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  12596. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  12597. if (!AStmt)
  12598. return StmtError();
  12599. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  12600. OMPLoopBasedDirective::HelperExprs B;
  12601. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  12602. // define the nested loops number.
  12603. unsigned NestedLoopCount =
  12604. checkOpenMPLoop(OMPD_masked_taskloop, getCollapseNumberExpr(Clauses),
  12605. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  12606. VarsWithImplicitDSA, B);
  12607. if (NestedLoopCount == 0)
  12608. return StmtError();
  12609. assert((CurContext->isDependentContext() || B.builtAll()) &&
  12610. "omp for loop exprs were not built");
  12611. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12612. // The grainsize clause and num_tasks clause are mutually exclusive and may
  12613. // not appear on the same taskloop directive.
  12614. if (checkMutuallyExclusiveClauses(*this, Clauses,
  12615. {OMPC_grainsize, OMPC_num_tasks}))
  12616. return StmtError();
  12617. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12618. // If a reduction clause is present on the taskloop directive, the nogroup
  12619. // clause must not be specified.
  12620. if (checkReductionClauseWithNogroup(*this, Clauses))
  12621. return StmtError();
  12622. setFunctionHasBranchProtectedScope();
  12623. return OMPMaskedTaskLoopDirective::Create(Context, StartLoc, EndLoc,
  12624. NestedLoopCount, Clauses, AStmt, B,
  12625. DSAStack->isCancelRegion());
  12626. }
  12627. StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
  12628. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  12629. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  12630. if (!AStmt)
  12631. return StmtError();
  12632. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  12633. OMPLoopBasedDirective::HelperExprs B;
  12634. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  12635. // define the nested loops number.
  12636. unsigned NestedLoopCount =
  12637. checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
  12638. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  12639. VarsWithImplicitDSA, B);
  12640. if (NestedLoopCount == 0)
  12641. return StmtError();
  12642. assert((CurContext->isDependentContext() || B.builtAll()) &&
  12643. "omp for loop exprs were not built");
  12644. if (!CurContext->isDependentContext()) {
  12645. // Finalize the clauses that need pre-built expressions for CodeGen.
  12646. for (OMPClause *C : Clauses) {
  12647. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  12648. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  12649. B.NumIterations, *this, CurScope,
  12650. DSAStack))
  12651. return StmtError();
  12652. }
  12653. }
  12654. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12655. // The grainsize clause and num_tasks clause are mutually exclusive and may
  12656. // not appear on the same taskloop directive.
  12657. if (checkMutuallyExclusiveClauses(*this, Clauses,
  12658. {OMPC_grainsize, OMPC_num_tasks}))
  12659. return StmtError();
  12660. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12661. // If a reduction clause is present on the taskloop directive, the nogroup
  12662. // clause must not be specified.
  12663. if (checkReductionClauseWithNogroup(*this, Clauses))
  12664. return StmtError();
  12665. if (checkSimdlenSafelenSpecified(*this, Clauses))
  12666. return StmtError();
  12667. setFunctionHasBranchProtectedScope();
  12668. return OMPMasterTaskLoopSimdDirective::Create(
  12669. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  12670. }
  12671. StmtResult Sema::ActOnOpenMPMaskedTaskLoopSimdDirective(
  12672. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  12673. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  12674. if (!AStmt)
  12675. return StmtError();
  12676. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  12677. OMPLoopBasedDirective::HelperExprs B;
  12678. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  12679. // define the nested loops number.
  12680. unsigned NestedLoopCount =
  12681. checkOpenMPLoop(OMPD_masked_taskloop_simd, getCollapseNumberExpr(Clauses),
  12682. /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
  12683. VarsWithImplicitDSA, B);
  12684. if (NestedLoopCount == 0)
  12685. return StmtError();
  12686. assert((CurContext->isDependentContext() || B.builtAll()) &&
  12687. "omp for loop exprs were not built");
  12688. if (!CurContext->isDependentContext()) {
  12689. // Finalize the clauses that need pre-built expressions for CodeGen.
  12690. for (OMPClause *C : Clauses) {
  12691. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  12692. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  12693. B.NumIterations, *this, CurScope,
  12694. DSAStack))
  12695. return StmtError();
  12696. }
  12697. }
  12698. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12699. // The grainsize clause and num_tasks clause are mutually exclusive and may
  12700. // not appear on the same taskloop directive.
  12701. if (checkMutuallyExclusiveClauses(*this, Clauses,
  12702. {OMPC_grainsize, OMPC_num_tasks}))
  12703. return StmtError();
  12704. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12705. // If a reduction clause is present on the taskloop directive, the nogroup
  12706. // clause must not be specified.
  12707. if (checkReductionClauseWithNogroup(*this, Clauses))
  12708. return StmtError();
  12709. if (checkSimdlenSafelenSpecified(*this, Clauses))
  12710. return StmtError();
  12711. setFunctionHasBranchProtectedScope();
  12712. return OMPMaskedTaskLoopSimdDirective::Create(
  12713. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  12714. }
  12715. StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
  12716. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  12717. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  12718. if (!AStmt)
  12719. return StmtError();
  12720. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  12721. auto *CS = cast<CapturedStmt>(AStmt);
  12722. // 1.2.2 OpenMP Language Terminology
  12723. // Structured block - An executable statement with a single entry at the
  12724. // top and a single exit at the bottom.
  12725. // The point of exit cannot be a branch out of the structured block.
  12726. // longjmp() and throw() must not violate the entry/exit criteria.
  12727. CS->getCapturedDecl()->setNothrow();
  12728. for (int ThisCaptureLevel =
  12729. getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
  12730. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  12731. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  12732. // 1.2.2 OpenMP Language Terminology
  12733. // Structured block - An executable statement with a single entry at the
  12734. // top and a single exit at the bottom.
  12735. // The point of exit cannot be a branch out of the structured block.
  12736. // longjmp() and throw() must not violate the entry/exit criteria.
  12737. CS->getCapturedDecl()->setNothrow();
  12738. }
  12739. OMPLoopBasedDirective::HelperExprs B;
  12740. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  12741. // define the nested loops number.
  12742. unsigned NestedLoopCount = checkOpenMPLoop(
  12743. OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
  12744. /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
  12745. VarsWithImplicitDSA, B);
  12746. if (NestedLoopCount == 0)
  12747. return StmtError();
  12748. assert((CurContext->isDependentContext() || B.builtAll()) &&
  12749. "omp for loop exprs were not built");
  12750. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12751. // The grainsize clause and num_tasks clause are mutually exclusive and may
  12752. // not appear on the same taskloop directive.
  12753. if (checkMutuallyExclusiveClauses(*this, Clauses,
  12754. {OMPC_grainsize, OMPC_num_tasks}))
  12755. return StmtError();
  12756. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12757. // If a reduction clause is present on the taskloop directive, the nogroup
  12758. // clause must not be specified.
  12759. if (checkReductionClauseWithNogroup(*this, Clauses))
  12760. return StmtError();
  12761. setFunctionHasBranchProtectedScope();
  12762. return OMPParallelMasterTaskLoopDirective::Create(
  12763. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  12764. DSAStack->isCancelRegion());
  12765. }
  12766. StmtResult Sema::ActOnOpenMPParallelMaskedTaskLoopDirective(
  12767. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  12768. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  12769. if (!AStmt)
  12770. return StmtError();
  12771. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  12772. auto *CS = cast<CapturedStmt>(AStmt);
  12773. // 1.2.2 OpenMP Language Terminology
  12774. // Structured block - An executable statement with a single entry at the
  12775. // top and a single exit at the bottom.
  12776. // The point of exit cannot be a branch out of the structured block.
  12777. // longjmp() and throw() must not violate the entry/exit criteria.
  12778. CS->getCapturedDecl()->setNothrow();
  12779. for (int ThisCaptureLevel =
  12780. getOpenMPCaptureLevels(OMPD_parallel_masked_taskloop);
  12781. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  12782. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  12783. // 1.2.2 OpenMP Language Terminology
  12784. // Structured block - An executable statement with a single entry at the
  12785. // top and a single exit at the bottom.
  12786. // The point of exit cannot be a branch out of the structured block.
  12787. // longjmp() and throw() must not violate the entry/exit criteria.
  12788. CS->getCapturedDecl()->setNothrow();
  12789. }
  12790. OMPLoopBasedDirective::HelperExprs B;
  12791. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  12792. // define the nested loops number.
  12793. unsigned NestedLoopCount = checkOpenMPLoop(
  12794. OMPD_parallel_masked_taskloop, getCollapseNumberExpr(Clauses),
  12795. /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
  12796. VarsWithImplicitDSA, B);
  12797. if (NestedLoopCount == 0)
  12798. return StmtError();
  12799. assert((CurContext->isDependentContext() || B.builtAll()) &&
  12800. "omp for loop exprs were not built");
  12801. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12802. // The grainsize clause and num_tasks clause are mutually exclusive and may
  12803. // not appear on the same taskloop directive.
  12804. if (checkMutuallyExclusiveClauses(*this, Clauses,
  12805. {OMPC_grainsize, OMPC_num_tasks}))
  12806. return StmtError();
  12807. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12808. // If a reduction clause is present on the taskloop directive, the nogroup
  12809. // clause must not be specified.
  12810. if (checkReductionClauseWithNogroup(*this, Clauses))
  12811. return StmtError();
  12812. setFunctionHasBranchProtectedScope();
  12813. return OMPParallelMaskedTaskLoopDirective::Create(
  12814. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  12815. DSAStack->isCancelRegion());
  12816. }
  12817. StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
  12818. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  12819. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  12820. if (!AStmt)
  12821. return StmtError();
  12822. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  12823. auto *CS = cast<CapturedStmt>(AStmt);
  12824. // 1.2.2 OpenMP Language Terminology
  12825. // Structured block - An executable statement with a single entry at the
  12826. // top and a single exit at the bottom.
  12827. // The point of exit cannot be a branch out of the structured block.
  12828. // longjmp() and throw() must not violate the entry/exit criteria.
  12829. CS->getCapturedDecl()->setNothrow();
  12830. for (int ThisCaptureLevel =
  12831. getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
  12832. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  12833. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  12834. // 1.2.2 OpenMP Language Terminology
  12835. // Structured block - An executable statement with a single entry at the
  12836. // top and a single exit at the bottom.
  12837. // The point of exit cannot be a branch out of the structured block.
  12838. // longjmp() and throw() must not violate the entry/exit criteria.
  12839. CS->getCapturedDecl()->setNothrow();
  12840. }
  12841. OMPLoopBasedDirective::HelperExprs B;
  12842. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  12843. // define the nested loops number.
  12844. unsigned NestedLoopCount = checkOpenMPLoop(
  12845. OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
  12846. /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
  12847. VarsWithImplicitDSA, B);
  12848. if (NestedLoopCount == 0)
  12849. return StmtError();
  12850. assert((CurContext->isDependentContext() || B.builtAll()) &&
  12851. "omp for loop exprs were not built");
  12852. if (!CurContext->isDependentContext()) {
  12853. // Finalize the clauses that need pre-built expressions for CodeGen.
  12854. for (OMPClause *C : Clauses) {
  12855. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  12856. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  12857. B.NumIterations, *this, CurScope,
  12858. DSAStack))
  12859. return StmtError();
  12860. }
  12861. }
  12862. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12863. // The grainsize clause and num_tasks clause are mutually exclusive and may
  12864. // not appear on the same taskloop directive.
  12865. if (checkMutuallyExclusiveClauses(*this, Clauses,
  12866. {OMPC_grainsize, OMPC_num_tasks}))
  12867. return StmtError();
  12868. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12869. // If a reduction clause is present on the taskloop directive, the nogroup
  12870. // clause must not be specified.
  12871. if (checkReductionClauseWithNogroup(*this, Clauses))
  12872. return StmtError();
  12873. if (checkSimdlenSafelenSpecified(*this, Clauses))
  12874. return StmtError();
  12875. setFunctionHasBranchProtectedScope();
  12876. return OMPParallelMasterTaskLoopSimdDirective::Create(
  12877. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  12878. }
  12879. StmtResult Sema::ActOnOpenMPParallelMaskedTaskLoopSimdDirective(
  12880. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  12881. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  12882. if (!AStmt)
  12883. return StmtError();
  12884. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  12885. auto *CS = cast<CapturedStmt>(AStmt);
  12886. // 1.2.2 OpenMP Language Terminology
  12887. // Structured block - An executable statement with a single entry at the
  12888. // top and a single exit at the bottom.
  12889. // The point of exit cannot be a branch out of the structured block.
  12890. // longjmp() and throw() must not violate the entry/exit criteria.
  12891. CS->getCapturedDecl()->setNothrow();
  12892. for (int ThisCaptureLevel =
  12893. getOpenMPCaptureLevels(OMPD_parallel_masked_taskloop_simd);
  12894. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  12895. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  12896. // 1.2.2 OpenMP Language Terminology
  12897. // Structured block - An executable statement with a single entry at the
  12898. // top and a single exit at the bottom.
  12899. // The point of exit cannot be a branch out of the structured block.
  12900. // longjmp() and throw() must not violate the entry/exit criteria.
  12901. CS->getCapturedDecl()->setNothrow();
  12902. }
  12903. OMPLoopBasedDirective::HelperExprs B;
  12904. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  12905. // define the nested loops number.
  12906. unsigned NestedLoopCount = checkOpenMPLoop(
  12907. OMPD_parallel_masked_taskloop_simd, getCollapseNumberExpr(Clauses),
  12908. /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
  12909. VarsWithImplicitDSA, B);
  12910. if (NestedLoopCount == 0)
  12911. return StmtError();
  12912. assert((CurContext->isDependentContext() || B.builtAll()) &&
  12913. "omp for loop exprs were not built");
  12914. if (!CurContext->isDependentContext()) {
  12915. // Finalize the clauses that need pre-built expressions for CodeGen.
  12916. for (OMPClause *C : Clauses) {
  12917. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  12918. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  12919. B.NumIterations, *this, CurScope,
  12920. DSAStack))
  12921. return StmtError();
  12922. }
  12923. }
  12924. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12925. // The grainsize clause and num_tasks clause are mutually exclusive and may
  12926. // not appear on the same taskloop directive.
  12927. if (checkMutuallyExclusiveClauses(*this, Clauses,
  12928. {OMPC_grainsize, OMPC_num_tasks}))
  12929. return StmtError();
  12930. // OpenMP, [2.9.2 taskloop Construct, Restrictions]
  12931. // If a reduction clause is present on the taskloop directive, the nogroup
  12932. // clause must not be specified.
  12933. if (checkReductionClauseWithNogroup(*this, Clauses))
  12934. return StmtError();
  12935. if (checkSimdlenSafelenSpecified(*this, Clauses))
  12936. return StmtError();
  12937. setFunctionHasBranchProtectedScope();
  12938. return OMPParallelMaskedTaskLoopSimdDirective::Create(
  12939. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  12940. }
  12941. StmtResult Sema::ActOnOpenMPDistributeDirective(
  12942. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  12943. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  12944. if (!AStmt)
  12945. return StmtError();
  12946. assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
  12947. OMPLoopBasedDirective::HelperExprs B;
  12948. // In presence of clause 'collapse' with number of loops, it will
  12949. // define the nested loops number.
  12950. unsigned NestedLoopCount =
  12951. checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
  12952. nullptr /*ordered not a clause on distribute*/, AStmt,
  12953. *this, *DSAStack, VarsWithImplicitDSA, B);
  12954. if (NestedLoopCount == 0)
  12955. return StmtError();
  12956. assert((CurContext->isDependentContext() || B.builtAll()) &&
  12957. "omp for loop exprs were not built");
  12958. setFunctionHasBranchProtectedScope();
  12959. return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
  12960. NestedLoopCount, Clauses, AStmt, B);
  12961. }
  12962. StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
  12963. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  12964. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  12965. if (!AStmt)
  12966. return StmtError();
  12967. auto *CS = cast<CapturedStmt>(AStmt);
  12968. // 1.2.2 OpenMP Language Terminology
  12969. // Structured block - An executable statement with a single entry at the
  12970. // top and a single exit at the bottom.
  12971. // The point of exit cannot be a branch out of the structured block.
  12972. // longjmp() and throw() must not violate the entry/exit criteria.
  12973. CS->getCapturedDecl()->setNothrow();
  12974. for (int ThisCaptureLevel =
  12975. getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
  12976. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  12977. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  12978. // 1.2.2 OpenMP Language Terminology
  12979. // Structured block - An executable statement with a single entry at the
  12980. // top and a single exit at the bottom.
  12981. // The point of exit cannot be a branch out of the structured block.
  12982. // longjmp() and throw() must not violate the entry/exit criteria.
  12983. CS->getCapturedDecl()->setNothrow();
  12984. }
  12985. OMPLoopBasedDirective::HelperExprs B;
  12986. // In presence of clause 'collapse' with number of loops, it will
  12987. // define the nested loops number.
  12988. unsigned NestedLoopCount = checkOpenMPLoop(
  12989. OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  12990. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  12991. VarsWithImplicitDSA, B);
  12992. if (NestedLoopCount == 0)
  12993. return StmtError();
  12994. assert((CurContext->isDependentContext() || B.builtAll()) &&
  12995. "omp for loop exprs were not built");
  12996. setFunctionHasBranchProtectedScope();
  12997. return OMPDistributeParallelForDirective::Create(
  12998. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  12999. DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
  13000. }
  13001. StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
  13002. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  13003. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  13004. if (!AStmt)
  13005. return StmtError();
  13006. auto *CS = cast<CapturedStmt>(AStmt);
  13007. // 1.2.2 OpenMP Language Terminology
  13008. // Structured block - An executable statement with a single entry at the
  13009. // top and a single exit at the bottom.
  13010. // The point of exit cannot be a branch out of the structured block.
  13011. // longjmp() and throw() must not violate the entry/exit criteria.
  13012. CS->getCapturedDecl()->setNothrow();
  13013. for (int ThisCaptureLevel =
  13014. getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
  13015. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  13016. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  13017. // 1.2.2 OpenMP Language Terminology
  13018. // Structured block - An executable statement with a single entry at the
  13019. // top and a single exit at the bottom.
  13020. // The point of exit cannot be a branch out of the structured block.
  13021. // longjmp() and throw() must not violate the entry/exit criteria.
  13022. CS->getCapturedDecl()->setNothrow();
  13023. }
  13024. OMPLoopBasedDirective::HelperExprs B;
  13025. // In presence of clause 'collapse' with number of loops, it will
  13026. // define the nested loops number.
  13027. unsigned NestedLoopCount = checkOpenMPLoop(
  13028. OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  13029. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  13030. VarsWithImplicitDSA, B);
  13031. if (NestedLoopCount == 0)
  13032. return StmtError();
  13033. assert((CurContext->isDependentContext() || B.builtAll()) &&
  13034. "omp for loop exprs were not built");
  13035. if (!CurContext->isDependentContext()) {
  13036. // Finalize the clauses that need pre-built expressions for CodeGen.
  13037. for (OMPClause *C : Clauses) {
  13038. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  13039. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  13040. B.NumIterations, *this, CurScope,
  13041. DSAStack))
  13042. return StmtError();
  13043. }
  13044. }
  13045. if (checkSimdlenSafelenSpecified(*this, Clauses))
  13046. return StmtError();
  13047. setFunctionHasBranchProtectedScope();
  13048. return OMPDistributeParallelForSimdDirective::Create(
  13049. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  13050. }
  13051. StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
  13052. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  13053. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  13054. if (!AStmt)
  13055. return StmtError();
  13056. auto *CS = cast<CapturedStmt>(AStmt);
  13057. // 1.2.2 OpenMP Language Terminology
  13058. // Structured block - An executable statement with a single entry at the
  13059. // top and a single exit at the bottom.
  13060. // The point of exit cannot be a branch out of the structured block.
  13061. // longjmp() and throw() must not violate the entry/exit criteria.
  13062. CS->getCapturedDecl()->setNothrow();
  13063. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
  13064. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  13065. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  13066. // 1.2.2 OpenMP Language Terminology
  13067. // Structured block - An executable statement with a single entry at the
  13068. // top and a single exit at the bottom.
  13069. // The point of exit cannot be a branch out of the structured block.
  13070. // longjmp() and throw() must not violate the entry/exit criteria.
  13071. CS->getCapturedDecl()->setNothrow();
  13072. }
  13073. OMPLoopBasedDirective::HelperExprs B;
  13074. // In presence of clause 'collapse' with number of loops, it will
  13075. // define the nested loops number.
  13076. unsigned NestedLoopCount =
  13077. checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
  13078. nullptr /*ordered not a clause on distribute*/, CS, *this,
  13079. *DSAStack, VarsWithImplicitDSA, B);
  13080. if (NestedLoopCount == 0)
  13081. return StmtError();
  13082. assert((CurContext->isDependentContext() || B.builtAll()) &&
  13083. "omp for loop exprs were not built");
  13084. if (!CurContext->isDependentContext()) {
  13085. // Finalize the clauses that need pre-built expressions for CodeGen.
  13086. for (OMPClause *C : Clauses) {
  13087. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  13088. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  13089. B.NumIterations, *this, CurScope,
  13090. DSAStack))
  13091. return StmtError();
  13092. }
  13093. }
  13094. if (checkSimdlenSafelenSpecified(*this, Clauses))
  13095. return StmtError();
  13096. setFunctionHasBranchProtectedScope();
  13097. return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
  13098. NestedLoopCount, Clauses, AStmt, B);
  13099. }
  13100. StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
  13101. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  13102. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  13103. if (!AStmt)
  13104. return StmtError();
  13105. auto *CS = cast<CapturedStmt>(AStmt);
  13106. // 1.2.2 OpenMP Language Terminology
  13107. // Structured block - An executable statement with a single entry at the
  13108. // top and a single exit at the bottom.
  13109. // The point of exit cannot be a branch out of the structured block.
  13110. // longjmp() and throw() must not violate the entry/exit criteria.
  13111. CS->getCapturedDecl()->setNothrow();
  13112. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
  13113. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  13114. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  13115. // 1.2.2 OpenMP Language Terminology
  13116. // Structured block - An executable statement with a single entry at the
  13117. // top and a single exit at the bottom.
  13118. // The point of exit cannot be a branch out of the structured block.
  13119. // longjmp() and throw() must not violate the entry/exit criteria.
  13120. CS->getCapturedDecl()->setNothrow();
  13121. }
  13122. OMPLoopBasedDirective::HelperExprs B;
  13123. // In presence of clause 'collapse' or 'ordered' with number of loops, it will
  13124. // define the nested loops number.
  13125. unsigned NestedLoopCount = checkOpenMPLoop(
  13126. OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
  13127. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, VarsWithImplicitDSA,
  13128. B);
  13129. if (NestedLoopCount == 0)
  13130. return StmtError();
  13131. assert((CurContext->isDependentContext() || B.builtAll()) &&
  13132. "omp target parallel for simd loop exprs were not built");
  13133. if (!CurContext->isDependentContext()) {
  13134. // Finalize the clauses that need pre-built expressions for CodeGen.
  13135. for (OMPClause *C : Clauses) {
  13136. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  13137. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  13138. B.NumIterations, *this, CurScope,
  13139. DSAStack))
  13140. return StmtError();
  13141. }
  13142. }
  13143. if (checkSimdlenSafelenSpecified(*this, Clauses))
  13144. return StmtError();
  13145. setFunctionHasBranchProtectedScope();
  13146. return OMPTargetParallelForSimdDirective::Create(
  13147. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  13148. }
  13149. StmtResult Sema::ActOnOpenMPTargetSimdDirective(
  13150. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  13151. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  13152. if (!AStmt)
  13153. return StmtError();
  13154. auto *CS = cast<CapturedStmt>(AStmt);
  13155. // 1.2.2 OpenMP Language Terminology
  13156. // Structured block - An executable statement with a single entry at the
  13157. // top and a single exit at the bottom.
  13158. // The point of exit cannot be a branch out of the structured block.
  13159. // longjmp() and throw() must not violate the entry/exit criteria.
  13160. CS->getCapturedDecl()->setNothrow();
  13161. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
  13162. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  13163. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  13164. // 1.2.2 OpenMP Language Terminology
  13165. // Structured block - An executable statement with a single entry at the
  13166. // top and a single exit at the bottom.
  13167. // The point of exit cannot be a branch out of the structured block.
  13168. // longjmp() and throw() must not violate the entry/exit criteria.
  13169. CS->getCapturedDecl()->setNothrow();
  13170. }
  13171. OMPLoopBasedDirective::HelperExprs B;
  13172. // In presence of clause 'collapse' with number of loops, it will define the
  13173. // nested loops number.
  13174. unsigned NestedLoopCount =
  13175. checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
  13176. getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
  13177. VarsWithImplicitDSA, B);
  13178. if (NestedLoopCount == 0)
  13179. return StmtError();
  13180. assert((CurContext->isDependentContext() || B.builtAll()) &&
  13181. "omp target simd loop exprs were not built");
  13182. if (!CurContext->isDependentContext()) {
  13183. // Finalize the clauses that need pre-built expressions for CodeGen.
  13184. for (OMPClause *C : Clauses) {
  13185. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  13186. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  13187. B.NumIterations, *this, CurScope,
  13188. DSAStack))
  13189. return StmtError();
  13190. }
  13191. }
  13192. if (checkSimdlenSafelenSpecified(*this, Clauses))
  13193. return StmtError();
  13194. setFunctionHasBranchProtectedScope();
  13195. return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
  13196. NestedLoopCount, Clauses, AStmt, B);
  13197. }
  13198. StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
  13199. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  13200. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  13201. if (!AStmt)
  13202. return StmtError();
  13203. auto *CS = cast<CapturedStmt>(AStmt);
  13204. // 1.2.2 OpenMP Language Terminology
  13205. // Structured block - An executable statement with a single entry at the
  13206. // top and a single exit at the bottom.
  13207. // The point of exit cannot be a branch out of the structured block.
  13208. // longjmp() and throw() must not violate the entry/exit criteria.
  13209. CS->getCapturedDecl()->setNothrow();
  13210. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
  13211. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  13212. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  13213. // 1.2.2 OpenMP Language Terminology
  13214. // Structured block - An executable statement with a single entry at the
  13215. // top and a single exit at the bottom.
  13216. // The point of exit cannot be a branch out of the structured block.
  13217. // longjmp() and throw() must not violate the entry/exit criteria.
  13218. CS->getCapturedDecl()->setNothrow();
  13219. }
  13220. OMPLoopBasedDirective::HelperExprs B;
  13221. // In presence of clause 'collapse' with number of loops, it will
  13222. // define the nested loops number.
  13223. unsigned NestedLoopCount =
  13224. checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
  13225. nullptr /*ordered not a clause on distribute*/, CS, *this,
  13226. *DSAStack, VarsWithImplicitDSA, B);
  13227. if (NestedLoopCount == 0)
  13228. return StmtError();
  13229. assert((CurContext->isDependentContext() || B.builtAll()) &&
  13230. "omp teams distribute loop exprs were not built");
  13231. setFunctionHasBranchProtectedScope();
  13232. DSAStack->setParentTeamsRegionLoc(StartLoc);
  13233. return OMPTeamsDistributeDirective::Create(
  13234. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  13235. }
  13236. StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
  13237. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  13238. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  13239. if (!AStmt)
  13240. return StmtError();
  13241. auto *CS = cast<CapturedStmt>(AStmt);
  13242. // 1.2.2 OpenMP Language Terminology
  13243. // Structured block - An executable statement with a single entry at the
  13244. // top and a single exit at the bottom.
  13245. // The point of exit cannot be a branch out of the structured block.
  13246. // longjmp() and throw() must not violate the entry/exit criteria.
  13247. CS->getCapturedDecl()->setNothrow();
  13248. for (int ThisCaptureLevel =
  13249. getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
  13250. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  13251. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  13252. // 1.2.2 OpenMP Language Terminology
  13253. // Structured block - An executable statement with a single entry at the
  13254. // top and a single exit at the bottom.
  13255. // The point of exit cannot be a branch out of the structured block.
  13256. // longjmp() and throw() must not violate the entry/exit criteria.
  13257. CS->getCapturedDecl()->setNothrow();
  13258. }
  13259. OMPLoopBasedDirective::HelperExprs B;
  13260. // In presence of clause 'collapse' with number of loops, it will
  13261. // define the nested loops number.
  13262. unsigned NestedLoopCount = checkOpenMPLoop(
  13263. OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  13264. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  13265. VarsWithImplicitDSA, B);
  13266. if (NestedLoopCount == 0)
  13267. return StmtError();
  13268. assert((CurContext->isDependentContext() || B.builtAll()) &&
  13269. "omp teams distribute simd loop exprs were not built");
  13270. if (!CurContext->isDependentContext()) {
  13271. // Finalize the clauses that need pre-built expressions for CodeGen.
  13272. for (OMPClause *C : Clauses) {
  13273. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  13274. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  13275. B.NumIterations, *this, CurScope,
  13276. DSAStack))
  13277. return StmtError();
  13278. }
  13279. }
  13280. if (checkSimdlenSafelenSpecified(*this, Clauses))
  13281. return StmtError();
  13282. setFunctionHasBranchProtectedScope();
  13283. DSAStack->setParentTeamsRegionLoc(StartLoc);
  13284. return OMPTeamsDistributeSimdDirective::Create(
  13285. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  13286. }
  13287. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
  13288. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  13289. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  13290. if (!AStmt)
  13291. return StmtError();
  13292. auto *CS = cast<CapturedStmt>(AStmt);
  13293. // 1.2.2 OpenMP Language Terminology
  13294. // Structured block - An executable statement with a single entry at the
  13295. // top and a single exit at the bottom.
  13296. // The point of exit cannot be a branch out of the structured block.
  13297. // longjmp() and throw() must not violate the entry/exit criteria.
  13298. CS->getCapturedDecl()->setNothrow();
  13299. for (int ThisCaptureLevel =
  13300. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
  13301. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  13302. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  13303. // 1.2.2 OpenMP Language Terminology
  13304. // Structured block - An executable statement with a single entry at the
  13305. // top and a single exit at the bottom.
  13306. // The point of exit cannot be a branch out of the structured block.
  13307. // longjmp() and throw() must not violate the entry/exit criteria.
  13308. CS->getCapturedDecl()->setNothrow();
  13309. }
  13310. OMPLoopBasedDirective::HelperExprs B;
  13311. // In presence of clause 'collapse' with number of loops, it will
  13312. // define the nested loops number.
  13313. unsigned NestedLoopCount = checkOpenMPLoop(
  13314. OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
  13315. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  13316. VarsWithImplicitDSA, B);
  13317. if (NestedLoopCount == 0)
  13318. return StmtError();
  13319. assert((CurContext->isDependentContext() || B.builtAll()) &&
  13320. "omp for loop exprs were not built");
  13321. if (!CurContext->isDependentContext()) {
  13322. // Finalize the clauses that need pre-built expressions for CodeGen.
  13323. for (OMPClause *C : Clauses) {
  13324. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  13325. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  13326. B.NumIterations, *this, CurScope,
  13327. DSAStack))
  13328. return StmtError();
  13329. }
  13330. }
  13331. if (checkSimdlenSafelenSpecified(*this, Clauses))
  13332. return StmtError();
  13333. setFunctionHasBranchProtectedScope();
  13334. DSAStack->setParentTeamsRegionLoc(StartLoc);
  13335. return OMPTeamsDistributeParallelForSimdDirective::Create(
  13336. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  13337. }
  13338. StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
  13339. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  13340. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  13341. if (!AStmt)
  13342. return StmtError();
  13343. auto *CS = cast<CapturedStmt>(AStmt);
  13344. // 1.2.2 OpenMP Language Terminology
  13345. // Structured block - An executable statement with a single entry at the
  13346. // top and a single exit at the bottom.
  13347. // The point of exit cannot be a branch out of the structured block.
  13348. // longjmp() and throw() must not violate the entry/exit criteria.
  13349. CS->getCapturedDecl()->setNothrow();
  13350. for (int ThisCaptureLevel =
  13351. getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
  13352. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  13353. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  13354. // 1.2.2 OpenMP Language Terminology
  13355. // Structured block - An executable statement with a single entry at the
  13356. // top and a single exit at the bottom.
  13357. // The point of exit cannot be a branch out of the structured block.
  13358. // longjmp() and throw() must not violate the entry/exit criteria.
  13359. CS->getCapturedDecl()->setNothrow();
  13360. }
  13361. OMPLoopBasedDirective::HelperExprs B;
  13362. // In presence of clause 'collapse' with number of loops, it will
  13363. // define the nested loops number.
  13364. unsigned NestedLoopCount = checkOpenMPLoop(
  13365. OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  13366. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  13367. VarsWithImplicitDSA, B);
  13368. if (NestedLoopCount == 0)
  13369. return StmtError();
  13370. assert((CurContext->isDependentContext() || B.builtAll()) &&
  13371. "omp for loop exprs were not built");
  13372. setFunctionHasBranchProtectedScope();
  13373. DSAStack->setParentTeamsRegionLoc(StartLoc);
  13374. return OMPTeamsDistributeParallelForDirective::Create(
  13375. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  13376. DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
  13377. }
  13378. StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
  13379. Stmt *AStmt,
  13380. SourceLocation StartLoc,
  13381. SourceLocation EndLoc) {
  13382. if (!AStmt)
  13383. return StmtError();
  13384. auto *CS = cast<CapturedStmt>(AStmt);
  13385. // 1.2.2 OpenMP Language Terminology
  13386. // Structured block - An executable statement with a single entry at the
  13387. // top and a single exit at the bottom.
  13388. // The point of exit cannot be a branch out of the structured block.
  13389. // longjmp() and throw() must not violate the entry/exit criteria.
  13390. CS->getCapturedDecl()->setNothrow();
  13391. for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
  13392. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  13393. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  13394. // 1.2.2 OpenMP Language Terminology
  13395. // Structured block - An executable statement with a single entry at the
  13396. // top and a single exit at the bottom.
  13397. // The point of exit cannot be a branch out of the structured block.
  13398. // longjmp() and throw() must not violate the entry/exit criteria.
  13399. CS->getCapturedDecl()->setNothrow();
  13400. }
  13401. setFunctionHasBranchProtectedScope();
  13402. return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
  13403. AStmt);
  13404. }
  13405. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
  13406. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  13407. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  13408. if (!AStmt)
  13409. return StmtError();
  13410. auto *CS = cast<CapturedStmt>(AStmt);
  13411. // 1.2.2 OpenMP Language Terminology
  13412. // Structured block - An executable statement with a single entry at the
  13413. // top and a single exit at the bottom.
  13414. // The point of exit cannot be a branch out of the structured block.
  13415. // longjmp() and throw() must not violate the entry/exit criteria.
  13416. CS->getCapturedDecl()->setNothrow();
  13417. for (int ThisCaptureLevel =
  13418. getOpenMPCaptureLevels(OMPD_target_teams_distribute);
  13419. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  13420. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  13421. // 1.2.2 OpenMP Language Terminology
  13422. // Structured block - An executable statement with a single entry at the
  13423. // top and a single exit at the bottom.
  13424. // The point of exit cannot be a branch out of the structured block.
  13425. // longjmp() and throw() must not violate the entry/exit criteria.
  13426. CS->getCapturedDecl()->setNothrow();
  13427. }
  13428. OMPLoopBasedDirective::HelperExprs B;
  13429. // In presence of clause 'collapse' with number of loops, it will
  13430. // define the nested loops number.
  13431. unsigned NestedLoopCount = checkOpenMPLoop(
  13432. OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
  13433. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  13434. VarsWithImplicitDSA, B);
  13435. if (NestedLoopCount == 0)
  13436. return StmtError();
  13437. assert((CurContext->isDependentContext() || B.builtAll()) &&
  13438. "omp target teams distribute loop exprs were not built");
  13439. setFunctionHasBranchProtectedScope();
  13440. return OMPTargetTeamsDistributeDirective::Create(
  13441. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  13442. }
  13443. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
  13444. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  13445. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  13446. if (!AStmt)
  13447. return StmtError();
  13448. auto *CS = cast<CapturedStmt>(AStmt);
  13449. // 1.2.2 OpenMP Language Terminology
  13450. // Structured block - An executable statement with a single entry at the
  13451. // top and a single exit at the bottom.
  13452. // The point of exit cannot be a branch out of the structured block.
  13453. // longjmp() and throw() must not violate the entry/exit criteria.
  13454. CS->getCapturedDecl()->setNothrow();
  13455. for (int ThisCaptureLevel =
  13456. getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
  13457. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  13458. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  13459. // 1.2.2 OpenMP Language Terminology
  13460. // Structured block - An executable statement with a single entry at the
  13461. // top and a single exit at the bottom.
  13462. // The point of exit cannot be a branch out of the structured block.
  13463. // longjmp() and throw() must not violate the entry/exit criteria.
  13464. CS->getCapturedDecl()->setNothrow();
  13465. }
  13466. OMPLoopBasedDirective::HelperExprs B;
  13467. // In presence of clause 'collapse' with number of loops, it will
  13468. // define the nested loops number.
  13469. unsigned NestedLoopCount = checkOpenMPLoop(
  13470. OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
  13471. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  13472. VarsWithImplicitDSA, B);
  13473. if (NestedLoopCount == 0)
  13474. return StmtError();
  13475. assert((CurContext->isDependentContext() || B.builtAll()) &&
  13476. "omp target teams distribute parallel for loop exprs were not built");
  13477. if (!CurContext->isDependentContext()) {
  13478. // Finalize the clauses that need pre-built expressions for CodeGen.
  13479. for (OMPClause *C : Clauses) {
  13480. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  13481. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  13482. B.NumIterations, *this, CurScope,
  13483. DSAStack))
  13484. return StmtError();
  13485. }
  13486. }
  13487. setFunctionHasBranchProtectedScope();
  13488. return OMPTargetTeamsDistributeParallelForDirective::Create(
  13489. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
  13490. DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion());
  13491. }
  13492. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
  13493. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  13494. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  13495. if (!AStmt)
  13496. return StmtError();
  13497. auto *CS = cast<CapturedStmt>(AStmt);
  13498. // 1.2.2 OpenMP Language Terminology
  13499. // Structured block - An executable statement with a single entry at the
  13500. // top and a single exit at the bottom.
  13501. // The point of exit cannot be a branch out of the structured block.
  13502. // longjmp() and throw() must not violate the entry/exit criteria.
  13503. CS->getCapturedDecl()->setNothrow();
  13504. for (int ThisCaptureLevel = getOpenMPCaptureLevels(
  13505. OMPD_target_teams_distribute_parallel_for_simd);
  13506. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  13507. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  13508. // 1.2.2 OpenMP Language Terminology
  13509. // Structured block - An executable statement with a single entry at the
  13510. // top and a single exit at the bottom.
  13511. // The point of exit cannot be a branch out of the structured block.
  13512. // longjmp() and throw() must not violate the entry/exit criteria.
  13513. CS->getCapturedDecl()->setNothrow();
  13514. }
  13515. OMPLoopBasedDirective::HelperExprs B;
  13516. // In presence of clause 'collapse' with number of loops, it will
  13517. // define the nested loops number.
  13518. unsigned NestedLoopCount =
  13519. checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
  13520. getCollapseNumberExpr(Clauses),
  13521. nullptr /*ordered not a clause on distribute*/, CS, *this,
  13522. *DSAStack, VarsWithImplicitDSA, B);
  13523. if (NestedLoopCount == 0)
  13524. return StmtError();
  13525. assert((CurContext->isDependentContext() || B.builtAll()) &&
  13526. "omp target teams distribute parallel for simd loop exprs were not "
  13527. "built");
  13528. if (!CurContext->isDependentContext()) {
  13529. // Finalize the clauses that need pre-built expressions for CodeGen.
  13530. for (OMPClause *C : Clauses) {
  13531. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  13532. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  13533. B.NumIterations, *this, CurScope,
  13534. DSAStack))
  13535. return StmtError();
  13536. }
  13537. }
  13538. if (checkSimdlenSafelenSpecified(*this, Clauses))
  13539. return StmtError();
  13540. setFunctionHasBranchProtectedScope();
  13541. return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
  13542. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  13543. }
  13544. StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
  13545. ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
  13546. SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
  13547. if (!AStmt)
  13548. return StmtError();
  13549. auto *CS = cast<CapturedStmt>(AStmt);
  13550. // 1.2.2 OpenMP Language Terminology
  13551. // Structured block - An executable statement with a single entry at the
  13552. // top and a single exit at the bottom.
  13553. // The point of exit cannot be a branch out of the structured block.
  13554. // longjmp() and throw() must not violate the entry/exit criteria.
  13555. CS->getCapturedDecl()->setNothrow();
  13556. for (int ThisCaptureLevel =
  13557. getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
  13558. ThisCaptureLevel > 1; --ThisCaptureLevel) {
  13559. CS = cast<CapturedStmt>(CS->getCapturedStmt());
  13560. // 1.2.2 OpenMP Language Terminology
  13561. // Structured block - An executable statement with a single entry at the
  13562. // top and a single exit at the bottom.
  13563. // The point of exit cannot be a branch out of the structured block.
  13564. // longjmp() and throw() must not violate the entry/exit criteria.
  13565. CS->getCapturedDecl()->setNothrow();
  13566. }
  13567. OMPLoopBasedDirective::HelperExprs B;
  13568. // In presence of clause 'collapse' with number of loops, it will
  13569. // define the nested loops number.
  13570. unsigned NestedLoopCount = checkOpenMPLoop(
  13571. OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
  13572. nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
  13573. VarsWithImplicitDSA, B);
  13574. if (NestedLoopCount == 0)
  13575. return StmtError();
  13576. assert((CurContext->isDependentContext() || B.builtAll()) &&
  13577. "omp target teams distribute simd loop exprs were not built");
  13578. if (!CurContext->isDependentContext()) {
  13579. // Finalize the clauses that need pre-built expressions for CodeGen.
  13580. for (OMPClause *C : Clauses) {
  13581. if (auto *LC = dyn_cast<OMPLinearClause>(C))
  13582. if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
  13583. B.NumIterations, *this, CurScope,
  13584. DSAStack))
  13585. return StmtError();
  13586. }
  13587. }
  13588. if (checkSimdlenSafelenSpecified(*this, Clauses))
  13589. return StmtError();
  13590. setFunctionHasBranchProtectedScope();
  13591. return OMPTargetTeamsDistributeSimdDirective::Create(
  13592. Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
  13593. }
  13594. bool Sema::checkTransformableLoopNest(
  13595. OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
  13596. SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
  13597. Stmt *&Body,
  13598. SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
  13599. &OriginalInits) {
  13600. OriginalInits.emplace_back();
  13601. bool Result = OMPLoopBasedDirective::doForAllLoops(
  13602. AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, NumLoops,
  13603. [this, &LoopHelpers, &Body, &OriginalInits, Kind](unsigned Cnt,
  13604. Stmt *CurStmt) {
  13605. VarsWithInheritedDSAType TmpDSA;
  13606. unsigned SingleNumLoops =
  13607. checkOpenMPLoop(Kind, nullptr, nullptr, CurStmt, *this, *DSAStack,
  13608. TmpDSA, LoopHelpers[Cnt]);
  13609. if (SingleNumLoops == 0)
  13610. return true;
  13611. assert(SingleNumLoops == 1 && "Expect single loop iteration space");
  13612. if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
  13613. OriginalInits.back().push_back(For->getInit());
  13614. Body = For->getBody();
  13615. } else {
  13616. assert(isa<CXXForRangeStmt>(CurStmt) &&
  13617. "Expected canonical for or range-based for loops.");
  13618. auto *CXXFor = cast<CXXForRangeStmt>(CurStmt);
  13619. OriginalInits.back().push_back(CXXFor->getBeginStmt());
  13620. Body = CXXFor->getBody();
  13621. }
  13622. OriginalInits.emplace_back();
  13623. return false;
  13624. },
  13625. [&OriginalInits](OMPLoopBasedDirective *Transform) {
  13626. Stmt *DependentPreInits;
  13627. if (auto *Dir = dyn_cast<OMPTileDirective>(Transform))
  13628. DependentPreInits = Dir->getPreInits();
  13629. else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform))
  13630. DependentPreInits = Dir->getPreInits();
  13631. else
  13632. llvm_unreachable("Unhandled loop transformation");
  13633. if (!DependentPreInits)
  13634. return;
  13635. llvm::append_range(OriginalInits.back(),
  13636. cast<DeclStmt>(DependentPreInits)->getDeclGroup());
  13637. });
  13638. assert(OriginalInits.back().empty() && "No preinit after innermost loop");
  13639. OriginalInits.pop_back();
  13640. return Result;
  13641. }
  13642. StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
  13643. Stmt *AStmt, SourceLocation StartLoc,
  13644. SourceLocation EndLoc) {
  13645. auto SizesClauses =
  13646. OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses);
  13647. if (SizesClauses.empty()) {
  13648. // A missing 'sizes' clause is already reported by the parser.
  13649. return StmtError();
  13650. }
  13651. const OMPSizesClause *SizesClause = *SizesClauses.begin();
  13652. unsigned NumLoops = SizesClause->getNumSizes();
  13653. // Empty statement should only be possible if there already was an error.
  13654. if (!AStmt)
  13655. return StmtError();
  13656. // Verify and diagnose loop nest.
  13657. SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops);
  13658. Stmt *Body = nullptr;
  13659. SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, 4>
  13660. OriginalInits;
  13661. if (!checkTransformableLoopNest(OMPD_tile, AStmt, NumLoops, LoopHelpers, Body,
  13662. OriginalInits))
  13663. return StmtError();
  13664. // Delay tiling to when template is completely instantiated.
  13665. if (CurContext->isDependentContext())
  13666. return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses,
  13667. NumLoops, AStmt, nullptr, nullptr);
  13668. SmallVector<Decl *, 4> PreInits;
  13669. // Create iteration variables for the generated loops.
  13670. SmallVector<VarDecl *, 4> FloorIndVars;
  13671. SmallVector<VarDecl *, 4> TileIndVars;
  13672. FloorIndVars.resize(NumLoops);
  13673. TileIndVars.resize(NumLoops);
  13674. for (unsigned I = 0; I < NumLoops; ++I) {
  13675. OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
  13676. assert(LoopHelper.Counters.size() == 1 &&
  13677. "Expect single-dimensional loop iteration space");
  13678. auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
  13679. std::string OrigVarName = OrigCntVar->getNameInfo().getAsString();
  13680. DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
  13681. QualType CntTy = IterVarRef->getType();
  13682. // Iteration variable for the floor (i.e. outer) loop.
  13683. {
  13684. std::string FloorCntName =
  13685. (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
  13686. VarDecl *FloorCntDecl =
  13687. buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar);
  13688. FloorIndVars[I] = FloorCntDecl;
  13689. }
  13690. // Iteration variable for the tile (i.e. inner) loop.
  13691. {
  13692. std::string TileCntName =
  13693. (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str();
  13694. // Reuse the iteration variable created by checkOpenMPLoop. It is also
  13695. // used by the expressions to derive the original iteration variable's
  13696. // value from the logical iteration number.
  13697. auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl());
  13698. TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName));
  13699. TileIndVars[I] = TileCntDecl;
  13700. }
  13701. for (auto &P : OriginalInits[I]) {
  13702. if (auto *D = P.dyn_cast<Decl *>())
  13703. PreInits.push_back(D);
  13704. else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
  13705. PreInits.append(PI->decl_begin(), PI->decl_end());
  13706. }
  13707. if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
  13708. PreInits.append(PI->decl_begin(), PI->decl_end());
  13709. // Gather declarations for the data members used as counters.
  13710. for (Expr *CounterRef : LoopHelper.Counters) {
  13711. auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
  13712. if (isa<OMPCapturedExprDecl>(CounterDecl))
  13713. PreInits.push_back(CounterDecl);
  13714. }
  13715. }
  13716. // Once the original iteration values are set, append the innermost body.
  13717. Stmt *Inner = Body;
  13718. // Create tile loops from the inside to the outside.
  13719. for (int I = NumLoops - 1; I >= 0; --I) {
  13720. OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I];
  13721. Expr *NumIterations = LoopHelper.NumIterations;
  13722. auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
  13723. QualType CntTy = OrigCntVar->getType();
  13724. Expr *DimTileSize = SizesClause->getSizesRefs()[I];
  13725. Scope *CurScope = getCurScope();
  13726. // Commonly used variables.
  13727. DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy,
  13728. OrigCntVar->getExprLoc());
  13729. DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
  13730. OrigCntVar->getExprLoc());
  13731. // For init-statement: auto .tile.iv = .floor.iv
  13732. AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(),
  13733. /*DirectInit=*/false);
  13734. Decl *CounterDecl = TileIndVars[I];
  13735. StmtResult InitStmt = new (Context)
  13736. DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
  13737. OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
  13738. if (!InitStmt.isUsable())
  13739. return StmtError();
  13740. // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize,
  13741. // NumIterations)
  13742. ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
  13743. BO_Add, FloorIV, DimTileSize);
  13744. if (!EndOfTile.isUsable())
  13745. return StmtError();
  13746. ExprResult IsPartialTile =
  13747. BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
  13748. NumIterations, EndOfTile.get());
  13749. if (!IsPartialTile.isUsable())
  13750. return StmtError();
  13751. ExprResult MinTileAndIterSpace = ActOnConditionalOp(
  13752. LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(),
  13753. IsPartialTile.get(), NumIterations, EndOfTile.get());
  13754. if (!MinTileAndIterSpace.isUsable())
  13755. return StmtError();
  13756. ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
  13757. BO_LT, TileIV, MinTileAndIterSpace.get());
  13758. if (!CondExpr.isUsable())
  13759. return StmtError();
  13760. // For incr-statement: ++.tile.iv
  13761. ExprResult IncrStmt =
  13762. BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV);
  13763. if (!IncrStmt.isUsable())
  13764. return StmtError();
  13765. // Statements to set the original iteration variable's value from the
  13766. // logical iteration number.
  13767. // Generated for loop is:
  13768. // Original_for_init;
  13769. // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize,
  13770. // NumIterations); ++.tile.iv) {
  13771. // Original_Body;
  13772. // Original_counter_update;
  13773. // }
  13774. // FIXME: If the innermost body is an loop itself, inserting these
  13775. // statements stops it being recognized as a perfectly nested loop (e.g.
  13776. // for applying tiling again). If this is the case, sink the expressions
  13777. // further into the inner loop.
  13778. SmallVector<Stmt *, 4> BodyParts;
  13779. BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
  13780. BodyParts.push_back(Inner);
  13781. Inner = CompoundStmt::Create(Context, BodyParts, FPOptionsOverride(),
  13782. Inner->getBeginLoc(), Inner->getEndLoc());
  13783. Inner = new (Context)
  13784. ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
  13785. IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
  13786. LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
  13787. }
  13788. // Create floor loops from the inside to the outside.
  13789. for (int I = NumLoops - 1; I >= 0; --I) {
  13790. auto &LoopHelper = LoopHelpers[I];
  13791. Expr *NumIterations = LoopHelper.NumIterations;
  13792. DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]);
  13793. QualType CntTy = OrigCntVar->getType();
  13794. Expr *DimTileSize = SizesClause->getSizesRefs()[I];
  13795. Scope *CurScope = getCurScope();
  13796. // Commonly used variables.
  13797. DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy,
  13798. OrigCntVar->getExprLoc());
  13799. // For init-statement: auto .floor.iv = 0
  13800. AddInitializerToDecl(
  13801. FloorIndVars[I],
  13802. ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
  13803. /*DirectInit=*/false);
  13804. Decl *CounterDecl = FloorIndVars[I];
  13805. StmtResult InitStmt = new (Context)
  13806. DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
  13807. OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc());
  13808. if (!InitStmt.isUsable())
  13809. return StmtError();
  13810. // For cond-expression: .floor.iv < NumIterations
  13811. ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
  13812. BO_LT, FloorIV, NumIterations);
  13813. if (!CondExpr.isUsable())
  13814. return StmtError();
  13815. // For incr-statement: .floor.iv += DimTileSize
  13816. ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(),
  13817. BO_AddAssign, FloorIV, DimTileSize);
  13818. if (!IncrStmt.isUsable())
  13819. return StmtError();
  13820. Inner = new (Context)
  13821. ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr,
  13822. IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(),
  13823. LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
  13824. }
  13825. return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops,
  13826. AStmt, Inner,
  13827. buildPreInits(Context, PreInits));
  13828. }
  13829. StmtResult Sema::ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
  13830. Stmt *AStmt,
  13831. SourceLocation StartLoc,
  13832. SourceLocation EndLoc) {
  13833. // Empty statement should only be possible if there already was an error.
  13834. if (!AStmt)
  13835. return StmtError();
  13836. if (checkMutuallyExclusiveClauses(*this, Clauses, {OMPC_partial, OMPC_full}))
  13837. return StmtError();
  13838. const OMPFullClause *FullClause =
  13839. OMPExecutableDirective::getSingleClause<OMPFullClause>(Clauses);
  13840. const OMPPartialClause *PartialClause =
  13841. OMPExecutableDirective::getSingleClause<OMPPartialClause>(Clauses);
  13842. assert(!(FullClause && PartialClause) &&
  13843. "mutual exclusivity must have been checked before");
  13844. constexpr unsigned NumLoops = 1;
  13845. Stmt *Body = nullptr;
  13846. SmallVector<OMPLoopBasedDirective::HelperExprs, NumLoops> LoopHelpers(
  13847. NumLoops);
  13848. SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, NumLoops + 1>
  13849. OriginalInits;
  13850. if (!checkTransformableLoopNest(OMPD_unroll, AStmt, NumLoops, LoopHelpers,
  13851. Body, OriginalInits))
  13852. return StmtError();
  13853. unsigned NumGeneratedLoops = PartialClause ? 1 : 0;
  13854. // Delay unrolling to when template is completely instantiated.
  13855. if (CurContext->isDependentContext())
  13856. return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  13857. NumGeneratedLoops, nullptr, nullptr);
  13858. OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front();
  13859. if (FullClause) {
  13860. if (!VerifyPositiveIntegerConstantInClause(
  13861. LoopHelper.NumIterations, OMPC_full, /*StrictlyPositive=*/false,
  13862. /*SuppressExprDiags=*/true)
  13863. .isUsable()) {
  13864. Diag(AStmt->getBeginLoc(), diag::err_omp_unroll_full_variable_trip_count);
  13865. Diag(FullClause->getBeginLoc(), diag::note_omp_directive_here)
  13866. << "#pragma omp unroll full";
  13867. return StmtError();
  13868. }
  13869. }
  13870. // The generated loop may only be passed to other loop-associated directive
  13871. // when a partial clause is specified. Without the requirement it is
  13872. // sufficient to generate loop unroll metadata at code-generation.
  13873. if (NumGeneratedLoops == 0)
  13874. return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  13875. NumGeneratedLoops, nullptr, nullptr);
  13876. // Otherwise, we need to provide a de-sugared/transformed AST that can be
  13877. // associated with another loop directive.
  13878. //
  13879. // The canonical loop analysis return by checkTransformableLoopNest assumes
  13880. // the following structure to be the same loop without transformations or
  13881. // directives applied: \code OriginalInits; LoopHelper.PreInits;
  13882. // LoopHelper.Counters;
  13883. // for (; IV < LoopHelper.NumIterations; ++IV) {
  13884. // LoopHelper.Updates;
  13885. // Body;
  13886. // }
  13887. // \endcode
  13888. // where IV is a variable declared and initialized to 0 in LoopHelper.PreInits
  13889. // and referenced by LoopHelper.IterationVarRef.
  13890. //
  13891. // The unrolling directive transforms this into the following loop:
  13892. // \code
  13893. // OriginalInits; \
  13894. // LoopHelper.PreInits; > NewPreInits
  13895. // LoopHelper.Counters; /
  13896. // for (auto UIV = 0; UIV < LoopHelper.NumIterations; UIV+=Factor) {
  13897. // #pragma clang loop unroll_count(Factor)
  13898. // for (IV = UIV; IV < UIV + Factor && UIV < LoopHelper.NumIterations; ++IV)
  13899. // {
  13900. // LoopHelper.Updates;
  13901. // Body;
  13902. // }
  13903. // }
  13904. // \endcode
  13905. // where UIV is a new logical iteration counter. IV must be the same VarDecl
  13906. // as the original LoopHelper.IterationVarRef because LoopHelper.Updates
  13907. // references it. If the partially unrolled loop is associated with another
  13908. // loop directive (like an OMPForDirective), it will use checkOpenMPLoop to
  13909. // analyze this loop, i.e. the outer loop must fulfill the constraints of an
  13910. // OpenMP canonical loop. The inner loop is not an associable canonical loop
  13911. // and only exists to defer its unrolling to LLVM's LoopUnroll instead of
  13912. // doing it in the frontend (by adding loop metadata). NewPreInits becomes a
  13913. // property of the OMPLoopBasedDirective instead of statements in
  13914. // CompoundStatement. This is to allow the loop to become a non-outermost loop
  13915. // of a canonical loop nest where these PreInits are emitted before the
  13916. // outermost directive.
  13917. // Determine the PreInit declarations.
  13918. SmallVector<Decl *, 4> PreInits;
  13919. assert(OriginalInits.size() == 1 &&
  13920. "Expecting a single-dimensional loop iteration space");
  13921. for (auto &P : OriginalInits[0]) {
  13922. if (auto *D = P.dyn_cast<Decl *>())
  13923. PreInits.push_back(D);
  13924. else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>()))
  13925. PreInits.append(PI->decl_begin(), PI->decl_end());
  13926. }
  13927. if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits))
  13928. PreInits.append(PI->decl_begin(), PI->decl_end());
  13929. // Gather declarations for the data members used as counters.
  13930. for (Expr *CounterRef : LoopHelper.Counters) {
  13931. auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl();
  13932. if (isa<OMPCapturedExprDecl>(CounterDecl))
  13933. PreInits.push_back(CounterDecl);
  13934. }
  13935. auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef);
  13936. QualType IVTy = IterationVarRef->getType();
  13937. assert(LoopHelper.Counters.size() == 1 &&
  13938. "Expecting a single-dimensional loop iteration space");
  13939. auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front());
  13940. // Determine the unroll factor.
  13941. uint64_t Factor;
  13942. SourceLocation FactorLoc;
  13943. if (Expr *FactorVal = PartialClause->getFactor()) {
  13944. Factor = FactorVal->getIntegerConstantExpr(Context)->getZExtValue();
  13945. FactorLoc = FactorVal->getExprLoc();
  13946. } else {
  13947. // TODO: Use a better profitability model.
  13948. Factor = 2;
  13949. }
  13950. assert(Factor > 0 && "Expected positive unroll factor");
  13951. auto MakeFactorExpr = [this, Factor, IVTy, FactorLoc]() {
  13952. return IntegerLiteral::Create(
  13953. Context, llvm::APInt(Context.getIntWidth(IVTy), Factor), IVTy,
  13954. FactorLoc);
  13955. };
  13956. // Iteration variable SourceLocations.
  13957. SourceLocation OrigVarLoc = OrigVar->getExprLoc();
  13958. SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc();
  13959. SourceLocation OrigVarLocEnd = OrigVar->getEndLoc();
  13960. // Internal variable names.
  13961. std::string OrigVarName = OrigVar->getNameInfo().getAsString();
  13962. std::string OuterIVName = (Twine(".unrolled.iv.") + OrigVarName).str();
  13963. std::string InnerIVName = (Twine(".unroll_inner.iv.") + OrigVarName).str();
  13964. std::string InnerTripCountName =
  13965. (Twine(".unroll_inner.tripcount.") + OrigVarName).str();
  13966. // Create the iteration variable for the unrolled loop.
  13967. VarDecl *OuterIVDecl =
  13968. buildVarDecl(*this, {}, IVTy, OuterIVName, nullptr, OrigVar);
  13969. auto MakeOuterRef = [this, OuterIVDecl, IVTy, OrigVarLoc]() {
  13970. return buildDeclRefExpr(*this, OuterIVDecl, IVTy, OrigVarLoc);
  13971. };
  13972. // Iteration variable for the inner loop: Reuse the iteration variable created
  13973. // by checkOpenMPLoop.
  13974. auto *InnerIVDecl = cast<VarDecl>(IterationVarRef->getDecl());
  13975. InnerIVDecl->setDeclName(&PP.getIdentifierTable().get(InnerIVName));
  13976. auto MakeInnerRef = [this, InnerIVDecl, IVTy, OrigVarLoc]() {
  13977. return buildDeclRefExpr(*this, InnerIVDecl, IVTy, OrigVarLoc);
  13978. };
  13979. // Make a copy of the NumIterations expression for each use: By the AST
  13980. // constraints, every expression object in a DeclContext must be unique.
  13981. CaptureVars CopyTransformer(*this);
  13982. auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * {
  13983. return AssertSuccess(
  13984. CopyTransformer.TransformExpr(LoopHelper.NumIterations));
  13985. };
  13986. // Inner For init-statement: auto .unroll_inner.iv = .unrolled.iv
  13987. ExprResult LValueConv = DefaultLvalueConversion(MakeOuterRef());
  13988. AddInitializerToDecl(InnerIVDecl, LValueConv.get(), /*DirectInit=*/false);
  13989. StmtResult InnerInit = new (Context)
  13990. DeclStmt(DeclGroupRef(InnerIVDecl), OrigVarLocBegin, OrigVarLocEnd);
  13991. if (!InnerInit.isUsable())
  13992. return StmtError();
  13993. // Inner For cond-expression:
  13994. // \code
  13995. // .unroll_inner.iv < .unrolled.iv + Factor &&
  13996. // .unroll_inner.iv < NumIterations
  13997. // \endcode
  13998. // This conjunction of two conditions allows ScalarEvolution to derive the
  13999. // maximum trip count of the inner loop.
  14000. ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
  14001. BO_Add, MakeOuterRef(), MakeFactorExpr());
  14002. if (!EndOfTile.isUsable())
  14003. return StmtError();
  14004. ExprResult InnerCond1 = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(),
  14005. BO_LT, MakeInnerRef(), EndOfTile.get());
  14006. if (!InnerCond1.isUsable())
  14007. return StmtError();
  14008. ExprResult InnerCond2 =
  14009. BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeInnerRef(),
  14010. MakeNumIterations());
  14011. if (!InnerCond2.isUsable())
  14012. return StmtError();
  14013. ExprResult InnerCond =
  14014. BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LAnd,
  14015. InnerCond1.get(), InnerCond2.get());
  14016. if (!InnerCond.isUsable())
  14017. return StmtError();
  14018. // Inner For incr-statement: ++.unroll_inner.iv
  14019. ExprResult InnerIncr = BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(),
  14020. UO_PreInc, MakeInnerRef());
  14021. if (!InnerIncr.isUsable())
  14022. return StmtError();
  14023. // Inner For statement.
  14024. SmallVector<Stmt *> InnerBodyStmts;
  14025. InnerBodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end());
  14026. InnerBodyStmts.push_back(Body);
  14027. CompoundStmt *InnerBody =
  14028. CompoundStmt::Create(Context, InnerBodyStmts, FPOptionsOverride(),
  14029. Body->getBeginLoc(), Body->getEndLoc());
  14030. ForStmt *InnerFor = new (Context)
  14031. ForStmt(Context, InnerInit.get(), InnerCond.get(), nullptr,
  14032. InnerIncr.get(), InnerBody, LoopHelper.Init->getBeginLoc(),
  14033. LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
  14034. // Unroll metadata for the inner loop.
  14035. // This needs to take into account the remainder portion of the unrolled loop,
  14036. // hence `unroll(full)` does not apply here, even though the LoopUnroll pass
  14037. // supports multiple loop exits. Instead, unroll using a factor equivalent to
  14038. // the maximum trip count, which will also generate a remainder loop. Just
  14039. // `unroll(enable)` (which could have been useful if the user has not
  14040. // specified a concrete factor; even though the outer loop cannot be
  14041. // influenced anymore, would avoid more code bloat than necessary) will refuse
  14042. // the loop because "Won't unroll; remainder loop could not be generated when
  14043. // assuming runtime trip count". Even if it did work, it must not choose a
  14044. // larger unroll factor than the maximum loop length, or it would always just
  14045. // execute the remainder loop.
  14046. LoopHintAttr *UnrollHintAttr =
  14047. LoopHintAttr::CreateImplicit(Context, LoopHintAttr::UnrollCount,
  14048. LoopHintAttr::Numeric, MakeFactorExpr());
  14049. AttributedStmt *InnerUnrolled =
  14050. AttributedStmt::Create(Context, StartLoc, {UnrollHintAttr}, InnerFor);
  14051. // Outer For init-statement: auto .unrolled.iv = 0
  14052. AddInitializerToDecl(
  14053. OuterIVDecl, ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(),
  14054. /*DirectInit=*/false);
  14055. StmtResult OuterInit = new (Context)
  14056. DeclStmt(DeclGroupRef(OuterIVDecl), OrigVarLocBegin, OrigVarLocEnd);
  14057. if (!OuterInit.isUsable())
  14058. return StmtError();
  14059. // Outer For cond-expression: .unrolled.iv < NumIterations
  14060. ExprResult OuterConde =
  14061. BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeOuterRef(),
  14062. MakeNumIterations());
  14063. if (!OuterConde.isUsable())
  14064. return StmtError();
  14065. // Outer For incr-statement: .unrolled.iv += Factor
  14066. ExprResult OuterIncr =
  14067. BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign,
  14068. MakeOuterRef(), MakeFactorExpr());
  14069. if (!OuterIncr.isUsable())
  14070. return StmtError();
  14071. // Outer For statement.
  14072. ForStmt *OuterFor = new (Context)
  14073. ForStmt(Context, OuterInit.get(), OuterConde.get(), nullptr,
  14074. OuterIncr.get(), InnerUnrolled, LoopHelper.Init->getBeginLoc(),
  14075. LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc());
  14076. return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
  14077. NumGeneratedLoops, OuterFor,
  14078. buildPreInits(Context, PreInits));
  14079. }
  14080. OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
  14081. SourceLocation StartLoc,
  14082. SourceLocation LParenLoc,
  14083. SourceLocation EndLoc) {
  14084. OMPClause *Res = nullptr;
  14085. switch (Kind) {
  14086. case OMPC_final:
  14087. Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
  14088. break;
  14089. case OMPC_num_threads:
  14090. Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
  14091. break;
  14092. case OMPC_safelen:
  14093. Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
  14094. break;
  14095. case OMPC_simdlen:
  14096. Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
  14097. break;
  14098. case OMPC_allocator:
  14099. Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
  14100. break;
  14101. case OMPC_collapse:
  14102. Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
  14103. break;
  14104. case OMPC_ordered:
  14105. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
  14106. break;
  14107. case OMPC_num_teams:
  14108. Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
  14109. break;
  14110. case OMPC_thread_limit:
  14111. Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
  14112. break;
  14113. case OMPC_priority:
  14114. Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
  14115. break;
  14116. case OMPC_hint:
  14117. Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
  14118. break;
  14119. case OMPC_depobj:
  14120. Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc);
  14121. break;
  14122. case OMPC_detach:
  14123. Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc);
  14124. break;
  14125. case OMPC_novariants:
  14126. Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc);
  14127. break;
  14128. case OMPC_nocontext:
  14129. Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc);
  14130. break;
  14131. case OMPC_filter:
  14132. Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc);
  14133. break;
  14134. case OMPC_partial:
  14135. Res = ActOnOpenMPPartialClause(Expr, StartLoc, LParenLoc, EndLoc);
  14136. break;
  14137. case OMPC_message:
  14138. Res = ActOnOpenMPMessageClause(Expr, StartLoc, LParenLoc, EndLoc);
  14139. break;
  14140. case OMPC_align:
  14141. Res = ActOnOpenMPAlignClause(Expr, StartLoc, LParenLoc, EndLoc);
  14142. break;
  14143. case OMPC_ompx_dyn_cgroup_mem:
  14144. Res = ActOnOpenMPXDynCGroupMemClause(Expr, StartLoc, LParenLoc, EndLoc);
  14145. break;
  14146. case OMPC_grainsize:
  14147. case OMPC_num_tasks:
  14148. case OMPC_device:
  14149. case OMPC_if:
  14150. case OMPC_default:
  14151. case OMPC_proc_bind:
  14152. case OMPC_schedule:
  14153. case OMPC_private:
  14154. case OMPC_firstprivate:
  14155. case OMPC_lastprivate:
  14156. case OMPC_shared:
  14157. case OMPC_reduction:
  14158. case OMPC_task_reduction:
  14159. case OMPC_in_reduction:
  14160. case OMPC_linear:
  14161. case OMPC_aligned:
  14162. case OMPC_copyin:
  14163. case OMPC_copyprivate:
  14164. case OMPC_nowait:
  14165. case OMPC_untied:
  14166. case OMPC_mergeable:
  14167. case OMPC_threadprivate:
  14168. case OMPC_sizes:
  14169. case OMPC_allocate:
  14170. case OMPC_flush:
  14171. case OMPC_read:
  14172. case OMPC_write:
  14173. case OMPC_update:
  14174. case OMPC_capture:
  14175. case OMPC_compare:
  14176. case OMPC_seq_cst:
  14177. case OMPC_acq_rel:
  14178. case OMPC_acquire:
  14179. case OMPC_release:
  14180. case OMPC_relaxed:
  14181. case OMPC_depend:
  14182. case OMPC_threads:
  14183. case OMPC_simd:
  14184. case OMPC_map:
  14185. case OMPC_nogroup:
  14186. case OMPC_dist_schedule:
  14187. case OMPC_defaultmap:
  14188. case OMPC_unknown:
  14189. case OMPC_uniform:
  14190. case OMPC_to:
  14191. case OMPC_from:
  14192. case OMPC_use_device_ptr:
  14193. case OMPC_use_device_addr:
  14194. case OMPC_is_device_ptr:
  14195. case OMPC_unified_address:
  14196. case OMPC_unified_shared_memory:
  14197. case OMPC_reverse_offload:
  14198. case OMPC_dynamic_allocators:
  14199. case OMPC_atomic_default_mem_order:
  14200. case OMPC_device_type:
  14201. case OMPC_match:
  14202. case OMPC_nontemporal:
  14203. case OMPC_order:
  14204. case OMPC_at:
  14205. case OMPC_severity:
  14206. case OMPC_destroy:
  14207. case OMPC_inclusive:
  14208. case OMPC_exclusive:
  14209. case OMPC_uses_allocators:
  14210. case OMPC_affinity:
  14211. case OMPC_when:
  14212. case OMPC_bind:
  14213. default:
  14214. llvm_unreachable("Clause is not allowed.");
  14215. }
  14216. return Res;
  14217. }
  14218. // An OpenMP directive such as 'target parallel' has two captured regions:
  14219. // for the 'target' and 'parallel' respectively. This function returns
  14220. // the region in which to capture expressions associated with a clause.
  14221. // A return value of OMPD_unknown signifies that the expression should not
  14222. // be captured.
  14223. static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
  14224. OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
  14225. OpenMPDirectiveKind NameModifier = OMPD_unknown) {
  14226. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  14227. switch (CKind) {
  14228. case OMPC_if:
  14229. switch (DKind) {
  14230. case OMPD_target_parallel_for_simd:
  14231. if (OpenMPVersion >= 50 &&
  14232. (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
  14233. CaptureRegion = OMPD_parallel;
  14234. break;
  14235. }
  14236. [[fallthrough]];
  14237. case OMPD_target_parallel:
  14238. case OMPD_target_parallel_for:
  14239. case OMPD_target_parallel_loop:
  14240. // If this clause applies to the nested 'parallel' region, capture within
  14241. // the 'target' region, otherwise do not capture.
  14242. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  14243. CaptureRegion = OMPD_target;
  14244. break;
  14245. case OMPD_target_teams_distribute_parallel_for_simd:
  14246. if (OpenMPVersion >= 50 &&
  14247. (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
  14248. CaptureRegion = OMPD_parallel;
  14249. break;
  14250. }
  14251. [[fallthrough]];
  14252. case OMPD_target_teams_distribute_parallel_for:
  14253. // If this clause applies to the nested 'parallel' region, capture within
  14254. // the 'teams' region, otherwise do not capture.
  14255. if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
  14256. CaptureRegion = OMPD_teams;
  14257. break;
  14258. case OMPD_teams_distribute_parallel_for_simd:
  14259. if (OpenMPVersion >= 50 &&
  14260. (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
  14261. CaptureRegion = OMPD_parallel;
  14262. break;
  14263. }
  14264. [[fallthrough]];
  14265. case OMPD_teams_distribute_parallel_for:
  14266. CaptureRegion = OMPD_teams;
  14267. break;
  14268. case OMPD_target_update:
  14269. case OMPD_target_enter_data:
  14270. case OMPD_target_exit_data:
  14271. CaptureRegion = OMPD_task;
  14272. break;
  14273. case OMPD_parallel_masked_taskloop:
  14274. if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
  14275. CaptureRegion = OMPD_parallel;
  14276. break;
  14277. case OMPD_parallel_master_taskloop:
  14278. if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
  14279. CaptureRegion = OMPD_parallel;
  14280. break;
  14281. case OMPD_parallel_masked_taskloop_simd:
  14282. if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
  14283. NameModifier == OMPD_taskloop) {
  14284. CaptureRegion = OMPD_parallel;
  14285. break;
  14286. }
  14287. if (OpenMPVersion <= 45)
  14288. break;
  14289. if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
  14290. CaptureRegion = OMPD_taskloop;
  14291. break;
  14292. case OMPD_parallel_master_taskloop_simd:
  14293. if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
  14294. NameModifier == OMPD_taskloop) {
  14295. CaptureRegion = OMPD_parallel;
  14296. break;
  14297. }
  14298. if (OpenMPVersion <= 45)
  14299. break;
  14300. if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
  14301. CaptureRegion = OMPD_taskloop;
  14302. break;
  14303. case OMPD_parallel_for_simd:
  14304. if (OpenMPVersion <= 45)
  14305. break;
  14306. if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
  14307. CaptureRegion = OMPD_parallel;
  14308. break;
  14309. case OMPD_taskloop_simd:
  14310. case OMPD_master_taskloop_simd:
  14311. case OMPD_masked_taskloop_simd:
  14312. if (OpenMPVersion <= 45)
  14313. break;
  14314. if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
  14315. CaptureRegion = OMPD_taskloop;
  14316. break;
  14317. case OMPD_distribute_parallel_for_simd:
  14318. if (OpenMPVersion <= 45)
  14319. break;
  14320. if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
  14321. CaptureRegion = OMPD_parallel;
  14322. break;
  14323. case OMPD_target_simd:
  14324. if (OpenMPVersion >= 50 &&
  14325. (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
  14326. CaptureRegion = OMPD_target;
  14327. break;
  14328. case OMPD_teams_distribute_simd:
  14329. case OMPD_target_teams_distribute_simd:
  14330. if (OpenMPVersion >= 50 &&
  14331. (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
  14332. CaptureRegion = OMPD_teams;
  14333. break;
  14334. case OMPD_cancel:
  14335. case OMPD_parallel:
  14336. case OMPD_parallel_master:
  14337. case OMPD_parallel_masked:
  14338. case OMPD_parallel_sections:
  14339. case OMPD_parallel_for:
  14340. case OMPD_parallel_loop:
  14341. case OMPD_target:
  14342. case OMPD_target_teams:
  14343. case OMPD_target_teams_distribute:
  14344. case OMPD_target_teams_loop:
  14345. case OMPD_distribute_parallel_for:
  14346. case OMPD_task:
  14347. case OMPD_taskloop:
  14348. case OMPD_master_taskloop:
  14349. case OMPD_masked_taskloop:
  14350. case OMPD_target_data:
  14351. case OMPD_simd:
  14352. case OMPD_for_simd:
  14353. case OMPD_distribute_simd:
  14354. // Do not capture if-clause expressions.
  14355. break;
  14356. case OMPD_threadprivate:
  14357. case OMPD_allocate:
  14358. case OMPD_taskyield:
  14359. case OMPD_error:
  14360. case OMPD_barrier:
  14361. case OMPD_taskwait:
  14362. case OMPD_cancellation_point:
  14363. case OMPD_flush:
  14364. case OMPD_depobj:
  14365. case OMPD_scan:
  14366. case OMPD_declare_reduction:
  14367. case OMPD_declare_mapper:
  14368. case OMPD_declare_simd:
  14369. case OMPD_declare_variant:
  14370. case OMPD_begin_declare_variant:
  14371. case OMPD_end_declare_variant:
  14372. case OMPD_declare_target:
  14373. case OMPD_end_declare_target:
  14374. case OMPD_loop:
  14375. case OMPD_teams_loop:
  14376. case OMPD_teams:
  14377. case OMPD_tile:
  14378. case OMPD_unroll:
  14379. case OMPD_for:
  14380. case OMPD_sections:
  14381. case OMPD_section:
  14382. case OMPD_single:
  14383. case OMPD_master:
  14384. case OMPD_masked:
  14385. case OMPD_critical:
  14386. case OMPD_taskgroup:
  14387. case OMPD_distribute:
  14388. case OMPD_ordered:
  14389. case OMPD_atomic:
  14390. case OMPD_teams_distribute:
  14391. case OMPD_requires:
  14392. case OMPD_metadirective:
  14393. llvm_unreachable("Unexpected OpenMP directive with if-clause");
  14394. case OMPD_unknown:
  14395. default:
  14396. llvm_unreachable("Unknown OpenMP directive");
  14397. }
  14398. break;
  14399. case OMPC_num_threads:
  14400. switch (DKind) {
  14401. case OMPD_target_parallel:
  14402. case OMPD_target_parallel_for:
  14403. case OMPD_target_parallel_for_simd:
  14404. case OMPD_target_parallel_loop:
  14405. CaptureRegion = OMPD_target;
  14406. break;
  14407. case OMPD_teams_distribute_parallel_for:
  14408. case OMPD_teams_distribute_parallel_for_simd:
  14409. case OMPD_target_teams_distribute_parallel_for:
  14410. case OMPD_target_teams_distribute_parallel_for_simd:
  14411. CaptureRegion = OMPD_teams;
  14412. break;
  14413. case OMPD_parallel:
  14414. case OMPD_parallel_master:
  14415. case OMPD_parallel_masked:
  14416. case OMPD_parallel_sections:
  14417. case OMPD_parallel_for:
  14418. case OMPD_parallel_for_simd:
  14419. case OMPD_parallel_loop:
  14420. case OMPD_distribute_parallel_for:
  14421. case OMPD_distribute_parallel_for_simd:
  14422. case OMPD_parallel_master_taskloop:
  14423. case OMPD_parallel_masked_taskloop:
  14424. case OMPD_parallel_master_taskloop_simd:
  14425. case OMPD_parallel_masked_taskloop_simd:
  14426. // Do not capture num_threads-clause expressions.
  14427. break;
  14428. case OMPD_target_data:
  14429. case OMPD_target_enter_data:
  14430. case OMPD_target_exit_data:
  14431. case OMPD_target_update:
  14432. case OMPD_target:
  14433. case OMPD_target_simd:
  14434. case OMPD_target_teams:
  14435. case OMPD_target_teams_distribute:
  14436. case OMPD_target_teams_distribute_simd:
  14437. case OMPD_cancel:
  14438. case OMPD_task:
  14439. case OMPD_taskloop:
  14440. case OMPD_taskloop_simd:
  14441. case OMPD_master_taskloop:
  14442. case OMPD_masked_taskloop:
  14443. case OMPD_master_taskloop_simd:
  14444. case OMPD_masked_taskloop_simd:
  14445. case OMPD_threadprivate:
  14446. case OMPD_allocate:
  14447. case OMPD_taskyield:
  14448. case OMPD_error:
  14449. case OMPD_barrier:
  14450. case OMPD_taskwait:
  14451. case OMPD_cancellation_point:
  14452. case OMPD_flush:
  14453. case OMPD_depobj:
  14454. case OMPD_scan:
  14455. case OMPD_declare_reduction:
  14456. case OMPD_declare_mapper:
  14457. case OMPD_declare_simd:
  14458. case OMPD_declare_variant:
  14459. case OMPD_begin_declare_variant:
  14460. case OMPD_end_declare_variant:
  14461. case OMPD_declare_target:
  14462. case OMPD_end_declare_target:
  14463. case OMPD_loop:
  14464. case OMPD_teams_loop:
  14465. case OMPD_target_teams_loop:
  14466. case OMPD_teams:
  14467. case OMPD_simd:
  14468. case OMPD_tile:
  14469. case OMPD_unroll:
  14470. case OMPD_for:
  14471. case OMPD_for_simd:
  14472. case OMPD_sections:
  14473. case OMPD_section:
  14474. case OMPD_single:
  14475. case OMPD_master:
  14476. case OMPD_masked:
  14477. case OMPD_critical:
  14478. case OMPD_taskgroup:
  14479. case OMPD_distribute:
  14480. case OMPD_ordered:
  14481. case OMPD_atomic:
  14482. case OMPD_distribute_simd:
  14483. case OMPD_teams_distribute:
  14484. case OMPD_teams_distribute_simd:
  14485. case OMPD_requires:
  14486. case OMPD_metadirective:
  14487. llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
  14488. case OMPD_unknown:
  14489. default:
  14490. llvm_unreachable("Unknown OpenMP directive");
  14491. }
  14492. break;
  14493. case OMPC_num_teams:
  14494. switch (DKind) {
  14495. case OMPD_target_teams:
  14496. case OMPD_target_teams_distribute:
  14497. case OMPD_target_teams_distribute_simd:
  14498. case OMPD_target_teams_distribute_parallel_for:
  14499. case OMPD_target_teams_distribute_parallel_for_simd:
  14500. case OMPD_target_teams_loop:
  14501. CaptureRegion = OMPD_target;
  14502. break;
  14503. case OMPD_teams_distribute_parallel_for:
  14504. case OMPD_teams_distribute_parallel_for_simd:
  14505. case OMPD_teams:
  14506. case OMPD_teams_distribute:
  14507. case OMPD_teams_distribute_simd:
  14508. case OMPD_teams_loop:
  14509. // Do not capture num_teams-clause expressions.
  14510. break;
  14511. case OMPD_distribute_parallel_for:
  14512. case OMPD_distribute_parallel_for_simd:
  14513. case OMPD_task:
  14514. case OMPD_taskloop:
  14515. case OMPD_taskloop_simd:
  14516. case OMPD_master_taskloop:
  14517. case OMPD_masked_taskloop:
  14518. case OMPD_master_taskloop_simd:
  14519. case OMPD_masked_taskloop_simd:
  14520. case OMPD_parallel_master_taskloop:
  14521. case OMPD_parallel_masked_taskloop:
  14522. case OMPD_parallel_master_taskloop_simd:
  14523. case OMPD_parallel_masked_taskloop_simd:
  14524. case OMPD_target_data:
  14525. case OMPD_target_enter_data:
  14526. case OMPD_target_exit_data:
  14527. case OMPD_target_update:
  14528. case OMPD_cancel:
  14529. case OMPD_parallel:
  14530. case OMPD_parallel_master:
  14531. case OMPD_parallel_masked:
  14532. case OMPD_parallel_sections:
  14533. case OMPD_parallel_for:
  14534. case OMPD_parallel_for_simd:
  14535. case OMPD_parallel_loop:
  14536. case OMPD_target:
  14537. case OMPD_target_simd:
  14538. case OMPD_target_parallel:
  14539. case OMPD_target_parallel_for:
  14540. case OMPD_target_parallel_for_simd:
  14541. case OMPD_target_parallel_loop:
  14542. case OMPD_threadprivate:
  14543. case OMPD_allocate:
  14544. case OMPD_taskyield:
  14545. case OMPD_error:
  14546. case OMPD_barrier:
  14547. case OMPD_taskwait:
  14548. case OMPD_cancellation_point:
  14549. case OMPD_flush:
  14550. case OMPD_depobj:
  14551. case OMPD_scan:
  14552. case OMPD_declare_reduction:
  14553. case OMPD_declare_mapper:
  14554. case OMPD_declare_simd:
  14555. case OMPD_declare_variant:
  14556. case OMPD_begin_declare_variant:
  14557. case OMPD_end_declare_variant:
  14558. case OMPD_declare_target:
  14559. case OMPD_end_declare_target:
  14560. case OMPD_loop:
  14561. case OMPD_simd:
  14562. case OMPD_tile:
  14563. case OMPD_unroll:
  14564. case OMPD_for:
  14565. case OMPD_for_simd:
  14566. case OMPD_sections:
  14567. case OMPD_section:
  14568. case OMPD_single:
  14569. case OMPD_master:
  14570. case OMPD_masked:
  14571. case OMPD_critical:
  14572. case OMPD_taskgroup:
  14573. case OMPD_distribute:
  14574. case OMPD_ordered:
  14575. case OMPD_atomic:
  14576. case OMPD_distribute_simd:
  14577. case OMPD_requires:
  14578. case OMPD_metadirective:
  14579. llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
  14580. case OMPD_unknown:
  14581. default:
  14582. llvm_unreachable("Unknown OpenMP directive");
  14583. }
  14584. break;
  14585. case OMPC_thread_limit:
  14586. switch (DKind) {
  14587. case OMPD_target:
  14588. case OMPD_target_teams:
  14589. case OMPD_target_teams_distribute:
  14590. case OMPD_target_teams_distribute_simd:
  14591. case OMPD_target_teams_distribute_parallel_for:
  14592. case OMPD_target_teams_distribute_parallel_for_simd:
  14593. case OMPD_target_teams_loop:
  14594. CaptureRegion = OMPD_target;
  14595. break;
  14596. case OMPD_teams_distribute_parallel_for:
  14597. case OMPD_teams_distribute_parallel_for_simd:
  14598. case OMPD_teams:
  14599. case OMPD_teams_distribute:
  14600. case OMPD_teams_distribute_simd:
  14601. case OMPD_teams_loop:
  14602. // Do not capture thread_limit-clause expressions.
  14603. break;
  14604. case OMPD_distribute_parallel_for:
  14605. case OMPD_distribute_parallel_for_simd:
  14606. case OMPD_task:
  14607. case OMPD_taskloop:
  14608. case OMPD_taskloop_simd:
  14609. case OMPD_master_taskloop:
  14610. case OMPD_masked_taskloop:
  14611. case OMPD_master_taskloop_simd:
  14612. case OMPD_masked_taskloop_simd:
  14613. case OMPD_parallel_master_taskloop:
  14614. case OMPD_parallel_masked_taskloop:
  14615. case OMPD_parallel_master_taskloop_simd:
  14616. case OMPD_parallel_masked_taskloop_simd:
  14617. case OMPD_target_data:
  14618. case OMPD_target_enter_data:
  14619. case OMPD_target_exit_data:
  14620. case OMPD_target_update:
  14621. case OMPD_cancel:
  14622. case OMPD_parallel:
  14623. case OMPD_parallel_master:
  14624. case OMPD_parallel_masked:
  14625. case OMPD_parallel_sections:
  14626. case OMPD_parallel_for:
  14627. case OMPD_parallel_for_simd:
  14628. case OMPD_parallel_loop:
  14629. case OMPD_target_simd:
  14630. case OMPD_target_parallel:
  14631. case OMPD_target_parallel_for:
  14632. case OMPD_target_parallel_for_simd:
  14633. case OMPD_target_parallel_loop:
  14634. case OMPD_threadprivate:
  14635. case OMPD_allocate:
  14636. case OMPD_taskyield:
  14637. case OMPD_error:
  14638. case OMPD_barrier:
  14639. case OMPD_taskwait:
  14640. case OMPD_cancellation_point:
  14641. case OMPD_flush:
  14642. case OMPD_depobj:
  14643. case OMPD_scan:
  14644. case OMPD_declare_reduction:
  14645. case OMPD_declare_mapper:
  14646. case OMPD_declare_simd:
  14647. case OMPD_declare_variant:
  14648. case OMPD_begin_declare_variant:
  14649. case OMPD_end_declare_variant:
  14650. case OMPD_declare_target:
  14651. case OMPD_end_declare_target:
  14652. case OMPD_loop:
  14653. case OMPD_simd:
  14654. case OMPD_tile:
  14655. case OMPD_unroll:
  14656. case OMPD_for:
  14657. case OMPD_for_simd:
  14658. case OMPD_sections:
  14659. case OMPD_section:
  14660. case OMPD_single:
  14661. case OMPD_master:
  14662. case OMPD_masked:
  14663. case OMPD_critical:
  14664. case OMPD_taskgroup:
  14665. case OMPD_distribute:
  14666. case OMPD_ordered:
  14667. case OMPD_atomic:
  14668. case OMPD_distribute_simd:
  14669. case OMPD_requires:
  14670. case OMPD_metadirective:
  14671. llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
  14672. case OMPD_unknown:
  14673. default:
  14674. llvm_unreachable("Unknown OpenMP directive");
  14675. }
  14676. break;
  14677. case OMPC_schedule:
  14678. switch (DKind) {
  14679. case OMPD_parallel_for:
  14680. case OMPD_parallel_for_simd:
  14681. case OMPD_distribute_parallel_for:
  14682. case OMPD_distribute_parallel_for_simd:
  14683. case OMPD_teams_distribute_parallel_for:
  14684. case OMPD_teams_distribute_parallel_for_simd:
  14685. case OMPD_target_parallel_for:
  14686. case OMPD_target_parallel_for_simd:
  14687. case OMPD_target_teams_distribute_parallel_for:
  14688. case OMPD_target_teams_distribute_parallel_for_simd:
  14689. CaptureRegion = OMPD_parallel;
  14690. break;
  14691. case OMPD_for:
  14692. case OMPD_for_simd:
  14693. // Do not capture schedule-clause expressions.
  14694. break;
  14695. case OMPD_task:
  14696. case OMPD_taskloop:
  14697. case OMPD_taskloop_simd:
  14698. case OMPD_master_taskloop:
  14699. case OMPD_masked_taskloop:
  14700. case OMPD_master_taskloop_simd:
  14701. case OMPD_masked_taskloop_simd:
  14702. case OMPD_parallel_master_taskloop:
  14703. case OMPD_parallel_masked_taskloop:
  14704. case OMPD_parallel_master_taskloop_simd:
  14705. case OMPD_parallel_masked_taskloop_simd:
  14706. case OMPD_target_data:
  14707. case OMPD_target_enter_data:
  14708. case OMPD_target_exit_data:
  14709. case OMPD_target_update:
  14710. case OMPD_teams:
  14711. case OMPD_teams_distribute:
  14712. case OMPD_teams_distribute_simd:
  14713. case OMPD_target_teams_distribute:
  14714. case OMPD_target_teams_distribute_simd:
  14715. case OMPD_target:
  14716. case OMPD_target_simd:
  14717. case OMPD_target_parallel:
  14718. case OMPD_cancel:
  14719. case OMPD_parallel:
  14720. case OMPD_parallel_master:
  14721. case OMPD_parallel_masked:
  14722. case OMPD_parallel_sections:
  14723. case OMPD_threadprivate:
  14724. case OMPD_allocate:
  14725. case OMPD_taskyield:
  14726. case OMPD_error:
  14727. case OMPD_barrier:
  14728. case OMPD_taskwait:
  14729. case OMPD_cancellation_point:
  14730. case OMPD_flush:
  14731. case OMPD_depobj:
  14732. case OMPD_scan:
  14733. case OMPD_declare_reduction:
  14734. case OMPD_declare_mapper:
  14735. case OMPD_declare_simd:
  14736. case OMPD_declare_variant:
  14737. case OMPD_begin_declare_variant:
  14738. case OMPD_end_declare_variant:
  14739. case OMPD_declare_target:
  14740. case OMPD_end_declare_target:
  14741. case OMPD_loop:
  14742. case OMPD_teams_loop:
  14743. case OMPD_target_teams_loop:
  14744. case OMPD_parallel_loop:
  14745. case OMPD_target_parallel_loop:
  14746. case OMPD_simd:
  14747. case OMPD_tile:
  14748. case OMPD_unroll:
  14749. case OMPD_sections:
  14750. case OMPD_section:
  14751. case OMPD_single:
  14752. case OMPD_master:
  14753. case OMPD_masked:
  14754. case OMPD_critical:
  14755. case OMPD_taskgroup:
  14756. case OMPD_distribute:
  14757. case OMPD_ordered:
  14758. case OMPD_atomic:
  14759. case OMPD_distribute_simd:
  14760. case OMPD_target_teams:
  14761. case OMPD_requires:
  14762. case OMPD_metadirective:
  14763. llvm_unreachable("Unexpected OpenMP directive with schedule clause");
  14764. case OMPD_unknown:
  14765. default:
  14766. llvm_unreachable("Unknown OpenMP directive");
  14767. }
  14768. break;
  14769. case OMPC_dist_schedule:
  14770. switch (DKind) {
  14771. case OMPD_teams_distribute_parallel_for:
  14772. case OMPD_teams_distribute_parallel_for_simd:
  14773. case OMPD_teams_distribute:
  14774. case OMPD_teams_distribute_simd:
  14775. case OMPD_target_teams_distribute_parallel_for:
  14776. case OMPD_target_teams_distribute_parallel_for_simd:
  14777. case OMPD_target_teams_distribute:
  14778. case OMPD_target_teams_distribute_simd:
  14779. CaptureRegion = OMPD_teams;
  14780. break;
  14781. case OMPD_distribute_parallel_for:
  14782. case OMPD_distribute_parallel_for_simd:
  14783. case OMPD_distribute:
  14784. case OMPD_distribute_simd:
  14785. // Do not capture dist_schedule-clause expressions.
  14786. break;
  14787. case OMPD_parallel_for:
  14788. case OMPD_parallel_for_simd:
  14789. case OMPD_target_parallel_for_simd:
  14790. case OMPD_target_parallel_for:
  14791. case OMPD_task:
  14792. case OMPD_taskloop:
  14793. case OMPD_taskloop_simd:
  14794. case OMPD_master_taskloop:
  14795. case OMPD_masked_taskloop:
  14796. case OMPD_master_taskloop_simd:
  14797. case OMPD_masked_taskloop_simd:
  14798. case OMPD_parallel_master_taskloop:
  14799. case OMPD_parallel_masked_taskloop:
  14800. case OMPD_parallel_master_taskloop_simd:
  14801. case OMPD_parallel_masked_taskloop_simd:
  14802. case OMPD_target_data:
  14803. case OMPD_target_enter_data:
  14804. case OMPD_target_exit_data:
  14805. case OMPD_target_update:
  14806. case OMPD_teams:
  14807. case OMPD_target:
  14808. case OMPD_target_simd:
  14809. case OMPD_target_parallel:
  14810. case OMPD_cancel:
  14811. case OMPD_parallel:
  14812. case OMPD_parallel_master:
  14813. case OMPD_parallel_masked:
  14814. case OMPD_parallel_sections:
  14815. case OMPD_threadprivate:
  14816. case OMPD_allocate:
  14817. case OMPD_taskyield:
  14818. case OMPD_error:
  14819. case OMPD_barrier:
  14820. case OMPD_taskwait:
  14821. case OMPD_cancellation_point:
  14822. case OMPD_flush:
  14823. case OMPD_depobj:
  14824. case OMPD_scan:
  14825. case OMPD_declare_reduction:
  14826. case OMPD_declare_mapper:
  14827. case OMPD_declare_simd:
  14828. case OMPD_declare_variant:
  14829. case OMPD_begin_declare_variant:
  14830. case OMPD_end_declare_variant:
  14831. case OMPD_declare_target:
  14832. case OMPD_end_declare_target:
  14833. case OMPD_loop:
  14834. case OMPD_teams_loop:
  14835. case OMPD_target_teams_loop:
  14836. case OMPD_parallel_loop:
  14837. case OMPD_target_parallel_loop:
  14838. case OMPD_simd:
  14839. case OMPD_tile:
  14840. case OMPD_unroll:
  14841. case OMPD_for:
  14842. case OMPD_for_simd:
  14843. case OMPD_sections:
  14844. case OMPD_section:
  14845. case OMPD_single:
  14846. case OMPD_master:
  14847. case OMPD_masked:
  14848. case OMPD_critical:
  14849. case OMPD_taskgroup:
  14850. case OMPD_ordered:
  14851. case OMPD_atomic:
  14852. case OMPD_target_teams:
  14853. case OMPD_requires:
  14854. case OMPD_metadirective:
  14855. llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause");
  14856. case OMPD_unknown:
  14857. default:
  14858. llvm_unreachable("Unknown OpenMP directive");
  14859. }
  14860. break;
  14861. case OMPC_ompx_dyn_cgroup_mem:
  14862. switch (DKind) {
  14863. case OMPD_target:
  14864. case OMPD_target_simd:
  14865. case OMPD_target_teams:
  14866. case OMPD_target_parallel:
  14867. case OMPD_target_teams_distribute:
  14868. case OMPD_target_teams_distribute_simd:
  14869. case OMPD_target_parallel_for:
  14870. case OMPD_target_parallel_for_simd:
  14871. case OMPD_target_parallel_loop:
  14872. case OMPD_target_teams_distribute_parallel_for:
  14873. case OMPD_target_teams_distribute_parallel_for_simd:
  14874. case OMPD_target_teams_loop:
  14875. CaptureRegion = OMPD_target;
  14876. break;
  14877. default:
  14878. llvm_unreachable("Unknown OpenMP directive");
  14879. }
  14880. break;
  14881. case OMPC_device:
  14882. switch (DKind) {
  14883. case OMPD_target_update:
  14884. case OMPD_target_enter_data:
  14885. case OMPD_target_exit_data:
  14886. case OMPD_target:
  14887. case OMPD_target_simd:
  14888. case OMPD_target_teams:
  14889. case OMPD_target_parallel:
  14890. case OMPD_target_teams_distribute:
  14891. case OMPD_target_teams_distribute_simd:
  14892. case OMPD_target_parallel_for:
  14893. case OMPD_target_parallel_for_simd:
  14894. case OMPD_target_parallel_loop:
  14895. case OMPD_target_teams_distribute_parallel_for:
  14896. case OMPD_target_teams_distribute_parallel_for_simd:
  14897. case OMPD_target_teams_loop:
  14898. case OMPD_dispatch:
  14899. CaptureRegion = OMPD_task;
  14900. break;
  14901. case OMPD_target_data:
  14902. case OMPD_interop:
  14903. // Do not capture device-clause expressions.
  14904. break;
  14905. case OMPD_teams_distribute_parallel_for:
  14906. case OMPD_teams_distribute_parallel_for_simd:
  14907. case OMPD_teams:
  14908. case OMPD_teams_distribute:
  14909. case OMPD_teams_distribute_simd:
  14910. case OMPD_distribute_parallel_for:
  14911. case OMPD_distribute_parallel_for_simd:
  14912. case OMPD_task:
  14913. case OMPD_taskloop:
  14914. case OMPD_taskloop_simd:
  14915. case OMPD_master_taskloop:
  14916. case OMPD_masked_taskloop:
  14917. case OMPD_master_taskloop_simd:
  14918. case OMPD_masked_taskloop_simd:
  14919. case OMPD_parallel_master_taskloop:
  14920. case OMPD_parallel_masked_taskloop:
  14921. case OMPD_parallel_master_taskloop_simd:
  14922. case OMPD_parallel_masked_taskloop_simd:
  14923. case OMPD_cancel:
  14924. case OMPD_parallel:
  14925. case OMPD_parallel_master:
  14926. case OMPD_parallel_masked:
  14927. case OMPD_parallel_sections:
  14928. case OMPD_parallel_for:
  14929. case OMPD_parallel_for_simd:
  14930. case OMPD_threadprivate:
  14931. case OMPD_allocate:
  14932. case OMPD_taskyield:
  14933. case OMPD_error:
  14934. case OMPD_barrier:
  14935. case OMPD_taskwait:
  14936. case OMPD_cancellation_point:
  14937. case OMPD_flush:
  14938. case OMPD_depobj:
  14939. case OMPD_scan:
  14940. case OMPD_declare_reduction:
  14941. case OMPD_declare_mapper:
  14942. case OMPD_declare_simd:
  14943. case OMPD_declare_variant:
  14944. case OMPD_begin_declare_variant:
  14945. case OMPD_end_declare_variant:
  14946. case OMPD_declare_target:
  14947. case OMPD_end_declare_target:
  14948. case OMPD_loop:
  14949. case OMPD_teams_loop:
  14950. case OMPD_parallel_loop:
  14951. case OMPD_simd:
  14952. case OMPD_tile:
  14953. case OMPD_unroll:
  14954. case OMPD_for:
  14955. case OMPD_for_simd:
  14956. case OMPD_sections:
  14957. case OMPD_section:
  14958. case OMPD_single:
  14959. case OMPD_master:
  14960. case OMPD_masked:
  14961. case OMPD_critical:
  14962. case OMPD_taskgroup:
  14963. case OMPD_distribute:
  14964. case OMPD_ordered:
  14965. case OMPD_atomic:
  14966. case OMPD_distribute_simd:
  14967. case OMPD_requires:
  14968. case OMPD_metadirective:
  14969. llvm_unreachable("Unexpected OpenMP directive with device-clause");
  14970. case OMPD_unknown:
  14971. default:
  14972. llvm_unreachable("Unknown OpenMP directive");
  14973. }
  14974. break;
  14975. case OMPC_grainsize:
  14976. case OMPC_num_tasks:
  14977. case OMPC_final:
  14978. case OMPC_priority:
  14979. switch (DKind) {
  14980. case OMPD_task:
  14981. case OMPD_taskloop:
  14982. case OMPD_taskloop_simd:
  14983. case OMPD_master_taskloop:
  14984. case OMPD_masked_taskloop:
  14985. case OMPD_master_taskloop_simd:
  14986. case OMPD_masked_taskloop_simd:
  14987. break;
  14988. case OMPD_parallel_masked_taskloop:
  14989. case OMPD_parallel_masked_taskloop_simd:
  14990. case OMPD_parallel_master_taskloop:
  14991. case OMPD_parallel_master_taskloop_simd:
  14992. CaptureRegion = OMPD_parallel;
  14993. break;
  14994. case OMPD_target_update:
  14995. case OMPD_target_enter_data:
  14996. case OMPD_target_exit_data:
  14997. case OMPD_target:
  14998. case OMPD_target_simd:
  14999. case OMPD_target_teams:
  15000. case OMPD_target_parallel:
  15001. case OMPD_target_teams_distribute:
  15002. case OMPD_target_teams_distribute_simd:
  15003. case OMPD_target_parallel_for:
  15004. case OMPD_target_parallel_for_simd:
  15005. case OMPD_target_teams_distribute_parallel_for:
  15006. case OMPD_target_teams_distribute_parallel_for_simd:
  15007. case OMPD_target_data:
  15008. case OMPD_teams_distribute_parallel_for:
  15009. case OMPD_teams_distribute_parallel_for_simd:
  15010. case OMPD_teams:
  15011. case OMPD_teams_distribute:
  15012. case OMPD_teams_distribute_simd:
  15013. case OMPD_distribute_parallel_for:
  15014. case OMPD_distribute_parallel_for_simd:
  15015. case OMPD_cancel:
  15016. case OMPD_parallel:
  15017. case OMPD_parallel_master:
  15018. case OMPD_parallel_masked:
  15019. case OMPD_parallel_sections:
  15020. case OMPD_parallel_for:
  15021. case OMPD_parallel_for_simd:
  15022. case OMPD_threadprivate:
  15023. case OMPD_allocate:
  15024. case OMPD_taskyield:
  15025. case OMPD_error:
  15026. case OMPD_barrier:
  15027. case OMPD_taskwait:
  15028. case OMPD_cancellation_point:
  15029. case OMPD_flush:
  15030. case OMPD_depobj:
  15031. case OMPD_scan:
  15032. case OMPD_declare_reduction:
  15033. case OMPD_declare_mapper:
  15034. case OMPD_declare_simd:
  15035. case OMPD_declare_variant:
  15036. case OMPD_begin_declare_variant:
  15037. case OMPD_end_declare_variant:
  15038. case OMPD_declare_target:
  15039. case OMPD_end_declare_target:
  15040. case OMPD_loop:
  15041. case OMPD_teams_loop:
  15042. case OMPD_target_teams_loop:
  15043. case OMPD_parallel_loop:
  15044. case OMPD_target_parallel_loop:
  15045. case OMPD_simd:
  15046. case OMPD_tile:
  15047. case OMPD_unroll:
  15048. case OMPD_for:
  15049. case OMPD_for_simd:
  15050. case OMPD_sections:
  15051. case OMPD_section:
  15052. case OMPD_single:
  15053. case OMPD_master:
  15054. case OMPD_masked:
  15055. case OMPD_critical:
  15056. case OMPD_taskgroup:
  15057. case OMPD_distribute:
  15058. case OMPD_ordered:
  15059. case OMPD_atomic:
  15060. case OMPD_distribute_simd:
  15061. case OMPD_requires:
  15062. case OMPD_metadirective:
  15063. llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
  15064. case OMPD_unknown:
  15065. default:
  15066. llvm_unreachable("Unknown OpenMP directive");
  15067. }
  15068. break;
  15069. case OMPC_novariants:
  15070. case OMPC_nocontext:
  15071. switch (DKind) {
  15072. case OMPD_dispatch:
  15073. CaptureRegion = OMPD_task;
  15074. break;
  15075. default:
  15076. llvm_unreachable("Unexpected OpenMP directive");
  15077. }
  15078. break;
  15079. case OMPC_filter:
  15080. // Do not capture filter-clause expressions.
  15081. break;
  15082. case OMPC_when:
  15083. if (DKind == OMPD_metadirective) {
  15084. CaptureRegion = OMPD_metadirective;
  15085. } else if (DKind == OMPD_unknown) {
  15086. llvm_unreachable("Unknown OpenMP directive");
  15087. } else {
  15088. llvm_unreachable("Unexpected OpenMP directive with when clause");
  15089. }
  15090. break;
  15091. case OMPC_firstprivate:
  15092. case OMPC_lastprivate:
  15093. case OMPC_reduction:
  15094. case OMPC_task_reduction:
  15095. case OMPC_in_reduction:
  15096. case OMPC_linear:
  15097. case OMPC_default:
  15098. case OMPC_proc_bind:
  15099. case OMPC_safelen:
  15100. case OMPC_simdlen:
  15101. case OMPC_sizes:
  15102. case OMPC_allocator:
  15103. case OMPC_collapse:
  15104. case OMPC_private:
  15105. case OMPC_shared:
  15106. case OMPC_aligned:
  15107. case OMPC_copyin:
  15108. case OMPC_copyprivate:
  15109. case OMPC_ordered:
  15110. case OMPC_nowait:
  15111. case OMPC_untied:
  15112. case OMPC_mergeable:
  15113. case OMPC_threadprivate:
  15114. case OMPC_allocate:
  15115. case OMPC_flush:
  15116. case OMPC_depobj:
  15117. case OMPC_read:
  15118. case OMPC_write:
  15119. case OMPC_update:
  15120. case OMPC_capture:
  15121. case OMPC_compare:
  15122. case OMPC_seq_cst:
  15123. case OMPC_acq_rel:
  15124. case OMPC_acquire:
  15125. case OMPC_release:
  15126. case OMPC_relaxed:
  15127. case OMPC_depend:
  15128. case OMPC_threads:
  15129. case OMPC_simd:
  15130. case OMPC_map:
  15131. case OMPC_nogroup:
  15132. case OMPC_hint:
  15133. case OMPC_defaultmap:
  15134. case OMPC_unknown:
  15135. case OMPC_uniform:
  15136. case OMPC_to:
  15137. case OMPC_from:
  15138. case OMPC_use_device_ptr:
  15139. case OMPC_use_device_addr:
  15140. case OMPC_is_device_ptr:
  15141. case OMPC_unified_address:
  15142. case OMPC_unified_shared_memory:
  15143. case OMPC_reverse_offload:
  15144. case OMPC_dynamic_allocators:
  15145. case OMPC_atomic_default_mem_order:
  15146. case OMPC_device_type:
  15147. case OMPC_match:
  15148. case OMPC_nontemporal:
  15149. case OMPC_order:
  15150. case OMPC_at:
  15151. case OMPC_severity:
  15152. case OMPC_message:
  15153. case OMPC_destroy:
  15154. case OMPC_detach:
  15155. case OMPC_inclusive:
  15156. case OMPC_exclusive:
  15157. case OMPC_uses_allocators:
  15158. case OMPC_affinity:
  15159. case OMPC_bind:
  15160. default:
  15161. llvm_unreachable("Unexpected OpenMP clause.");
  15162. }
  15163. return CaptureRegion;
  15164. }
  15165. OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
  15166. Expr *Condition, SourceLocation StartLoc,
  15167. SourceLocation LParenLoc,
  15168. SourceLocation NameModifierLoc,
  15169. SourceLocation ColonLoc,
  15170. SourceLocation EndLoc) {
  15171. Expr *ValExpr = Condition;
  15172. Stmt *HelperValStmt = nullptr;
  15173. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  15174. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  15175. !Condition->isInstantiationDependent() &&
  15176. !Condition->containsUnexpandedParameterPack()) {
  15177. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  15178. if (Val.isInvalid())
  15179. return nullptr;
  15180. ValExpr = Val.get();
  15181. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  15182. CaptureRegion = getOpenMPCaptureRegionForClause(
  15183. DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
  15184. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  15185. ValExpr = MakeFullExpr(ValExpr).get();
  15186. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  15187. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  15188. HelperValStmt = buildPreInits(Context, Captures);
  15189. }
  15190. }
  15191. return new (Context)
  15192. OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  15193. LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
  15194. }
  15195. OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
  15196. SourceLocation StartLoc,
  15197. SourceLocation LParenLoc,
  15198. SourceLocation EndLoc) {
  15199. Expr *ValExpr = Condition;
  15200. Stmt *HelperValStmt = nullptr;
  15201. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  15202. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  15203. !Condition->isInstantiationDependent() &&
  15204. !Condition->containsUnexpandedParameterPack()) {
  15205. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  15206. if (Val.isInvalid())
  15207. return nullptr;
  15208. ValExpr = MakeFullExpr(Val.get()).get();
  15209. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  15210. CaptureRegion =
  15211. getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
  15212. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  15213. ValExpr = MakeFullExpr(ValExpr).get();
  15214. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  15215. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  15216. HelperValStmt = buildPreInits(Context, Captures);
  15217. }
  15218. }
  15219. return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
  15220. StartLoc, LParenLoc, EndLoc);
  15221. }
  15222. ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
  15223. Expr *Op) {
  15224. if (!Op)
  15225. return ExprError();
  15226. class IntConvertDiagnoser : public ICEConvertDiagnoser {
  15227. public:
  15228. IntConvertDiagnoser()
  15229. : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
  15230. SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
  15231. QualType T) override {
  15232. return S.Diag(Loc, diag::err_omp_not_integral) << T;
  15233. }
  15234. SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
  15235. QualType T) override {
  15236. return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
  15237. }
  15238. SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
  15239. QualType T,
  15240. QualType ConvTy) override {
  15241. return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
  15242. }
  15243. SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
  15244. QualType ConvTy) override {
  15245. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  15246. << ConvTy->isEnumeralType() << ConvTy;
  15247. }
  15248. SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
  15249. QualType T) override {
  15250. return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
  15251. }
  15252. SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
  15253. QualType ConvTy) override {
  15254. return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
  15255. << ConvTy->isEnumeralType() << ConvTy;
  15256. }
  15257. SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
  15258. QualType) override {
  15259. llvm_unreachable("conversion functions are permitted");
  15260. }
  15261. } ConvertDiagnoser;
  15262. return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
  15263. }
  15264. static bool
  15265. isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
  15266. bool StrictlyPositive, bool BuildCapture = false,
  15267. OpenMPDirectiveKind DKind = OMPD_unknown,
  15268. OpenMPDirectiveKind *CaptureRegion = nullptr,
  15269. Stmt **HelperValStmt = nullptr) {
  15270. if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
  15271. !ValExpr->isInstantiationDependent()) {
  15272. SourceLocation Loc = ValExpr->getExprLoc();
  15273. ExprResult Value =
  15274. SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
  15275. if (Value.isInvalid())
  15276. return false;
  15277. ValExpr = Value.get();
  15278. // The expression must evaluate to a non-negative integer value.
  15279. if (std::optional<llvm::APSInt> Result =
  15280. ValExpr->getIntegerConstantExpr(SemaRef.Context)) {
  15281. if (Result->isSigned() &&
  15282. !((!StrictlyPositive && Result->isNonNegative()) ||
  15283. (StrictlyPositive && Result->isStrictlyPositive()))) {
  15284. SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
  15285. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  15286. << ValExpr->getSourceRange();
  15287. return false;
  15288. }
  15289. }
  15290. if (!BuildCapture)
  15291. return true;
  15292. *CaptureRegion =
  15293. getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
  15294. if (*CaptureRegion != OMPD_unknown &&
  15295. !SemaRef.CurContext->isDependentContext()) {
  15296. ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
  15297. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  15298. ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
  15299. *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
  15300. }
  15301. }
  15302. return true;
  15303. }
  15304. OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
  15305. SourceLocation StartLoc,
  15306. SourceLocation LParenLoc,
  15307. SourceLocation EndLoc) {
  15308. Expr *ValExpr = NumThreads;
  15309. Stmt *HelperValStmt = nullptr;
  15310. // OpenMP [2.5, Restrictions]
  15311. // The num_threads expression must evaluate to a positive integer value.
  15312. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
  15313. /*StrictlyPositive=*/true))
  15314. return nullptr;
  15315. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  15316. OpenMPDirectiveKind CaptureRegion =
  15317. getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
  15318. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  15319. ValExpr = MakeFullExpr(ValExpr).get();
  15320. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  15321. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  15322. HelperValStmt = buildPreInits(Context, Captures);
  15323. }
  15324. return new (Context) OMPNumThreadsClause(
  15325. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  15326. }
  15327. ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
  15328. OpenMPClauseKind CKind,
  15329. bool StrictlyPositive,
  15330. bool SuppressExprDiags) {
  15331. if (!E)
  15332. return ExprError();
  15333. if (E->isValueDependent() || E->isTypeDependent() ||
  15334. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  15335. return E;
  15336. llvm::APSInt Result;
  15337. ExprResult ICE;
  15338. if (SuppressExprDiags) {
  15339. // Use a custom diagnoser that suppresses 'note' diagnostics about the
  15340. // expression.
  15341. struct SuppressedDiagnoser : public Sema::VerifyICEDiagnoser {
  15342. SuppressedDiagnoser() : VerifyICEDiagnoser(/*Suppress=*/true) {}
  15343. Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
  15344. SourceLocation Loc) override {
  15345. llvm_unreachable("Diagnostic suppressed");
  15346. }
  15347. } Diagnoser;
  15348. ICE = VerifyIntegerConstantExpression(E, &Result, Diagnoser, AllowFold);
  15349. } else {
  15350. ICE = VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold);
  15351. }
  15352. if (ICE.isInvalid())
  15353. return ExprError();
  15354. if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
  15355. (!StrictlyPositive && !Result.isNonNegative())) {
  15356. Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
  15357. << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
  15358. << E->getSourceRange();
  15359. return ExprError();
  15360. }
  15361. if ((CKind == OMPC_aligned || CKind == OMPC_align) && !Result.isPowerOf2()) {
  15362. Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
  15363. << E->getSourceRange();
  15364. return ExprError();
  15365. }
  15366. if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
  15367. DSAStack->setAssociatedLoops(Result.getExtValue());
  15368. else if (CKind == OMPC_ordered)
  15369. DSAStack->setAssociatedLoops(Result.getExtValue());
  15370. return ICE;
  15371. }
  15372. OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
  15373. SourceLocation LParenLoc,
  15374. SourceLocation EndLoc) {
  15375. // OpenMP [2.8.1, simd construct, Description]
  15376. // The parameter of the safelen clause must be a constant
  15377. // positive integer expression.
  15378. ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
  15379. if (Safelen.isInvalid())
  15380. return nullptr;
  15381. return new (Context)
  15382. OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
  15383. }
  15384. OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
  15385. SourceLocation LParenLoc,
  15386. SourceLocation EndLoc) {
  15387. // OpenMP [2.8.1, simd construct, Description]
  15388. // The parameter of the simdlen clause must be a constant
  15389. // positive integer expression.
  15390. ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
  15391. if (Simdlen.isInvalid())
  15392. return nullptr;
  15393. return new (Context)
  15394. OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
  15395. }
  15396. /// Tries to find omp_allocator_handle_t type.
  15397. static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
  15398. DSAStackTy *Stack) {
  15399. if (!Stack->getOMPAllocatorHandleT().isNull())
  15400. return true;
  15401. // Set the allocator handle type.
  15402. IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_allocator_handle_t");
  15403. ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
  15404. if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
  15405. S.Diag(Loc, diag::err_omp_implied_type_not_found)
  15406. << "omp_allocator_handle_t";
  15407. return false;
  15408. }
  15409. QualType AllocatorHandleEnumTy = PT.get();
  15410. AllocatorHandleEnumTy.addConst();
  15411. Stack->setOMPAllocatorHandleT(AllocatorHandleEnumTy);
  15412. // Fill the predefined allocator map.
  15413. bool ErrorFound = false;
  15414. for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  15415. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  15416. StringRef Allocator =
  15417. OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
  15418. DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
  15419. auto *VD = dyn_cast_or_null<ValueDecl>(
  15420. S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
  15421. if (!VD) {
  15422. ErrorFound = true;
  15423. break;
  15424. }
  15425. QualType AllocatorType =
  15426. VD->getType().getNonLValueExprType(S.getASTContext());
  15427. ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
  15428. if (!Res.isUsable()) {
  15429. ErrorFound = true;
  15430. break;
  15431. }
  15432. Res = S.PerformImplicitConversion(Res.get(), AllocatorHandleEnumTy,
  15433. Sema::AA_Initializing,
  15434. /* AllowExplicit */ true);
  15435. if (!Res.isUsable()) {
  15436. ErrorFound = true;
  15437. break;
  15438. }
  15439. Stack->setAllocator(AllocatorKind, Res.get());
  15440. }
  15441. if (ErrorFound) {
  15442. S.Diag(Loc, diag::err_omp_implied_type_not_found)
  15443. << "omp_allocator_handle_t";
  15444. return false;
  15445. }
  15446. return true;
  15447. }
  15448. OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
  15449. SourceLocation LParenLoc,
  15450. SourceLocation EndLoc) {
  15451. // OpenMP [2.11.3, allocate Directive, Description]
  15452. // allocator is an expression of omp_allocator_handle_t type.
  15453. if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
  15454. return nullptr;
  15455. ExprResult Allocator = DefaultLvalueConversion(A);
  15456. if (Allocator.isInvalid())
  15457. return nullptr;
  15458. Allocator = PerformImplicitConversion(Allocator.get(),
  15459. DSAStack->getOMPAllocatorHandleT(),
  15460. Sema::AA_Initializing,
  15461. /*AllowExplicit=*/true);
  15462. if (Allocator.isInvalid())
  15463. return nullptr;
  15464. return new (Context)
  15465. OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
  15466. }
  15467. OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
  15468. SourceLocation StartLoc,
  15469. SourceLocation LParenLoc,
  15470. SourceLocation EndLoc) {
  15471. // OpenMP [2.7.1, loop construct, Description]
  15472. // OpenMP [2.8.1, simd construct, Description]
  15473. // OpenMP [2.9.6, distribute construct, Description]
  15474. // The parameter of the collapse clause must be a constant
  15475. // positive integer expression.
  15476. ExprResult NumForLoopsResult =
  15477. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
  15478. if (NumForLoopsResult.isInvalid())
  15479. return nullptr;
  15480. return new (Context)
  15481. OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
  15482. }
  15483. OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
  15484. SourceLocation EndLoc,
  15485. SourceLocation LParenLoc,
  15486. Expr *NumForLoops) {
  15487. // OpenMP [2.7.1, loop construct, Description]
  15488. // OpenMP [2.8.1, simd construct, Description]
  15489. // OpenMP [2.9.6, distribute construct, Description]
  15490. // The parameter of the ordered clause must be a constant
  15491. // positive integer expression if any.
  15492. if (NumForLoops && LParenLoc.isValid()) {
  15493. ExprResult NumForLoopsResult =
  15494. VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
  15495. if (NumForLoopsResult.isInvalid())
  15496. return nullptr;
  15497. NumForLoops = NumForLoopsResult.get();
  15498. } else {
  15499. NumForLoops = nullptr;
  15500. }
  15501. auto *Clause = OMPOrderedClause::Create(
  15502. Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
  15503. StartLoc, LParenLoc, EndLoc);
  15504. DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
  15505. return Clause;
  15506. }
  15507. OMPClause *Sema::ActOnOpenMPSimpleClause(
  15508. OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
  15509. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  15510. OMPClause *Res = nullptr;
  15511. switch (Kind) {
  15512. case OMPC_default:
  15513. Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument),
  15514. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  15515. break;
  15516. case OMPC_proc_bind:
  15517. Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
  15518. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  15519. break;
  15520. case OMPC_atomic_default_mem_order:
  15521. Res = ActOnOpenMPAtomicDefaultMemOrderClause(
  15522. static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
  15523. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  15524. break;
  15525. case OMPC_update:
  15526. Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument),
  15527. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  15528. break;
  15529. case OMPC_bind:
  15530. Res = ActOnOpenMPBindClause(static_cast<OpenMPBindClauseKind>(Argument),
  15531. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  15532. break;
  15533. case OMPC_at:
  15534. Res = ActOnOpenMPAtClause(static_cast<OpenMPAtClauseKind>(Argument),
  15535. ArgumentLoc, StartLoc, LParenLoc, EndLoc);
  15536. break;
  15537. case OMPC_severity:
  15538. Res = ActOnOpenMPSeverityClause(
  15539. static_cast<OpenMPSeverityClauseKind>(Argument), ArgumentLoc, StartLoc,
  15540. LParenLoc, EndLoc);
  15541. break;
  15542. case OMPC_if:
  15543. case OMPC_final:
  15544. case OMPC_num_threads:
  15545. case OMPC_safelen:
  15546. case OMPC_simdlen:
  15547. case OMPC_sizes:
  15548. case OMPC_allocator:
  15549. case OMPC_collapse:
  15550. case OMPC_schedule:
  15551. case OMPC_private:
  15552. case OMPC_firstprivate:
  15553. case OMPC_lastprivate:
  15554. case OMPC_shared:
  15555. case OMPC_reduction:
  15556. case OMPC_task_reduction:
  15557. case OMPC_in_reduction:
  15558. case OMPC_linear:
  15559. case OMPC_aligned:
  15560. case OMPC_copyin:
  15561. case OMPC_copyprivate:
  15562. case OMPC_ordered:
  15563. case OMPC_nowait:
  15564. case OMPC_untied:
  15565. case OMPC_mergeable:
  15566. case OMPC_threadprivate:
  15567. case OMPC_allocate:
  15568. case OMPC_flush:
  15569. case OMPC_depobj:
  15570. case OMPC_read:
  15571. case OMPC_write:
  15572. case OMPC_capture:
  15573. case OMPC_compare:
  15574. case OMPC_seq_cst:
  15575. case OMPC_acq_rel:
  15576. case OMPC_acquire:
  15577. case OMPC_release:
  15578. case OMPC_relaxed:
  15579. case OMPC_depend:
  15580. case OMPC_device:
  15581. case OMPC_threads:
  15582. case OMPC_simd:
  15583. case OMPC_map:
  15584. case OMPC_num_teams:
  15585. case OMPC_thread_limit:
  15586. case OMPC_priority:
  15587. case OMPC_grainsize:
  15588. case OMPC_nogroup:
  15589. case OMPC_num_tasks:
  15590. case OMPC_hint:
  15591. case OMPC_dist_schedule:
  15592. case OMPC_defaultmap:
  15593. case OMPC_unknown:
  15594. case OMPC_uniform:
  15595. case OMPC_to:
  15596. case OMPC_from:
  15597. case OMPC_use_device_ptr:
  15598. case OMPC_use_device_addr:
  15599. case OMPC_is_device_ptr:
  15600. case OMPC_has_device_addr:
  15601. case OMPC_unified_address:
  15602. case OMPC_unified_shared_memory:
  15603. case OMPC_reverse_offload:
  15604. case OMPC_dynamic_allocators:
  15605. case OMPC_device_type:
  15606. case OMPC_match:
  15607. case OMPC_nontemporal:
  15608. case OMPC_destroy:
  15609. case OMPC_novariants:
  15610. case OMPC_nocontext:
  15611. case OMPC_detach:
  15612. case OMPC_inclusive:
  15613. case OMPC_exclusive:
  15614. case OMPC_uses_allocators:
  15615. case OMPC_affinity:
  15616. case OMPC_when:
  15617. case OMPC_message:
  15618. default:
  15619. llvm_unreachable("Clause is not allowed.");
  15620. }
  15621. return Res;
  15622. }
  15623. static std::string
  15624. getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
  15625. ArrayRef<unsigned> Exclude = std::nullopt) {
  15626. SmallString<256> Buffer;
  15627. llvm::raw_svector_ostream Out(Buffer);
  15628. unsigned Skipped = Exclude.size();
  15629. for (unsigned I = First; I < Last; ++I) {
  15630. if (llvm::is_contained(Exclude, I)) {
  15631. --Skipped;
  15632. continue;
  15633. }
  15634. Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
  15635. if (I + Skipped + 2 == Last)
  15636. Out << " or ";
  15637. else if (I + Skipped + 1 != Last)
  15638. Out << ", ";
  15639. }
  15640. return std::string(Out.str());
  15641. }
  15642. OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind,
  15643. SourceLocation KindKwLoc,
  15644. SourceLocation StartLoc,
  15645. SourceLocation LParenLoc,
  15646. SourceLocation EndLoc) {
  15647. if (Kind == OMP_DEFAULT_unknown) {
  15648. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  15649. << getListOfPossibleValues(OMPC_default, /*First=*/0,
  15650. /*Last=*/unsigned(OMP_DEFAULT_unknown))
  15651. << getOpenMPClauseName(OMPC_default);
  15652. return nullptr;
  15653. }
  15654. switch (Kind) {
  15655. case OMP_DEFAULT_none:
  15656. DSAStack->setDefaultDSANone(KindKwLoc);
  15657. break;
  15658. case OMP_DEFAULT_shared:
  15659. DSAStack->setDefaultDSAShared(KindKwLoc);
  15660. break;
  15661. case OMP_DEFAULT_firstprivate:
  15662. DSAStack->setDefaultDSAFirstPrivate(KindKwLoc);
  15663. break;
  15664. case OMP_DEFAULT_private:
  15665. DSAStack->setDefaultDSAPrivate(KindKwLoc);
  15666. break;
  15667. default:
  15668. llvm_unreachable("DSA unexpected in OpenMP default clause");
  15669. }
  15670. return new (Context)
  15671. OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  15672. }
  15673. OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
  15674. SourceLocation KindKwLoc,
  15675. SourceLocation StartLoc,
  15676. SourceLocation LParenLoc,
  15677. SourceLocation EndLoc) {
  15678. if (Kind == OMP_PROC_BIND_unknown) {
  15679. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  15680. << getListOfPossibleValues(OMPC_proc_bind,
  15681. /*First=*/unsigned(OMP_PROC_BIND_master),
  15682. /*Last=*/
  15683. unsigned(LangOpts.OpenMP > 50
  15684. ? OMP_PROC_BIND_primary
  15685. : OMP_PROC_BIND_spread) +
  15686. 1)
  15687. << getOpenMPClauseName(OMPC_proc_bind);
  15688. return nullptr;
  15689. }
  15690. if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51)
  15691. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  15692. << getListOfPossibleValues(OMPC_proc_bind,
  15693. /*First=*/unsigned(OMP_PROC_BIND_master),
  15694. /*Last=*/
  15695. unsigned(OMP_PROC_BIND_spread) + 1)
  15696. << getOpenMPClauseName(OMPC_proc_bind);
  15697. return new (Context)
  15698. OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  15699. }
  15700. OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
  15701. OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
  15702. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  15703. if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
  15704. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  15705. << getListOfPossibleValues(
  15706. OMPC_atomic_default_mem_order, /*First=*/0,
  15707. /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
  15708. << getOpenMPClauseName(OMPC_atomic_default_mem_order);
  15709. return nullptr;
  15710. }
  15711. return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
  15712. LParenLoc, EndLoc);
  15713. }
  15714. OMPClause *Sema::ActOnOpenMPAtClause(OpenMPAtClauseKind Kind,
  15715. SourceLocation KindKwLoc,
  15716. SourceLocation StartLoc,
  15717. SourceLocation LParenLoc,
  15718. SourceLocation EndLoc) {
  15719. if (Kind == OMPC_AT_unknown) {
  15720. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  15721. << getListOfPossibleValues(OMPC_at, /*First=*/0,
  15722. /*Last=*/OMPC_AT_unknown)
  15723. << getOpenMPClauseName(OMPC_at);
  15724. return nullptr;
  15725. }
  15726. return new (Context)
  15727. OMPAtClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  15728. }
  15729. OMPClause *Sema::ActOnOpenMPSeverityClause(OpenMPSeverityClauseKind Kind,
  15730. SourceLocation KindKwLoc,
  15731. SourceLocation StartLoc,
  15732. SourceLocation LParenLoc,
  15733. SourceLocation EndLoc) {
  15734. if (Kind == OMPC_SEVERITY_unknown) {
  15735. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  15736. << getListOfPossibleValues(OMPC_severity, /*First=*/0,
  15737. /*Last=*/OMPC_SEVERITY_unknown)
  15738. << getOpenMPClauseName(OMPC_severity);
  15739. return nullptr;
  15740. }
  15741. return new (Context)
  15742. OMPSeverityClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
  15743. }
  15744. OMPClause *Sema::ActOnOpenMPMessageClause(Expr *ME, SourceLocation StartLoc,
  15745. SourceLocation LParenLoc,
  15746. SourceLocation EndLoc) {
  15747. assert(ME && "NULL expr in Message clause");
  15748. if (!isa<StringLiteral>(ME)) {
  15749. Diag(ME->getBeginLoc(), diag::warn_clause_expected_string)
  15750. << getOpenMPClauseName(OMPC_message);
  15751. return nullptr;
  15752. }
  15753. return new (Context) OMPMessageClause(ME, StartLoc, LParenLoc, EndLoc);
  15754. }
  15755. OMPClause *Sema::ActOnOpenMPOrderClause(
  15756. OpenMPOrderClauseModifier Modifier, OpenMPOrderClauseKind Kind,
  15757. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  15758. SourceLocation KindLoc, SourceLocation EndLoc) {
  15759. if (Kind != OMPC_ORDER_concurrent ||
  15760. (LangOpts.OpenMP < 51 && MLoc.isValid())) {
  15761. // Kind should be concurrent,
  15762. // Modifiers introduced in OpenMP 5.1
  15763. static_assert(OMPC_ORDER_unknown > 0,
  15764. "OMPC_ORDER_unknown not greater than 0");
  15765. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  15766. << getListOfPossibleValues(OMPC_order,
  15767. /*First=*/0,
  15768. /*Last=*/OMPC_ORDER_unknown)
  15769. << getOpenMPClauseName(OMPC_order);
  15770. return nullptr;
  15771. }
  15772. if (LangOpts.OpenMP >= 51) {
  15773. if (Modifier == OMPC_ORDER_MODIFIER_unknown && MLoc.isValid()) {
  15774. Diag(MLoc, diag::err_omp_unexpected_clause_value)
  15775. << getListOfPossibleValues(OMPC_order,
  15776. /*First=*/OMPC_ORDER_MODIFIER_unknown + 1,
  15777. /*Last=*/OMPC_ORDER_MODIFIER_last)
  15778. << getOpenMPClauseName(OMPC_order);
  15779. } else {
  15780. DSAStack->setRegionHasOrderConcurrent(/*HasOrderConcurrent=*/true);
  15781. if (DSAStack->getCurScope()) {
  15782. // mark the current scope with 'order' flag
  15783. unsigned existingFlags = DSAStack->getCurScope()->getFlags();
  15784. DSAStack->getCurScope()->setFlags(existingFlags |
  15785. Scope::OpenMPOrderClauseScope);
  15786. }
  15787. }
  15788. }
  15789. return new (Context) OMPOrderClause(Kind, KindLoc, StartLoc, LParenLoc,
  15790. EndLoc, Modifier, MLoc);
  15791. }
  15792. OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
  15793. SourceLocation KindKwLoc,
  15794. SourceLocation StartLoc,
  15795. SourceLocation LParenLoc,
  15796. SourceLocation EndLoc) {
  15797. if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source ||
  15798. Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) {
  15799. SmallVector<unsigned> Except = {
  15800. OMPC_DEPEND_source, OMPC_DEPEND_sink, OMPC_DEPEND_depobj,
  15801. OMPC_DEPEND_outallmemory, OMPC_DEPEND_inoutallmemory};
  15802. if (LangOpts.OpenMP < 51)
  15803. Except.push_back(OMPC_DEPEND_inoutset);
  15804. Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
  15805. << getListOfPossibleValues(OMPC_depend, /*First=*/0,
  15806. /*Last=*/OMPC_DEPEND_unknown, Except)
  15807. << getOpenMPClauseName(OMPC_update);
  15808. return nullptr;
  15809. }
  15810. return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind,
  15811. EndLoc);
  15812. }
  15813. OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
  15814. SourceLocation StartLoc,
  15815. SourceLocation LParenLoc,
  15816. SourceLocation EndLoc) {
  15817. for (Expr *SizeExpr : SizeExprs) {
  15818. ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause(
  15819. SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true);
  15820. if (!NumForLoopsResult.isUsable())
  15821. return nullptr;
  15822. }
  15823. DSAStack->setAssociatedLoops(SizeExprs.size());
  15824. return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  15825. SizeExprs);
  15826. }
  15827. OMPClause *Sema::ActOnOpenMPFullClause(SourceLocation StartLoc,
  15828. SourceLocation EndLoc) {
  15829. return OMPFullClause::Create(Context, StartLoc, EndLoc);
  15830. }
  15831. OMPClause *Sema::ActOnOpenMPPartialClause(Expr *FactorExpr,
  15832. SourceLocation StartLoc,
  15833. SourceLocation LParenLoc,
  15834. SourceLocation EndLoc) {
  15835. if (FactorExpr) {
  15836. // If an argument is specified, it must be a constant (or an unevaluated
  15837. // template expression).
  15838. ExprResult FactorResult = VerifyPositiveIntegerConstantInClause(
  15839. FactorExpr, OMPC_partial, /*StrictlyPositive=*/true);
  15840. if (FactorResult.isInvalid())
  15841. return nullptr;
  15842. FactorExpr = FactorResult.get();
  15843. }
  15844. return OMPPartialClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  15845. FactorExpr);
  15846. }
  15847. OMPClause *Sema::ActOnOpenMPAlignClause(Expr *A, SourceLocation StartLoc,
  15848. SourceLocation LParenLoc,
  15849. SourceLocation EndLoc) {
  15850. ExprResult AlignVal;
  15851. AlignVal = VerifyPositiveIntegerConstantInClause(A, OMPC_align);
  15852. if (AlignVal.isInvalid())
  15853. return nullptr;
  15854. return OMPAlignClause::Create(Context, AlignVal.get(), StartLoc, LParenLoc,
  15855. EndLoc);
  15856. }
  15857. OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
  15858. OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
  15859. SourceLocation StartLoc, SourceLocation LParenLoc,
  15860. ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
  15861. SourceLocation EndLoc) {
  15862. OMPClause *Res = nullptr;
  15863. switch (Kind) {
  15864. case OMPC_schedule:
  15865. enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
  15866. assert(Argument.size() == NumberOfElements &&
  15867. ArgumentLoc.size() == NumberOfElements);
  15868. Res = ActOnOpenMPScheduleClause(
  15869. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
  15870. static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
  15871. static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
  15872. StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
  15873. ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
  15874. break;
  15875. case OMPC_if:
  15876. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  15877. Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
  15878. Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
  15879. DelimLoc, EndLoc);
  15880. break;
  15881. case OMPC_dist_schedule:
  15882. Res = ActOnOpenMPDistScheduleClause(
  15883. static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
  15884. StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
  15885. break;
  15886. case OMPC_defaultmap:
  15887. enum { Modifier, DefaultmapKind };
  15888. Res = ActOnOpenMPDefaultmapClause(
  15889. static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
  15890. static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
  15891. StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
  15892. EndLoc);
  15893. break;
  15894. case OMPC_order:
  15895. enum { OrderModifier, OrderKind };
  15896. Res = ActOnOpenMPOrderClause(
  15897. static_cast<OpenMPOrderClauseModifier>(Argument[OrderModifier]),
  15898. static_cast<OpenMPOrderClauseKind>(Argument[OrderKind]), StartLoc,
  15899. LParenLoc, ArgumentLoc[OrderModifier], ArgumentLoc[OrderKind], EndLoc);
  15900. break;
  15901. case OMPC_device:
  15902. assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
  15903. Res = ActOnOpenMPDeviceClause(
  15904. static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr,
  15905. StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
  15906. break;
  15907. case OMPC_grainsize:
  15908. assert(Argument.size() == 1 && ArgumentLoc.size() == 1 &&
  15909. "Modifier for grainsize clause and its location are expected.");
  15910. Res = ActOnOpenMPGrainsizeClause(
  15911. static_cast<OpenMPGrainsizeClauseModifier>(Argument.back()), Expr,
  15912. StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
  15913. break;
  15914. case OMPC_num_tasks:
  15915. assert(Argument.size() == 1 && ArgumentLoc.size() == 1 &&
  15916. "Modifier for num_tasks clause and its location are expected.");
  15917. Res = ActOnOpenMPNumTasksClause(
  15918. static_cast<OpenMPNumTasksClauseModifier>(Argument.back()), Expr,
  15919. StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc);
  15920. break;
  15921. case OMPC_final:
  15922. case OMPC_num_threads:
  15923. case OMPC_safelen:
  15924. case OMPC_simdlen:
  15925. case OMPC_sizes:
  15926. case OMPC_allocator:
  15927. case OMPC_collapse:
  15928. case OMPC_default:
  15929. case OMPC_proc_bind:
  15930. case OMPC_private:
  15931. case OMPC_firstprivate:
  15932. case OMPC_lastprivate:
  15933. case OMPC_shared:
  15934. case OMPC_reduction:
  15935. case OMPC_task_reduction:
  15936. case OMPC_in_reduction:
  15937. case OMPC_linear:
  15938. case OMPC_aligned:
  15939. case OMPC_copyin:
  15940. case OMPC_copyprivate:
  15941. case OMPC_ordered:
  15942. case OMPC_nowait:
  15943. case OMPC_untied:
  15944. case OMPC_mergeable:
  15945. case OMPC_threadprivate:
  15946. case OMPC_allocate:
  15947. case OMPC_flush:
  15948. case OMPC_depobj:
  15949. case OMPC_read:
  15950. case OMPC_write:
  15951. case OMPC_update:
  15952. case OMPC_capture:
  15953. case OMPC_compare:
  15954. case OMPC_seq_cst:
  15955. case OMPC_acq_rel:
  15956. case OMPC_acquire:
  15957. case OMPC_release:
  15958. case OMPC_relaxed:
  15959. case OMPC_depend:
  15960. case OMPC_threads:
  15961. case OMPC_simd:
  15962. case OMPC_map:
  15963. case OMPC_num_teams:
  15964. case OMPC_thread_limit:
  15965. case OMPC_priority:
  15966. case OMPC_nogroup:
  15967. case OMPC_hint:
  15968. case OMPC_unknown:
  15969. case OMPC_uniform:
  15970. case OMPC_to:
  15971. case OMPC_from:
  15972. case OMPC_use_device_ptr:
  15973. case OMPC_use_device_addr:
  15974. case OMPC_is_device_ptr:
  15975. case OMPC_has_device_addr:
  15976. case OMPC_unified_address:
  15977. case OMPC_unified_shared_memory:
  15978. case OMPC_reverse_offload:
  15979. case OMPC_dynamic_allocators:
  15980. case OMPC_atomic_default_mem_order:
  15981. case OMPC_device_type:
  15982. case OMPC_match:
  15983. case OMPC_nontemporal:
  15984. case OMPC_at:
  15985. case OMPC_severity:
  15986. case OMPC_message:
  15987. case OMPC_destroy:
  15988. case OMPC_novariants:
  15989. case OMPC_nocontext:
  15990. case OMPC_detach:
  15991. case OMPC_inclusive:
  15992. case OMPC_exclusive:
  15993. case OMPC_uses_allocators:
  15994. case OMPC_affinity:
  15995. case OMPC_when:
  15996. case OMPC_bind:
  15997. default:
  15998. llvm_unreachable("Clause is not allowed.");
  15999. }
  16000. return Res;
  16001. }
  16002. static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
  16003. OpenMPScheduleClauseModifier M2,
  16004. SourceLocation M1Loc, SourceLocation M2Loc) {
  16005. if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
  16006. SmallVector<unsigned, 2> Excluded;
  16007. if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
  16008. Excluded.push_back(M2);
  16009. if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
  16010. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
  16011. if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
  16012. Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
  16013. S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
  16014. << getListOfPossibleValues(OMPC_schedule,
  16015. /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
  16016. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  16017. Excluded)
  16018. << getOpenMPClauseName(OMPC_schedule);
  16019. return true;
  16020. }
  16021. return false;
  16022. }
  16023. OMPClause *Sema::ActOnOpenMPScheduleClause(
  16024. OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
  16025. OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  16026. SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
  16027. SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
  16028. if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
  16029. checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
  16030. return nullptr;
  16031. // OpenMP, 2.7.1, Loop Construct, Restrictions
  16032. // Either the monotonic modifier or the nonmonotonic modifier can be specified
  16033. // but not both.
  16034. if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
  16035. (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
  16036. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
  16037. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
  16038. M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
  16039. Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
  16040. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
  16041. << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
  16042. return nullptr;
  16043. }
  16044. if (Kind == OMPC_SCHEDULE_unknown) {
  16045. std::string Values;
  16046. if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
  16047. unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
  16048. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  16049. /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
  16050. Exclude);
  16051. } else {
  16052. Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
  16053. /*Last=*/OMPC_SCHEDULE_unknown);
  16054. }
  16055. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  16056. << Values << getOpenMPClauseName(OMPC_schedule);
  16057. return nullptr;
  16058. }
  16059. // OpenMP, 2.7.1, Loop Construct, Restrictions
  16060. // The nonmonotonic modifier can only be specified with schedule(dynamic) or
  16061. // schedule(guided).
  16062. // OpenMP 5.0 does not have this restriction.
  16063. if (LangOpts.OpenMP < 50 &&
  16064. (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
  16065. M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
  16066. Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
  16067. Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
  16068. diag::err_omp_schedule_nonmonotonic_static);
  16069. return nullptr;
  16070. }
  16071. Expr *ValExpr = ChunkSize;
  16072. Stmt *HelperValStmt = nullptr;
  16073. if (ChunkSize) {
  16074. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  16075. !ChunkSize->isInstantiationDependent() &&
  16076. !ChunkSize->containsUnexpandedParameterPack()) {
  16077. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  16078. ExprResult Val =
  16079. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  16080. if (Val.isInvalid())
  16081. return nullptr;
  16082. ValExpr = Val.get();
  16083. // OpenMP [2.7.1, Restrictions]
  16084. // chunk_size must be a loop invariant integer expression with a positive
  16085. // value.
  16086. if (std::optional<llvm::APSInt> Result =
  16087. ValExpr->getIntegerConstantExpr(Context)) {
  16088. if (Result->isSigned() && !Result->isStrictlyPositive()) {
  16089. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  16090. << "schedule" << 1 << ChunkSize->getSourceRange();
  16091. return nullptr;
  16092. }
  16093. } else if (getOpenMPCaptureRegionForClause(
  16094. DSAStack->getCurrentDirective(), OMPC_schedule,
  16095. LangOpts.OpenMP) != OMPD_unknown &&
  16096. !CurContext->isDependentContext()) {
  16097. ValExpr = MakeFullExpr(ValExpr).get();
  16098. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  16099. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  16100. HelperValStmt = buildPreInits(Context, Captures);
  16101. }
  16102. }
  16103. }
  16104. return new (Context)
  16105. OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
  16106. ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
  16107. }
  16108. OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
  16109. SourceLocation StartLoc,
  16110. SourceLocation EndLoc) {
  16111. OMPClause *Res = nullptr;
  16112. switch (Kind) {
  16113. case OMPC_ordered:
  16114. Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
  16115. break;
  16116. case OMPC_nowait:
  16117. Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
  16118. break;
  16119. case OMPC_untied:
  16120. Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
  16121. break;
  16122. case OMPC_mergeable:
  16123. Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
  16124. break;
  16125. case OMPC_read:
  16126. Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
  16127. break;
  16128. case OMPC_write:
  16129. Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
  16130. break;
  16131. case OMPC_update:
  16132. Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
  16133. break;
  16134. case OMPC_capture:
  16135. Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
  16136. break;
  16137. case OMPC_compare:
  16138. Res = ActOnOpenMPCompareClause(StartLoc, EndLoc);
  16139. break;
  16140. case OMPC_seq_cst:
  16141. Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
  16142. break;
  16143. case OMPC_acq_rel:
  16144. Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc);
  16145. break;
  16146. case OMPC_acquire:
  16147. Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc);
  16148. break;
  16149. case OMPC_release:
  16150. Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc);
  16151. break;
  16152. case OMPC_relaxed:
  16153. Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc);
  16154. break;
  16155. case OMPC_threads:
  16156. Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
  16157. break;
  16158. case OMPC_simd:
  16159. Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
  16160. break;
  16161. case OMPC_nogroup:
  16162. Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
  16163. break;
  16164. case OMPC_unified_address:
  16165. Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
  16166. break;
  16167. case OMPC_unified_shared_memory:
  16168. Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  16169. break;
  16170. case OMPC_reverse_offload:
  16171. Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
  16172. break;
  16173. case OMPC_dynamic_allocators:
  16174. Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
  16175. break;
  16176. case OMPC_destroy:
  16177. Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc,
  16178. /*LParenLoc=*/SourceLocation(),
  16179. /*VarLoc=*/SourceLocation(), EndLoc);
  16180. break;
  16181. case OMPC_full:
  16182. Res = ActOnOpenMPFullClause(StartLoc, EndLoc);
  16183. break;
  16184. case OMPC_partial:
  16185. Res = ActOnOpenMPPartialClause(nullptr, StartLoc, /*LParenLoc=*/{}, EndLoc);
  16186. break;
  16187. case OMPC_if:
  16188. case OMPC_final:
  16189. case OMPC_num_threads:
  16190. case OMPC_safelen:
  16191. case OMPC_simdlen:
  16192. case OMPC_sizes:
  16193. case OMPC_allocator:
  16194. case OMPC_collapse:
  16195. case OMPC_schedule:
  16196. case OMPC_private:
  16197. case OMPC_firstprivate:
  16198. case OMPC_lastprivate:
  16199. case OMPC_shared:
  16200. case OMPC_reduction:
  16201. case OMPC_task_reduction:
  16202. case OMPC_in_reduction:
  16203. case OMPC_linear:
  16204. case OMPC_aligned:
  16205. case OMPC_copyin:
  16206. case OMPC_copyprivate:
  16207. case OMPC_default:
  16208. case OMPC_proc_bind:
  16209. case OMPC_threadprivate:
  16210. case OMPC_allocate:
  16211. case OMPC_flush:
  16212. case OMPC_depobj:
  16213. case OMPC_depend:
  16214. case OMPC_device:
  16215. case OMPC_map:
  16216. case OMPC_num_teams:
  16217. case OMPC_thread_limit:
  16218. case OMPC_priority:
  16219. case OMPC_grainsize:
  16220. case OMPC_num_tasks:
  16221. case OMPC_hint:
  16222. case OMPC_dist_schedule:
  16223. case OMPC_defaultmap:
  16224. case OMPC_unknown:
  16225. case OMPC_uniform:
  16226. case OMPC_to:
  16227. case OMPC_from:
  16228. case OMPC_use_device_ptr:
  16229. case OMPC_use_device_addr:
  16230. case OMPC_is_device_ptr:
  16231. case OMPC_has_device_addr:
  16232. case OMPC_atomic_default_mem_order:
  16233. case OMPC_device_type:
  16234. case OMPC_match:
  16235. case OMPC_nontemporal:
  16236. case OMPC_order:
  16237. case OMPC_at:
  16238. case OMPC_severity:
  16239. case OMPC_message:
  16240. case OMPC_novariants:
  16241. case OMPC_nocontext:
  16242. case OMPC_detach:
  16243. case OMPC_inclusive:
  16244. case OMPC_exclusive:
  16245. case OMPC_uses_allocators:
  16246. case OMPC_affinity:
  16247. case OMPC_when:
  16248. case OMPC_ompx_dyn_cgroup_mem:
  16249. default:
  16250. llvm_unreachable("Clause is not allowed.");
  16251. }
  16252. return Res;
  16253. }
  16254. OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
  16255. SourceLocation EndLoc) {
  16256. DSAStack->setNowaitRegion();
  16257. return new (Context) OMPNowaitClause(StartLoc, EndLoc);
  16258. }
  16259. OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
  16260. SourceLocation EndLoc) {
  16261. DSAStack->setUntiedRegion();
  16262. return new (Context) OMPUntiedClause(StartLoc, EndLoc);
  16263. }
  16264. OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
  16265. SourceLocation EndLoc) {
  16266. return new (Context) OMPMergeableClause(StartLoc, EndLoc);
  16267. }
  16268. OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
  16269. SourceLocation EndLoc) {
  16270. return new (Context) OMPReadClause(StartLoc, EndLoc);
  16271. }
  16272. OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
  16273. SourceLocation EndLoc) {
  16274. return new (Context) OMPWriteClause(StartLoc, EndLoc);
  16275. }
  16276. OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
  16277. SourceLocation EndLoc) {
  16278. return OMPUpdateClause::Create(Context, StartLoc, EndLoc);
  16279. }
  16280. OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
  16281. SourceLocation EndLoc) {
  16282. return new (Context) OMPCaptureClause(StartLoc, EndLoc);
  16283. }
  16284. OMPClause *Sema::ActOnOpenMPCompareClause(SourceLocation StartLoc,
  16285. SourceLocation EndLoc) {
  16286. return new (Context) OMPCompareClause(StartLoc, EndLoc);
  16287. }
  16288. OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
  16289. SourceLocation EndLoc) {
  16290. return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
  16291. }
  16292. OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
  16293. SourceLocation EndLoc) {
  16294. return new (Context) OMPAcqRelClause(StartLoc, EndLoc);
  16295. }
  16296. OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc,
  16297. SourceLocation EndLoc) {
  16298. return new (Context) OMPAcquireClause(StartLoc, EndLoc);
  16299. }
  16300. OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc,
  16301. SourceLocation EndLoc) {
  16302. return new (Context) OMPReleaseClause(StartLoc, EndLoc);
  16303. }
  16304. OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
  16305. SourceLocation EndLoc) {
  16306. return new (Context) OMPRelaxedClause(StartLoc, EndLoc);
  16307. }
  16308. OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
  16309. SourceLocation EndLoc) {
  16310. return new (Context) OMPThreadsClause(StartLoc, EndLoc);
  16311. }
  16312. OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
  16313. SourceLocation EndLoc) {
  16314. return new (Context) OMPSIMDClause(StartLoc, EndLoc);
  16315. }
  16316. OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
  16317. SourceLocation EndLoc) {
  16318. return new (Context) OMPNogroupClause(StartLoc, EndLoc);
  16319. }
  16320. OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
  16321. SourceLocation EndLoc) {
  16322. return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
  16323. }
  16324. OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
  16325. SourceLocation EndLoc) {
  16326. return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
  16327. }
  16328. OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
  16329. SourceLocation EndLoc) {
  16330. return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
  16331. }
  16332. OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
  16333. SourceLocation EndLoc) {
  16334. return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
  16335. }
  16336. StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
  16337. SourceLocation StartLoc,
  16338. SourceLocation EndLoc) {
  16339. // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
  16340. // At least one action-clause must appear on a directive.
  16341. if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) {
  16342. StringRef Expected = "'init', 'use', 'destroy', or 'nowait'";
  16343. Diag(StartLoc, diag::err_omp_no_clause_for_directive)
  16344. << Expected << getOpenMPDirectiveName(OMPD_interop);
  16345. return StmtError();
  16346. }
  16347. // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
  16348. // A depend clause can only appear on the directive if a targetsync
  16349. // interop-type is present or the interop-var was initialized with
  16350. // the targetsync interop-type.
  16351. // If there is any 'init' clause diagnose if there is no 'init' clause with
  16352. // interop-type of 'targetsync'. Cases involving other directives cannot be
  16353. // diagnosed.
  16354. const OMPDependClause *DependClause = nullptr;
  16355. bool HasInitClause = false;
  16356. bool IsTargetSync = false;
  16357. for (const OMPClause *C : Clauses) {
  16358. if (IsTargetSync)
  16359. break;
  16360. if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) {
  16361. HasInitClause = true;
  16362. if (InitClause->getIsTargetSync())
  16363. IsTargetSync = true;
  16364. } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) {
  16365. DependClause = DC;
  16366. }
  16367. }
  16368. if (DependClause && HasInitClause && !IsTargetSync) {
  16369. Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause);
  16370. return StmtError();
  16371. }
  16372. // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
  16373. // Each interop-var may be specified for at most one action-clause of each
  16374. // interop construct.
  16375. llvm::SmallPtrSet<const ValueDecl *, 4> InteropVars;
  16376. for (OMPClause *C : Clauses) {
  16377. OpenMPClauseKind ClauseKind = C->getClauseKind();
  16378. std::pair<ValueDecl *, bool> DeclResult;
  16379. SourceLocation ELoc;
  16380. SourceRange ERange;
  16381. if (ClauseKind == OMPC_init) {
  16382. auto *E = cast<OMPInitClause>(C)->getInteropVar();
  16383. DeclResult = getPrivateItem(*this, E, ELoc, ERange);
  16384. } else if (ClauseKind == OMPC_use) {
  16385. auto *E = cast<OMPUseClause>(C)->getInteropVar();
  16386. DeclResult = getPrivateItem(*this, E, ELoc, ERange);
  16387. } else if (ClauseKind == OMPC_destroy) {
  16388. auto *E = cast<OMPDestroyClause>(C)->getInteropVar();
  16389. DeclResult = getPrivateItem(*this, E, ELoc, ERange);
  16390. }
  16391. if (DeclResult.first) {
  16392. if (!InteropVars.insert(DeclResult.first).second) {
  16393. Diag(ELoc, diag::err_omp_interop_var_multiple_actions)
  16394. << DeclResult.first;
  16395. return StmtError();
  16396. }
  16397. }
  16398. }
  16399. return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses);
  16400. }
  16401. static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr,
  16402. SourceLocation VarLoc,
  16403. OpenMPClauseKind Kind) {
  16404. SourceLocation ELoc;
  16405. SourceRange ERange;
  16406. Expr *RefExpr = InteropVarExpr;
  16407. auto Res =
  16408. getPrivateItem(SemaRef, RefExpr, ELoc, ERange,
  16409. /*AllowArraySection=*/false, /*DiagType=*/"omp_interop_t");
  16410. if (Res.second) {
  16411. // It will be analyzed later.
  16412. return true;
  16413. }
  16414. if (!Res.first)
  16415. return false;
  16416. // Interop variable should be of type omp_interop_t.
  16417. bool HasError = false;
  16418. QualType InteropType;
  16419. LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"),
  16420. VarLoc, Sema::LookupOrdinaryName);
  16421. if (SemaRef.LookupName(Result, SemaRef.getCurScope())) {
  16422. NamedDecl *ND = Result.getFoundDecl();
  16423. if (const auto *TD = dyn_cast<TypeDecl>(ND)) {
  16424. InteropType = QualType(TD->getTypeForDecl(), 0);
  16425. } else {
  16426. HasError = true;
  16427. }
  16428. } else {
  16429. HasError = true;
  16430. }
  16431. if (HasError) {
  16432. SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found)
  16433. << "omp_interop_t";
  16434. return false;
  16435. }
  16436. QualType VarType = InteropVarExpr->getType().getUnqualifiedType();
  16437. if (!SemaRef.Context.hasSameType(InteropType, VarType)) {
  16438. SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type);
  16439. return false;
  16440. }
  16441. // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
  16442. // The interop-var passed to init or destroy must be non-const.
  16443. if ((Kind == OMPC_init || Kind == OMPC_destroy) &&
  16444. isConstNotMutableType(SemaRef, InteropVarExpr->getType())) {
  16445. SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected)
  16446. << /*non-const*/ 1;
  16447. return false;
  16448. }
  16449. return true;
  16450. }
  16451. OMPClause *
  16452. Sema::ActOnOpenMPInitClause(Expr *InteropVar, OMPInteropInfo &InteropInfo,
  16453. SourceLocation StartLoc, SourceLocation LParenLoc,
  16454. SourceLocation VarLoc, SourceLocation EndLoc) {
  16455. if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init))
  16456. return nullptr;
  16457. // Check prefer_type values. These foreign-runtime-id values are either
  16458. // string literals or constant integral expressions.
  16459. for (const Expr *E : InteropInfo.PreferTypes) {
  16460. if (E->isValueDependent() || E->isTypeDependent() ||
  16461. E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
  16462. continue;
  16463. if (E->isIntegerConstantExpr(Context))
  16464. continue;
  16465. if (isa<StringLiteral>(E))
  16466. continue;
  16467. Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type);
  16468. return nullptr;
  16469. }
  16470. return OMPInitClause::Create(Context, InteropVar, InteropInfo, StartLoc,
  16471. LParenLoc, VarLoc, EndLoc);
  16472. }
  16473. OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
  16474. SourceLocation LParenLoc,
  16475. SourceLocation VarLoc,
  16476. SourceLocation EndLoc) {
  16477. if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use))
  16478. return nullptr;
  16479. return new (Context)
  16480. OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
  16481. }
  16482. OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar,
  16483. SourceLocation StartLoc,
  16484. SourceLocation LParenLoc,
  16485. SourceLocation VarLoc,
  16486. SourceLocation EndLoc) {
  16487. if (InteropVar &&
  16488. !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy))
  16489. return nullptr;
  16490. return new (Context)
  16491. OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc);
  16492. }
  16493. OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition,
  16494. SourceLocation StartLoc,
  16495. SourceLocation LParenLoc,
  16496. SourceLocation EndLoc) {
  16497. Expr *ValExpr = Condition;
  16498. Stmt *HelperValStmt = nullptr;
  16499. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  16500. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  16501. !Condition->isInstantiationDependent() &&
  16502. !Condition->containsUnexpandedParameterPack()) {
  16503. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  16504. if (Val.isInvalid())
  16505. return nullptr;
  16506. ValExpr = MakeFullExpr(Val.get()).get();
  16507. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  16508. CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants,
  16509. LangOpts.OpenMP);
  16510. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  16511. ValExpr = MakeFullExpr(ValExpr).get();
  16512. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  16513. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  16514. HelperValStmt = buildPreInits(Context, Captures);
  16515. }
  16516. }
  16517. return new (Context) OMPNovariantsClause(
  16518. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  16519. }
  16520. OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition,
  16521. SourceLocation StartLoc,
  16522. SourceLocation LParenLoc,
  16523. SourceLocation EndLoc) {
  16524. Expr *ValExpr = Condition;
  16525. Stmt *HelperValStmt = nullptr;
  16526. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  16527. if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
  16528. !Condition->isInstantiationDependent() &&
  16529. !Condition->containsUnexpandedParameterPack()) {
  16530. ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
  16531. if (Val.isInvalid())
  16532. return nullptr;
  16533. ValExpr = MakeFullExpr(Val.get()).get();
  16534. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  16535. CaptureRegion =
  16536. getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP);
  16537. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  16538. ValExpr = MakeFullExpr(ValExpr).get();
  16539. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  16540. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  16541. HelperValStmt = buildPreInits(Context, Captures);
  16542. }
  16543. }
  16544. return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion,
  16545. StartLoc, LParenLoc, EndLoc);
  16546. }
  16547. OMPClause *Sema::ActOnOpenMPFilterClause(Expr *ThreadID,
  16548. SourceLocation StartLoc,
  16549. SourceLocation LParenLoc,
  16550. SourceLocation EndLoc) {
  16551. Expr *ValExpr = ThreadID;
  16552. Stmt *HelperValStmt = nullptr;
  16553. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  16554. OpenMPDirectiveKind CaptureRegion =
  16555. getOpenMPCaptureRegionForClause(DKind, OMPC_filter, LangOpts.OpenMP);
  16556. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  16557. ValExpr = MakeFullExpr(ValExpr).get();
  16558. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  16559. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  16560. HelperValStmt = buildPreInits(Context, Captures);
  16561. }
  16562. return new (Context) OMPFilterClause(ValExpr, HelperValStmt, CaptureRegion,
  16563. StartLoc, LParenLoc, EndLoc);
  16564. }
  16565. OMPClause *Sema::ActOnOpenMPVarListClause(OpenMPClauseKind Kind,
  16566. ArrayRef<Expr *> VarList,
  16567. const OMPVarListLocTy &Locs,
  16568. OpenMPVarListDataTy &Data) {
  16569. SourceLocation StartLoc = Locs.StartLoc;
  16570. SourceLocation LParenLoc = Locs.LParenLoc;
  16571. SourceLocation EndLoc = Locs.EndLoc;
  16572. OMPClause *Res = nullptr;
  16573. int ExtraModifier = Data.ExtraModifier;
  16574. SourceLocation ExtraModifierLoc = Data.ExtraModifierLoc;
  16575. SourceLocation ColonLoc = Data.ColonLoc;
  16576. switch (Kind) {
  16577. case OMPC_private:
  16578. Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  16579. break;
  16580. case OMPC_firstprivate:
  16581. Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  16582. break;
  16583. case OMPC_lastprivate:
  16584. assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
  16585. "Unexpected lastprivate modifier.");
  16586. Res = ActOnOpenMPLastprivateClause(
  16587. VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
  16588. ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
  16589. break;
  16590. case OMPC_shared:
  16591. Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
  16592. break;
  16593. case OMPC_reduction:
  16594. assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown &&
  16595. "Unexpected lastprivate modifier.");
  16596. Res = ActOnOpenMPReductionClause(
  16597. VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier),
  16598. StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc,
  16599. Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId);
  16600. break;
  16601. case OMPC_task_reduction:
  16602. Res = ActOnOpenMPTaskReductionClause(
  16603. VarList, StartLoc, LParenLoc, ColonLoc, EndLoc,
  16604. Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId);
  16605. break;
  16606. case OMPC_in_reduction:
  16607. Res = ActOnOpenMPInReductionClause(
  16608. VarList, StartLoc, LParenLoc, ColonLoc, EndLoc,
  16609. Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId);
  16610. break;
  16611. case OMPC_linear:
  16612. assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
  16613. "Unexpected linear modifier.");
  16614. Res = ActOnOpenMPLinearClause(
  16615. VarList, Data.DepModOrTailExpr, StartLoc, LParenLoc,
  16616. static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc,
  16617. ColonLoc, EndLoc);
  16618. break;
  16619. case OMPC_aligned:
  16620. Res = ActOnOpenMPAlignedClause(VarList, Data.DepModOrTailExpr, StartLoc,
  16621. LParenLoc, ColonLoc, EndLoc);
  16622. break;
  16623. case OMPC_copyin:
  16624. Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
  16625. break;
  16626. case OMPC_copyprivate:
  16627. Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
  16628. break;
  16629. case OMPC_flush:
  16630. Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
  16631. break;
  16632. case OMPC_depend:
  16633. assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
  16634. "Unexpected depend modifier.");
  16635. Res = ActOnOpenMPDependClause(
  16636. {static_cast<OpenMPDependClauseKind>(ExtraModifier), ExtraModifierLoc,
  16637. ColonLoc, Data.OmpAllMemoryLoc},
  16638. Data.DepModOrTailExpr, VarList, StartLoc, LParenLoc, EndLoc);
  16639. break;
  16640. case OMPC_map:
  16641. assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
  16642. "Unexpected map modifier.");
  16643. Res = ActOnOpenMPMapClause(
  16644. Data.IteratorExpr, Data.MapTypeModifiers, Data.MapTypeModifiersLoc,
  16645. Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId,
  16646. static_cast<OpenMPMapClauseKind>(ExtraModifier), Data.IsMapTypeImplicit,
  16647. ExtraModifierLoc, ColonLoc, VarList, Locs);
  16648. break;
  16649. case OMPC_to:
  16650. Res =
  16651. ActOnOpenMPToClause(Data.MotionModifiers, Data.MotionModifiersLoc,
  16652. Data.ReductionOrMapperIdScopeSpec,
  16653. Data.ReductionOrMapperId, ColonLoc, VarList, Locs);
  16654. break;
  16655. case OMPC_from:
  16656. Res = ActOnOpenMPFromClause(Data.MotionModifiers, Data.MotionModifiersLoc,
  16657. Data.ReductionOrMapperIdScopeSpec,
  16658. Data.ReductionOrMapperId, ColonLoc, VarList,
  16659. Locs);
  16660. break;
  16661. case OMPC_use_device_ptr:
  16662. Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
  16663. break;
  16664. case OMPC_use_device_addr:
  16665. Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
  16666. break;
  16667. case OMPC_is_device_ptr:
  16668. Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
  16669. break;
  16670. case OMPC_has_device_addr:
  16671. Res = ActOnOpenMPHasDeviceAddrClause(VarList, Locs);
  16672. break;
  16673. case OMPC_allocate:
  16674. Res = ActOnOpenMPAllocateClause(Data.DepModOrTailExpr, VarList, StartLoc,
  16675. LParenLoc, ColonLoc, EndLoc);
  16676. break;
  16677. case OMPC_nontemporal:
  16678. Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
  16679. break;
  16680. case OMPC_inclusive:
  16681. Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
  16682. break;
  16683. case OMPC_exclusive:
  16684. Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc);
  16685. break;
  16686. case OMPC_affinity:
  16687. Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc,
  16688. Data.DepModOrTailExpr, VarList);
  16689. break;
  16690. case OMPC_if:
  16691. case OMPC_depobj:
  16692. case OMPC_final:
  16693. case OMPC_num_threads:
  16694. case OMPC_safelen:
  16695. case OMPC_simdlen:
  16696. case OMPC_sizes:
  16697. case OMPC_allocator:
  16698. case OMPC_collapse:
  16699. case OMPC_default:
  16700. case OMPC_proc_bind:
  16701. case OMPC_schedule:
  16702. case OMPC_ordered:
  16703. case OMPC_nowait:
  16704. case OMPC_untied:
  16705. case OMPC_mergeable:
  16706. case OMPC_threadprivate:
  16707. case OMPC_read:
  16708. case OMPC_write:
  16709. case OMPC_update:
  16710. case OMPC_capture:
  16711. case OMPC_compare:
  16712. case OMPC_seq_cst:
  16713. case OMPC_acq_rel:
  16714. case OMPC_acquire:
  16715. case OMPC_release:
  16716. case OMPC_relaxed:
  16717. case OMPC_device:
  16718. case OMPC_threads:
  16719. case OMPC_simd:
  16720. case OMPC_num_teams:
  16721. case OMPC_thread_limit:
  16722. case OMPC_priority:
  16723. case OMPC_grainsize:
  16724. case OMPC_nogroup:
  16725. case OMPC_num_tasks:
  16726. case OMPC_hint:
  16727. case OMPC_dist_schedule:
  16728. case OMPC_defaultmap:
  16729. case OMPC_unknown:
  16730. case OMPC_uniform:
  16731. case OMPC_unified_address:
  16732. case OMPC_unified_shared_memory:
  16733. case OMPC_reverse_offload:
  16734. case OMPC_dynamic_allocators:
  16735. case OMPC_atomic_default_mem_order:
  16736. case OMPC_device_type:
  16737. case OMPC_match:
  16738. case OMPC_order:
  16739. case OMPC_at:
  16740. case OMPC_severity:
  16741. case OMPC_message:
  16742. case OMPC_destroy:
  16743. case OMPC_novariants:
  16744. case OMPC_nocontext:
  16745. case OMPC_detach:
  16746. case OMPC_uses_allocators:
  16747. case OMPC_when:
  16748. case OMPC_bind:
  16749. default:
  16750. llvm_unreachable("Clause is not allowed.");
  16751. }
  16752. return Res;
  16753. }
  16754. ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
  16755. ExprObjectKind OK, SourceLocation Loc) {
  16756. ExprResult Res = BuildDeclRefExpr(
  16757. Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
  16758. if (!Res.isUsable())
  16759. return ExprError();
  16760. if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
  16761. Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
  16762. if (!Res.isUsable())
  16763. return ExprError();
  16764. }
  16765. if (VK != VK_LValue && Res.get()->isGLValue()) {
  16766. Res = DefaultLvalueConversion(Res.get());
  16767. if (!Res.isUsable())
  16768. return ExprError();
  16769. }
  16770. return Res;
  16771. }
  16772. OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
  16773. SourceLocation StartLoc,
  16774. SourceLocation LParenLoc,
  16775. SourceLocation EndLoc) {
  16776. SmallVector<Expr *, 8> Vars;
  16777. SmallVector<Expr *, 8> PrivateCopies;
  16778. bool IsImplicitClause =
  16779. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  16780. for (Expr *RefExpr : VarList) {
  16781. assert(RefExpr && "NULL expr in OpenMP private clause.");
  16782. SourceLocation ELoc;
  16783. SourceRange ERange;
  16784. Expr *SimpleRefExpr = RefExpr;
  16785. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  16786. if (Res.second) {
  16787. // It will be analyzed later.
  16788. Vars.push_back(RefExpr);
  16789. PrivateCopies.push_back(nullptr);
  16790. }
  16791. ValueDecl *D = Res.first;
  16792. if (!D)
  16793. continue;
  16794. QualType Type = D->getType();
  16795. auto *VD = dyn_cast<VarDecl>(D);
  16796. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  16797. // A variable that appears in a private clause must not have an incomplete
  16798. // type or a reference type.
  16799. if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
  16800. continue;
  16801. Type = Type.getNonReferenceType();
  16802. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  16803. // A variable that is privatized must not have a const-qualified type
  16804. // unless it is of class type with a mutable member. This restriction does
  16805. // not apply to the firstprivate clause.
  16806. //
  16807. // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
  16808. // A variable that appears in a private clause must not have a
  16809. // const-qualified type unless it is of class type with a mutable member.
  16810. if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
  16811. continue;
  16812. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  16813. // in a Construct]
  16814. // Variables with the predetermined data-sharing attributes may not be
  16815. // listed in data-sharing attributes clauses, except for the cases
  16816. // listed below. For these exceptions only, listing a predetermined
  16817. // variable in a data-sharing attribute clause is allowed and overrides
  16818. // the variable's predetermined data-sharing attributes.
  16819. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  16820. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
  16821. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  16822. << getOpenMPClauseName(OMPC_private);
  16823. reportOriginalDsa(*this, DSAStack, D, DVar);
  16824. continue;
  16825. }
  16826. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  16827. // Variably modified types are not supported for tasks.
  16828. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  16829. isOpenMPTaskingDirective(CurrDir)) {
  16830. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  16831. << getOpenMPClauseName(OMPC_private) << Type
  16832. << getOpenMPDirectiveName(CurrDir);
  16833. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  16834. VarDecl::DeclarationOnly;
  16835. Diag(D->getLocation(),
  16836. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  16837. << D;
  16838. continue;
  16839. }
  16840. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  16841. // A list item cannot appear in both a map clause and a data-sharing
  16842. // attribute clause on the same construct
  16843. //
  16844. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  16845. // A list item cannot appear in both a map clause and a data-sharing
  16846. // attribute clause on the same construct unless the construct is a
  16847. // combined construct.
  16848. if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
  16849. CurrDir == OMPD_target) {
  16850. OpenMPClauseKind ConflictKind;
  16851. if (DSAStack->checkMappableExprComponentListsForDecl(
  16852. VD, /*CurrentRegionOnly=*/true,
  16853. [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
  16854. OpenMPClauseKind WhereFoundClauseKind) -> bool {
  16855. ConflictKind = WhereFoundClauseKind;
  16856. return true;
  16857. })) {
  16858. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  16859. << getOpenMPClauseName(OMPC_private)
  16860. << getOpenMPClauseName(ConflictKind)
  16861. << getOpenMPDirectiveName(CurrDir);
  16862. reportOriginalDsa(*this, DSAStack, D, DVar);
  16863. continue;
  16864. }
  16865. }
  16866. // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
  16867. // A variable of class type (or array thereof) that appears in a private
  16868. // clause requires an accessible, unambiguous default constructor for the
  16869. // class type.
  16870. // Generate helper private variable and initialize it with the default
  16871. // value. The address of the original variable is replaced by the address of
  16872. // the new private variable in CodeGen. This new variable is not added to
  16873. // IdResolver, so the code in the OpenMP region uses original variable for
  16874. // proper diagnostics.
  16875. Type = Type.getUnqualifiedType();
  16876. VarDecl *VDPrivate =
  16877. buildVarDecl(*this, ELoc, Type, D->getName(),
  16878. D->hasAttrs() ? &D->getAttrs() : nullptr,
  16879. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  16880. ActOnUninitializedDecl(VDPrivate);
  16881. if (VDPrivate->isInvalidDecl())
  16882. continue;
  16883. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  16884. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  16885. DeclRefExpr *Ref = nullptr;
  16886. if (!VD && !CurContext->isDependentContext()) {
  16887. auto *FD = dyn_cast<FieldDecl>(D);
  16888. VarDecl *VD = FD ? DSAStack->getImplicitFDCapExprDecl(FD) : nullptr;
  16889. if (VD)
  16890. Ref = buildDeclRefExpr(*this, VD, VD->getType().getNonReferenceType(),
  16891. RefExpr->getExprLoc());
  16892. else
  16893. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  16894. }
  16895. if (!IsImplicitClause)
  16896. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
  16897. Vars.push_back((VD || CurContext->isDependentContext())
  16898. ? RefExpr->IgnoreParens()
  16899. : Ref);
  16900. PrivateCopies.push_back(VDPrivateRefExpr);
  16901. }
  16902. if (Vars.empty())
  16903. return nullptr;
  16904. return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  16905. PrivateCopies);
  16906. }
  16907. OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
  16908. SourceLocation StartLoc,
  16909. SourceLocation LParenLoc,
  16910. SourceLocation EndLoc) {
  16911. SmallVector<Expr *, 8> Vars;
  16912. SmallVector<Expr *, 8> PrivateCopies;
  16913. SmallVector<Expr *, 8> Inits;
  16914. SmallVector<Decl *, 4> ExprCaptures;
  16915. bool IsImplicitClause =
  16916. StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
  16917. SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
  16918. for (Expr *RefExpr : VarList) {
  16919. assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
  16920. SourceLocation ELoc;
  16921. SourceRange ERange;
  16922. Expr *SimpleRefExpr = RefExpr;
  16923. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  16924. if (Res.second) {
  16925. // It will be analyzed later.
  16926. Vars.push_back(RefExpr);
  16927. PrivateCopies.push_back(nullptr);
  16928. Inits.push_back(nullptr);
  16929. }
  16930. ValueDecl *D = Res.first;
  16931. if (!D)
  16932. continue;
  16933. ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
  16934. QualType Type = D->getType();
  16935. auto *VD = dyn_cast<VarDecl>(D);
  16936. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  16937. // A variable that appears in a private clause must not have an incomplete
  16938. // type or a reference type.
  16939. if (RequireCompleteType(ELoc, Type,
  16940. diag::err_omp_firstprivate_incomplete_type))
  16941. continue;
  16942. Type = Type.getNonReferenceType();
  16943. // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
  16944. // A variable of class type (or array thereof) that appears in a private
  16945. // clause requires an accessible, unambiguous copy constructor for the
  16946. // class type.
  16947. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  16948. // If an implicit firstprivate variable found it was checked already.
  16949. DSAStackTy::DSAVarData TopDVar;
  16950. if (!IsImplicitClause) {
  16951. DSAStackTy::DSAVarData DVar =
  16952. DSAStack->getTopDSA(D, /*FromParent=*/false);
  16953. TopDVar = DVar;
  16954. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  16955. bool IsConstant = ElemType.isConstant(Context);
  16956. // OpenMP [2.4.13, Data-sharing Attribute Clauses]
  16957. // A list item that specifies a given variable may not appear in more
  16958. // than one clause on the same directive, except that a variable may be
  16959. // specified in both firstprivate and lastprivate clauses.
  16960. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  16961. // A list item may appear in a firstprivate or lastprivate clause but not
  16962. // both.
  16963. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  16964. (isOpenMPDistributeDirective(CurrDir) ||
  16965. DVar.CKind != OMPC_lastprivate) &&
  16966. DVar.RefExpr) {
  16967. Diag(ELoc, diag::err_omp_wrong_dsa)
  16968. << getOpenMPClauseName(DVar.CKind)
  16969. << getOpenMPClauseName(OMPC_firstprivate);
  16970. reportOriginalDsa(*this, DSAStack, D, DVar);
  16971. continue;
  16972. }
  16973. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  16974. // in a Construct]
  16975. // Variables with the predetermined data-sharing attributes may not be
  16976. // listed in data-sharing attributes clauses, except for the cases
  16977. // listed below. For these exceptions only, listing a predetermined
  16978. // variable in a data-sharing attribute clause is allowed and overrides
  16979. // the variable's predetermined data-sharing attributes.
  16980. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  16981. // in a Construct, C/C++, p.2]
  16982. // Variables with const-qualified type having no mutable member may be
  16983. // listed in a firstprivate clause, even if they are static data members.
  16984. if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
  16985. DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
  16986. Diag(ELoc, diag::err_omp_wrong_dsa)
  16987. << getOpenMPClauseName(DVar.CKind)
  16988. << getOpenMPClauseName(OMPC_firstprivate);
  16989. reportOriginalDsa(*this, DSAStack, D, DVar);
  16990. continue;
  16991. }
  16992. // OpenMP [2.9.3.4, Restrictions, p.2]
  16993. // A list item that is private within a parallel region must not appear
  16994. // in a firstprivate clause on a worksharing construct if any of the
  16995. // worksharing regions arising from the worksharing construct ever bind
  16996. // to any of the parallel regions arising from the parallel construct.
  16997. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  16998. // A list item that is private within a teams region must not appear in a
  16999. // firstprivate clause on a distribute construct if any of the distribute
  17000. // regions arising from the distribute construct ever bind to any of the
  17001. // teams regions arising from the teams construct.
  17002. // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
  17003. // A list item that appears in a reduction clause of a teams construct
  17004. // must not appear in a firstprivate clause on a distribute construct if
  17005. // any of the distribute regions arising from the distribute construct
  17006. // ever bind to any of the teams regions arising from the teams construct.
  17007. if ((isOpenMPWorksharingDirective(CurrDir) ||
  17008. isOpenMPDistributeDirective(CurrDir)) &&
  17009. !isOpenMPParallelDirective(CurrDir) &&
  17010. !isOpenMPTeamsDirective(CurrDir)) {
  17011. DVar = DSAStack->getImplicitDSA(D, true);
  17012. if (DVar.CKind != OMPC_shared &&
  17013. (isOpenMPParallelDirective(DVar.DKind) ||
  17014. isOpenMPTeamsDirective(DVar.DKind) ||
  17015. DVar.DKind == OMPD_unknown)) {
  17016. Diag(ELoc, diag::err_omp_required_access)
  17017. << getOpenMPClauseName(OMPC_firstprivate)
  17018. << getOpenMPClauseName(OMPC_shared);
  17019. reportOriginalDsa(*this, DSAStack, D, DVar);
  17020. continue;
  17021. }
  17022. }
  17023. // OpenMP [2.9.3.4, Restrictions, p.3]
  17024. // A list item that appears in a reduction clause of a parallel construct
  17025. // must not appear in a firstprivate clause on a worksharing or task
  17026. // construct if any of the worksharing or task regions arising from the
  17027. // worksharing or task construct ever bind to any of the parallel regions
  17028. // arising from the parallel construct.
  17029. // OpenMP [2.9.3.4, Restrictions, p.4]
  17030. // A list item that appears in a reduction clause in worksharing
  17031. // construct must not appear in a firstprivate clause in a task construct
  17032. // encountered during execution of any of the worksharing regions arising
  17033. // from the worksharing construct.
  17034. if (isOpenMPTaskingDirective(CurrDir)) {
  17035. DVar = DSAStack->hasInnermostDSA(
  17036. D,
  17037. [](OpenMPClauseKind C, bool AppliedToPointee) {
  17038. return C == OMPC_reduction && !AppliedToPointee;
  17039. },
  17040. [](OpenMPDirectiveKind K) {
  17041. return isOpenMPParallelDirective(K) ||
  17042. isOpenMPWorksharingDirective(K) ||
  17043. isOpenMPTeamsDirective(K);
  17044. },
  17045. /*FromParent=*/true);
  17046. if (DVar.CKind == OMPC_reduction &&
  17047. (isOpenMPParallelDirective(DVar.DKind) ||
  17048. isOpenMPWorksharingDirective(DVar.DKind) ||
  17049. isOpenMPTeamsDirective(DVar.DKind))) {
  17050. Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
  17051. << getOpenMPDirectiveName(DVar.DKind);
  17052. reportOriginalDsa(*this, DSAStack, D, DVar);
  17053. continue;
  17054. }
  17055. }
  17056. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  17057. // A list item cannot appear in both a map clause and a data-sharing
  17058. // attribute clause on the same construct
  17059. //
  17060. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  17061. // A list item cannot appear in both a map clause and a data-sharing
  17062. // attribute clause on the same construct unless the construct is a
  17063. // combined construct.
  17064. if ((LangOpts.OpenMP <= 45 &&
  17065. isOpenMPTargetExecutionDirective(CurrDir)) ||
  17066. CurrDir == OMPD_target) {
  17067. OpenMPClauseKind ConflictKind;
  17068. if (DSAStack->checkMappableExprComponentListsForDecl(
  17069. VD, /*CurrentRegionOnly=*/true,
  17070. [&ConflictKind](
  17071. OMPClauseMappableExprCommon::MappableExprComponentListRef,
  17072. OpenMPClauseKind WhereFoundClauseKind) {
  17073. ConflictKind = WhereFoundClauseKind;
  17074. return true;
  17075. })) {
  17076. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  17077. << getOpenMPClauseName(OMPC_firstprivate)
  17078. << getOpenMPClauseName(ConflictKind)
  17079. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  17080. reportOriginalDsa(*this, DSAStack, D, DVar);
  17081. continue;
  17082. }
  17083. }
  17084. }
  17085. // Variably modified types are not supported for tasks.
  17086. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
  17087. isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
  17088. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  17089. << getOpenMPClauseName(OMPC_firstprivate) << Type
  17090. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  17091. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  17092. VarDecl::DeclarationOnly;
  17093. Diag(D->getLocation(),
  17094. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  17095. << D;
  17096. continue;
  17097. }
  17098. Type = Type.getUnqualifiedType();
  17099. VarDecl *VDPrivate =
  17100. buildVarDecl(*this, ELoc, Type, D->getName(),
  17101. D->hasAttrs() ? &D->getAttrs() : nullptr,
  17102. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  17103. // Generate helper private variable and initialize it with the value of the
  17104. // original variable. The address of the original variable is replaced by
  17105. // the address of the new private variable in the CodeGen. This new variable
  17106. // is not added to IdResolver, so the code in the OpenMP region uses
  17107. // original variable for proper diagnostics and variable capturing.
  17108. Expr *VDInitRefExpr = nullptr;
  17109. // For arrays generate initializer for single element and replace it by the
  17110. // original array element in CodeGen.
  17111. if (Type->isArrayType()) {
  17112. VarDecl *VDInit =
  17113. buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
  17114. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
  17115. Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
  17116. ElemType = ElemType.getUnqualifiedType();
  17117. VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
  17118. ".firstprivate.temp");
  17119. InitializedEntity Entity =
  17120. InitializedEntity::InitializeVariable(VDInitTemp);
  17121. InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
  17122. InitializationSequence InitSeq(*this, Entity, Kind, Init);
  17123. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
  17124. if (Result.isInvalid())
  17125. VDPrivate->setInvalidDecl();
  17126. else
  17127. VDPrivate->setInit(Result.getAs<Expr>());
  17128. // Remove temp variable declaration.
  17129. Context.Deallocate(VDInitTemp);
  17130. } else {
  17131. VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
  17132. ".firstprivate.temp");
  17133. VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
  17134. RefExpr->getExprLoc());
  17135. AddInitializerToDecl(VDPrivate,
  17136. DefaultLvalueConversion(VDInitRefExpr).get(),
  17137. /*DirectInit=*/false);
  17138. }
  17139. if (VDPrivate->isInvalidDecl()) {
  17140. if (IsImplicitClause) {
  17141. Diag(RefExpr->getExprLoc(),
  17142. diag::note_omp_task_predetermined_firstprivate_here);
  17143. }
  17144. continue;
  17145. }
  17146. CurContext->addDecl(VDPrivate);
  17147. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  17148. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
  17149. RefExpr->getExprLoc());
  17150. DeclRefExpr *Ref = nullptr;
  17151. if (!VD && !CurContext->isDependentContext()) {
  17152. if (TopDVar.CKind == OMPC_lastprivate) {
  17153. Ref = TopDVar.PrivateCopy;
  17154. } else {
  17155. auto *FD = dyn_cast<FieldDecl>(D);
  17156. VarDecl *VD = FD ? DSAStack->getImplicitFDCapExprDecl(FD) : nullptr;
  17157. if (VD)
  17158. Ref = buildDeclRefExpr(*this, VD, VD->getType().getNonReferenceType(),
  17159. RefExpr->getExprLoc());
  17160. else
  17161. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  17162. if (VD || !isOpenMPCapturedDecl(D))
  17163. ExprCaptures.push_back(Ref->getDecl());
  17164. }
  17165. }
  17166. if (!IsImplicitClause)
  17167. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  17168. Vars.push_back((VD || CurContext->isDependentContext())
  17169. ? RefExpr->IgnoreParens()
  17170. : Ref);
  17171. PrivateCopies.push_back(VDPrivateRefExpr);
  17172. Inits.push_back(VDInitRefExpr);
  17173. }
  17174. if (Vars.empty())
  17175. return nullptr;
  17176. return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  17177. Vars, PrivateCopies, Inits,
  17178. buildPreInits(Context, ExprCaptures));
  17179. }
  17180. OMPClause *Sema::ActOnOpenMPLastprivateClause(
  17181. ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
  17182. SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
  17183. SourceLocation LParenLoc, SourceLocation EndLoc) {
  17184. if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
  17185. assert(ColonLoc.isValid() && "Colon location must be valid.");
  17186. Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
  17187. << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
  17188. /*Last=*/OMPC_LASTPRIVATE_unknown)
  17189. << getOpenMPClauseName(OMPC_lastprivate);
  17190. return nullptr;
  17191. }
  17192. SmallVector<Expr *, 8> Vars;
  17193. SmallVector<Expr *, 8> SrcExprs;
  17194. SmallVector<Expr *, 8> DstExprs;
  17195. SmallVector<Expr *, 8> AssignmentOps;
  17196. SmallVector<Decl *, 4> ExprCaptures;
  17197. SmallVector<Expr *, 4> ExprPostUpdates;
  17198. for (Expr *RefExpr : VarList) {
  17199. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  17200. SourceLocation ELoc;
  17201. SourceRange ERange;
  17202. Expr *SimpleRefExpr = RefExpr;
  17203. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  17204. if (Res.second) {
  17205. // It will be analyzed later.
  17206. Vars.push_back(RefExpr);
  17207. SrcExprs.push_back(nullptr);
  17208. DstExprs.push_back(nullptr);
  17209. AssignmentOps.push_back(nullptr);
  17210. }
  17211. ValueDecl *D = Res.first;
  17212. if (!D)
  17213. continue;
  17214. QualType Type = D->getType();
  17215. auto *VD = dyn_cast<VarDecl>(D);
  17216. // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
  17217. // A variable that appears in a lastprivate clause must not have an
  17218. // incomplete type or a reference type.
  17219. if (RequireCompleteType(ELoc, Type,
  17220. diag::err_omp_lastprivate_incomplete_type))
  17221. continue;
  17222. Type = Type.getNonReferenceType();
  17223. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  17224. // A variable that is privatized must not have a const-qualified type
  17225. // unless it is of class type with a mutable member. This restriction does
  17226. // not apply to the firstprivate clause.
  17227. //
  17228. // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
  17229. // A variable that appears in a lastprivate clause must not have a
  17230. // const-qualified type unless it is of class type with a mutable member.
  17231. if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
  17232. continue;
  17233. // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
  17234. // A list item that appears in a lastprivate clause with the conditional
  17235. // modifier must be a scalar variable.
  17236. if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
  17237. Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
  17238. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  17239. VarDecl::DeclarationOnly;
  17240. Diag(D->getLocation(),
  17241. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  17242. << D;
  17243. continue;
  17244. }
  17245. OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
  17246. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  17247. // in a Construct]
  17248. // Variables with the predetermined data-sharing attributes may not be
  17249. // listed in data-sharing attributes clauses, except for the cases
  17250. // listed below.
  17251. // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
  17252. // A list item may appear in a firstprivate or lastprivate clause but not
  17253. // both.
  17254. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  17255. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
  17256. (isOpenMPDistributeDirective(CurrDir) ||
  17257. DVar.CKind != OMPC_firstprivate) &&
  17258. (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
  17259. Diag(ELoc, diag::err_omp_wrong_dsa)
  17260. << getOpenMPClauseName(DVar.CKind)
  17261. << getOpenMPClauseName(OMPC_lastprivate);
  17262. reportOriginalDsa(*this, DSAStack, D, DVar);
  17263. continue;
  17264. }
  17265. // OpenMP [2.14.3.5, Restrictions, p.2]
  17266. // A list item that is private within a parallel region, or that appears in
  17267. // the reduction clause of a parallel construct, must not appear in a
  17268. // lastprivate clause on a worksharing construct if any of the corresponding
  17269. // worksharing regions ever binds to any of the corresponding parallel
  17270. // regions.
  17271. DSAStackTy::DSAVarData TopDVar = DVar;
  17272. if (isOpenMPWorksharingDirective(CurrDir) &&
  17273. !isOpenMPParallelDirective(CurrDir) &&
  17274. !isOpenMPTeamsDirective(CurrDir)) {
  17275. DVar = DSAStack->getImplicitDSA(D, true);
  17276. if (DVar.CKind != OMPC_shared) {
  17277. Diag(ELoc, diag::err_omp_required_access)
  17278. << getOpenMPClauseName(OMPC_lastprivate)
  17279. << getOpenMPClauseName(OMPC_shared);
  17280. reportOriginalDsa(*this, DSAStack, D, DVar);
  17281. continue;
  17282. }
  17283. }
  17284. // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
  17285. // A variable of class type (or array thereof) that appears in a
  17286. // lastprivate clause requires an accessible, unambiguous default
  17287. // constructor for the class type, unless the list item is also specified
  17288. // in a firstprivate clause.
  17289. // A variable of class type (or array thereof) that appears in a
  17290. // lastprivate clause requires an accessible, unambiguous copy assignment
  17291. // operator for the class type.
  17292. Type = Context.getBaseElementType(Type).getNonReferenceType();
  17293. VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
  17294. Type.getUnqualifiedType(), ".lastprivate.src",
  17295. D->hasAttrs() ? &D->getAttrs() : nullptr);
  17296. DeclRefExpr *PseudoSrcExpr =
  17297. buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
  17298. VarDecl *DstVD =
  17299. buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
  17300. D->hasAttrs() ? &D->getAttrs() : nullptr);
  17301. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  17302. // For arrays generate assignment operation for single element and replace
  17303. // it by the original array element in CodeGen.
  17304. ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
  17305. PseudoDstExpr, PseudoSrcExpr);
  17306. if (AssignmentOp.isInvalid())
  17307. continue;
  17308. AssignmentOp =
  17309. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  17310. if (AssignmentOp.isInvalid())
  17311. continue;
  17312. DeclRefExpr *Ref = nullptr;
  17313. if (!VD && !CurContext->isDependentContext()) {
  17314. if (TopDVar.CKind == OMPC_firstprivate) {
  17315. Ref = TopDVar.PrivateCopy;
  17316. } else {
  17317. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  17318. if (!isOpenMPCapturedDecl(D))
  17319. ExprCaptures.push_back(Ref->getDecl());
  17320. }
  17321. if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) ||
  17322. (!isOpenMPCapturedDecl(D) &&
  17323. Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
  17324. ExprResult RefRes = DefaultLvalueConversion(Ref);
  17325. if (!RefRes.isUsable())
  17326. continue;
  17327. ExprResult PostUpdateRes =
  17328. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  17329. RefRes.get());
  17330. if (!PostUpdateRes.isUsable())
  17331. continue;
  17332. ExprPostUpdates.push_back(
  17333. IgnoredValueConversions(PostUpdateRes.get()).get());
  17334. }
  17335. }
  17336. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
  17337. Vars.push_back((VD || CurContext->isDependentContext())
  17338. ? RefExpr->IgnoreParens()
  17339. : Ref);
  17340. SrcExprs.push_back(PseudoSrcExpr);
  17341. DstExprs.push_back(PseudoDstExpr);
  17342. AssignmentOps.push_back(AssignmentOp.get());
  17343. }
  17344. if (Vars.empty())
  17345. return nullptr;
  17346. return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  17347. Vars, SrcExprs, DstExprs, AssignmentOps,
  17348. LPKind, LPKindLoc, ColonLoc,
  17349. buildPreInits(Context, ExprCaptures),
  17350. buildPostUpdate(*this, ExprPostUpdates));
  17351. }
  17352. OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
  17353. SourceLocation StartLoc,
  17354. SourceLocation LParenLoc,
  17355. SourceLocation EndLoc) {
  17356. SmallVector<Expr *, 8> Vars;
  17357. for (Expr *RefExpr : VarList) {
  17358. assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
  17359. SourceLocation ELoc;
  17360. SourceRange ERange;
  17361. Expr *SimpleRefExpr = RefExpr;
  17362. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  17363. if (Res.second) {
  17364. // It will be analyzed later.
  17365. Vars.push_back(RefExpr);
  17366. }
  17367. ValueDecl *D = Res.first;
  17368. if (!D)
  17369. continue;
  17370. auto *VD = dyn_cast<VarDecl>(D);
  17371. // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
  17372. // in a Construct]
  17373. // Variables with the predetermined data-sharing attributes may not be
  17374. // listed in data-sharing attributes clauses, except for the cases
  17375. // listed below. For these exceptions only, listing a predetermined
  17376. // variable in a data-sharing attribute clause is allowed and overrides
  17377. // the variable's predetermined data-sharing attributes.
  17378. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  17379. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
  17380. DVar.RefExpr) {
  17381. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  17382. << getOpenMPClauseName(OMPC_shared);
  17383. reportOriginalDsa(*this, DSAStack, D, DVar);
  17384. continue;
  17385. }
  17386. DeclRefExpr *Ref = nullptr;
  17387. if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
  17388. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  17389. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
  17390. Vars.push_back((VD || !Ref || CurContext->isDependentContext())
  17391. ? RefExpr->IgnoreParens()
  17392. : Ref);
  17393. }
  17394. if (Vars.empty())
  17395. return nullptr;
  17396. return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  17397. }
  17398. namespace {
  17399. class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
  17400. DSAStackTy *Stack;
  17401. public:
  17402. bool VisitDeclRefExpr(DeclRefExpr *E) {
  17403. if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
  17404. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
  17405. if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
  17406. return false;
  17407. if (DVar.CKind != OMPC_unknown)
  17408. return true;
  17409. DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
  17410. VD,
  17411. [](OpenMPClauseKind C, bool AppliedToPointee, bool) {
  17412. return isOpenMPPrivate(C) && !AppliedToPointee;
  17413. },
  17414. [](OpenMPDirectiveKind) { return true; },
  17415. /*FromParent=*/true);
  17416. return DVarPrivate.CKind != OMPC_unknown;
  17417. }
  17418. return false;
  17419. }
  17420. bool VisitStmt(Stmt *S) {
  17421. for (Stmt *Child : S->children()) {
  17422. if (Child && Visit(Child))
  17423. return true;
  17424. }
  17425. return false;
  17426. }
  17427. explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
  17428. };
  17429. } // namespace
  17430. namespace {
  17431. // Transform MemberExpression for specified FieldDecl of current class to
  17432. // DeclRefExpr to specified OMPCapturedExprDecl.
  17433. class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
  17434. typedef TreeTransform<TransformExprToCaptures> BaseTransform;
  17435. ValueDecl *Field = nullptr;
  17436. DeclRefExpr *CapturedExpr = nullptr;
  17437. public:
  17438. TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
  17439. : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
  17440. ExprResult TransformMemberExpr(MemberExpr *E) {
  17441. if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
  17442. E->getMemberDecl() == Field) {
  17443. CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
  17444. return CapturedExpr;
  17445. }
  17446. return BaseTransform::TransformMemberExpr(E);
  17447. }
  17448. DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
  17449. };
  17450. } // namespace
  17451. template <typename T, typename U>
  17452. static T filterLookupForUDReductionAndMapper(
  17453. SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
  17454. for (U &Set : Lookups) {
  17455. for (auto *D : Set) {
  17456. if (T Res = Gen(cast<ValueDecl>(D)))
  17457. return Res;
  17458. }
  17459. }
  17460. return T();
  17461. }
  17462. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
  17463. assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
  17464. for (auto *RD : D->redecls()) {
  17465. // Don't bother with extra checks if we already know this one isn't visible.
  17466. if (RD == D)
  17467. continue;
  17468. auto ND = cast<NamedDecl>(RD);
  17469. if (LookupResult::isVisible(SemaRef, ND))
  17470. return ND;
  17471. }
  17472. return nullptr;
  17473. }
  17474. static void
  17475. argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
  17476. SourceLocation Loc, QualType Ty,
  17477. SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
  17478. // Find all of the associated namespaces and classes based on the
  17479. // arguments we have.
  17480. Sema::AssociatedNamespaceSet AssociatedNamespaces;
  17481. Sema::AssociatedClassSet AssociatedClasses;
  17482. OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
  17483. SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
  17484. AssociatedClasses);
  17485. // C++ [basic.lookup.argdep]p3:
  17486. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  17487. // and let Y be the lookup set produced by argument dependent
  17488. // lookup (defined as follows). If X contains [...] then Y is
  17489. // empty. Otherwise Y is the set of declarations found in the
  17490. // namespaces associated with the argument types as described
  17491. // below. The set of declarations found by the lookup of the name
  17492. // is the union of X and Y.
  17493. //
  17494. // Here, we compute Y and add its members to the overloaded
  17495. // candidate set.
  17496. for (auto *NS : AssociatedNamespaces) {
  17497. // When considering an associated namespace, the lookup is the
  17498. // same as the lookup performed when the associated namespace is
  17499. // used as a qualifier (3.4.3.2) except that:
  17500. //
  17501. // -- Any using-directives in the associated namespace are
  17502. // ignored.
  17503. //
  17504. // -- Any namespace-scope friend functions declared in
  17505. // associated classes are visible within their respective
  17506. // namespaces even if they are not visible during an ordinary
  17507. // lookup (11.4).
  17508. DeclContext::lookup_result R = NS->lookup(Id.getName());
  17509. for (auto *D : R) {
  17510. auto *Underlying = D;
  17511. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  17512. Underlying = USD->getTargetDecl();
  17513. if (!isa<OMPDeclareReductionDecl>(Underlying) &&
  17514. !isa<OMPDeclareMapperDecl>(Underlying))
  17515. continue;
  17516. if (!SemaRef.isVisible(D)) {
  17517. D = findAcceptableDecl(SemaRef, D);
  17518. if (!D)
  17519. continue;
  17520. if (auto *USD = dyn_cast<UsingShadowDecl>(D))
  17521. Underlying = USD->getTargetDecl();
  17522. }
  17523. Lookups.emplace_back();
  17524. Lookups.back().addDecl(Underlying);
  17525. }
  17526. }
  17527. }
  17528. static ExprResult
  17529. buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
  17530. Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
  17531. const DeclarationNameInfo &ReductionId, QualType Ty,
  17532. CXXCastPath &BasePath, Expr *UnresolvedReduction) {
  17533. if (ReductionIdScopeSpec.isInvalid())
  17534. return ExprError();
  17535. SmallVector<UnresolvedSet<8>, 4> Lookups;
  17536. if (S) {
  17537. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  17538. Lookup.suppressDiagnostics();
  17539. while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
  17540. NamedDecl *D = Lookup.getRepresentativeDecl();
  17541. do {
  17542. S = S->getParent();
  17543. } while (S && !S->isDeclScope(D));
  17544. if (S)
  17545. S = S->getParent();
  17546. Lookups.emplace_back();
  17547. Lookups.back().append(Lookup.begin(), Lookup.end());
  17548. Lookup.clear();
  17549. }
  17550. } else if (auto *ULE =
  17551. cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
  17552. Lookups.push_back(UnresolvedSet<8>());
  17553. Decl *PrevD = nullptr;
  17554. for (NamedDecl *D : ULE->decls()) {
  17555. if (D == PrevD)
  17556. Lookups.push_back(UnresolvedSet<8>());
  17557. else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
  17558. Lookups.back().addDecl(DRD);
  17559. PrevD = D;
  17560. }
  17561. }
  17562. if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
  17563. Ty->isInstantiationDependentType() ||
  17564. Ty->containsUnexpandedParameterPack() ||
  17565. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  17566. return !D->isInvalidDecl() &&
  17567. (D->getType()->isDependentType() ||
  17568. D->getType()->isInstantiationDependentType() ||
  17569. D->getType()->containsUnexpandedParameterPack());
  17570. })) {
  17571. UnresolvedSet<8> ResSet;
  17572. for (const UnresolvedSet<8> &Set : Lookups) {
  17573. if (Set.empty())
  17574. continue;
  17575. ResSet.append(Set.begin(), Set.end());
  17576. // The last item marks the end of all declarations at the specified scope.
  17577. ResSet.addDecl(Set[Set.size() - 1]);
  17578. }
  17579. return UnresolvedLookupExpr::Create(
  17580. SemaRef.Context, /*NamingClass=*/nullptr,
  17581. ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
  17582. /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
  17583. }
  17584. // Lookup inside the classes.
  17585. // C++ [over.match.oper]p3:
  17586. // For a unary operator @ with an operand of a type whose
  17587. // cv-unqualified version is T1, and for a binary operator @ with
  17588. // a left operand of a type whose cv-unqualified version is T1 and
  17589. // a right operand of a type whose cv-unqualified version is T2,
  17590. // three sets of candidate functions, designated member
  17591. // candidates, non-member candidates and built-in candidates, are
  17592. // constructed as follows:
  17593. // -- If T1 is a complete class type or a class currently being
  17594. // defined, the set of member candidates is the result of the
  17595. // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
  17596. // the set of member candidates is empty.
  17597. LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
  17598. Lookup.suppressDiagnostics();
  17599. if (const auto *TyRec = Ty->getAs<RecordType>()) {
  17600. // Complete the type if it can be completed.
  17601. // If the type is neither complete nor being defined, bail out now.
  17602. if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
  17603. TyRec->getDecl()->getDefinition()) {
  17604. Lookup.clear();
  17605. SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
  17606. if (Lookup.empty()) {
  17607. Lookups.emplace_back();
  17608. Lookups.back().append(Lookup.begin(), Lookup.end());
  17609. }
  17610. }
  17611. }
  17612. // Perform ADL.
  17613. if (SemaRef.getLangOpts().CPlusPlus)
  17614. argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
  17615. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  17616. Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
  17617. if (!D->isInvalidDecl() &&
  17618. SemaRef.Context.hasSameType(D->getType(), Ty))
  17619. return D;
  17620. return nullptr;
  17621. }))
  17622. return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
  17623. VK_LValue, Loc);
  17624. if (SemaRef.getLangOpts().CPlusPlus) {
  17625. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  17626. Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
  17627. if (!D->isInvalidDecl() &&
  17628. SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
  17629. !Ty.isMoreQualifiedThan(D->getType()))
  17630. return D;
  17631. return nullptr;
  17632. })) {
  17633. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  17634. /*DetectVirtual=*/false);
  17635. if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
  17636. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  17637. VD->getType().getUnqualifiedType()))) {
  17638. if (SemaRef.CheckBaseClassAccess(
  17639. Loc, VD->getType(), Ty, Paths.front(),
  17640. /*DiagID=*/0) != Sema::AR_inaccessible) {
  17641. SemaRef.BuildBasePathArray(Paths, BasePath);
  17642. return SemaRef.BuildDeclRefExpr(
  17643. VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
  17644. }
  17645. }
  17646. }
  17647. }
  17648. }
  17649. if (ReductionIdScopeSpec.isSet()) {
  17650. SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
  17651. << Ty << Range;
  17652. return ExprError();
  17653. }
  17654. return ExprEmpty();
  17655. }
  17656. namespace {
  17657. /// Data for the reduction-based clauses.
  17658. struct ReductionData {
  17659. /// List of original reduction items.
  17660. SmallVector<Expr *, 8> Vars;
  17661. /// List of private copies of the reduction items.
  17662. SmallVector<Expr *, 8> Privates;
  17663. /// LHS expressions for the reduction_op expressions.
  17664. SmallVector<Expr *, 8> LHSs;
  17665. /// RHS expressions for the reduction_op expressions.
  17666. SmallVector<Expr *, 8> RHSs;
  17667. /// Reduction operation expression.
  17668. SmallVector<Expr *, 8> ReductionOps;
  17669. /// inscan copy operation expressions.
  17670. SmallVector<Expr *, 8> InscanCopyOps;
  17671. /// inscan copy temp array expressions for prefix sums.
  17672. SmallVector<Expr *, 8> InscanCopyArrayTemps;
  17673. /// inscan copy temp array element expressions for prefix sums.
  17674. SmallVector<Expr *, 8> InscanCopyArrayElems;
  17675. /// Taskgroup descriptors for the corresponding reduction items in
  17676. /// in_reduction clauses.
  17677. SmallVector<Expr *, 8> TaskgroupDescriptors;
  17678. /// List of captures for clause.
  17679. SmallVector<Decl *, 4> ExprCaptures;
  17680. /// List of postupdate expressions.
  17681. SmallVector<Expr *, 4> ExprPostUpdates;
  17682. /// Reduction modifier.
  17683. unsigned RedModifier = 0;
  17684. ReductionData() = delete;
  17685. /// Reserves required memory for the reduction data.
  17686. ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) {
  17687. Vars.reserve(Size);
  17688. Privates.reserve(Size);
  17689. LHSs.reserve(Size);
  17690. RHSs.reserve(Size);
  17691. ReductionOps.reserve(Size);
  17692. if (RedModifier == OMPC_REDUCTION_inscan) {
  17693. InscanCopyOps.reserve(Size);
  17694. InscanCopyArrayTemps.reserve(Size);
  17695. InscanCopyArrayElems.reserve(Size);
  17696. }
  17697. TaskgroupDescriptors.reserve(Size);
  17698. ExprCaptures.reserve(Size);
  17699. ExprPostUpdates.reserve(Size);
  17700. }
  17701. /// Stores reduction item and reduction operation only (required for dependent
  17702. /// reduction item).
  17703. void push(Expr *Item, Expr *ReductionOp) {
  17704. Vars.emplace_back(Item);
  17705. Privates.emplace_back(nullptr);
  17706. LHSs.emplace_back(nullptr);
  17707. RHSs.emplace_back(nullptr);
  17708. ReductionOps.emplace_back(ReductionOp);
  17709. TaskgroupDescriptors.emplace_back(nullptr);
  17710. if (RedModifier == OMPC_REDUCTION_inscan) {
  17711. InscanCopyOps.push_back(nullptr);
  17712. InscanCopyArrayTemps.push_back(nullptr);
  17713. InscanCopyArrayElems.push_back(nullptr);
  17714. }
  17715. }
  17716. /// Stores reduction data.
  17717. void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
  17718. Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp,
  17719. Expr *CopyArrayElem) {
  17720. Vars.emplace_back(Item);
  17721. Privates.emplace_back(Private);
  17722. LHSs.emplace_back(LHS);
  17723. RHSs.emplace_back(RHS);
  17724. ReductionOps.emplace_back(ReductionOp);
  17725. TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
  17726. if (RedModifier == OMPC_REDUCTION_inscan) {
  17727. InscanCopyOps.push_back(CopyOp);
  17728. InscanCopyArrayTemps.push_back(CopyArrayTemp);
  17729. InscanCopyArrayElems.push_back(CopyArrayElem);
  17730. } else {
  17731. assert(CopyOp == nullptr && CopyArrayTemp == nullptr &&
  17732. CopyArrayElem == nullptr &&
  17733. "Copy operation must be used for inscan reductions only.");
  17734. }
  17735. }
  17736. };
  17737. } // namespace
  17738. static bool checkOMPArraySectionConstantForReduction(
  17739. ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
  17740. SmallVectorImpl<llvm::APSInt> &ArraySizes) {
  17741. const Expr *Length = OASE->getLength();
  17742. if (Length == nullptr) {
  17743. // For array sections of the form [1:] or [:], we would need to analyze
  17744. // the lower bound...
  17745. if (OASE->getColonLocFirst().isValid())
  17746. return false;
  17747. // This is an array subscript which has implicit length 1!
  17748. SingleElement = true;
  17749. ArraySizes.push_back(llvm::APSInt::get(1));
  17750. } else {
  17751. Expr::EvalResult Result;
  17752. if (!Length->EvaluateAsInt(Result, Context))
  17753. return false;
  17754. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  17755. SingleElement = (ConstantLengthValue.getSExtValue() == 1);
  17756. ArraySizes.push_back(ConstantLengthValue);
  17757. }
  17758. // Get the base of this array section and walk up from there.
  17759. const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
  17760. // We require length = 1 for all array sections except the right-most to
  17761. // guarantee that the memory region is contiguous and has no holes in it.
  17762. while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
  17763. Length = TempOASE->getLength();
  17764. if (Length == nullptr) {
  17765. // For array sections of the form [1:] or [:], we would need to analyze
  17766. // the lower bound...
  17767. if (OASE->getColonLocFirst().isValid())
  17768. return false;
  17769. // This is an array subscript which has implicit length 1!
  17770. ArraySizes.push_back(llvm::APSInt::get(1));
  17771. } else {
  17772. Expr::EvalResult Result;
  17773. if (!Length->EvaluateAsInt(Result, Context))
  17774. return false;
  17775. llvm::APSInt ConstantLengthValue = Result.Val.getInt();
  17776. if (ConstantLengthValue.getSExtValue() != 1)
  17777. return false;
  17778. ArraySizes.push_back(ConstantLengthValue);
  17779. }
  17780. Base = TempOASE->getBase()->IgnoreParenImpCasts();
  17781. }
  17782. // If we have a single element, we don't need to add the implicit lengths.
  17783. if (!SingleElement) {
  17784. while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
  17785. // Has implicit length 1!
  17786. ArraySizes.push_back(llvm::APSInt::get(1));
  17787. Base = TempASE->getBase()->IgnoreParenImpCasts();
  17788. }
  17789. }
  17790. // This array section can be privatized as a single value or as a constant
  17791. // sized array.
  17792. return true;
  17793. }
  17794. static BinaryOperatorKind
  17795. getRelatedCompoundReductionOp(BinaryOperatorKind BOK) {
  17796. if (BOK == BO_Add)
  17797. return BO_AddAssign;
  17798. if (BOK == BO_Mul)
  17799. return BO_MulAssign;
  17800. if (BOK == BO_And)
  17801. return BO_AndAssign;
  17802. if (BOK == BO_Or)
  17803. return BO_OrAssign;
  17804. if (BOK == BO_Xor)
  17805. return BO_XorAssign;
  17806. return BOK;
  17807. }
  17808. static bool actOnOMPReductionKindClause(
  17809. Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
  17810. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  17811. SourceLocation ColonLoc, SourceLocation EndLoc,
  17812. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  17813. ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
  17814. DeclarationName DN = ReductionId.getName();
  17815. OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
  17816. BinaryOperatorKind BOK = BO_Comma;
  17817. ASTContext &Context = S.Context;
  17818. // OpenMP [2.14.3.6, reduction clause]
  17819. // C
  17820. // reduction-identifier is either an identifier or one of the following
  17821. // operators: +, -, *, &, |, ^, && and ||
  17822. // C++
  17823. // reduction-identifier is either an id-expression or one of the following
  17824. // operators: +, -, *, &, |, ^, && and ||
  17825. switch (OOK) {
  17826. case OO_Plus:
  17827. case OO_Minus:
  17828. BOK = BO_Add;
  17829. break;
  17830. case OO_Star:
  17831. BOK = BO_Mul;
  17832. break;
  17833. case OO_Amp:
  17834. BOK = BO_And;
  17835. break;
  17836. case OO_Pipe:
  17837. BOK = BO_Or;
  17838. break;
  17839. case OO_Caret:
  17840. BOK = BO_Xor;
  17841. break;
  17842. case OO_AmpAmp:
  17843. BOK = BO_LAnd;
  17844. break;
  17845. case OO_PipePipe:
  17846. BOK = BO_LOr;
  17847. break;
  17848. case OO_New:
  17849. case OO_Delete:
  17850. case OO_Array_New:
  17851. case OO_Array_Delete:
  17852. case OO_Slash:
  17853. case OO_Percent:
  17854. case OO_Tilde:
  17855. case OO_Exclaim:
  17856. case OO_Equal:
  17857. case OO_Less:
  17858. case OO_Greater:
  17859. case OO_LessEqual:
  17860. case OO_GreaterEqual:
  17861. case OO_PlusEqual:
  17862. case OO_MinusEqual:
  17863. case OO_StarEqual:
  17864. case OO_SlashEqual:
  17865. case OO_PercentEqual:
  17866. case OO_CaretEqual:
  17867. case OO_AmpEqual:
  17868. case OO_PipeEqual:
  17869. case OO_LessLess:
  17870. case OO_GreaterGreater:
  17871. case OO_LessLessEqual:
  17872. case OO_GreaterGreaterEqual:
  17873. case OO_EqualEqual:
  17874. case OO_ExclaimEqual:
  17875. case OO_Spaceship:
  17876. case OO_PlusPlus:
  17877. case OO_MinusMinus:
  17878. case OO_Comma:
  17879. case OO_ArrowStar:
  17880. case OO_Arrow:
  17881. case OO_Call:
  17882. case OO_Subscript:
  17883. case OO_Conditional:
  17884. case OO_Coawait:
  17885. case NUM_OVERLOADED_OPERATORS:
  17886. llvm_unreachable("Unexpected reduction identifier");
  17887. case OO_None:
  17888. if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
  17889. if (II->isStr("max"))
  17890. BOK = BO_GT;
  17891. else if (II->isStr("min"))
  17892. BOK = BO_LT;
  17893. }
  17894. break;
  17895. }
  17896. SourceRange ReductionIdRange;
  17897. if (ReductionIdScopeSpec.isValid())
  17898. ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
  17899. else
  17900. ReductionIdRange.setBegin(ReductionId.getBeginLoc());
  17901. ReductionIdRange.setEnd(ReductionId.getEndLoc());
  17902. auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
  17903. bool FirstIter = true;
  17904. for (Expr *RefExpr : VarList) {
  17905. assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
  17906. // OpenMP [2.1, C/C++]
  17907. // A list item is a variable or array section, subject to the restrictions
  17908. // specified in Section 2.4 on page 42 and in each of the sections
  17909. // describing clauses and directives for which a list appears.
  17910. // OpenMP [2.14.3.3, Restrictions, p.1]
  17911. // A variable that is part of another variable (as an array or
  17912. // structure element) cannot appear in a private clause.
  17913. if (!FirstIter && IR != ER)
  17914. ++IR;
  17915. FirstIter = false;
  17916. SourceLocation ELoc;
  17917. SourceRange ERange;
  17918. Expr *SimpleRefExpr = RefExpr;
  17919. auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
  17920. /*AllowArraySection=*/true);
  17921. if (Res.second) {
  17922. // Try to find 'declare reduction' corresponding construct before using
  17923. // builtin/overloaded operators.
  17924. QualType Type = Context.DependentTy;
  17925. CXXCastPath BasePath;
  17926. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  17927. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  17928. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  17929. Expr *ReductionOp = nullptr;
  17930. if (S.CurContext->isDependentContext() &&
  17931. (DeclareReductionRef.isUnset() ||
  17932. isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
  17933. ReductionOp = DeclareReductionRef.get();
  17934. // It will be analyzed later.
  17935. RD.push(RefExpr, ReductionOp);
  17936. }
  17937. ValueDecl *D = Res.first;
  17938. if (!D)
  17939. continue;
  17940. Expr *TaskgroupDescriptor = nullptr;
  17941. QualType Type;
  17942. auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
  17943. auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
  17944. if (ASE) {
  17945. Type = ASE->getType().getNonReferenceType();
  17946. } else if (OASE) {
  17947. QualType BaseType =
  17948. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  17949. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  17950. Type = ATy->getElementType();
  17951. else
  17952. Type = BaseType->getPointeeType();
  17953. Type = Type.getNonReferenceType();
  17954. } else {
  17955. Type = Context.getBaseElementType(D->getType().getNonReferenceType());
  17956. }
  17957. auto *VD = dyn_cast<VarDecl>(D);
  17958. // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
  17959. // A variable that appears in a private clause must not have an incomplete
  17960. // type or a reference type.
  17961. if (S.RequireCompleteType(ELoc, D->getType(),
  17962. diag::err_omp_reduction_incomplete_type))
  17963. continue;
  17964. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  17965. // A list item that appears in a reduction clause must not be
  17966. // const-qualified.
  17967. if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
  17968. /*AcceptIfMutable*/ false, ASE || OASE))
  17969. continue;
  17970. OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
  17971. // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
  17972. // If a list-item is a reference type then it must bind to the same object
  17973. // for all threads of the team.
  17974. if (!ASE && !OASE) {
  17975. if (VD) {
  17976. VarDecl *VDDef = VD->getDefinition();
  17977. if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
  17978. DSARefChecker Check(Stack);
  17979. if (Check.Visit(VDDef->getInit())) {
  17980. S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
  17981. << getOpenMPClauseName(ClauseKind) << ERange;
  17982. S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
  17983. continue;
  17984. }
  17985. }
  17986. }
  17987. // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
  17988. // in a Construct]
  17989. // Variables with the predetermined data-sharing attributes may not be
  17990. // listed in data-sharing attributes clauses, except for the cases
  17991. // listed below. For these exceptions only, listing a predetermined
  17992. // variable in a data-sharing attribute clause is allowed and overrides
  17993. // the variable's predetermined data-sharing attributes.
  17994. // OpenMP [2.14.3.6, Restrictions, p.3]
  17995. // Any number of reduction clauses can be specified on the directive,
  17996. // but a list item can appear only once in the reduction clauses for that
  17997. // directive.
  17998. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
  17999. if (DVar.CKind == OMPC_reduction) {
  18000. S.Diag(ELoc, diag::err_omp_once_referenced)
  18001. << getOpenMPClauseName(ClauseKind);
  18002. if (DVar.RefExpr)
  18003. S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
  18004. continue;
  18005. }
  18006. if (DVar.CKind != OMPC_unknown) {
  18007. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  18008. << getOpenMPClauseName(DVar.CKind)
  18009. << getOpenMPClauseName(OMPC_reduction);
  18010. reportOriginalDsa(S, Stack, D, DVar);
  18011. continue;
  18012. }
  18013. // OpenMP [2.14.3.6, Restrictions, p.1]
  18014. // A list item that appears in a reduction clause of a worksharing
  18015. // construct must be shared in the parallel regions to which any of the
  18016. // worksharing regions arising from the worksharing construct bind.
  18017. if (isOpenMPWorksharingDirective(CurrDir) &&
  18018. !isOpenMPParallelDirective(CurrDir) &&
  18019. !isOpenMPTeamsDirective(CurrDir)) {
  18020. DVar = Stack->getImplicitDSA(D, true);
  18021. if (DVar.CKind != OMPC_shared) {
  18022. S.Diag(ELoc, diag::err_omp_required_access)
  18023. << getOpenMPClauseName(OMPC_reduction)
  18024. << getOpenMPClauseName(OMPC_shared);
  18025. reportOriginalDsa(S, Stack, D, DVar);
  18026. continue;
  18027. }
  18028. }
  18029. } else {
  18030. // Threadprivates cannot be shared between threads, so dignose if the base
  18031. // is a threadprivate variable.
  18032. DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
  18033. if (DVar.CKind == OMPC_threadprivate) {
  18034. S.Diag(ELoc, diag::err_omp_wrong_dsa)
  18035. << getOpenMPClauseName(DVar.CKind)
  18036. << getOpenMPClauseName(OMPC_reduction);
  18037. reportOriginalDsa(S, Stack, D, DVar);
  18038. continue;
  18039. }
  18040. }
  18041. // Try to find 'declare reduction' corresponding construct before using
  18042. // builtin/overloaded operators.
  18043. CXXCastPath BasePath;
  18044. ExprResult DeclareReductionRef = buildDeclareReductionRef(
  18045. S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
  18046. ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
  18047. if (DeclareReductionRef.isInvalid())
  18048. continue;
  18049. if (S.CurContext->isDependentContext() &&
  18050. (DeclareReductionRef.isUnset() ||
  18051. isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
  18052. RD.push(RefExpr, DeclareReductionRef.get());
  18053. continue;
  18054. }
  18055. if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
  18056. // Not allowed reduction identifier is found.
  18057. S.Diag(ReductionId.getBeginLoc(),
  18058. diag::err_omp_unknown_reduction_identifier)
  18059. << Type << ReductionIdRange;
  18060. continue;
  18061. }
  18062. // OpenMP [2.14.3.6, reduction clause, Restrictions]
  18063. // The type of a list item that appears in a reduction clause must be valid
  18064. // for the reduction-identifier. For a max or min reduction in C, the type
  18065. // of the list item must be an allowed arithmetic data type: char, int,
  18066. // float, double, or _Bool, possibly modified with long, short, signed, or
  18067. // unsigned. For a max or min reduction in C++, the type of the list item
  18068. // must be an allowed arithmetic data type: char, wchar_t, int, float,
  18069. // double, or bool, possibly modified with long, short, signed, or unsigned.
  18070. if (DeclareReductionRef.isUnset()) {
  18071. if ((BOK == BO_GT || BOK == BO_LT) &&
  18072. !(Type->isScalarType() ||
  18073. (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
  18074. S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
  18075. << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
  18076. if (!ASE && !OASE) {
  18077. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  18078. VarDecl::DeclarationOnly;
  18079. S.Diag(D->getLocation(),
  18080. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  18081. << D;
  18082. }
  18083. continue;
  18084. }
  18085. if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
  18086. !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
  18087. S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
  18088. << getOpenMPClauseName(ClauseKind);
  18089. if (!ASE && !OASE) {
  18090. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  18091. VarDecl::DeclarationOnly;
  18092. S.Diag(D->getLocation(),
  18093. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  18094. << D;
  18095. }
  18096. continue;
  18097. }
  18098. }
  18099. Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
  18100. VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
  18101. D->hasAttrs() ? &D->getAttrs() : nullptr);
  18102. VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
  18103. D->hasAttrs() ? &D->getAttrs() : nullptr);
  18104. QualType PrivateTy = Type;
  18105. // Try if we can determine constant lengths for all array sections and avoid
  18106. // the VLA.
  18107. bool ConstantLengthOASE = false;
  18108. if (OASE) {
  18109. bool SingleElement;
  18110. llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
  18111. ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
  18112. Context, OASE, SingleElement, ArraySizes);
  18113. // If we don't have a single element, we must emit a constant array type.
  18114. if (ConstantLengthOASE && !SingleElement) {
  18115. for (llvm::APSInt &Size : ArraySizes)
  18116. PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
  18117. ArrayType::Normal,
  18118. /*IndexTypeQuals=*/0);
  18119. }
  18120. }
  18121. if ((OASE && !ConstantLengthOASE) ||
  18122. (!OASE && !ASE &&
  18123. D->getType().getNonReferenceType()->isVariablyModifiedType())) {
  18124. if (!Context.getTargetInfo().isVLASupported()) {
  18125. if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
  18126. S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  18127. S.Diag(ELoc, diag::note_vla_unsupported);
  18128. continue;
  18129. } else {
  18130. S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
  18131. S.targetDiag(ELoc, diag::note_vla_unsupported);
  18132. }
  18133. }
  18134. // For arrays/array sections only:
  18135. // Create pseudo array type for private copy. The size for this array will
  18136. // be generated during codegen.
  18137. // For array subscripts or single variables Private Ty is the same as Type
  18138. // (type of the variable or single array element).
  18139. PrivateTy = Context.getVariableArrayType(
  18140. Type,
  18141. new (Context)
  18142. OpaqueValueExpr(ELoc, Context.getSizeType(), VK_PRValue),
  18143. ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
  18144. } else if (!ASE && !OASE &&
  18145. Context.getAsArrayType(D->getType().getNonReferenceType())) {
  18146. PrivateTy = D->getType().getNonReferenceType();
  18147. }
  18148. // Private copy.
  18149. VarDecl *PrivateVD =
  18150. buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  18151. D->hasAttrs() ? &D->getAttrs() : nullptr,
  18152. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  18153. // Add initializer for private variable.
  18154. Expr *Init = nullptr;
  18155. DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
  18156. DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
  18157. if (DeclareReductionRef.isUsable()) {
  18158. auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
  18159. auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
  18160. if (DRD->getInitializer()) {
  18161. Init = DRDRef;
  18162. RHSVD->setInit(DRDRef);
  18163. RHSVD->setInitStyle(VarDecl::CallInit);
  18164. }
  18165. } else {
  18166. switch (BOK) {
  18167. case BO_Add:
  18168. case BO_Xor:
  18169. case BO_Or:
  18170. case BO_LOr:
  18171. // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
  18172. if (Type->isScalarType() || Type->isAnyComplexType())
  18173. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
  18174. break;
  18175. case BO_Mul:
  18176. case BO_LAnd:
  18177. if (Type->isScalarType() || Type->isAnyComplexType()) {
  18178. // '*' and '&&' reduction ops - initializer is '1'.
  18179. Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
  18180. }
  18181. break;
  18182. case BO_And: {
  18183. // '&' reduction op - initializer is '~0'.
  18184. QualType OrigType = Type;
  18185. if (auto *ComplexTy = OrigType->getAs<ComplexType>())
  18186. Type = ComplexTy->getElementType();
  18187. if (Type->isRealFloatingType()) {
  18188. llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue(
  18189. Context.getFloatTypeSemantics(Type));
  18190. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  18191. Type, ELoc);
  18192. } else if (Type->isScalarType()) {
  18193. uint64_t Size = Context.getTypeSize(Type);
  18194. QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
  18195. llvm::APInt InitValue = llvm::APInt::getAllOnes(Size);
  18196. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  18197. }
  18198. if (Init && OrigType->isAnyComplexType()) {
  18199. // Init = 0xFFFF + 0xFFFFi;
  18200. auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
  18201. Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
  18202. }
  18203. Type = OrigType;
  18204. break;
  18205. }
  18206. case BO_LT:
  18207. case BO_GT: {
  18208. // 'min' reduction op - initializer is 'Largest representable number in
  18209. // the reduction list item type'.
  18210. // 'max' reduction op - initializer is 'Least representable number in
  18211. // the reduction list item type'.
  18212. if (Type->isIntegerType() || Type->isPointerType()) {
  18213. bool IsSigned = Type->hasSignedIntegerRepresentation();
  18214. uint64_t Size = Context.getTypeSize(Type);
  18215. QualType IntTy =
  18216. Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
  18217. llvm::APInt InitValue =
  18218. (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
  18219. : llvm::APInt::getMinValue(Size)
  18220. : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
  18221. : llvm::APInt::getMaxValue(Size);
  18222. Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
  18223. if (Type->isPointerType()) {
  18224. // Cast to pointer type.
  18225. ExprResult CastExpr = S.BuildCStyleCastExpr(
  18226. ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
  18227. if (CastExpr.isInvalid())
  18228. continue;
  18229. Init = CastExpr.get();
  18230. }
  18231. } else if (Type->isRealFloatingType()) {
  18232. llvm::APFloat InitValue = llvm::APFloat::getLargest(
  18233. Context.getFloatTypeSemantics(Type), BOK != BO_LT);
  18234. Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
  18235. Type, ELoc);
  18236. }
  18237. break;
  18238. }
  18239. case BO_PtrMemD:
  18240. case BO_PtrMemI:
  18241. case BO_MulAssign:
  18242. case BO_Div:
  18243. case BO_Rem:
  18244. case BO_Sub:
  18245. case BO_Shl:
  18246. case BO_Shr:
  18247. case BO_LE:
  18248. case BO_GE:
  18249. case BO_EQ:
  18250. case BO_NE:
  18251. case BO_Cmp:
  18252. case BO_AndAssign:
  18253. case BO_XorAssign:
  18254. case BO_OrAssign:
  18255. case BO_Assign:
  18256. case BO_AddAssign:
  18257. case BO_SubAssign:
  18258. case BO_DivAssign:
  18259. case BO_RemAssign:
  18260. case BO_ShlAssign:
  18261. case BO_ShrAssign:
  18262. case BO_Comma:
  18263. llvm_unreachable("Unexpected reduction operation");
  18264. }
  18265. }
  18266. if (Init && DeclareReductionRef.isUnset()) {
  18267. S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
  18268. // Store initializer for single element in private copy. Will be used
  18269. // during codegen.
  18270. PrivateVD->setInit(RHSVD->getInit());
  18271. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  18272. } else if (!Init) {
  18273. S.ActOnUninitializedDecl(RHSVD);
  18274. // Store initializer for single element in private copy. Will be used
  18275. // during codegen.
  18276. PrivateVD->setInit(RHSVD->getInit());
  18277. PrivateVD->setInitStyle(RHSVD->getInitStyle());
  18278. }
  18279. if (RHSVD->isInvalidDecl())
  18280. continue;
  18281. if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
  18282. S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
  18283. << Type << ReductionIdRange;
  18284. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  18285. VarDecl::DeclarationOnly;
  18286. S.Diag(D->getLocation(),
  18287. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  18288. << D;
  18289. continue;
  18290. }
  18291. DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
  18292. ExprResult ReductionOp;
  18293. if (DeclareReductionRef.isUsable()) {
  18294. QualType RedTy = DeclareReductionRef.get()->getType();
  18295. QualType PtrRedTy = Context.getPointerType(RedTy);
  18296. ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
  18297. ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
  18298. if (!BasePath.empty()) {
  18299. LHS = S.DefaultLvalueConversion(LHS.get());
  18300. RHS = S.DefaultLvalueConversion(RHS.get());
  18301. LHS = ImplicitCastExpr::Create(
  18302. Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath,
  18303. LHS.get()->getValueKind(), FPOptionsOverride());
  18304. RHS = ImplicitCastExpr::Create(
  18305. Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath,
  18306. RHS.get()->getValueKind(), FPOptionsOverride());
  18307. }
  18308. FunctionProtoType::ExtProtoInfo EPI;
  18309. QualType Params[] = {PtrRedTy, PtrRedTy};
  18310. QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
  18311. auto *OVE = new (Context) OpaqueValueExpr(
  18312. ELoc, Context.getPointerType(FnTy), VK_PRValue, OK_Ordinary,
  18313. S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
  18314. Expr *Args[] = {LHS.get(), RHS.get()};
  18315. ReductionOp =
  18316. CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_PRValue, ELoc,
  18317. S.CurFPFeatureOverrides());
  18318. } else {
  18319. BinaryOperatorKind CombBOK = getRelatedCompoundReductionOp(BOK);
  18320. if (Type->isRecordType() && CombBOK != BOK) {
  18321. Sema::TentativeAnalysisScope Trap(S);
  18322. ReductionOp =
  18323. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  18324. CombBOK, LHSDRE, RHSDRE);
  18325. }
  18326. if (!ReductionOp.isUsable()) {
  18327. ReductionOp =
  18328. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK,
  18329. LHSDRE, RHSDRE);
  18330. if (ReductionOp.isUsable()) {
  18331. if (BOK != BO_LT && BOK != BO_GT) {
  18332. ReductionOp =
  18333. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  18334. BO_Assign, LHSDRE, ReductionOp.get());
  18335. } else {
  18336. auto *ConditionalOp = new (Context)
  18337. ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc,
  18338. RHSDRE, Type, VK_LValue, OK_Ordinary);
  18339. ReductionOp =
  18340. S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
  18341. BO_Assign, LHSDRE, ConditionalOp);
  18342. }
  18343. }
  18344. }
  18345. if (ReductionOp.isUsable())
  18346. ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
  18347. /*DiscardedValue*/ false);
  18348. if (!ReductionOp.isUsable())
  18349. continue;
  18350. }
  18351. // Add copy operations for inscan reductions.
  18352. // LHS = RHS;
  18353. ExprResult CopyOpRes, TempArrayRes, TempArrayElem;
  18354. if (ClauseKind == OMPC_reduction &&
  18355. RD.RedModifier == OMPC_REDUCTION_inscan) {
  18356. ExprResult RHS = S.DefaultLvalueConversion(RHSDRE);
  18357. CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE,
  18358. RHS.get());
  18359. if (!CopyOpRes.isUsable())
  18360. continue;
  18361. CopyOpRes =
  18362. S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true);
  18363. if (!CopyOpRes.isUsable())
  18364. continue;
  18365. // For simd directive and simd-based directives in simd mode no need to
  18366. // construct temp array, need just a single temp element.
  18367. if (Stack->getCurrentDirective() == OMPD_simd ||
  18368. (S.getLangOpts().OpenMPSimd &&
  18369. isOpenMPSimdDirective(Stack->getCurrentDirective()))) {
  18370. VarDecl *TempArrayVD =
  18371. buildVarDecl(S, ELoc, PrivateTy, D->getName(),
  18372. D->hasAttrs() ? &D->getAttrs() : nullptr);
  18373. // Add a constructor to the temp decl.
  18374. S.ActOnUninitializedDecl(TempArrayVD);
  18375. TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc);
  18376. } else {
  18377. // Build temp array for prefix sum.
  18378. auto *Dim = new (S.Context)
  18379. OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
  18380. QualType ArrayTy =
  18381. S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal,
  18382. /*IndexTypeQuals=*/0, {ELoc, ELoc});
  18383. VarDecl *TempArrayVD =
  18384. buildVarDecl(S, ELoc, ArrayTy, D->getName(),
  18385. D->hasAttrs() ? &D->getAttrs() : nullptr);
  18386. // Add a constructor to the temp decl.
  18387. S.ActOnUninitializedDecl(TempArrayVD);
  18388. TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc);
  18389. TempArrayElem =
  18390. S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get());
  18391. auto *Idx = new (S.Context)
  18392. OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue);
  18393. TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(),
  18394. ELoc, Idx, ELoc);
  18395. }
  18396. }
  18397. // OpenMP [2.15.4.6, Restrictions, p.2]
  18398. // A list item that appears in an in_reduction clause of a task construct
  18399. // must appear in a task_reduction clause of a construct associated with a
  18400. // taskgroup region that includes the participating task in its taskgroup
  18401. // set. The construct associated with the innermost region that meets this
  18402. // condition must specify the same reduction-identifier as the in_reduction
  18403. // clause.
  18404. if (ClauseKind == OMPC_in_reduction) {
  18405. SourceRange ParentSR;
  18406. BinaryOperatorKind ParentBOK;
  18407. const Expr *ParentReductionOp = nullptr;
  18408. Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr;
  18409. DSAStackTy::DSAVarData ParentBOKDSA =
  18410. Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
  18411. ParentBOKTD);
  18412. DSAStackTy::DSAVarData ParentReductionOpDSA =
  18413. Stack->getTopMostTaskgroupReductionData(
  18414. D, ParentSR, ParentReductionOp, ParentReductionOpTD);
  18415. bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
  18416. bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
  18417. if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
  18418. (DeclareReductionRef.isUsable() && IsParentBOK) ||
  18419. (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) {
  18420. bool EmitError = true;
  18421. if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
  18422. llvm::FoldingSetNodeID RedId, ParentRedId;
  18423. ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
  18424. DeclareReductionRef.get()->Profile(RedId, Context,
  18425. /*Canonical=*/true);
  18426. EmitError = RedId != ParentRedId;
  18427. }
  18428. if (EmitError) {
  18429. S.Diag(ReductionId.getBeginLoc(),
  18430. diag::err_omp_reduction_identifier_mismatch)
  18431. << ReductionIdRange << RefExpr->getSourceRange();
  18432. S.Diag(ParentSR.getBegin(),
  18433. diag::note_omp_previous_reduction_identifier)
  18434. << ParentSR
  18435. << (IsParentBOK ? ParentBOKDSA.RefExpr
  18436. : ParentReductionOpDSA.RefExpr)
  18437. ->getSourceRange();
  18438. continue;
  18439. }
  18440. }
  18441. TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
  18442. }
  18443. DeclRefExpr *Ref = nullptr;
  18444. Expr *VarsExpr = RefExpr->IgnoreParens();
  18445. if (!VD && !S.CurContext->isDependentContext()) {
  18446. if (ASE || OASE) {
  18447. TransformExprToCaptures RebuildToCapture(S, D);
  18448. VarsExpr =
  18449. RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
  18450. Ref = RebuildToCapture.getCapturedExpr();
  18451. } else {
  18452. VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
  18453. }
  18454. if (!S.isOpenMPCapturedDecl(D)) {
  18455. RD.ExprCaptures.emplace_back(Ref->getDecl());
  18456. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  18457. ExprResult RefRes = S.DefaultLvalueConversion(Ref);
  18458. if (!RefRes.isUsable())
  18459. continue;
  18460. ExprResult PostUpdateRes =
  18461. S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
  18462. RefRes.get());
  18463. if (!PostUpdateRes.isUsable())
  18464. continue;
  18465. if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
  18466. Stack->getCurrentDirective() == OMPD_taskgroup) {
  18467. S.Diag(RefExpr->getExprLoc(),
  18468. diag::err_omp_reduction_non_addressable_expression)
  18469. << RefExpr->getSourceRange();
  18470. continue;
  18471. }
  18472. RD.ExprPostUpdates.emplace_back(
  18473. S.IgnoredValueConversions(PostUpdateRes.get()).get());
  18474. }
  18475. }
  18476. }
  18477. // All reduction items are still marked as reduction (to do not increase
  18478. // code base size).
  18479. unsigned Modifier = RD.RedModifier;
  18480. // Consider task_reductions as reductions with task modifier. Required for
  18481. // correct analysis of in_reduction clauses.
  18482. if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction)
  18483. Modifier = OMPC_REDUCTION_task;
  18484. Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier,
  18485. ASE || OASE);
  18486. if (Modifier == OMPC_REDUCTION_task &&
  18487. (CurrDir == OMPD_taskgroup ||
  18488. ((isOpenMPParallelDirective(CurrDir) ||
  18489. isOpenMPWorksharingDirective(CurrDir)) &&
  18490. !isOpenMPSimdDirective(CurrDir)))) {
  18491. if (DeclareReductionRef.isUsable())
  18492. Stack->addTaskgroupReductionData(D, ReductionIdRange,
  18493. DeclareReductionRef.get());
  18494. else
  18495. Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
  18496. }
  18497. RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
  18498. TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(),
  18499. TempArrayElem.get());
  18500. }
  18501. return RD.Vars.empty();
  18502. }
  18503. OMPClause *Sema::ActOnOpenMPReductionClause(
  18504. ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
  18505. SourceLocation StartLoc, SourceLocation LParenLoc,
  18506. SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
  18507. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  18508. ArrayRef<Expr *> UnresolvedReductions) {
  18509. if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) {
  18510. Diag(LParenLoc, diag::err_omp_unexpected_clause_value)
  18511. << getListOfPossibleValues(OMPC_reduction, /*First=*/0,
  18512. /*Last=*/OMPC_REDUCTION_unknown)
  18513. << getOpenMPClauseName(OMPC_reduction);
  18514. return nullptr;
  18515. }
  18516. // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions
  18517. // A reduction clause with the inscan reduction-modifier may only appear on a
  18518. // worksharing-loop construct, a worksharing-loop SIMD construct, a simd
  18519. // construct, a parallel worksharing-loop construct or a parallel
  18520. // worksharing-loop SIMD construct.
  18521. if (Modifier == OMPC_REDUCTION_inscan &&
  18522. (DSAStack->getCurrentDirective() != OMPD_for &&
  18523. DSAStack->getCurrentDirective() != OMPD_for_simd &&
  18524. DSAStack->getCurrentDirective() != OMPD_simd &&
  18525. DSAStack->getCurrentDirective() != OMPD_parallel_for &&
  18526. DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) {
  18527. Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction);
  18528. return nullptr;
  18529. }
  18530. ReductionData RD(VarList.size(), Modifier);
  18531. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
  18532. StartLoc, LParenLoc, ColonLoc, EndLoc,
  18533. ReductionIdScopeSpec, ReductionId,
  18534. UnresolvedReductions, RD))
  18535. return nullptr;
  18536. return OMPReductionClause::Create(
  18537. Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier,
  18538. RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  18539. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps,
  18540. RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems,
  18541. buildPreInits(Context, RD.ExprCaptures),
  18542. buildPostUpdate(*this, RD.ExprPostUpdates));
  18543. }
  18544. OMPClause *Sema::ActOnOpenMPTaskReductionClause(
  18545. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  18546. SourceLocation ColonLoc, SourceLocation EndLoc,
  18547. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  18548. ArrayRef<Expr *> UnresolvedReductions) {
  18549. ReductionData RD(VarList.size());
  18550. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
  18551. StartLoc, LParenLoc, ColonLoc, EndLoc,
  18552. ReductionIdScopeSpec, ReductionId,
  18553. UnresolvedReductions, RD))
  18554. return nullptr;
  18555. return OMPTaskReductionClause::Create(
  18556. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  18557. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  18558. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
  18559. buildPreInits(Context, RD.ExprCaptures),
  18560. buildPostUpdate(*this, RD.ExprPostUpdates));
  18561. }
  18562. OMPClause *Sema::ActOnOpenMPInReductionClause(
  18563. ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
  18564. SourceLocation ColonLoc, SourceLocation EndLoc,
  18565. CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
  18566. ArrayRef<Expr *> UnresolvedReductions) {
  18567. ReductionData RD(VarList.size());
  18568. if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
  18569. StartLoc, LParenLoc, ColonLoc, EndLoc,
  18570. ReductionIdScopeSpec, ReductionId,
  18571. UnresolvedReductions, RD))
  18572. return nullptr;
  18573. return OMPInReductionClause::Create(
  18574. Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
  18575. ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
  18576. RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
  18577. buildPreInits(Context, RD.ExprCaptures),
  18578. buildPostUpdate(*this, RD.ExprPostUpdates));
  18579. }
  18580. bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
  18581. SourceLocation LinLoc) {
  18582. if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
  18583. LinKind == OMPC_LINEAR_unknown) {
  18584. Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
  18585. return true;
  18586. }
  18587. return false;
  18588. }
  18589. bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
  18590. OpenMPLinearClauseKind LinKind, QualType Type,
  18591. bool IsDeclareSimd) {
  18592. const auto *VD = dyn_cast_or_null<VarDecl>(D);
  18593. // A variable must not have an incomplete type or a reference type.
  18594. if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
  18595. return true;
  18596. if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
  18597. !Type->isReferenceType()) {
  18598. Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
  18599. << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
  18600. return true;
  18601. }
  18602. Type = Type.getNonReferenceType();
  18603. // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
  18604. // A variable that is privatized must not have a const-qualified type
  18605. // unless it is of class type with a mutable member. This restriction does
  18606. // not apply to the firstprivate clause, nor to the linear clause on
  18607. // declarative directives (like declare simd).
  18608. if (!IsDeclareSimd &&
  18609. rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
  18610. return true;
  18611. // A list item must be of integral or pointer type.
  18612. Type = Type.getUnqualifiedType().getCanonicalType();
  18613. const auto *Ty = Type.getTypePtrOrNull();
  18614. if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
  18615. !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
  18616. Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
  18617. if (D) {
  18618. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  18619. VarDecl::DeclarationOnly;
  18620. Diag(D->getLocation(),
  18621. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  18622. << D;
  18623. }
  18624. return true;
  18625. }
  18626. return false;
  18627. }
  18628. OMPClause *Sema::ActOnOpenMPLinearClause(
  18629. ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
  18630. SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
  18631. SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  18632. SmallVector<Expr *, 8> Vars;
  18633. SmallVector<Expr *, 8> Privates;
  18634. SmallVector<Expr *, 8> Inits;
  18635. SmallVector<Decl *, 4> ExprCaptures;
  18636. SmallVector<Expr *, 4> ExprPostUpdates;
  18637. if (CheckOpenMPLinearModifier(LinKind, LinLoc))
  18638. LinKind = OMPC_LINEAR_val;
  18639. for (Expr *RefExpr : VarList) {
  18640. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  18641. SourceLocation ELoc;
  18642. SourceRange ERange;
  18643. Expr *SimpleRefExpr = RefExpr;
  18644. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  18645. if (Res.second) {
  18646. // It will be analyzed later.
  18647. Vars.push_back(RefExpr);
  18648. Privates.push_back(nullptr);
  18649. Inits.push_back(nullptr);
  18650. }
  18651. ValueDecl *D = Res.first;
  18652. if (!D)
  18653. continue;
  18654. QualType Type = D->getType();
  18655. auto *VD = dyn_cast<VarDecl>(D);
  18656. // OpenMP [2.14.3.7, linear clause]
  18657. // A list-item cannot appear in more than one linear clause.
  18658. // A list-item that appears in a linear clause cannot appear in any
  18659. // other data-sharing attribute clause.
  18660. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  18661. if (DVar.RefExpr) {
  18662. Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
  18663. << getOpenMPClauseName(OMPC_linear);
  18664. reportOriginalDsa(*this, DSAStack, D, DVar);
  18665. continue;
  18666. }
  18667. if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
  18668. continue;
  18669. Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  18670. // Build private copy of original var.
  18671. VarDecl *Private =
  18672. buildVarDecl(*this, ELoc, Type, D->getName(),
  18673. D->hasAttrs() ? &D->getAttrs() : nullptr,
  18674. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  18675. DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
  18676. // Build var to save initial value.
  18677. VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
  18678. Expr *InitExpr;
  18679. DeclRefExpr *Ref = nullptr;
  18680. if (!VD && !CurContext->isDependentContext()) {
  18681. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  18682. if (!isOpenMPCapturedDecl(D)) {
  18683. ExprCaptures.push_back(Ref->getDecl());
  18684. if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
  18685. ExprResult RefRes = DefaultLvalueConversion(Ref);
  18686. if (!RefRes.isUsable())
  18687. continue;
  18688. ExprResult PostUpdateRes =
  18689. BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
  18690. SimpleRefExpr, RefRes.get());
  18691. if (!PostUpdateRes.isUsable())
  18692. continue;
  18693. ExprPostUpdates.push_back(
  18694. IgnoredValueConversions(PostUpdateRes.get()).get());
  18695. }
  18696. }
  18697. }
  18698. if (LinKind == OMPC_LINEAR_uval)
  18699. InitExpr = VD ? VD->getInit() : SimpleRefExpr;
  18700. else
  18701. InitExpr = VD ? SimpleRefExpr : Ref;
  18702. AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
  18703. /*DirectInit=*/false);
  18704. DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
  18705. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
  18706. Vars.push_back((VD || CurContext->isDependentContext())
  18707. ? RefExpr->IgnoreParens()
  18708. : Ref);
  18709. Privates.push_back(PrivateRef);
  18710. Inits.push_back(InitRef);
  18711. }
  18712. if (Vars.empty())
  18713. return nullptr;
  18714. Expr *StepExpr = Step;
  18715. Expr *CalcStepExpr = nullptr;
  18716. if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
  18717. !Step->isInstantiationDependent() &&
  18718. !Step->containsUnexpandedParameterPack()) {
  18719. SourceLocation StepLoc = Step->getBeginLoc();
  18720. ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
  18721. if (Val.isInvalid())
  18722. return nullptr;
  18723. StepExpr = Val.get();
  18724. // Build var to save the step value.
  18725. VarDecl *SaveVar =
  18726. buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
  18727. ExprResult SaveRef =
  18728. buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
  18729. ExprResult CalcStep =
  18730. BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
  18731. CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
  18732. // Warn about zero linear step (it would be probably better specified as
  18733. // making corresponding variables 'const').
  18734. if (std::optional<llvm::APSInt> Result =
  18735. StepExpr->getIntegerConstantExpr(Context)) {
  18736. if (!Result->isNegative() && !Result->isStrictlyPositive())
  18737. Diag(StepLoc, diag::warn_omp_linear_step_zero)
  18738. << Vars[0] << (Vars.size() > 1);
  18739. } else if (CalcStep.isUsable()) {
  18740. // Calculate the step beforehand instead of doing this on each iteration.
  18741. // (This is not used if the number of iterations may be kfold-ed).
  18742. CalcStepExpr = CalcStep.get();
  18743. }
  18744. }
  18745. return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
  18746. ColonLoc, EndLoc, Vars, Privates, Inits,
  18747. StepExpr, CalcStepExpr,
  18748. buildPreInits(Context, ExprCaptures),
  18749. buildPostUpdate(*this, ExprPostUpdates));
  18750. }
  18751. static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
  18752. Expr *NumIterations, Sema &SemaRef,
  18753. Scope *S, DSAStackTy *Stack) {
  18754. // Walk the vars and build update/final expressions for the CodeGen.
  18755. SmallVector<Expr *, 8> Updates;
  18756. SmallVector<Expr *, 8> Finals;
  18757. SmallVector<Expr *, 8> UsedExprs;
  18758. Expr *Step = Clause.getStep();
  18759. Expr *CalcStep = Clause.getCalcStep();
  18760. // OpenMP [2.14.3.7, linear clause]
  18761. // If linear-step is not specified it is assumed to be 1.
  18762. if (!Step)
  18763. Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
  18764. else if (CalcStep)
  18765. Step = cast<BinaryOperator>(CalcStep)->getLHS();
  18766. bool HasErrors = false;
  18767. auto CurInit = Clause.inits().begin();
  18768. auto CurPrivate = Clause.privates().begin();
  18769. OpenMPLinearClauseKind LinKind = Clause.getModifier();
  18770. for (Expr *RefExpr : Clause.varlists()) {
  18771. SourceLocation ELoc;
  18772. SourceRange ERange;
  18773. Expr *SimpleRefExpr = RefExpr;
  18774. auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
  18775. ValueDecl *D = Res.first;
  18776. if (Res.second || !D) {
  18777. Updates.push_back(nullptr);
  18778. Finals.push_back(nullptr);
  18779. HasErrors = true;
  18780. continue;
  18781. }
  18782. auto &&Info = Stack->isLoopControlVariable(D);
  18783. // OpenMP [2.15.11, distribute simd Construct]
  18784. // A list item may not appear in a linear clause, unless it is the loop
  18785. // iteration variable.
  18786. if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
  18787. isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
  18788. SemaRef.Diag(ELoc,
  18789. diag::err_omp_linear_distribute_var_non_loop_iteration);
  18790. Updates.push_back(nullptr);
  18791. Finals.push_back(nullptr);
  18792. HasErrors = true;
  18793. continue;
  18794. }
  18795. Expr *InitExpr = *CurInit;
  18796. // Build privatized reference to the current linear var.
  18797. auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
  18798. Expr *CapturedRef;
  18799. if (LinKind == OMPC_LINEAR_uval)
  18800. CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
  18801. else
  18802. CapturedRef =
  18803. buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
  18804. DE->getType().getUnqualifiedType(), DE->getExprLoc(),
  18805. /*RefersToCapture=*/true);
  18806. // Build update: Var = InitExpr + IV * Step
  18807. ExprResult Update;
  18808. if (!Info.first)
  18809. Update = buildCounterUpdate(
  18810. SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
  18811. /*Subtract=*/false, /*IsNonRectangularLB=*/false);
  18812. else
  18813. Update = *CurPrivate;
  18814. Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
  18815. /*DiscardedValue*/ false);
  18816. // Build final: Var = PrivCopy;
  18817. ExprResult Final;
  18818. if (!Info.first)
  18819. Final = SemaRef.BuildBinOp(
  18820. S, RefExpr->getExprLoc(), BO_Assign, CapturedRef,
  18821. SemaRef.DefaultLvalueConversion(*CurPrivate).get());
  18822. else
  18823. Final = *CurPrivate;
  18824. Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
  18825. /*DiscardedValue*/ false);
  18826. if (!Update.isUsable() || !Final.isUsable()) {
  18827. Updates.push_back(nullptr);
  18828. Finals.push_back(nullptr);
  18829. UsedExprs.push_back(nullptr);
  18830. HasErrors = true;
  18831. } else {
  18832. Updates.push_back(Update.get());
  18833. Finals.push_back(Final.get());
  18834. if (!Info.first)
  18835. UsedExprs.push_back(SimpleRefExpr);
  18836. }
  18837. ++CurInit;
  18838. ++CurPrivate;
  18839. }
  18840. if (Expr *S = Clause.getStep())
  18841. UsedExprs.push_back(S);
  18842. // Fill the remaining part with the nullptr.
  18843. UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
  18844. Clause.setUpdates(Updates);
  18845. Clause.setFinals(Finals);
  18846. Clause.setUsedExprs(UsedExprs);
  18847. return HasErrors;
  18848. }
  18849. OMPClause *Sema::ActOnOpenMPAlignedClause(
  18850. ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
  18851. SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
  18852. SmallVector<Expr *, 8> Vars;
  18853. for (Expr *RefExpr : VarList) {
  18854. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  18855. SourceLocation ELoc;
  18856. SourceRange ERange;
  18857. Expr *SimpleRefExpr = RefExpr;
  18858. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  18859. if (Res.second) {
  18860. // It will be analyzed later.
  18861. Vars.push_back(RefExpr);
  18862. }
  18863. ValueDecl *D = Res.first;
  18864. if (!D)
  18865. continue;
  18866. QualType QType = D->getType();
  18867. auto *VD = dyn_cast<VarDecl>(D);
  18868. // OpenMP [2.8.1, simd construct, Restrictions]
  18869. // The type of list items appearing in the aligned clause must be
  18870. // array, pointer, reference to array, or reference to pointer.
  18871. QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
  18872. const Type *Ty = QType.getTypePtrOrNull();
  18873. if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
  18874. Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
  18875. << QType << getLangOpts().CPlusPlus << ERange;
  18876. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  18877. VarDecl::DeclarationOnly;
  18878. Diag(D->getLocation(),
  18879. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  18880. << D;
  18881. continue;
  18882. }
  18883. // OpenMP [2.8.1, simd construct, Restrictions]
  18884. // A list-item cannot appear in more than one aligned clause.
  18885. if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
  18886. Diag(ELoc, diag::err_omp_used_in_clause_twice)
  18887. << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
  18888. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  18889. << getOpenMPClauseName(OMPC_aligned);
  18890. continue;
  18891. }
  18892. DeclRefExpr *Ref = nullptr;
  18893. if (!VD && isOpenMPCapturedDecl(D))
  18894. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  18895. Vars.push_back(DefaultFunctionArrayConversion(
  18896. (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
  18897. .get());
  18898. }
  18899. // OpenMP [2.8.1, simd construct, Description]
  18900. // The parameter of the aligned clause, alignment, must be a constant
  18901. // positive integer expression.
  18902. // If no optional parameter is specified, implementation-defined default
  18903. // alignments for SIMD instructions on the target platforms are assumed.
  18904. if (Alignment != nullptr) {
  18905. ExprResult AlignResult =
  18906. VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
  18907. if (AlignResult.isInvalid())
  18908. return nullptr;
  18909. Alignment = AlignResult.get();
  18910. }
  18911. if (Vars.empty())
  18912. return nullptr;
  18913. return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  18914. EndLoc, Vars, Alignment);
  18915. }
  18916. OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
  18917. SourceLocation StartLoc,
  18918. SourceLocation LParenLoc,
  18919. SourceLocation EndLoc) {
  18920. SmallVector<Expr *, 8> Vars;
  18921. SmallVector<Expr *, 8> SrcExprs;
  18922. SmallVector<Expr *, 8> DstExprs;
  18923. SmallVector<Expr *, 8> AssignmentOps;
  18924. for (Expr *RefExpr : VarList) {
  18925. assert(RefExpr && "NULL expr in OpenMP copyin clause.");
  18926. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  18927. // It will be analyzed later.
  18928. Vars.push_back(RefExpr);
  18929. SrcExprs.push_back(nullptr);
  18930. DstExprs.push_back(nullptr);
  18931. AssignmentOps.push_back(nullptr);
  18932. continue;
  18933. }
  18934. SourceLocation ELoc = RefExpr->getExprLoc();
  18935. // OpenMP [2.1, C/C++]
  18936. // A list item is a variable name.
  18937. // OpenMP [2.14.4.1, Restrictions, p.1]
  18938. // A list item that appears in a copyin clause must be threadprivate.
  18939. auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
  18940. if (!DE || !isa<VarDecl>(DE->getDecl())) {
  18941. Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
  18942. << 0 << RefExpr->getSourceRange();
  18943. continue;
  18944. }
  18945. Decl *D = DE->getDecl();
  18946. auto *VD = cast<VarDecl>(D);
  18947. QualType Type = VD->getType();
  18948. if (Type->isDependentType() || Type->isInstantiationDependentType()) {
  18949. // It will be analyzed later.
  18950. Vars.push_back(DE);
  18951. SrcExprs.push_back(nullptr);
  18952. DstExprs.push_back(nullptr);
  18953. AssignmentOps.push_back(nullptr);
  18954. continue;
  18955. }
  18956. // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
  18957. // A list item that appears in a copyin clause must be threadprivate.
  18958. if (!DSAStack->isThreadPrivate(VD)) {
  18959. Diag(ELoc, diag::err_omp_required_access)
  18960. << getOpenMPClauseName(OMPC_copyin)
  18961. << getOpenMPDirectiveName(OMPD_threadprivate);
  18962. continue;
  18963. }
  18964. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  18965. // A variable of class type (or array thereof) that appears in a
  18966. // copyin clause requires an accessible, unambiguous copy assignment
  18967. // operator for the class type.
  18968. QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
  18969. VarDecl *SrcVD =
  18970. buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
  18971. ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  18972. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
  18973. *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
  18974. VarDecl *DstVD =
  18975. buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
  18976. VD->hasAttrs() ? &VD->getAttrs() : nullptr);
  18977. DeclRefExpr *PseudoDstExpr =
  18978. buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
  18979. // For arrays generate assignment operation for single element and replace
  18980. // it by the original array element in CodeGen.
  18981. ExprResult AssignmentOp =
  18982. BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
  18983. PseudoSrcExpr);
  18984. if (AssignmentOp.isInvalid())
  18985. continue;
  18986. AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
  18987. /*DiscardedValue*/ false);
  18988. if (AssignmentOp.isInvalid())
  18989. continue;
  18990. DSAStack->addDSA(VD, DE, OMPC_copyin);
  18991. Vars.push_back(DE);
  18992. SrcExprs.push_back(PseudoSrcExpr);
  18993. DstExprs.push_back(PseudoDstExpr);
  18994. AssignmentOps.push_back(AssignmentOp.get());
  18995. }
  18996. if (Vars.empty())
  18997. return nullptr;
  18998. return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
  18999. SrcExprs, DstExprs, AssignmentOps);
  19000. }
  19001. OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
  19002. SourceLocation StartLoc,
  19003. SourceLocation LParenLoc,
  19004. SourceLocation EndLoc) {
  19005. SmallVector<Expr *, 8> Vars;
  19006. SmallVector<Expr *, 8> SrcExprs;
  19007. SmallVector<Expr *, 8> DstExprs;
  19008. SmallVector<Expr *, 8> AssignmentOps;
  19009. for (Expr *RefExpr : VarList) {
  19010. assert(RefExpr && "NULL expr in OpenMP linear clause.");
  19011. SourceLocation ELoc;
  19012. SourceRange ERange;
  19013. Expr *SimpleRefExpr = RefExpr;
  19014. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  19015. if (Res.second) {
  19016. // It will be analyzed later.
  19017. Vars.push_back(RefExpr);
  19018. SrcExprs.push_back(nullptr);
  19019. DstExprs.push_back(nullptr);
  19020. AssignmentOps.push_back(nullptr);
  19021. }
  19022. ValueDecl *D = Res.first;
  19023. if (!D)
  19024. continue;
  19025. QualType Type = D->getType();
  19026. auto *VD = dyn_cast<VarDecl>(D);
  19027. // OpenMP [2.14.4.2, Restrictions, p.2]
  19028. // A list item that appears in a copyprivate clause may not appear in a
  19029. // private or firstprivate clause on the single construct.
  19030. if (!VD || !DSAStack->isThreadPrivate(VD)) {
  19031. DSAStackTy::DSAVarData DVar =
  19032. DSAStack->getTopDSA(D, /*FromParent=*/false);
  19033. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
  19034. DVar.RefExpr) {
  19035. Diag(ELoc, diag::err_omp_wrong_dsa)
  19036. << getOpenMPClauseName(DVar.CKind)
  19037. << getOpenMPClauseName(OMPC_copyprivate);
  19038. reportOriginalDsa(*this, DSAStack, D, DVar);
  19039. continue;
  19040. }
  19041. // OpenMP [2.11.4.2, Restrictions, p.1]
  19042. // All list items that appear in a copyprivate clause must be either
  19043. // threadprivate or private in the enclosing context.
  19044. if (DVar.CKind == OMPC_unknown) {
  19045. DVar = DSAStack->getImplicitDSA(D, false);
  19046. if (DVar.CKind == OMPC_shared) {
  19047. Diag(ELoc, diag::err_omp_required_access)
  19048. << getOpenMPClauseName(OMPC_copyprivate)
  19049. << "threadprivate or private in the enclosing context";
  19050. reportOriginalDsa(*this, DSAStack, D, DVar);
  19051. continue;
  19052. }
  19053. }
  19054. }
  19055. // Variably modified types are not supported.
  19056. if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
  19057. Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
  19058. << getOpenMPClauseName(OMPC_copyprivate) << Type
  19059. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  19060. bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
  19061. VarDecl::DeclarationOnly;
  19062. Diag(D->getLocation(),
  19063. IsDecl ? diag::note_previous_decl : diag::note_defined_here)
  19064. << D;
  19065. continue;
  19066. }
  19067. // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
  19068. // A variable of class type (or array thereof) that appears in a
  19069. // copyin clause requires an accessible, unambiguous copy assignment
  19070. // operator for the class type.
  19071. Type = Context.getBaseElementType(Type.getNonReferenceType())
  19072. .getUnqualifiedType();
  19073. VarDecl *SrcVD =
  19074. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
  19075. D->hasAttrs() ? &D->getAttrs() : nullptr);
  19076. DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
  19077. VarDecl *DstVD =
  19078. buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
  19079. D->hasAttrs() ? &D->getAttrs() : nullptr);
  19080. DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
  19081. ExprResult AssignmentOp = BuildBinOp(
  19082. DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
  19083. if (AssignmentOp.isInvalid())
  19084. continue;
  19085. AssignmentOp =
  19086. ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
  19087. if (AssignmentOp.isInvalid())
  19088. continue;
  19089. // No need to mark vars as copyprivate, they are already threadprivate or
  19090. // implicitly private.
  19091. assert(VD || isOpenMPCapturedDecl(D));
  19092. Vars.push_back(
  19093. VD ? RefExpr->IgnoreParens()
  19094. : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
  19095. SrcExprs.push_back(PseudoSrcExpr);
  19096. DstExprs.push_back(PseudoDstExpr);
  19097. AssignmentOps.push_back(AssignmentOp.get());
  19098. }
  19099. if (Vars.empty())
  19100. return nullptr;
  19101. return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  19102. Vars, SrcExprs, DstExprs, AssignmentOps);
  19103. }
  19104. OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
  19105. SourceLocation StartLoc,
  19106. SourceLocation LParenLoc,
  19107. SourceLocation EndLoc) {
  19108. if (VarList.empty())
  19109. return nullptr;
  19110. return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
  19111. }
  19112. /// Tries to find omp_depend_t. type.
  19113. static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack,
  19114. bool Diagnose = true) {
  19115. QualType OMPDependT = Stack->getOMPDependT();
  19116. if (!OMPDependT.isNull())
  19117. return true;
  19118. IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t");
  19119. ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
  19120. if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
  19121. if (Diagnose)
  19122. S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t";
  19123. return false;
  19124. }
  19125. Stack->setOMPDependT(PT.get());
  19126. return true;
  19127. }
  19128. OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
  19129. SourceLocation LParenLoc,
  19130. SourceLocation EndLoc) {
  19131. if (!Depobj)
  19132. return nullptr;
  19133. bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack);
  19134. // OpenMP 5.0, 2.17.10.1 depobj Construct
  19135. // depobj is an lvalue expression of type omp_depend_t.
  19136. if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() &&
  19137. !Depobj->isInstantiationDependent() &&
  19138. !Depobj->containsUnexpandedParameterPack() &&
  19139. (OMPDependTFound &&
  19140. !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(),
  19141. /*CompareUnqualified=*/true))) {
  19142. Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
  19143. << 0 << Depobj->getType() << Depobj->getSourceRange();
  19144. }
  19145. if (!Depobj->isLValue()) {
  19146. Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue)
  19147. << 1 << Depobj->getSourceRange();
  19148. }
  19149. return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj);
  19150. }
  19151. OMPClause *
  19152. Sema::ActOnOpenMPDependClause(const OMPDependClause::DependDataTy &Data,
  19153. Expr *DepModifier, ArrayRef<Expr *> VarList,
  19154. SourceLocation StartLoc, SourceLocation LParenLoc,
  19155. SourceLocation EndLoc) {
  19156. OpenMPDependClauseKind DepKind = Data.DepKind;
  19157. SourceLocation DepLoc = Data.DepLoc;
  19158. if (DSAStack->getCurrentDirective() == OMPD_ordered &&
  19159. DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
  19160. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  19161. << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
  19162. return nullptr;
  19163. }
  19164. if (DSAStack->getCurrentDirective() == OMPD_taskwait &&
  19165. DepKind == OMPC_DEPEND_mutexinoutset) {
  19166. Diag(DepLoc, diag::err_omp_taskwait_depend_mutexinoutset_not_allowed);
  19167. return nullptr;
  19168. }
  19169. if ((DSAStack->getCurrentDirective() != OMPD_ordered ||
  19170. DSAStack->getCurrentDirective() == OMPD_depobj) &&
  19171. (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
  19172. DepKind == OMPC_DEPEND_sink ||
  19173. ((LangOpts.OpenMP < 50 ||
  19174. DSAStack->getCurrentDirective() == OMPD_depobj) &&
  19175. DepKind == OMPC_DEPEND_depobj))) {
  19176. SmallVector<unsigned, 6> Except = {OMPC_DEPEND_source, OMPC_DEPEND_sink,
  19177. OMPC_DEPEND_outallmemory,
  19178. OMPC_DEPEND_inoutallmemory};
  19179. if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj)
  19180. Except.push_back(OMPC_DEPEND_depobj);
  19181. if (LangOpts.OpenMP < 51)
  19182. Except.push_back(OMPC_DEPEND_inoutset);
  19183. std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier)
  19184. ? "depend modifier(iterator) or "
  19185. : "";
  19186. Diag(DepLoc, diag::err_omp_unexpected_clause_value)
  19187. << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0,
  19188. /*Last=*/OMPC_DEPEND_unknown,
  19189. Except)
  19190. << getOpenMPClauseName(OMPC_depend);
  19191. return nullptr;
  19192. }
  19193. if (DepModifier &&
  19194. (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) {
  19195. Diag(DepModifier->getExprLoc(),
  19196. diag::err_omp_depend_sink_source_with_modifier);
  19197. return nullptr;
  19198. }
  19199. if (DepModifier &&
  19200. !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator))
  19201. Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator);
  19202. SmallVector<Expr *, 8> Vars;
  19203. DSAStackTy::OperatorOffsetTy OpsOffs;
  19204. llvm::APSInt DepCounter(/*BitWidth=*/32);
  19205. llvm::APSInt TotalDepCount(/*BitWidth=*/32);
  19206. if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
  19207. if (const Expr *OrderedCountExpr =
  19208. DSAStack->getParentOrderedRegionParam().first) {
  19209. TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
  19210. TotalDepCount.setIsUnsigned(/*Val=*/true);
  19211. }
  19212. }
  19213. for (Expr *RefExpr : VarList) {
  19214. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  19215. if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
  19216. // It will be analyzed later.
  19217. Vars.push_back(RefExpr);
  19218. continue;
  19219. }
  19220. SourceLocation ELoc = RefExpr->getExprLoc();
  19221. Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
  19222. if (DepKind == OMPC_DEPEND_sink) {
  19223. if (DSAStack->getParentOrderedRegionParam().first &&
  19224. DepCounter >= TotalDepCount) {
  19225. Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
  19226. continue;
  19227. }
  19228. ++DepCounter;
  19229. // OpenMP [2.13.9, Summary]
  19230. // depend(dependence-type : vec), where dependence-type is:
  19231. // 'sink' and where vec is the iteration vector, which has the form:
  19232. // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
  19233. // where n is the value specified by the ordered clause in the loop
  19234. // directive, xi denotes the loop iteration variable of the i-th nested
  19235. // loop associated with the loop directive, and di is a constant
  19236. // non-negative integer.
  19237. if (CurContext->isDependentContext()) {
  19238. // It will be analyzed later.
  19239. Vars.push_back(RefExpr);
  19240. continue;
  19241. }
  19242. SimpleExpr = SimpleExpr->IgnoreImplicit();
  19243. OverloadedOperatorKind OOK = OO_None;
  19244. SourceLocation OOLoc;
  19245. Expr *LHS = SimpleExpr;
  19246. Expr *RHS = nullptr;
  19247. if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
  19248. OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
  19249. OOLoc = BO->getOperatorLoc();
  19250. LHS = BO->getLHS()->IgnoreParenImpCasts();
  19251. RHS = BO->getRHS()->IgnoreParenImpCasts();
  19252. } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
  19253. OOK = OCE->getOperator();
  19254. OOLoc = OCE->getOperatorLoc();
  19255. LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  19256. RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
  19257. } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
  19258. OOK = MCE->getMethodDecl()
  19259. ->getNameInfo()
  19260. .getName()
  19261. .getCXXOverloadedOperator();
  19262. OOLoc = MCE->getCallee()->getExprLoc();
  19263. LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
  19264. RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
  19265. }
  19266. SourceLocation ELoc;
  19267. SourceRange ERange;
  19268. auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
  19269. if (Res.second) {
  19270. // It will be analyzed later.
  19271. Vars.push_back(RefExpr);
  19272. }
  19273. ValueDecl *D = Res.first;
  19274. if (!D)
  19275. continue;
  19276. if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
  19277. Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
  19278. continue;
  19279. }
  19280. if (RHS) {
  19281. ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
  19282. RHS, OMPC_depend, /*StrictlyPositive=*/false);
  19283. if (RHSRes.isInvalid())
  19284. continue;
  19285. }
  19286. if (!CurContext->isDependentContext() &&
  19287. DSAStack->getParentOrderedRegionParam().first &&
  19288. DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
  19289. const ValueDecl *VD =
  19290. DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
  19291. if (VD)
  19292. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
  19293. << 1 << VD;
  19294. else
  19295. Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
  19296. continue;
  19297. }
  19298. OpsOffs.emplace_back(RHS, OOK);
  19299. } else {
  19300. bool OMPDependTFound = LangOpts.OpenMP >= 50;
  19301. if (OMPDependTFound)
  19302. OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack,
  19303. DepKind == OMPC_DEPEND_depobj);
  19304. if (DepKind == OMPC_DEPEND_depobj) {
  19305. // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
  19306. // List items used in depend clauses with the depobj dependence type
  19307. // must be expressions of the omp_depend_t type.
  19308. if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
  19309. !RefExpr->isInstantiationDependent() &&
  19310. !RefExpr->containsUnexpandedParameterPack() &&
  19311. (OMPDependTFound &&
  19312. !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(),
  19313. RefExpr->getType()))) {
  19314. Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
  19315. << 0 << RefExpr->getType() << RefExpr->getSourceRange();
  19316. continue;
  19317. }
  19318. if (!RefExpr->isLValue()) {
  19319. Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue)
  19320. << 1 << RefExpr->getType() << RefExpr->getSourceRange();
  19321. continue;
  19322. }
  19323. } else {
  19324. // OpenMP 5.0 [2.17.11, Restrictions]
  19325. // List items used in depend clauses cannot be zero-length array
  19326. // sections.
  19327. QualType ExprTy = RefExpr->getType().getNonReferenceType();
  19328. const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
  19329. if (OASE) {
  19330. QualType BaseType =
  19331. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  19332. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  19333. ExprTy = ATy->getElementType();
  19334. else
  19335. ExprTy = BaseType->getPointeeType();
  19336. ExprTy = ExprTy.getNonReferenceType();
  19337. const Expr *Length = OASE->getLength();
  19338. Expr::EvalResult Result;
  19339. if (Length && !Length->isValueDependent() &&
  19340. Length->EvaluateAsInt(Result, Context) &&
  19341. Result.Val.getInt().isZero()) {
  19342. Diag(ELoc,
  19343. diag::err_omp_depend_zero_length_array_section_not_allowed)
  19344. << SimpleExpr->getSourceRange();
  19345. continue;
  19346. }
  19347. }
  19348. // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++
  19349. // List items used in depend clauses with the in, out, inout,
  19350. // inoutset, or mutexinoutset dependence types cannot be
  19351. // expressions of the omp_depend_t type.
  19352. if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() &&
  19353. !RefExpr->isInstantiationDependent() &&
  19354. !RefExpr->containsUnexpandedParameterPack() &&
  19355. (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
  19356. (OMPDependTFound &&
  19357. DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr()))) {
  19358. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  19359. << (LangOpts.OpenMP >= 50 ? 1 : 0)
  19360. << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
  19361. continue;
  19362. }
  19363. auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
  19364. if (ASE && !ASE->getBase()->isTypeDependent() &&
  19365. !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
  19366. !ASE->getBase()->getType().getNonReferenceType()->isArrayType()) {
  19367. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  19368. << (LangOpts.OpenMP >= 50 ? 1 : 0)
  19369. << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
  19370. continue;
  19371. }
  19372. ExprResult Res;
  19373. {
  19374. Sema::TentativeAnalysisScope Trap(*this);
  19375. Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
  19376. RefExpr->IgnoreParenImpCasts());
  19377. }
  19378. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
  19379. !isa<OMPArrayShapingExpr>(SimpleExpr)) {
  19380. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  19381. << (LangOpts.OpenMP >= 50 ? 1 : 0)
  19382. << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange();
  19383. continue;
  19384. }
  19385. }
  19386. }
  19387. Vars.push_back(RefExpr->IgnoreParenImpCasts());
  19388. }
  19389. if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
  19390. TotalDepCount > VarList.size() &&
  19391. DSAStack->getParentOrderedRegionParam().first &&
  19392. DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
  19393. Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
  19394. << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
  19395. }
  19396. if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
  19397. DepKind != OMPC_DEPEND_outallmemory &&
  19398. DepKind != OMPC_DEPEND_inoutallmemory && Vars.empty())
  19399. return nullptr;
  19400. auto *C = OMPDependClause::Create(
  19401. Context, StartLoc, LParenLoc, EndLoc,
  19402. {DepKind, DepLoc, Data.ColonLoc, Data.OmpAllMemoryLoc}, DepModifier, Vars,
  19403. TotalDepCount.getZExtValue());
  19404. if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
  19405. DSAStack->isParentOrderedRegion())
  19406. DSAStack->addDoacrossDependClause(C, OpsOffs);
  19407. return C;
  19408. }
  19409. OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
  19410. Expr *Device, SourceLocation StartLoc,
  19411. SourceLocation LParenLoc,
  19412. SourceLocation ModifierLoc,
  19413. SourceLocation EndLoc) {
  19414. assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) &&
  19415. "Unexpected device modifier in OpenMP < 50.");
  19416. bool ErrorFound = false;
  19417. if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) {
  19418. std::string Values =
  19419. getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown);
  19420. Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
  19421. << Values << getOpenMPClauseName(OMPC_device);
  19422. ErrorFound = true;
  19423. }
  19424. Expr *ValExpr = Device;
  19425. Stmt *HelperValStmt = nullptr;
  19426. // OpenMP [2.9.1, Restrictions]
  19427. // The device expression must evaluate to a non-negative integer value.
  19428. ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
  19429. /*StrictlyPositive=*/false) ||
  19430. ErrorFound;
  19431. if (ErrorFound)
  19432. return nullptr;
  19433. // OpenMP 5.0 [2.12.5, Restrictions]
  19434. // In case of ancestor device-modifier, a requires directive with
  19435. // the reverse_offload clause must be specified.
  19436. if (Modifier == OMPC_DEVICE_ancestor) {
  19437. if (!DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>()) {
  19438. targetDiag(
  19439. StartLoc,
  19440. diag::err_omp_device_ancestor_without_requires_reverse_offload);
  19441. ErrorFound = true;
  19442. }
  19443. }
  19444. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  19445. OpenMPDirectiveKind CaptureRegion =
  19446. getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
  19447. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  19448. ValExpr = MakeFullExpr(ValExpr).get();
  19449. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  19450. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  19451. HelperValStmt = buildPreInits(Context, Captures);
  19452. }
  19453. return new (Context)
  19454. OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
  19455. LParenLoc, ModifierLoc, EndLoc);
  19456. }
  19457. static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
  19458. DSAStackTy *Stack, QualType QTy,
  19459. bool FullCheck = true) {
  19460. if (SemaRef.RequireCompleteType(SL, QTy, diag::err_incomplete_type))
  19461. return false;
  19462. if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
  19463. !QTy.isTriviallyCopyableType(SemaRef.Context))
  19464. SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
  19465. return true;
  19466. }
  19467. /// Return true if it can be proven that the provided array expression
  19468. /// (array section or array subscript) does NOT specify the whole size of the
  19469. /// array whose base type is \a BaseQTy.
  19470. static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
  19471. const Expr *E,
  19472. QualType BaseQTy) {
  19473. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  19474. // If this is an array subscript, it refers to the whole size if the size of
  19475. // the dimension is constant and equals 1. Also, an array section assumes the
  19476. // format of an array subscript if no colon is used.
  19477. if (isa<ArraySubscriptExpr>(E) ||
  19478. (OASE && OASE->getColonLocFirst().isInvalid())) {
  19479. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  19480. return ATy->getSize().getSExtValue() != 1;
  19481. // Size can't be evaluated statically.
  19482. return false;
  19483. }
  19484. assert(OASE && "Expecting array section if not an array subscript.");
  19485. const Expr *LowerBound = OASE->getLowerBound();
  19486. const Expr *Length = OASE->getLength();
  19487. // If there is a lower bound that does not evaluates to zero, we are not
  19488. // covering the whole dimension.
  19489. if (LowerBound) {
  19490. Expr::EvalResult Result;
  19491. if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
  19492. return false; // Can't get the integer value as a constant.
  19493. llvm::APSInt ConstLowerBound = Result.Val.getInt();
  19494. if (ConstLowerBound.getSExtValue())
  19495. return true;
  19496. }
  19497. // If we don't have a length we covering the whole dimension.
  19498. if (!Length)
  19499. return false;
  19500. // If the base is a pointer, we don't have a way to get the size of the
  19501. // pointee.
  19502. if (BaseQTy->isPointerType())
  19503. return false;
  19504. // We can only check if the length is the same as the size of the dimension
  19505. // if we have a constant array.
  19506. const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
  19507. if (!CATy)
  19508. return false;
  19509. Expr::EvalResult Result;
  19510. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  19511. return false; // Can't get the integer value as a constant.
  19512. llvm::APSInt ConstLength = Result.Val.getInt();
  19513. return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
  19514. }
  19515. // Return true if it can be proven that the provided array expression (array
  19516. // section or array subscript) does NOT specify a single element of the array
  19517. // whose base type is \a BaseQTy.
  19518. static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
  19519. const Expr *E,
  19520. QualType BaseQTy) {
  19521. const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
  19522. // An array subscript always refer to a single element. Also, an array section
  19523. // assumes the format of an array subscript if no colon is used.
  19524. if (isa<ArraySubscriptExpr>(E) ||
  19525. (OASE && OASE->getColonLocFirst().isInvalid()))
  19526. return false;
  19527. assert(OASE && "Expecting array section if not an array subscript.");
  19528. const Expr *Length = OASE->getLength();
  19529. // If we don't have a length we have to check if the array has unitary size
  19530. // for this dimension. Also, we should always expect a length if the base type
  19531. // is pointer.
  19532. if (!Length) {
  19533. if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
  19534. return ATy->getSize().getSExtValue() != 1;
  19535. // We cannot assume anything.
  19536. return false;
  19537. }
  19538. // Check if the length evaluates to 1.
  19539. Expr::EvalResult Result;
  19540. if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
  19541. return false; // Can't get the integer value as a constant.
  19542. llvm::APSInt ConstLength = Result.Val.getInt();
  19543. return ConstLength.getSExtValue() != 1;
  19544. }
  19545. // The base of elements of list in a map clause have to be either:
  19546. // - a reference to variable or field.
  19547. // - a member expression.
  19548. // - an array expression.
  19549. //
  19550. // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
  19551. // reference to 'r'.
  19552. //
  19553. // If we have:
  19554. //
  19555. // struct SS {
  19556. // Bla S;
  19557. // foo() {
  19558. // #pragma omp target map (S.Arr[:12]);
  19559. // }
  19560. // }
  19561. //
  19562. // We want to retrieve the member expression 'this->S';
  19563. // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2]
  19564. // If a list item is an array section, it must specify contiguous storage.
  19565. //
  19566. // For this restriction it is sufficient that we make sure only references
  19567. // to variables or fields and array expressions, and that no array sections
  19568. // exist except in the rightmost expression (unless they cover the whole
  19569. // dimension of the array). E.g. these would be invalid:
  19570. //
  19571. // r.ArrS[3:5].Arr[6:7]
  19572. //
  19573. // r.ArrS[3:5].x
  19574. //
  19575. // but these would be valid:
  19576. // r.ArrS[3].Arr[6:7]
  19577. //
  19578. // r.ArrS[3].x
  19579. namespace {
  19580. class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> {
  19581. Sema &SemaRef;
  19582. OpenMPClauseKind CKind = OMPC_unknown;
  19583. OpenMPDirectiveKind DKind = OMPD_unknown;
  19584. OMPClauseMappableExprCommon::MappableExprComponentList &Components;
  19585. bool IsNonContiguous = false;
  19586. bool NoDiagnose = false;
  19587. const Expr *RelevantExpr = nullptr;
  19588. bool AllowUnitySizeArraySection = true;
  19589. bool AllowWholeSizeArraySection = true;
  19590. bool AllowAnotherPtr = true;
  19591. SourceLocation ELoc;
  19592. SourceRange ERange;
  19593. void emitErrorMsg() {
  19594. // If nothing else worked, this is not a valid map clause expression.
  19595. if (SemaRef.getLangOpts().OpenMP < 50) {
  19596. SemaRef.Diag(ELoc,
  19597. diag::err_omp_expected_named_var_member_or_array_expression)
  19598. << ERange;
  19599. } else {
  19600. SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
  19601. << getOpenMPClauseName(CKind) << ERange;
  19602. }
  19603. }
  19604. public:
  19605. bool VisitDeclRefExpr(DeclRefExpr *DRE) {
  19606. if (!isa<VarDecl>(DRE->getDecl())) {
  19607. emitErrorMsg();
  19608. return false;
  19609. }
  19610. assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
  19611. RelevantExpr = DRE;
  19612. // Record the component.
  19613. Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous);
  19614. return true;
  19615. }
  19616. bool VisitMemberExpr(MemberExpr *ME) {
  19617. Expr *E = ME;
  19618. Expr *BaseE = ME->getBase()->IgnoreParenCasts();
  19619. if (isa<CXXThisExpr>(BaseE)) {
  19620. assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
  19621. // We found a base expression: this->Val.
  19622. RelevantExpr = ME;
  19623. } else {
  19624. E = BaseE;
  19625. }
  19626. if (!isa<FieldDecl>(ME->getMemberDecl())) {
  19627. if (!NoDiagnose) {
  19628. SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
  19629. << ME->getSourceRange();
  19630. return false;
  19631. }
  19632. if (RelevantExpr)
  19633. return false;
  19634. return Visit(E);
  19635. }
  19636. auto *FD = cast<FieldDecl>(ME->getMemberDecl());
  19637. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
  19638. // A bit-field cannot appear in a map clause.
  19639. //
  19640. if (FD->isBitField()) {
  19641. if (!NoDiagnose) {
  19642. SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
  19643. << ME->getSourceRange() << getOpenMPClauseName(CKind);
  19644. return false;
  19645. }
  19646. if (RelevantExpr)
  19647. return false;
  19648. return Visit(E);
  19649. }
  19650. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  19651. // If the type of a list item is a reference to a type T then the type
  19652. // will be considered to be T for all purposes of this clause.
  19653. QualType CurType = BaseE->getType().getNonReferenceType();
  19654. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
  19655. // A list item cannot be a variable that is a member of a structure with
  19656. // a union type.
  19657. //
  19658. if (CurType->isUnionType()) {
  19659. if (!NoDiagnose) {
  19660. SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
  19661. << ME->getSourceRange();
  19662. return false;
  19663. }
  19664. return RelevantExpr || Visit(E);
  19665. }
  19666. // If we got a member expression, we should not expect any array section
  19667. // before that:
  19668. //
  19669. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
  19670. // If a list item is an element of a structure, only the rightmost symbol
  19671. // of the variable reference can be an array section.
  19672. //
  19673. AllowUnitySizeArraySection = false;
  19674. AllowWholeSizeArraySection = false;
  19675. // Record the component.
  19676. Components.emplace_back(ME, FD, IsNonContiguous);
  19677. return RelevantExpr || Visit(E);
  19678. }
  19679. bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) {
  19680. Expr *E = AE->getBase()->IgnoreParenImpCasts();
  19681. if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
  19682. if (!NoDiagnose) {
  19683. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  19684. << 0 << AE->getSourceRange();
  19685. return false;
  19686. }
  19687. return RelevantExpr || Visit(E);
  19688. }
  19689. // If we got an array subscript that express the whole dimension we
  19690. // can have any array expressions before. If it only expressing part of
  19691. // the dimension, we can only have unitary-size array expressions.
  19692. if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE, E->getType()))
  19693. AllowWholeSizeArraySection = false;
  19694. if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) {
  19695. Expr::EvalResult Result;
  19696. if (!AE->getIdx()->isValueDependent() &&
  19697. AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) &&
  19698. !Result.Val.getInt().isZero()) {
  19699. SemaRef.Diag(AE->getIdx()->getExprLoc(),
  19700. diag::err_omp_invalid_map_this_expr);
  19701. SemaRef.Diag(AE->getIdx()->getExprLoc(),
  19702. diag::note_omp_invalid_subscript_on_this_ptr_map);
  19703. }
  19704. assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
  19705. RelevantExpr = TE;
  19706. }
  19707. // Record the component - we don't have any declaration associated.
  19708. Components.emplace_back(AE, nullptr, IsNonContiguous);
  19709. return RelevantExpr || Visit(E);
  19710. }
  19711. bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) {
  19712. // After OMP 5.0 Array section in reduction clause will be implicitly
  19713. // mapped
  19714. assert(!(SemaRef.getLangOpts().OpenMP < 50 && NoDiagnose) &&
  19715. "Array sections cannot be implicitly mapped.");
  19716. Expr *E = OASE->getBase()->IgnoreParenImpCasts();
  19717. QualType CurType =
  19718. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  19719. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  19720. // If the type of a list item is a reference to a type T then the type
  19721. // will be considered to be T for all purposes of this clause.
  19722. if (CurType->isReferenceType())
  19723. CurType = CurType->getPointeeType();
  19724. bool IsPointer = CurType->isAnyPointerType();
  19725. if (!IsPointer && !CurType->isArrayType()) {
  19726. SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
  19727. << 0 << OASE->getSourceRange();
  19728. return false;
  19729. }
  19730. bool NotWhole =
  19731. checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType);
  19732. bool NotUnity =
  19733. checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType);
  19734. if (AllowWholeSizeArraySection) {
  19735. // Any array section is currently allowed. Allowing a whole size array
  19736. // section implies allowing a unity array section as well.
  19737. //
  19738. // If this array section refers to the whole dimension we can still
  19739. // accept other array sections before this one, except if the base is a
  19740. // pointer. Otherwise, only unitary sections are accepted.
  19741. if (NotWhole || IsPointer)
  19742. AllowWholeSizeArraySection = false;
  19743. } else if (DKind == OMPD_target_update &&
  19744. SemaRef.getLangOpts().OpenMP >= 50) {
  19745. if (IsPointer && !AllowAnotherPtr)
  19746. SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined)
  19747. << /*array of unknown bound */ 1;
  19748. else
  19749. IsNonContiguous = true;
  19750. } else if (AllowUnitySizeArraySection && NotUnity) {
  19751. // A unity or whole array section is not allowed and that is not
  19752. // compatible with the properties of the current array section.
  19753. if (NoDiagnose)
  19754. return false;
  19755. SemaRef.Diag(ELoc,
  19756. diag::err_array_section_does_not_specify_contiguous_storage)
  19757. << OASE->getSourceRange();
  19758. return false;
  19759. }
  19760. if (IsPointer)
  19761. AllowAnotherPtr = false;
  19762. if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
  19763. Expr::EvalResult ResultR;
  19764. Expr::EvalResult ResultL;
  19765. if (!OASE->getLength()->isValueDependent() &&
  19766. OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) &&
  19767. !ResultR.Val.getInt().isOne()) {
  19768. SemaRef.Diag(OASE->getLength()->getExprLoc(),
  19769. diag::err_omp_invalid_map_this_expr);
  19770. SemaRef.Diag(OASE->getLength()->getExprLoc(),
  19771. diag::note_omp_invalid_length_on_this_ptr_mapping);
  19772. }
  19773. if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() &&
  19774. OASE->getLowerBound()->EvaluateAsInt(ResultL,
  19775. SemaRef.getASTContext()) &&
  19776. !ResultL.Val.getInt().isZero()) {
  19777. SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
  19778. diag::err_omp_invalid_map_this_expr);
  19779. SemaRef.Diag(OASE->getLowerBound()->getExprLoc(),
  19780. diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
  19781. }
  19782. assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
  19783. RelevantExpr = TE;
  19784. }
  19785. // Record the component - we don't have any declaration associated.
  19786. Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false);
  19787. return RelevantExpr || Visit(E);
  19788. }
  19789. bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
  19790. Expr *Base = E->getBase();
  19791. // Record the component - we don't have any declaration associated.
  19792. Components.emplace_back(E, nullptr, IsNonContiguous);
  19793. return Visit(Base->IgnoreParenImpCasts());
  19794. }
  19795. bool VisitUnaryOperator(UnaryOperator *UO) {
  19796. if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() ||
  19797. UO->getOpcode() != UO_Deref) {
  19798. emitErrorMsg();
  19799. return false;
  19800. }
  19801. if (!RelevantExpr) {
  19802. // Record the component if haven't found base decl.
  19803. Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false);
  19804. }
  19805. return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts());
  19806. }
  19807. bool VisitBinaryOperator(BinaryOperator *BO) {
  19808. if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) {
  19809. emitErrorMsg();
  19810. return false;
  19811. }
  19812. // Pointer arithmetic is the only thing we expect to happen here so after we
  19813. // make sure the binary operator is a pointer type, the only thing we need
  19814. // to do is to visit the subtree that has the same type as root (so that we
  19815. // know the other subtree is just an offset)
  19816. Expr *LE = BO->getLHS()->IgnoreParenImpCasts();
  19817. Expr *RE = BO->getRHS()->IgnoreParenImpCasts();
  19818. Components.emplace_back(BO, nullptr, false);
  19819. assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() ||
  19820. RE->getType().getTypePtr() == BO->getType().getTypePtr()) &&
  19821. "Either LHS or RHS have base decl inside");
  19822. if (BO->getType().getTypePtr() == LE->getType().getTypePtr())
  19823. return RelevantExpr || Visit(LE);
  19824. return RelevantExpr || Visit(RE);
  19825. }
  19826. bool VisitCXXThisExpr(CXXThisExpr *CTE) {
  19827. assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
  19828. RelevantExpr = CTE;
  19829. Components.emplace_back(CTE, nullptr, IsNonContiguous);
  19830. return true;
  19831. }
  19832. bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) {
  19833. assert(!RelevantExpr && "RelevantExpr is expected to be nullptr");
  19834. Components.emplace_back(COCE, nullptr, IsNonContiguous);
  19835. return true;
  19836. }
  19837. bool VisitOpaqueValueExpr(OpaqueValueExpr *E) {
  19838. Expr *Source = E->getSourceExpr();
  19839. if (!Source) {
  19840. emitErrorMsg();
  19841. return false;
  19842. }
  19843. return Visit(Source);
  19844. }
  19845. bool VisitStmt(Stmt *) {
  19846. emitErrorMsg();
  19847. return false;
  19848. }
  19849. const Expr *getFoundBase() const { return RelevantExpr; }
  19850. explicit MapBaseChecker(
  19851. Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind,
  19852. OMPClauseMappableExprCommon::MappableExprComponentList &Components,
  19853. bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange)
  19854. : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components),
  19855. NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {}
  19856. };
  19857. } // namespace
  19858. /// Return the expression of the base of the mappable expression or null if it
  19859. /// cannot be determined and do all the necessary checks to see if the
  19860. /// expression is valid as a standalone mappable expression. In the process,
  19861. /// record all the components of the expression.
  19862. static const Expr *checkMapClauseExpressionBase(
  19863. Sema &SemaRef, Expr *E,
  19864. OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
  19865. OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) {
  19866. SourceLocation ELoc = E->getExprLoc();
  19867. SourceRange ERange = E->getSourceRange();
  19868. MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc,
  19869. ERange);
  19870. if (Checker.Visit(E->IgnoreParens())) {
  19871. // Check if the highest dimension array section has length specified
  19872. if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() &&
  19873. (CKind == OMPC_to || CKind == OMPC_from)) {
  19874. auto CI = CurComponents.rbegin();
  19875. auto CE = CurComponents.rend();
  19876. for (; CI != CE; ++CI) {
  19877. const auto *OASE =
  19878. dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression());
  19879. if (!OASE)
  19880. continue;
  19881. if (OASE && OASE->getLength())
  19882. break;
  19883. SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length)
  19884. << ERange;
  19885. }
  19886. }
  19887. return Checker.getFoundBase();
  19888. }
  19889. return nullptr;
  19890. }
  19891. // Return true if expression E associated with value VD has conflicts with other
  19892. // map information.
  19893. static bool checkMapConflicts(
  19894. Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
  19895. bool CurrentRegionOnly,
  19896. OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
  19897. OpenMPClauseKind CKind) {
  19898. assert(VD && E);
  19899. SourceLocation ELoc = E->getExprLoc();
  19900. SourceRange ERange = E->getSourceRange();
  19901. // In order to easily check the conflicts we need to match each component of
  19902. // the expression under test with the components of the expressions that are
  19903. // already in the stack.
  19904. assert(!CurComponents.empty() && "Map clause expression with no components!");
  19905. assert(CurComponents.back().getAssociatedDeclaration() == VD &&
  19906. "Map clause expression with unexpected base!");
  19907. // Variables to help detecting enclosing problems in data environment nests.
  19908. bool IsEnclosedByDataEnvironmentExpr = false;
  19909. const Expr *EnclosingExpr = nullptr;
  19910. bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
  19911. VD, CurrentRegionOnly,
  19912. [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
  19913. ERange, CKind, &EnclosingExpr,
  19914. CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
  19915. StackComponents,
  19916. OpenMPClauseKind Kind) {
  19917. if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50)
  19918. return false;
  19919. assert(!StackComponents.empty() &&
  19920. "Map clause expression with no components!");
  19921. assert(StackComponents.back().getAssociatedDeclaration() == VD &&
  19922. "Map clause expression with unexpected base!");
  19923. (void)VD;
  19924. // The whole expression in the stack.
  19925. const Expr *RE = StackComponents.front().getAssociatedExpression();
  19926. // Expressions must start from the same base. Here we detect at which
  19927. // point both expressions diverge from each other and see if we can
  19928. // detect if the memory referred to both expressions is contiguous and
  19929. // do not overlap.
  19930. auto CI = CurComponents.rbegin();
  19931. auto CE = CurComponents.rend();
  19932. auto SI = StackComponents.rbegin();
  19933. auto SE = StackComponents.rend();
  19934. for (; CI != CE && SI != SE; ++CI, ++SI) {
  19935. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
  19936. // At most one list item can be an array item derived from a given
  19937. // variable in map clauses of the same construct.
  19938. if (CurrentRegionOnly &&
  19939. (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
  19940. isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) ||
  19941. isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) &&
  19942. (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
  19943. isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) ||
  19944. isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) {
  19945. SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
  19946. diag::err_omp_multiple_array_items_in_map_clause)
  19947. << CI->getAssociatedExpression()->getSourceRange();
  19948. SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
  19949. diag::note_used_here)
  19950. << SI->getAssociatedExpression()->getSourceRange();
  19951. return true;
  19952. }
  19953. // Do both expressions have the same kind?
  19954. if (CI->getAssociatedExpression()->getStmtClass() !=
  19955. SI->getAssociatedExpression()->getStmtClass())
  19956. break;
  19957. // Are we dealing with different variables/fields?
  19958. if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
  19959. break;
  19960. }
  19961. // Check if the extra components of the expressions in the enclosing
  19962. // data environment are redundant for the current base declaration.
  19963. // If they are, the maps completely overlap, which is legal.
  19964. for (; SI != SE; ++SI) {
  19965. QualType Type;
  19966. if (const auto *ASE =
  19967. dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
  19968. Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
  19969. } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
  19970. SI->getAssociatedExpression())) {
  19971. const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
  19972. Type =
  19973. OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
  19974. } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>(
  19975. SI->getAssociatedExpression())) {
  19976. Type = OASE->getBase()->getType()->getPointeeType();
  19977. }
  19978. if (Type.isNull() || Type->isAnyPointerType() ||
  19979. checkArrayExpressionDoesNotReferToWholeSize(
  19980. SemaRef, SI->getAssociatedExpression(), Type))
  19981. break;
  19982. }
  19983. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  19984. // List items of map clauses in the same construct must not share
  19985. // original storage.
  19986. //
  19987. // If the expressions are exactly the same or one is a subset of the
  19988. // other, it means they are sharing storage.
  19989. if (CI == CE && SI == SE) {
  19990. if (CurrentRegionOnly) {
  19991. if (CKind == OMPC_map) {
  19992. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  19993. } else {
  19994. assert(CKind == OMPC_to || CKind == OMPC_from);
  19995. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  19996. << ERange;
  19997. }
  19998. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  19999. << RE->getSourceRange();
  20000. return true;
  20001. }
  20002. // If we find the same expression in the enclosing data environment,
  20003. // that is legal.
  20004. IsEnclosedByDataEnvironmentExpr = true;
  20005. return false;
  20006. }
  20007. QualType DerivedType =
  20008. std::prev(CI)->getAssociatedDeclaration()->getType();
  20009. SourceLocation DerivedLoc =
  20010. std::prev(CI)->getAssociatedExpression()->getExprLoc();
  20011. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  20012. // If the type of a list item is a reference to a type T then the type
  20013. // will be considered to be T for all purposes of this clause.
  20014. DerivedType = DerivedType.getNonReferenceType();
  20015. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
  20016. // A variable for which the type is pointer and an array section
  20017. // derived from that variable must not appear as list items of map
  20018. // clauses of the same construct.
  20019. //
  20020. // Also, cover one of the cases in:
  20021. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  20022. // If any part of the original storage of a list item has corresponding
  20023. // storage in the device data environment, all of the original storage
  20024. // must have corresponding storage in the device data environment.
  20025. //
  20026. if (DerivedType->isAnyPointerType()) {
  20027. if (CI == CE || SI == SE) {
  20028. SemaRef.Diag(
  20029. DerivedLoc,
  20030. diag::err_omp_pointer_mapped_along_with_derived_section)
  20031. << DerivedLoc;
  20032. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  20033. << RE->getSourceRange();
  20034. return true;
  20035. }
  20036. if (CI->getAssociatedExpression()->getStmtClass() !=
  20037. SI->getAssociatedExpression()->getStmtClass() ||
  20038. CI->getAssociatedDeclaration()->getCanonicalDecl() ==
  20039. SI->getAssociatedDeclaration()->getCanonicalDecl()) {
  20040. assert(CI != CE && SI != SE);
  20041. SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
  20042. << DerivedLoc;
  20043. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  20044. << RE->getSourceRange();
  20045. return true;
  20046. }
  20047. }
  20048. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
  20049. // List items of map clauses in the same construct must not share
  20050. // original storage.
  20051. //
  20052. // An expression is a subset of the other.
  20053. if (CurrentRegionOnly && (CI == CE || SI == SE)) {
  20054. if (CKind == OMPC_map) {
  20055. if (CI != CE || SI != SE) {
  20056. // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
  20057. // a pointer.
  20058. auto Begin =
  20059. CI != CE ? CurComponents.begin() : StackComponents.begin();
  20060. auto End = CI != CE ? CurComponents.end() : StackComponents.end();
  20061. auto It = Begin;
  20062. while (It != End && !It->getAssociatedDeclaration())
  20063. std::advance(It, 1);
  20064. assert(It != End &&
  20065. "Expected at least one component with the declaration.");
  20066. if (It != Begin && It->getAssociatedDeclaration()
  20067. ->getType()
  20068. .getCanonicalType()
  20069. ->isAnyPointerType()) {
  20070. IsEnclosedByDataEnvironmentExpr = false;
  20071. EnclosingExpr = nullptr;
  20072. return false;
  20073. }
  20074. }
  20075. SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
  20076. } else {
  20077. assert(CKind == OMPC_to || CKind == OMPC_from);
  20078. SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
  20079. << ERange;
  20080. }
  20081. SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
  20082. << RE->getSourceRange();
  20083. return true;
  20084. }
  20085. // The current expression uses the same base as other expression in the
  20086. // data environment but does not contain it completely.
  20087. if (!CurrentRegionOnly && SI != SE)
  20088. EnclosingExpr = RE;
  20089. // The current expression is a subset of the expression in the data
  20090. // environment.
  20091. IsEnclosedByDataEnvironmentExpr |=
  20092. (!CurrentRegionOnly && CI != CE && SI == SE);
  20093. return false;
  20094. });
  20095. if (CurrentRegionOnly)
  20096. return FoundError;
  20097. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
  20098. // If any part of the original storage of a list item has corresponding
  20099. // storage in the device data environment, all of the original storage must
  20100. // have corresponding storage in the device data environment.
  20101. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
  20102. // If a list item is an element of a structure, and a different element of
  20103. // the structure has a corresponding list item in the device data environment
  20104. // prior to a task encountering the construct associated with the map clause,
  20105. // then the list item must also have a corresponding list item in the device
  20106. // data environment prior to the task encountering the construct.
  20107. //
  20108. if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
  20109. SemaRef.Diag(ELoc,
  20110. diag::err_omp_original_storage_is_shared_and_does_not_contain)
  20111. << ERange;
  20112. SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
  20113. << EnclosingExpr->getSourceRange();
  20114. return true;
  20115. }
  20116. return FoundError;
  20117. }
  20118. // Look up the user-defined mapper given the mapper name and mapped type, and
  20119. // build a reference to it.
  20120. static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
  20121. CXXScopeSpec &MapperIdScopeSpec,
  20122. const DeclarationNameInfo &MapperId,
  20123. QualType Type,
  20124. Expr *UnresolvedMapper) {
  20125. if (MapperIdScopeSpec.isInvalid())
  20126. return ExprError();
  20127. // Get the actual type for the array type.
  20128. if (Type->isArrayType()) {
  20129. assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
  20130. Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
  20131. }
  20132. // Find all user-defined mappers with the given MapperId.
  20133. SmallVector<UnresolvedSet<8>, 4> Lookups;
  20134. LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
  20135. Lookup.suppressDiagnostics();
  20136. if (S) {
  20137. while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
  20138. NamedDecl *D = Lookup.getRepresentativeDecl();
  20139. while (S && !S->isDeclScope(D))
  20140. S = S->getParent();
  20141. if (S)
  20142. S = S->getParent();
  20143. Lookups.emplace_back();
  20144. Lookups.back().append(Lookup.begin(), Lookup.end());
  20145. Lookup.clear();
  20146. }
  20147. } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
  20148. // Extract the user-defined mappers with the given MapperId.
  20149. Lookups.push_back(UnresolvedSet<8>());
  20150. for (NamedDecl *D : ULE->decls()) {
  20151. auto *DMD = cast<OMPDeclareMapperDecl>(D);
  20152. assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
  20153. Lookups.back().addDecl(DMD);
  20154. }
  20155. }
  20156. // Defer the lookup for dependent types. The results will be passed through
  20157. // UnresolvedMapper on instantiation.
  20158. if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
  20159. Type->isInstantiationDependentType() ||
  20160. Type->containsUnexpandedParameterPack() ||
  20161. filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
  20162. return !D->isInvalidDecl() &&
  20163. (D->getType()->isDependentType() ||
  20164. D->getType()->isInstantiationDependentType() ||
  20165. D->getType()->containsUnexpandedParameterPack());
  20166. })) {
  20167. UnresolvedSet<8> URS;
  20168. for (const UnresolvedSet<8> &Set : Lookups) {
  20169. if (Set.empty())
  20170. continue;
  20171. URS.append(Set.begin(), Set.end());
  20172. }
  20173. return UnresolvedLookupExpr::Create(
  20174. SemaRef.Context, /*NamingClass=*/nullptr,
  20175. MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
  20176. /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
  20177. }
  20178. SourceLocation Loc = MapperId.getLoc();
  20179. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  20180. // The type must be of struct, union or class type in C and C++
  20181. if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
  20182. (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
  20183. SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
  20184. return ExprError();
  20185. }
  20186. // Perform argument dependent lookup.
  20187. if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
  20188. argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
  20189. // Return the first user-defined mapper with the desired type.
  20190. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  20191. Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
  20192. if (!D->isInvalidDecl() &&
  20193. SemaRef.Context.hasSameType(D->getType(), Type))
  20194. return D;
  20195. return nullptr;
  20196. }))
  20197. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  20198. // Find the first user-defined mapper with a type derived from the desired
  20199. // type.
  20200. if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
  20201. Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
  20202. if (!D->isInvalidDecl() &&
  20203. SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
  20204. !Type.isMoreQualifiedThan(D->getType()))
  20205. return D;
  20206. return nullptr;
  20207. })) {
  20208. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
  20209. /*DetectVirtual=*/false);
  20210. if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
  20211. if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
  20212. VD->getType().getUnqualifiedType()))) {
  20213. if (SemaRef.CheckBaseClassAccess(
  20214. Loc, VD->getType(), Type, Paths.front(),
  20215. /*DiagID=*/0) != Sema::AR_inaccessible) {
  20216. return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
  20217. }
  20218. }
  20219. }
  20220. }
  20221. // Report error if a mapper is specified, but cannot be found.
  20222. if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
  20223. SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
  20224. << Type << MapperId.getName();
  20225. return ExprError();
  20226. }
  20227. return ExprEmpty();
  20228. }
  20229. namespace {
  20230. // Utility struct that gathers all the related lists associated with a mappable
  20231. // expression.
  20232. struct MappableVarListInfo {
  20233. // The list of expressions.
  20234. ArrayRef<Expr *> VarList;
  20235. // The list of processed expressions.
  20236. SmallVector<Expr *, 16> ProcessedVarList;
  20237. // The mappble components for each expression.
  20238. OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
  20239. // The base declaration of the variable.
  20240. SmallVector<ValueDecl *, 16> VarBaseDeclarations;
  20241. // The reference to the user-defined mapper associated with every expression.
  20242. SmallVector<Expr *, 16> UDMapperList;
  20243. MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
  20244. // We have a list of components and base declarations for each entry in the
  20245. // variable list.
  20246. VarComponents.reserve(VarList.size());
  20247. VarBaseDeclarations.reserve(VarList.size());
  20248. }
  20249. };
  20250. } // namespace
  20251. // Check the validity of the provided variable list for the provided clause kind
  20252. // \a CKind. In the check process the valid expressions, mappable expression
  20253. // components, variables, and user-defined mappers are extracted and used to
  20254. // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
  20255. // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
  20256. // and \a MapperId are expected to be valid if the clause kind is 'map'.
  20257. static void checkMappableExpressionList(
  20258. Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
  20259. MappableVarListInfo &MVLI, SourceLocation StartLoc,
  20260. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
  20261. ArrayRef<Expr *> UnresolvedMappers,
  20262. OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
  20263. ArrayRef<OpenMPMapModifierKind> Modifiers = std::nullopt,
  20264. bool IsMapTypeImplicit = false, bool NoDiagnose = false) {
  20265. // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
  20266. assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
  20267. "Unexpected clause kind with mappable expressions!");
  20268. // If the identifier of user-defined mapper is not specified, it is "default".
  20269. // We do not change the actual name in this clause to distinguish whether a
  20270. // mapper is specified explicitly, i.e., it is not explicitly specified when
  20271. // MapperId.getName() is empty.
  20272. if (!MapperId.getName() || MapperId.getName().isEmpty()) {
  20273. auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
  20274. MapperId.setName(DeclNames.getIdentifier(
  20275. &SemaRef.getASTContext().Idents.get("default")));
  20276. MapperId.setLoc(StartLoc);
  20277. }
  20278. // Iterators to find the current unresolved mapper expression.
  20279. auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
  20280. bool UpdateUMIt = false;
  20281. Expr *UnresolvedMapper = nullptr;
  20282. bool HasHoldModifier =
  20283. llvm::is_contained(Modifiers, OMPC_MAP_MODIFIER_ompx_hold);
  20284. // Keep track of the mappable components and base declarations in this clause.
  20285. // Each entry in the list is going to have a list of components associated. We
  20286. // record each set of the components so that we can build the clause later on.
  20287. // In the end we should have the same amount of declarations and component
  20288. // lists.
  20289. for (Expr *RE : MVLI.VarList) {
  20290. assert(RE && "Null expr in omp to/from/map clause");
  20291. SourceLocation ELoc = RE->getExprLoc();
  20292. // Find the current unresolved mapper expression.
  20293. if (UpdateUMIt && UMIt != UMEnd) {
  20294. UMIt++;
  20295. assert(
  20296. UMIt != UMEnd &&
  20297. "Expect the size of UnresolvedMappers to match with that of VarList");
  20298. }
  20299. UpdateUMIt = true;
  20300. if (UMIt != UMEnd)
  20301. UnresolvedMapper = *UMIt;
  20302. const Expr *VE = RE->IgnoreParenLValueCasts();
  20303. if (VE->isValueDependent() || VE->isTypeDependent() ||
  20304. VE->isInstantiationDependent() ||
  20305. VE->containsUnexpandedParameterPack()) {
  20306. // Try to find the associated user-defined mapper.
  20307. ExprResult ER = buildUserDefinedMapperRef(
  20308. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  20309. VE->getType().getCanonicalType(), UnresolvedMapper);
  20310. if (ER.isInvalid())
  20311. continue;
  20312. MVLI.UDMapperList.push_back(ER.get());
  20313. // We can only analyze this information once the missing information is
  20314. // resolved.
  20315. MVLI.ProcessedVarList.push_back(RE);
  20316. continue;
  20317. }
  20318. Expr *SimpleExpr = RE->IgnoreParenCasts();
  20319. if (!RE->isLValue()) {
  20320. if (SemaRef.getLangOpts().OpenMP < 50) {
  20321. SemaRef.Diag(
  20322. ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
  20323. << RE->getSourceRange();
  20324. } else {
  20325. SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses)
  20326. << getOpenMPClauseName(CKind) << RE->getSourceRange();
  20327. }
  20328. continue;
  20329. }
  20330. OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
  20331. ValueDecl *CurDeclaration = nullptr;
  20332. // Obtain the array or member expression bases if required. Also, fill the
  20333. // components array with all the components identified in the process.
  20334. const Expr *BE =
  20335. checkMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind,
  20336. DSAS->getCurrentDirective(), NoDiagnose);
  20337. if (!BE)
  20338. continue;
  20339. assert(!CurComponents.empty() &&
  20340. "Invalid mappable expression information.");
  20341. if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
  20342. // Add store "this" pointer to class in DSAStackTy for future checking
  20343. DSAS->addMappedClassesQualTypes(TE->getType());
  20344. // Try to find the associated user-defined mapper.
  20345. ExprResult ER = buildUserDefinedMapperRef(
  20346. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  20347. VE->getType().getCanonicalType(), UnresolvedMapper);
  20348. if (ER.isInvalid())
  20349. continue;
  20350. MVLI.UDMapperList.push_back(ER.get());
  20351. // Skip restriction checking for variable or field declarations
  20352. MVLI.ProcessedVarList.push_back(RE);
  20353. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  20354. MVLI.VarComponents.back().append(CurComponents.begin(),
  20355. CurComponents.end());
  20356. MVLI.VarBaseDeclarations.push_back(nullptr);
  20357. continue;
  20358. }
  20359. // For the following checks, we rely on the base declaration which is
  20360. // expected to be associated with the last component. The declaration is
  20361. // expected to be a variable or a field (if 'this' is being mapped).
  20362. CurDeclaration = CurComponents.back().getAssociatedDeclaration();
  20363. assert(CurDeclaration && "Null decl on map clause.");
  20364. assert(
  20365. CurDeclaration->isCanonicalDecl() &&
  20366. "Expecting components to have associated only canonical declarations.");
  20367. auto *VD = dyn_cast<VarDecl>(CurDeclaration);
  20368. const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
  20369. assert((VD || FD) && "Only variables or fields are expected here!");
  20370. (void)FD;
  20371. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
  20372. // threadprivate variables cannot appear in a map clause.
  20373. // OpenMP 4.5 [2.10.5, target update Construct]
  20374. // threadprivate variables cannot appear in a from clause.
  20375. if (VD && DSAS->isThreadPrivate(VD)) {
  20376. if (NoDiagnose)
  20377. continue;
  20378. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  20379. SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
  20380. << getOpenMPClauseName(CKind);
  20381. reportOriginalDsa(SemaRef, DSAS, VD, DVar);
  20382. continue;
  20383. }
  20384. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  20385. // A list item cannot appear in both a map clause and a data-sharing
  20386. // attribute clause on the same construct.
  20387. // Check conflicts with other map clause expressions. We check the conflicts
  20388. // with the current construct separately from the enclosing data
  20389. // environment, because the restrictions are different. We only have to
  20390. // check conflicts across regions for the map clauses.
  20391. if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  20392. /*CurrentRegionOnly=*/true, CurComponents, CKind))
  20393. break;
  20394. if (CKind == OMPC_map &&
  20395. (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) &&
  20396. checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
  20397. /*CurrentRegionOnly=*/false, CurComponents, CKind))
  20398. break;
  20399. // OpenMP 4.5 [2.10.5, target update Construct]
  20400. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
  20401. // If the type of a list item is a reference to a type T then the type will
  20402. // be considered to be T for all purposes of this clause.
  20403. auto I = llvm::find_if(
  20404. CurComponents,
  20405. [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
  20406. return MC.getAssociatedDeclaration();
  20407. });
  20408. assert(I != CurComponents.end() && "Null decl on map clause.");
  20409. (void)I;
  20410. QualType Type;
  20411. auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
  20412. auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
  20413. auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens());
  20414. if (ASE) {
  20415. Type = ASE->getType().getNonReferenceType();
  20416. } else if (OASE) {
  20417. QualType BaseType =
  20418. OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
  20419. if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
  20420. Type = ATy->getElementType();
  20421. else
  20422. Type = BaseType->getPointeeType();
  20423. Type = Type.getNonReferenceType();
  20424. } else if (OAShE) {
  20425. Type = OAShE->getBase()->getType()->getPointeeType();
  20426. } else {
  20427. Type = VE->getType();
  20428. }
  20429. // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
  20430. // A list item in a to or from clause must have a mappable type.
  20431. // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
  20432. // A list item must have a mappable type.
  20433. if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
  20434. DSAS, Type, /*FullCheck=*/true))
  20435. continue;
  20436. if (CKind == OMPC_map) {
  20437. // target enter data
  20438. // OpenMP [2.10.2, Restrictions, p. 99]
  20439. // A map-type must be specified in all map clauses and must be either
  20440. // to or alloc. Starting with OpenMP 5.2 the default map type is `to` if
  20441. // no map type is present.
  20442. OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
  20443. if (DKind == OMPD_target_enter_data &&
  20444. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc ||
  20445. SemaRef.getLangOpts().OpenMP >= 52)) {
  20446. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  20447. << (IsMapTypeImplicit ? 1 : 0)
  20448. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  20449. << getOpenMPDirectiveName(DKind);
  20450. continue;
  20451. }
  20452. // target exit_data
  20453. // OpenMP [2.10.3, Restrictions, p. 102]
  20454. // A map-type must be specified in all map clauses and must be either
  20455. // from, release, or delete. Starting with OpenMP 5.2 the default map
  20456. // type is `from` if no map type is present.
  20457. if (DKind == OMPD_target_exit_data &&
  20458. !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
  20459. MapType == OMPC_MAP_delete || SemaRef.getLangOpts().OpenMP >= 52)) {
  20460. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  20461. << (IsMapTypeImplicit ? 1 : 0)
  20462. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  20463. << getOpenMPDirectiveName(DKind);
  20464. continue;
  20465. }
  20466. // The 'ompx_hold' modifier is specifically intended to be used on a
  20467. // 'target' or 'target data' directive to prevent data from being unmapped
  20468. // during the associated statement. It is not permitted on a 'target
  20469. // enter data' or 'target exit data' directive, which have no associated
  20470. // statement.
  20471. if ((DKind == OMPD_target_enter_data || DKind == OMPD_target_exit_data) &&
  20472. HasHoldModifier) {
  20473. SemaRef.Diag(StartLoc,
  20474. diag::err_omp_invalid_map_type_modifier_for_directive)
  20475. << getOpenMPSimpleClauseTypeName(OMPC_map,
  20476. OMPC_MAP_MODIFIER_ompx_hold)
  20477. << getOpenMPDirectiveName(DKind);
  20478. continue;
  20479. }
  20480. // target, target data
  20481. // OpenMP 5.0 [2.12.2, Restrictions, p. 163]
  20482. // OpenMP 5.0 [2.12.5, Restrictions, p. 174]
  20483. // A map-type in a map clause must be to, from, tofrom or alloc
  20484. if ((DKind == OMPD_target_data ||
  20485. isOpenMPTargetExecutionDirective(DKind)) &&
  20486. !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from ||
  20487. MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) {
  20488. SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
  20489. << (IsMapTypeImplicit ? 1 : 0)
  20490. << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
  20491. << getOpenMPDirectiveName(DKind);
  20492. continue;
  20493. }
  20494. // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
  20495. // A list item cannot appear in both a map clause and a data-sharing
  20496. // attribute clause on the same construct
  20497. //
  20498. // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
  20499. // A list item cannot appear in both a map clause and a data-sharing
  20500. // attribute clause on the same construct unless the construct is a
  20501. // combined construct.
  20502. if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
  20503. isOpenMPTargetExecutionDirective(DKind)) ||
  20504. DKind == OMPD_target)) {
  20505. DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
  20506. if (isOpenMPPrivate(DVar.CKind)) {
  20507. SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  20508. << getOpenMPClauseName(DVar.CKind)
  20509. << getOpenMPClauseName(OMPC_map)
  20510. << getOpenMPDirectiveName(DSAS->getCurrentDirective());
  20511. reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
  20512. continue;
  20513. }
  20514. }
  20515. }
  20516. // Try to find the associated user-defined mapper.
  20517. ExprResult ER = buildUserDefinedMapperRef(
  20518. SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
  20519. Type.getCanonicalType(), UnresolvedMapper);
  20520. if (ER.isInvalid())
  20521. continue;
  20522. MVLI.UDMapperList.push_back(ER.get());
  20523. // Save the current expression.
  20524. MVLI.ProcessedVarList.push_back(RE);
  20525. // Store the components in the stack so that they can be used to check
  20526. // against other clauses later on.
  20527. DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
  20528. /*WhereFoundClauseKind=*/OMPC_map);
  20529. // Save the components and declaration to create the clause. For purposes of
  20530. // the clause creation, any component list that has base 'this' uses
  20531. // null as base declaration.
  20532. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  20533. MVLI.VarComponents.back().append(CurComponents.begin(),
  20534. CurComponents.end());
  20535. MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
  20536. : CurDeclaration);
  20537. }
  20538. }
  20539. OMPClause *Sema::ActOnOpenMPMapClause(
  20540. Expr *IteratorModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
  20541. ArrayRef<SourceLocation> MapTypeModifiersLoc,
  20542. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
  20543. OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
  20544. SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
  20545. const OMPVarListLocTy &Locs, bool NoDiagnose,
  20546. ArrayRef<Expr *> UnresolvedMappers) {
  20547. OpenMPMapModifierKind Modifiers[] = {
  20548. OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
  20549. OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown,
  20550. OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown};
  20551. SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers];
  20552. if (IteratorModifier && !IteratorModifier->getType()->isSpecificBuiltinType(
  20553. BuiltinType::OMPIterator))
  20554. Diag(IteratorModifier->getExprLoc(),
  20555. diag::err_omp_map_modifier_not_iterator);
  20556. // Process map-type-modifiers, flag errors for duplicate modifiers.
  20557. unsigned Count = 0;
  20558. for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
  20559. if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
  20560. llvm::is_contained(Modifiers, MapTypeModifiers[I])) {
  20561. Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
  20562. continue;
  20563. }
  20564. assert(Count < NumberOfOMPMapClauseModifiers &&
  20565. "Modifiers exceed the allowed number of map type modifiers");
  20566. Modifiers[Count] = MapTypeModifiers[I];
  20567. ModifiersLoc[Count] = MapTypeModifiersLoc[I];
  20568. ++Count;
  20569. }
  20570. MappableVarListInfo MVLI(VarList);
  20571. checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
  20572. MapperIdScopeSpec, MapperId, UnresolvedMappers,
  20573. MapType, Modifiers, IsMapTypeImplicit,
  20574. NoDiagnose);
  20575. // We need to produce a map clause even if we don't have variables so that
  20576. // other diagnostics related with non-existing map clauses are accurate.
  20577. return OMPMapClause::Create(
  20578. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  20579. MVLI.VarComponents, MVLI.UDMapperList, IteratorModifier, Modifiers,
  20580. ModifiersLoc, MapperIdScopeSpec.getWithLocInContext(Context), MapperId,
  20581. MapType, IsMapTypeImplicit, MapLoc);
  20582. }
  20583. QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
  20584. TypeResult ParsedType) {
  20585. assert(ParsedType.isUsable());
  20586. QualType ReductionType = GetTypeFromParser(ParsedType.get());
  20587. if (ReductionType.isNull())
  20588. return QualType();
  20589. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
  20590. // A type name in a declare reduction directive cannot be a function type, an
  20591. // array type, a reference type, or a type qualified with const, volatile or
  20592. // restrict.
  20593. if (ReductionType.hasQualifiers()) {
  20594. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
  20595. return QualType();
  20596. }
  20597. if (ReductionType->isFunctionType()) {
  20598. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
  20599. return QualType();
  20600. }
  20601. if (ReductionType->isReferenceType()) {
  20602. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
  20603. return QualType();
  20604. }
  20605. if (ReductionType->isArrayType()) {
  20606. Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
  20607. return QualType();
  20608. }
  20609. return ReductionType;
  20610. }
  20611. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
  20612. Scope *S, DeclContext *DC, DeclarationName Name,
  20613. ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
  20614. AccessSpecifier AS, Decl *PrevDeclInScope) {
  20615. SmallVector<Decl *, 8> Decls;
  20616. Decls.reserve(ReductionTypes.size());
  20617. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
  20618. forRedeclarationInCurContext());
  20619. // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
  20620. // A reduction-identifier may not be re-declared in the current scope for the
  20621. // same type or for a type that is compatible according to the base language
  20622. // rules.
  20623. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  20624. OMPDeclareReductionDecl *PrevDRD = nullptr;
  20625. bool InCompoundScope = true;
  20626. if (S != nullptr) {
  20627. // Find previous declaration with the same name not referenced in other
  20628. // declarations.
  20629. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  20630. InCompoundScope =
  20631. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  20632. LookupName(Lookup, S);
  20633. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  20634. /*AllowInlineNamespace=*/false);
  20635. llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
  20636. LookupResult::Filter Filter = Lookup.makeFilter();
  20637. while (Filter.hasNext()) {
  20638. auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
  20639. if (InCompoundScope) {
  20640. auto I = UsedAsPrevious.find(PrevDecl);
  20641. if (I == UsedAsPrevious.end())
  20642. UsedAsPrevious[PrevDecl] = false;
  20643. if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
  20644. UsedAsPrevious[D] = true;
  20645. }
  20646. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  20647. PrevDecl->getLocation();
  20648. }
  20649. Filter.done();
  20650. if (InCompoundScope) {
  20651. for (const auto &PrevData : UsedAsPrevious) {
  20652. if (!PrevData.second) {
  20653. PrevDRD = PrevData.first;
  20654. break;
  20655. }
  20656. }
  20657. }
  20658. } else if (PrevDeclInScope != nullptr) {
  20659. auto *PrevDRDInScope = PrevDRD =
  20660. cast<OMPDeclareReductionDecl>(PrevDeclInScope);
  20661. do {
  20662. PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
  20663. PrevDRDInScope->getLocation();
  20664. PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
  20665. } while (PrevDRDInScope != nullptr);
  20666. }
  20667. for (const auto &TyData : ReductionTypes) {
  20668. const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
  20669. bool Invalid = false;
  20670. if (I != PreviousRedeclTypes.end()) {
  20671. Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
  20672. << TyData.first;
  20673. Diag(I->second, diag::note_previous_definition);
  20674. Invalid = true;
  20675. }
  20676. PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
  20677. auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
  20678. Name, TyData.first, PrevDRD);
  20679. DC->addDecl(DRD);
  20680. DRD->setAccess(AS);
  20681. Decls.push_back(DRD);
  20682. if (Invalid)
  20683. DRD->setInvalidDecl();
  20684. else
  20685. PrevDRD = DRD;
  20686. }
  20687. return DeclGroupPtrTy::make(
  20688. DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
  20689. }
  20690. void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
  20691. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  20692. // Enter new function scope.
  20693. PushFunctionScope();
  20694. setFunctionHasBranchProtectedScope();
  20695. getCurFunction()->setHasOMPDeclareReductionCombiner();
  20696. if (S != nullptr)
  20697. PushDeclContext(S, DRD);
  20698. else
  20699. CurContext = DRD;
  20700. PushExpressionEvaluationContext(
  20701. ExpressionEvaluationContext::PotentiallyEvaluated);
  20702. QualType ReductionType = DRD->getType();
  20703. // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
  20704. // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
  20705. // uses semantics of argument handles by value, but it should be passed by
  20706. // reference. C lang does not support references, so pass all parameters as
  20707. // pointers.
  20708. // Create 'T omp_in;' variable.
  20709. VarDecl *OmpInParm =
  20710. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
  20711. // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
  20712. // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
  20713. // uses semantics of argument handles by value, but it should be passed by
  20714. // reference. C lang does not support references, so pass all parameters as
  20715. // pointers.
  20716. // Create 'T omp_out;' variable.
  20717. VarDecl *OmpOutParm =
  20718. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
  20719. if (S != nullptr) {
  20720. PushOnScopeChains(OmpInParm, S);
  20721. PushOnScopeChains(OmpOutParm, S);
  20722. } else {
  20723. DRD->addDecl(OmpInParm);
  20724. DRD->addDecl(OmpOutParm);
  20725. }
  20726. Expr *InE =
  20727. ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
  20728. Expr *OutE =
  20729. ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
  20730. DRD->setCombinerData(InE, OutE);
  20731. }
  20732. void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
  20733. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  20734. DiscardCleanupsInEvaluationContext();
  20735. PopExpressionEvaluationContext();
  20736. PopDeclContext();
  20737. PopFunctionScopeInfo();
  20738. if (Combiner != nullptr)
  20739. DRD->setCombiner(Combiner);
  20740. else
  20741. DRD->setInvalidDecl();
  20742. }
  20743. VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
  20744. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  20745. // Enter new function scope.
  20746. PushFunctionScope();
  20747. setFunctionHasBranchProtectedScope();
  20748. if (S != nullptr)
  20749. PushDeclContext(S, DRD);
  20750. else
  20751. CurContext = DRD;
  20752. PushExpressionEvaluationContext(
  20753. ExpressionEvaluationContext::PotentiallyEvaluated);
  20754. QualType ReductionType = DRD->getType();
  20755. // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
  20756. // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
  20757. // uses semantics of argument handles by value, but it should be passed by
  20758. // reference. C lang does not support references, so pass all parameters as
  20759. // pointers.
  20760. // Create 'T omp_priv;' variable.
  20761. VarDecl *OmpPrivParm =
  20762. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
  20763. // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
  20764. // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
  20765. // uses semantics of argument handles by value, but it should be passed by
  20766. // reference. C lang does not support references, so pass all parameters as
  20767. // pointers.
  20768. // Create 'T omp_orig;' variable.
  20769. VarDecl *OmpOrigParm =
  20770. buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
  20771. if (S != nullptr) {
  20772. PushOnScopeChains(OmpPrivParm, S);
  20773. PushOnScopeChains(OmpOrigParm, S);
  20774. } else {
  20775. DRD->addDecl(OmpPrivParm);
  20776. DRD->addDecl(OmpOrigParm);
  20777. }
  20778. Expr *OrigE =
  20779. ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
  20780. Expr *PrivE =
  20781. ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
  20782. DRD->setInitializerData(OrigE, PrivE);
  20783. return OmpPrivParm;
  20784. }
  20785. void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
  20786. VarDecl *OmpPrivParm) {
  20787. auto *DRD = cast<OMPDeclareReductionDecl>(D);
  20788. DiscardCleanupsInEvaluationContext();
  20789. PopExpressionEvaluationContext();
  20790. PopDeclContext();
  20791. PopFunctionScopeInfo();
  20792. if (Initializer != nullptr) {
  20793. DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
  20794. } else if (OmpPrivParm->hasInit()) {
  20795. DRD->setInitializer(OmpPrivParm->getInit(),
  20796. OmpPrivParm->isDirectInit()
  20797. ? OMPDeclareReductionDecl::DirectInit
  20798. : OMPDeclareReductionDecl::CopyInit);
  20799. } else {
  20800. DRD->setInvalidDecl();
  20801. }
  20802. }
  20803. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
  20804. Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
  20805. for (Decl *D : DeclReductions.get()) {
  20806. if (IsValid) {
  20807. if (S)
  20808. PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
  20809. /*AddToContext=*/false);
  20810. } else {
  20811. D->setInvalidDecl();
  20812. }
  20813. }
  20814. return DeclReductions;
  20815. }
  20816. TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
  20817. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  20818. QualType T = TInfo->getType();
  20819. if (D.isInvalidType())
  20820. return true;
  20821. if (getLangOpts().CPlusPlus) {
  20822. // Check that there are no default arguments (C++ only).
  20823. CheckExtraCXXDefaultArguments(D);
  20824. }
  20825. return CreateParsedType(T, TInfo);
  20826. }
  20827. QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
  20828. TypeResult ParsedType) {
  20829. assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
  20830. QualType MapperType = GetTypeFromParser(ParsedType.get());
  20831. assert(!MapperType.isNull() && "Expect valid mapper type");
  20832. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  20833. // The type must be of struct, union or class type in C and C++
  20834. if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
  20835. Diag(TyLoc, diag::err_omp_mapper_wrong_type);
  20836. return QualType();
  20837. }
  20838. return MapperType;
  20839. }
  20840. Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective(
  20841. Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
  20842. SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
  20843. Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) {
  20844. LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
  20845. forRedeclarationInCurContext());
  20846. // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
  20847. // A mapper-identifier may not be redeclared in the current scope for the
  20848. // same type or for a type that is compatible according to the base language
  20849. // rules.
  20850. llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
  20851. OMPDeclareMapperDecl *PrevDMD = nullptr;
  20852. bool InCompoundScope = true;
  20853. if (S != nullptr) {
  20854. // Find previous declaration with the same name not referenced in other
  20855. // declarations.
  20856. FunctionScopeInfo *ParentFn = getEnclosingFunction();
  20857. InCompoundScope =
  20858. (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
  20859. LookupName(Lookup, S);
  20860. FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
  20861. /*AllowInlineNamespace=*/false);
  20862. llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
  20863. LookupResult::Filter Filter = Lookup.makeFilter();
  20864. while (Filter.hasNext()) {
  20865. auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
  20866. if (InCompoundScope) {
  20867. auto I = UsedAsPrevious.find(PrevDecl);
  20868. if (I == UsedAsPrevious.end())
  20869. UsedAsPrevious[PrevDecl] = false;
  20870. if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
  20871. UsedAsPrevious[D] = true;
  20872. }
  20873. PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
  20874. PrevDecl->getLocation();
  20875. }
  20876. Filter.done();
  20877. if (InCompoundScope) {
  20878. for (const auto &PrevData : UsedAsPrevious) {
  20879. if (!PrevData.second) {
  20880. PrevDMD = PrevData.first;
  20881. break;
  20882. }
  20883. }
  20884. }
  20885. } else if (PrevDeclInScope) {
  20886. auto *PrevDMDInScope = PrevDMD =
  20887. cast<OMPDeclareMapperDecl>(PrevDeclInScope);
  20888. do {
  20889. PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
  20890. PrevDMDInScope->getLocation();
  20891. PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
  20892. } while (PrevDMDInScope != nullptr);
  20893. }
  20894. const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
  20895. bool Invalid = false;
  20896. if (I != PreviousRedeclTypes.end()) {
  20897. Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
  20898. << MapperType << Name;
  20899. Diag(I->second, diag::note_previous_definition);
  20900. Invalid = true;
  20901. }
  20902. // Build expressions for implicit maps of data members with 'default'
  20903. // mappers.
  20904. SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(),
  20905. Clauses.end());
  20906. if (LangOpts.OpenMP >= 50)
  20907. processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit);
  20908. auto *DMD =
  20909. OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN,
  20910. ClausesWithImplicit, PrevDMD);
  20911. if (S)
  20912. PushOnScopeChains(DMD, S);
  20913. else
  20914. DC->addDecl(DMD);
  20915. DMD->setAccess(AS);
  20916. if (Invalid)
  20917. DMD->setInvalidDecl();
  20918. auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl();
  20919. VD->setDeclContext(DMD);
  20920. VD->setLexicalDeclContext(DMD);
  20921. DMD->addDecl(VD);
  20922. DMD->setMapperVarRef(MapperVarRef);
  20923. return DeclGroupPtrTy::make(DeclGroupRef(DMD));
  20924. }
  20925. ExprResult
  20926. Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType,
  20927. SourceLocation StartLoc,
  20928. DeclarationName VN) {
  20929. TypeSourceInfo *TInfo =
  20930. Context.getTrivialTypeSourceInfo(MapperType, StartLoc);
  20931. auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(),
  20932. StartLoc, StartLoc, VN.getAsIdentifierInfo(),
  20933. MapperType, TInfo, SC_None);
  20934. if (S)
  20935. PushOnScopeChains(VD, S, /*AddToContext=*/false);
  20936. Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
  20937. DSAStack->addDeclareMapperVarRef(E);
  20938. return E;
  20939. }
  20940. void Sema::ActOnOpenMPIteratorVarDecl(VarDecl *VD) {
  20941. if (DSAStack->getDeclareMapperVarRef())
  20942. DSAStack->addIteratorVarDecl(VD);
  20943. }
  20944. bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const {
  20945. assert(LangOpts.OpenMP && "Expected OpenMP mode.");
  20946. const Expr *Ref = DSAStack->getDeclareMapperVarRef();
  20947. if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) {
  20948. if (VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl())
  20949. return true;
  20950. if (VD->isUsableInConstantExpressions(Context))
  20951. return true;
  20952. if (LangOpts.OpenMP >= 52 && DSAStack->isIteratorVarDecl(VD))
  20953. return true;
  20954. return false;
  20955. }
  20956. return true;
  20957. }
  20958. const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const {
  20959. assert(LangOpts.OpenMP && "Expected OpenMP mode.");
  20960. return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl();
  20961. }
  20962. OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
  20963. SourceLocation StartLoc,
  20964. SourceLocation LParenLoc,
  20965. SourceLocation EndLoc) {
  20966. Expr *ValExpr = NumTeams;
  20967. Stmt *HelperValStmt = nullptr;
  20968. // OpenMP [teams Constrcut, Restrictions]
  20969. // The num_teams expression must evaluate to a positive integer value.
  20970. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
  20971. /*StrictlyPositive=*/true))
  20972. return nullptr;
  20973. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  20974. OpenMPDirectiveKind CaptureRegion =
  20975. getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
  20976. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  20977. ValExpr = MakeFullExpr(ValExpr).get();
  20978. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  20979. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  20980. HelperValStmt = buildPreInits(Context, Captures);
  20981. }
  20982. return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
  20983. StartLoc, LParenLoc, EndLoc);
  20984. }
  20985. OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
  20986. SourceLocation StartLoc,
  20987. SourceLocation LParenLoc,
  20988. SourceLocation EndLoc) {
  20989. Expr *ValExpr = ThreadLimit;
  20990. Stmt *HelperValStmt = nullptr;
  20991. // OpenMP [teams Constrcut, Restrictions]
  20992. // The thread_limit expression must evaluate to a positive integer value.
  20993. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
  20994. /*StrictlyPositive=*/true))
  20995. return nullptr;
  20996. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  20997. OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
  20998. DKind, OMPC_thread_limit, LangOpts.OpenMP);
  20999. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  21000. ValExpr = MakeFullExpr(ValExpr).get();
  21001. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  21002. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  21003. HelperValStmt = buildPreInits(Context, Captures);
  21004. }
  21005. return new (Context) OMPThreadLimitClause(
  21006. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  21007. }
  21008. OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
  21009. SourceLocation StartLoc,
  21010. SourceLocation LParenLoc,
  21011. SourceLocation EndLoc) {
  21012. Expr *ValExpr = Priority;
  21013. Stmt *HelperValStmt = nullptr;
  21014. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  21015. // OpenMP [2.9.1, task Constrcut]
  21016. // The priority-value is a non-negative numerical scalar expression.
  21017. if (!isNonNegativeIntegerValue(
  21018. ValExpr, *this, OMPC_priority,
  21019. /*StrictlyPositive=*/false, /*BuildCapture=*/true,
  21020. DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
  21021. return nullptr;
  21022. return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
  21023. StartLoc, LParenLoc, EndLoc);
  21024. }
  21025. OMPClause *Sema::ActOnOpenMPGrainsizeClause(
  21026. OpenMPGrainsizeClauseModifier Modifier, Expr *Grainsize,
  21027. SourceLocation StartLoc, SourceLocation LParenLoc,
  21028. SourceLocation ModifierLoc, SourceLocation EndLoc) {
  21029. assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 51) &&
  21030. "Unexpected grainsize modifier in OpenMP < 51.");
  21031. if (ModifierLoc.isValid() && Modifier == OMPC_GRAINSIZE_unknown) {
  21032. std::string Values = getListOfPossibleValues(OMPC_grainsize, /*First=*/0,
  21033. OMPC_GRAINSIZE_unknown);
  21034. Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
  21035. << Values << getOpenMPClauseName(OMPC_grainsize);
  21036. return nullptr;
  21037. }
  21038. Expr *ValExpr = Grainsize;
  21039. Stmt *HelperValStmt = nullptr;
  21040. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  21041. // OpenMP [2.9.2, taskloop Constrcut]
  21042. // The parameter of the grainsize clause must be a positive integer
  21043. // expression.
  21044. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
  21045. /*StrictlyPositive=*/true,
  21046. /*BuildCapture=*/true,
  21047. DSAStack->getCurrentDirective(),
  21048. &CaptureRegion, &HelperValStmt))
  21049. return nullptr;
  21050. return new (Context)
  21051. OMPGrainsizeClause(Modifier, ValExpr, HelperValStmt, CaptureRegion,
  21052. StartLoc, LParenLoc, ModifierLoc, EndLoc);
  21053. }
  21054. OMPClause *Sema::ActOnOpenMPNumTasksClause(
  21055. OpenMPNumTasksClauseModifier Modifier, Expr *NumTasks,
  21056. SourceLocation StartLoc, SourceLocation LParenLoc,
  21057. SourceLocation ModifierLoc, SourceLocation EndLoc) {
  21058. assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 51) &&
  21059. "Unexpected num_tasks modifier in OpenMP < 51.");
  21060. if (ModifierLoc.isValid() && Modifier == OMPC_NUMTASKS_unknown) {
  21061. std::string Values = getListOfPossibleValues(OMPC_num_tasks, /*First=*/0,
  21062. OMPC_NUMTASKS_unknown);
  21063. Diag(ModifierLoc, diag::err_omp_unexpected_clause_value)
  21064. << Values << getOpenMPClauseName(OMPC_num_tasks);
  21065. return nullptr;
  21066. }
  21067. Expr *ValExpr = NumTasks;
  21068. Stmt *HelperValStmt = nullptr;
  21069. OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
  21070. // OpenMP [2.9.2, taskloop Constrcut]
  21071. // The parameter of the num_tasks clause must be a positive integer
  21072. // expression.
  21073. if (!isNonNegativeIntegerValue(
  21074. ValExpr, *this, OMPC_num_tasks,
  21075. /*StrictlyPositive=*/true, /*BuildCapture=*/true,
  21076. DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
  21077. return nullptr;
  21078. return new (Context)
  21079. OMPNumTasksClause(Modifier, ValExpr, HelperValStmt, CaptureRegion,
  21080. StartLoc, LParenLoc, ModifierLoc, EndLoc);
  21081. }
  21082. OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
  21083. SourceLocation LParenLoc,
  21084. SourceLocation EndLoc) {
  21085. // OpenMP [2.13.2, critical construct, Description]
  21086. // ... where hint-expression is an integer constant expression that evaluates
  21087. // to a valid lock hint.
  21088. ExprResult HintExpr =
  21089. VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint, false);
  21090. if (HintExpr.isInvalid())
  21091. return nullptr;
  21092. return new (Context)
  21093. OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
  21094. }
  21095. /// Tries to find omp_event_handle_t type.
  21096. static bool findOMPEventHandleT(Sema &S, SourceLocation Loc,
  21097. DSAStackTy *Stack) {
  21098. QualType OMPEventHandleT = Stack->getOMPEventHandleT();
  21099. if (!OMPEventHandleT.isNull())
  21100. return true;
  21101. IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t");
  21102. ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope());
  21103. if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
  21104. S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t";
  21105. return false;
  21106. }
  21107. Stack->setOMPEventHandleT(PT.get());
  21108. return true;
  21109. }
  21110. OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
  21111. SourceLocation LParenLoc,
  21112. SourceLocation EndLoc) {
  21113. if (!Evt->isValueDependent() && !Evt->isTypeDependent() &&
  21114. !Evt->isInstantiationDependent() &&
  21115. !Evt->containsUnexpandedParameterPack()) {
  21116. if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack))
  21117. return nullptr;
  21118. // OpenMP 5.0, 2.10.1 task Construct.
  21119. // event-handle is a variable of the omp_event_handle_t type.
  21120. auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts());
  21121. if (!Ref) {
  21122. Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
  21123. << "omp_event_handle_t" << 0 << Evt->getSourceRange();
  21124. return nullptr;
  21125. }
  21126. auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl());
  21127. if (!VD) {
  21128. Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
  21129. << "omp_event_handle_t" << 0 << Evt->getSourceRange();
  21130. return nullptr;
  21131. }
  21132. if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(),
  21133. VD->getType()) ||
  21134. VD->getType().isConstant(Context)) {
  21135. Diag(Evt->getExprLoc(), diag::err_omp_var_expected)
  21136. << "omp_event_handle_t" << 1 << VD->getType()
  21137. << Evt->getSourceRange();
  21138. return nullptr;
  21139. }
  21140. // OpenMP 5.0, 2.10.1 task Construct
  21141. // [detach clause]... The event-handle will be considered as if it was
  21142. // specified on a firstprivate clause.
  21143. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false);
  21144. if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
  21145. DVar.RefExpr) {
  21146. Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa)
  21147. << getOpenMPClauseName(DVar.CKind)
  21148. << getOpenMPClauseName(OMPC_firstprivate);
  21149. reportOriginalDsa(*this, DSAStack, VD, DVar);
  21150. return nullptr;
  21151. }
  21152. }
  21153. return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
  21154. }
  21155. OMPClause *Sema::ActOnOpenMPDistScheduleClause(
  21156. OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
  21157. SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
  21158. SourceLocation EndLoc) {
  21159. if (Kind == OMPC_DIST_SCHEDULE_unknown) {
  21160. std::string Values;
  21161. Values += "'";
  21162. Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
  21163. Values += "'";
  21164. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  21165. << Values << getOpenMPClauseName(OMPC_dist_schedule);
  21166. return nullptr;
  21167. }
  21168. Expr *ValExpr = ChunkSize;
  21169. Stmt *HelperValStmt = nullptr;
  21170. if (ChunkSize) {
  21171. if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
  21172. !ChunkSize->isInstantiationDependent() &&
  21173. !ChunkSize->containsUnexpandedParameterPack()) {
  21174. SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
  21175. ExprResult Val =
  21176. PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
  21177. if (Val.isInvalid())
  21178. return nullptr;
  21179. ValExpr = Val.get();
  21180. // OpenMP [2.7.1, Restrictions]
  21181. // chunk_size must be a loop invariant integer expression with a positive
  21182. // value.
  21183. if (std::optional<llvm::APSInt> Result =
  21184. ValExpr->getIntegerConstantExpr(Context)) {
  21185. if (Result->isSigned() && !Result->isStrictlyPositive()) {
  21186. Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
  21187. << "dist_schedule" << ChunkSize->getSourceRange();
  21188. return nullptr;
  21189. }
  21190. } else if (getOpenMPCaptureRegionForClause(
  21191. DSAStack->getCurrentDirective(), OMPC_dist_schedule,
  21192. LangOpts.OpenMP) != OMPD_unknown &&
  21193. !CurContext->isDependentContext()) {
  21194. ValExpr = MakeFullExpr(ValExpr).get();
  21195. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  21196. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  21197. HelperValStmt = buildPreInits(Context, Captures);
  21198. }
  21199. }
  21200. }
  21201. return new (Context)
  21202. OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
  21203. Kind, ValExpr, HelperValStmt);
  21204. }
  21205. OMPClause *Sema::ActOnOpenMPDefaultmapClause(
  21206. OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
  21207. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
  21208. SourceLocation KindLoc, SourceLocation EndLoc) {
  21209. if (getLangOpts().OpenMP < 50) {
  21210. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
  21211. Kind != OMPC_DEFAULTMAP_scalar) {
  21212. std::string Value;
  21213. SourceLocation Loc;
  21214. Value += "'";
  21215. if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
  21216. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  21217. OMPC_DEFAULTMAP_MODIFIER_tofrom);
  21218. Loc = MLoc;
  21219. } else {
  21220. Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
  21221. OMPC_DEFAULTMAP_scalar);
  21222. Loc = KindLoc;
  21223. }
  21224. Value += "'";
  21225. Diag(Loc, diag::err_omp_unexpected_clause_value)
  21226. << Value << getOpenMPClauseName(OMPC_defaultmap);
  21227. return nullptr;
  21228. }
  21229. } else {
  21230. bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
  21231. bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) ||
  21232. (LangOpts.OpenMP >= 50 && KindLoc.isInvalid());
  21233. if (!isDefaultmapKind || !isDefaultmapModifier) {
  21234. StringRef KindValue = "'scalar', 'aggregate', 'pointer'";
  21235. if (LangOpts.OpenMP == 50) {
  21236. StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
  21237. "'firstprivate', 'none', 'default'";
  21238. if (!isDefaultmapKind && isDefaultmapModifier) {
  21239. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  21240. << KindValue << getOpenMPClauseName(OMPC_defaultmap);
  21241. } else if (isDefaultmapKind && !isDefaultmapModifier) {
  21242. Diag(MLoc, diag::err_omp_unexpected_clause_value)
  21243. << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
  21244. } else {
  21245. Diag(MLoc, diag::err_omp_unexpected_clause_value)
  21246. << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
  21247. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  21248. << KindValue << getOpenMPClauseName(OMPC_defaultmap);
  21249. }
  21250. } else {
  21251. StringRef ModifierValue =
  21252. "'alloc', 'from', 'to', 'tofrom', "
  21253. "'firstprivate', 'none', 'default', 'present'";
  21254. if (!isDefaultmapKind && isDefaultmapModifier) {
  21255. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  21256. << KindValue << getOpenMPClauseName(OMPC_defaultmap);
  21257. } else if (isDefaultmapKind && !isDefaultmapModifier) {
  21258. Diag(MLoc, diag::err_omp_unexpected_clause_value)
  21259. << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
  21260. } else {
  21261. Diag(MLoc, diag::err_omp_unexpected_clause_value)
  21262. << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
  21263. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  21264. << KindValue << getOpenMPClauseName(OMPC_defaultmap);
  21265. }
  21266. }
  21267. return nullptr;
  21268. }
  21269. // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
  21270. // At most one defaultmap clause for each category can appear on the
  21271. // directive.
  21272. if (DSAStack->checkDefaultmapCategory(Kind)) {
  21273. Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
  21274. return nullptr;
  21275. }
  21276. }
  21277. if (Kind == OMPC_DEFAULTMAP_unknown) {
  21278. // Variable category is not specified - mark all categories.
  21279. DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc);
  21280. DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc);
  21281. DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc);
  21282. } else {
  21283. DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
  21284. }
  21285. return new (Context)
  21286. OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
  21287. }
  21288. bool Sema::ActOnStartOpenMPDeclareTargetContext(
  21289. DeclareTargetContextInfo &DTCI) {
  21290. DeclContext *CurLexicalContext = getCurLexicalContext();
  21291. if (!CurLexicalContext->isFileContext() &&
  21292. !CurLexicalContext->isExternCContext() &&
  21293. !CurLexicalContext->isExternCXXContext() &&
  21294. !isa<CXXRecordDecl>(CurLexicalContext) &&
  21295. !isa<ClassTemplateDecl>(CurLexicalContext) &&
  21296. !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
  21297. !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
  21298. Diag(DTCI.Loc, diag::err_omp_region_not_file_context);
  21299. return false;
  21300. }
  21301. DeclareTargetNesting.push_back(DTCI);
  21302. return true;
  21303. }
  21304. const Sema::DeclareTargetContextInfo
  21305. Sema::ActOnOpenMPEndDeclareTargetDirective() {
  21306. assert(!DeclareTargetNesting.empty() &&
  21307. "check isInOpenMPDeclareTargetContext() first!");
  21308. return DeclareTargetNesting.pop_back_val();
  21309. }
  21310. void Sema::ActOnFinishedOpenMPDeclareTargetContext(
  21311. DeclareTargetContextInfo &DTCI) {
  21312. for (auto &It : DTCI.ExplicitlyMapped)
  21313. ActOnOpenMPDeclareTargetName(It.first, It.second.Loc, It.second.MT, DTCI);
  21314. }
  21315. void Sema::DiagnoseUnterminatedOpenMPDeclareTarget() {
  21316. if (DeclareTargetNesting.empty())
  21317. return;
  21318. DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back();
  21319. Diag(DTCI.Loc, diag::warn_omp_unterminated_declare_target)
  21320. << getOpenMPDirectiveName(DTCI.Kind);
  21321. }
  21322. NamedDecl *Sema::lookupOpenMPDeclareTargetName(Scope *CurScope,
  21323. CXXScopeSpec &ScopeSpec,
  21324. const DeclarationNameInfo &Id) {
  21325. LookupResult Lookup(*this, Id, LookupOrdinaryName);
  21326. LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
  21327. if (Lookup.isAmbiguous())
  21328. return nullptr;
  21329. Lookup.suppressDiagnostics();
  21330. if (!Lookup.isSingleResult()) {
  21331. VarOrFuncDeclFilterCCC CCC(*this);
  21332. if (TypoCorrection Corrected =
  21333. CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
  21334. CTK_ErrorRecovery)) {
  21335. diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
  21336. << Id.getName());
  21337. checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
  21338. return nullptr;
  21339. }
  21340. Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
  21341. return nullptr;
  21342. }
  21343. NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
  21344. if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
  21345. !isa<FunctionTemplateDecl>(ND)) {
  21346. Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
  21347. return nullptr;
  21348. }
  21349. return ND;
  21350. }
  21351. void Sema::ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
  21352. OMPDeclareTargetDeclAttr::MapTypeTy MT,
  21353. DeclareTargetContextInfo &DTCI) {
  21354. assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
  21355. isa<FunctionTemplateDecl>(ND)) &&
  21356. "Expected variable, function or function template.");
  21357. // Diagnose marking after use as it may lead to incorrect diagnosis and
  21358. // codegen.
  21359. if (LangOpts.OpenMP >= 50 &&
  21360. (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
  21361. Diag(Loc, diag::warn_omp_declare_target_after_first_use);
  21362. // Explicit declare target lists have precedence.
  21363. const unsigned Level = -1;
  21364. auto *VD = cast<ValueDecl>(ND);
  21365. std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
  21366. OMPDeclareTargetDeclAttr::getActiveAttr(VD);
  21367. if (ActiveAttr && (*ActiveAttr)->getDevType() != DTCI.DT &&
  21368. (*ActiveAttr)->getLevel() == Level) {
  21369. Diag(Loc, diag::err_omp_device_type_mismatch)
  21370. << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DTCI.DT)
  21371. << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(
  21372. (*ActiveAttr)->getDevType());
  21373. return;
  21374. }
  21375. if (ActiveAttr && (*ActiveAttr)->getMapType() != MT &&
  21376. (*ActiveAttr)->getLevel() == Level) {
  21377. Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
  21378. return;
  21379. }
  21380. if (ActiveAttr && (*ActiveAttr)->getLevel() == Level)
  21381. return;
  21382. Expr *IndirectE = nullptr;
  21383. bool IsIndirect = false;
  21384. if (DTCI.Indirect) {
  21385. IndirectE = *DTCI.Indirect;
  21386. if (!IndirectE)
  21387. IsIndirect = true;
  21388. }
  21389. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  21390. Context, MT, DTCI.DT, IndirectE, IsIndirect, Level,
  21391. SourceRange(Loc, Loc));
  21392. ND->addAttr(A);
  21393. if (ASTMutationListener *ML = Context.getASTMutationListener())
  21394. ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
  21395. checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
  21396. }
  21397. static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
  21398. Sema &SemaRef, Decl *D) {
  21399. if (!D || !isa<VarDecl>(D))
  21400. return;
  21401. auto *VD = cast<VarDecl>(D);
  21402. std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
  21403. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  21404. if (SemaRef.LangOpts.OpenMP >= 50 &&
  21405. (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
  21406. SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
  21407. VD->hasGlobalStorage()) {
  21408. if (!MapTy || (*MapTy != OMPDeclareTargetDeclAttr::MT_To &&
  21409. *MapTy != OMPDeclareTargetDeclAttr::MT_Enter)) {
  21410. // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
  21411. // If a lambda declaration and definition appears between a
  21412. // declare target directive and the matching end declare target
  21413. // directive, all variables that are captured by the lambda
  21414. // expression must also appear in a to clause.
  21415. SemaRef.Diag(VD->getLocation(),
  21416. diag::err_omp_lambda_capture_in_declare_target_not_to);
  21417. SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
  21418. << VD << 0 << SR;
  21419. return;
  21420. }
  21421. }
  21422. if (MapTy)
  21423. return;
  21424. SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
  21425. SemaRef.Diag(SL, diag::note_used_here) << SR;
  21426. }
  21427. static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
  21428. Sema &SemaRef, DSAStackTy *Stack,
  21429. ValueDecl *VD) {
  21430. return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
  21431. checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
  21432. /*FullCheck=*/false);
  21433. }
  21434. void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
  21435. SourceLocation IdLoc) {
  21436. if (!D || D->isInvalidDecl())
  21437. return;
  21438. SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
  21439. SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
  21440. if (auto *VD = dyn_cast<VarDecl>(D)) {
  21441. // Only global variables can be marked as declare target.
  21442. if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
  21443. !VD->isStaticDataMember())
  21444. return;
  21445. // 2.10.6: threadprivate variable cannot appear in a declare target
  21446. // directive.
  21447. if (DSAStack->isThreadPrivate(VD)) {
  21448. Diag(SL, diag::err_omp_threadprivate_in_target);
  21449. reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
  21450. return;
  21451. }
  21452. }
  21453. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  21454. D = FTD->getTemplatedDecl();
  21455. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  21456. std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  21457. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
  21458. if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
  21459. Diag(IdLoc, diag::err_omp_function_in_link_clause);
  21460. Diag(FD->getLocation(), diag::note_defined_here) << FD;
  21461. return;
  21462. }
  21463. }
  21464. if (auto *VD = dyn_cast<ValueDecl>(D)) {
  21465. // Problem if any with var declared with incomplete type will be reported
  21466. // as normal, so no need to check it here.
  21467. if ((E || !VD->getType()->isIncompleteType()) &&
  21468. !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
  21469. return;
  21470. if (!E && isInOpenMPDeclareTargetContext()) {
  21471. // Checking declaration inside declare target region.
  21472. if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
  21473. isa<FunctionTemplateDecl>(D)) {
  21474. std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
  21475. OMPDeclareTargetDeclAttr::getActiveAttr(VD);
  21476. unsigned Level = DeclareTargetNesting.size();
  21477. if (ActiveAttr && (*ActiveAttr)->getLevel() >= Level)
  21478. return;
  21479. DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back();
  21480. Expr *IndirectE = nullptr;
  21481. bool IsIndirect = false;
  21482. if (DTCI.Indirect) {
  21483. IndirectE = *DTCI.Indirect;
  21484. if (!IndirectE)
  21485. IsIndirect = true;
  21486. }
  21487. auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
  21488. Context,
  21489. getLangOpts().OpenMP >= 52 ? OMPDeclareTargetDeclAttr::MT_Enter
  21490. : OMPDeclareTargetDeclAttr::MT_To,
  21491. DTCI.DT, IndirectE, IsIndirect, Level,
  21492. SourceRange(DTCI.Loc, DTCI.Loc));
  21493. D->addAttr(A);
  21494. if (ASTMutationListener *ML = Context.getASTMutationListener())
  21495. ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
  21496. }
  21497. return;
  21498. }
  21499. }
  21500. if (!E)
  21501. return;
  21502. checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
  21503. }
  21504. OMPClause *Sema::ActOnOpenMPToClause(
  21505. ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
  21506. ArrayRef<SourceLocation> MotionModifiersLoc,
  21507. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
  21508. SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
  21509. const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
  21510. OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
  21511. OMPC_MOTION_MODIFIER_unknown};
  21512. SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
  21513. // Process motion-modifiers, flag errors for duplicate modifiers.
  21514. unsigned Count = 0;
  21515. for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
  21516. if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
  21517. llvm::is_contained(Modifiers, MotionModifiers[I])) {
  21518. Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
  21519. continue;
  21520. }
  21521. assert(Count < NumberOfOMPMotionModifiers &&
  21522. "Modifiers exceed the allowed number of motion modifiers");
  21523. Modifiers[Count] = MotionModifiers[I];
  21524. ModifiersLoc[Count] = MotionModifiersLoc[I];
  21525. ++Count;
  21526. }
  21527. MappableVarListInfo MVLI(VarList);
  21528. checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
  21529. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  21530. if (MVLI.ProcessedVarList.empty())
  21531. return nullptr;
  21532. return OMPToClause::Create(
  21533. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  21534. MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
  21535. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  21536. }
  21537. OMPClause *Sema::ActOnOpenMPFromClause(
  21538. ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
  21539. ArrayRef<SourceLocation> MotionModifiersLoc,
  21540. CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
  21541. SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
  21542. const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
  21543. OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown,
  21544. OMPC_MOTION_MODIFIER_unknown};
  21545. SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers];
  21546. // Process motion-modifiers, flag errors for duplicate modifiers.
  21547. unsigned Count = 0;
  21548. for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) {
  21549. if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown &&
  21550. llvm::is_contained(Modifiers, MotionModifiers[I])) {
  21551. Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier);
  21552. continue;
  21553. }
  21554. assert(Count < NumberOfOMPMotionModifiers &&
  21555. "Modifiers exceed the allowed number of motion modifiers");
  21556. Modifiers[Count] = MotionModifiers[I];
  21557. ModifiersLoc[Count] = MotionModifiersLoc[I];
  21558. ++Count;
  21559. }
  21560. MappableVarListInfo MVLI(VarList);
  21561. checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
  21562. MapperIdScopeSpec, MapperId, UnresolvedMappers);
  21563. if (MVLI.ProcessedVarList.empty())
  21564. return nullptr;
  21565. return OMPFromClause::Create(
  21566. Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
  21567. MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc,
  21568. MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
  21569. }
  21570. OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
  21571. const OMPVarListLocTy &Locs) {
  21572. MappableVarListInfo MVLI(VarList);
  21573. SmallVector<Expr *, 8> PrivateCopies;
  21574. SmallVector<Expr *, 8> Inits;
  21575. for (Expr *RefExpr : VarList) {
  21576. assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
  21577. SourceLocation ELoc;
  21578. SourceRange ERange;
  21579. Expr *SimpleRefExpr = RefExpr;
  21580. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  21581. if (Res.second) {
  21582. // It will be analyzed later.
  21583. MVLI.ProcessedVarList.push_back(RefExpr);
  21584. PrivateCopies.push_back(nullptr);
  21585. Inits.push_back(nullptr);
  21586. }
  21587. ValueDecl *D = Res.first;
  21588. if (!D)
  21589. continue;
  21590. QualType Type = D->getType();
  21591. Type = Type.getNonReferenceType().getUnqualifiedType();
  21592. auto *VD = dyn_cast<VarDecl>(D);
  21593. // Item should be a pointer or reference to pointer.
  21594. if (!Type->isPointerType()) {
  21595. Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
  21596. << 0 << RefExpr->getSourceRange();
  21597. continue;
  21598. }
  21599. // Build the private variable and the expression that refers to it.
  21600. auto VDPrivate =
  21601. buildVarDecl(*this, ELoc, Type, D->getName(),
  21602. D->hasAttrs() ? &D->getAttrs() : nullptr,
  21603. VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
  21604. if (VDPrivate->isInvalidDecl())
  21605. continue;
  21606. CurContext->addDecl(VDPrivate);
  21607. DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
  21608. *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
  21609. // Add temporary variable to initialize the private copy of the pointer.
  21610. VarDecl *VDInit =
  21611. buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
  21612. DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
  21613. *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
  21614. AddInitializerToDecl(VDPrivate,
  21615. DefaultLvalueConversion(VDInitRefExpr).get(),
  21616. /*DirectInit=*/false);
  21617. // If required, build a capture to implement the privatization initialized
  21618. // with the current list item value.
  21619. DeclRefExpr *Ref = nullptr;
  21620. if (!VD)
  21621. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  21622. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  21623. PrivateCopies.push_back(VDPrivateRefExpr);
  21624. Inits.push_back(VDInitRefExpr);
  21625. // We need to add a data sharing attribute for this variable to make sure it
  21626. // is correctly captured. A variable that shows up in a use_device_ptr has
  21627. // similar properties of a first private variable.
  21628. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  21629. // Create a mappable component for the list item. List items in this clause
  21630. // only need a component.
  21631. MVLI.VarBaseDeclarations.push_back(D);
  21632. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  21633. MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D,
  21634. /*IsNonContiguous=*/false);
  21635. }
  21636. if (MVLI.ProcessedVarList.empty())
  21637. return nullptr;
  21638. return OMPUseDevicePtrClause::Create(
  21639. Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
  21640. MVLI.VarBaseDeclarations, MVLI.VarComponents);
  21641. }
  21642. OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
  21643. const OMPVarListLocTy &Locs) {
  21644. MappableVarListInfo MVLI(VarList);
  21645. for (Expr *RefExpr : VarList) {
  21646. assert(RefExpr && "NULL expr in OpenMP use_device_addr clause.");
  21647. SourceLocation ELoc;
  21648. SourceRange ERange;
  21649. Expr *SimpleRefExpr = RefExpr;
  21650. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  21651. /*AllowArraySection=*/true);
  21652. if (Res.second) {
  21653. // It will be analyzed later.
  21654. MVLI.ProcessedVarList.push_back(RefExpr);
  21655. }
  21656. ValueDecl *D = Res.first;
  21657. if (!D)
  21658. continue;
  21659. auto *VD = dyn_cast<VarDecl>(D);
  21660. // If required, build a capture to implement the privatization initialized
  21661. // with the current list item value.
  21662. DeclRefExpr *Ref = nullptr;
  21663. if (!VD)
  21664. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  21665. MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
  21666. // We need to add a data sharing attribute for this variable to make sure it
  21667. // is correctly captured. A variable that shows up in a use_device_addr has
  21668. // similar properties of a first private variable.
  21669. DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
  21670. // Create a mappable component for the list item. List items in this clause
  21671. // only need a component.
  21672. MVLI.VarBaseDeclarations.push_back(D);
  21673. MVLI.VarComponents.emplace_back();
  21674. Expr *Component = SimpleRefExpr;
  21675. if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) ||
  21676. isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts())))
  21677. Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get();
  21678. MVLI.VarComponents.back().emplace_back(Component, D,
  21679. /*IsNonContiguous=*/false);
  21680. }
  21681. if (MVLI.ProcessedVarList.empty())
  21682. return nullptr;
  21683. return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
  21684. MVLI.VarBaseDeclarations,
  21685. MVLI.VarComponents);
  21686. }
  21687. OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
  21688. const OMPVarListLocTy &Locs) {
  21689. MappableVarListInfo MVLI(VarList);
  21690. for (Expr *RefExpr : VarList) {
  21691. assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
  21692. SourceLocation ELoc;
  21693. SourceRange ERange;
  21694. Expr *SimpleRefExpr = RefExpr;
  21695. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  21696. if (Res.second) {
  21697. // It will be analyzed later.
  21698. MVLI.ProcessedVarList.push_back(RefExpr);
  21699. }
  21700. ValueDecl *D = Res.first;
  21701. if (!D)
  21702. continue;
  21703. QualType Type = D->getType();
  21704. // item should be a pointer or array or reference to pointer or array
  21705. if (!Type.getNonReferenceType()->isPointerType() &&
  21706. !Type.getNonReferenceType()->isArrayType()) {
  21707. Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
  21708. << 0 << RefExpr->getSourceRange();
  21709. continue;
  21710. }
  21711. // Check if the declaration in the clause does not show up in any data
  21712. // sharing attribute.
  21713. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  21714. if (isOpenMPPrivate(DVar.CKind)) {
  21715. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  21716. << getOpenMPClauseName(DVar.CKind)
  21717. << getOpenMPClauseName(OMPC_is_device_ptr)
  21718. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  21719. reportOriginalDsa(*this, DSAStack, D, DVar);
  21720. continue;
  21721. }
  21722. const Expr *ConflictExpr;
  21723. if (DSAStack->checkMappableExprComponentListsForDecl(
  21724. D, /*CurrentRegionOnly=*/true,
  21725. [&ConflictExpr](
  21726. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  21727. OpenMPClauseKind) -> bool {
  21728. ConflictExpr = R.front().getAssociatedExpression();
  21729. return true;
  21730. })) {
  21731. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  21732. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  21733. << ConflictExpr->getSourceRange();
  21734. continue;
  21735. }
  21736. // Store the components in the stack so that they can be used to check
  21737. // against other clauses later on.
  21738. OMPClauseMappableExprCommon::MappableComponent MC(
  21739. SimpleRefExpr, D, /*IsNonContiguous=*/false);
  21740. DSAStack->addMappableExpressionComponents(
  21741. D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
  21742. // Record the expression we've just processed.
  21743. MVLI.ProcessedVarList.push_back(SimpleRefExpr);
  21744. // Create a mappable component for the list item. List items in this clause
  21745. // only need a component. We use a null declaration to signal fields in
  21746. // 'this'.
  21747. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  21748. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  21749. "Unexpected device pointer expression!");
  21750. MVLI.VarBaseDeclarations.push_back(
  21751. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  21752. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  21753. MVLI.VarComponents.back().push_back(MC);
  21754. }
  21755. if (MVLI.ProcessedVarList.empty())
  21756. return nullptr;
  21757. return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
  21758. MVLI.VarBaseDeclarations,
  21759. MVLI.VarComponents);
  21760. }
  21761. OMPClause *Sema::ActOnOpenMPHasDeviceAddrClause(ArrayRef<Expr *> VarList,
  21762. const OMPVarListLocTy &Locs) {
  21763. MappableVarListInfo MVLI(VarList);
  21764. for (Expr *RefExpr : VarList) {
  21765. assert(RefExpr && "NULL expr in OpenMP has_device_addr clause.");
  21766. SourceLocation ELoc;
  21767. SourceRange ERange;
  21768. Expr *SimpleRefExpr = RefExpr;
  21769. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  21770. /*AllowArraySection=*/true);
  21771. if (Res.second) {
  21772. // It will be analyzed later.
  21773. MVLI.ProcessedVarList.push_back(RefExpr);
  21774. }
  21775. ValueDecl *D = Res.first;
  21776. if (!D)
  21777. continue;
  21778. // Check if the declaration in the clause does not show up in any data
  21779. // sharing attribute.
  21780. DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
  21781. if (isOpenMPPrivate(DVar.CKind)) {
  21782. Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
  21783. << getOpenMPClauseName(DVar.CKind)
  21784. << getOpenMPClauseName(OMPC_has_device_addr)
  21785. << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
  21786. reportOriginalDsa(*this, DSAStack, D, DVar);
  21787. continue;
  21788. }
  21789. const Expr *ConflictExpr;
  21790. if (DSAStack->checkMappableExprComponentListsForDecl(
  21791. D, /*CurrentRegionOnly=*/true,
  21792. [&ConflictExpr](
  21793. OMPClauseMappableExprCommon::MappableExprComponentListRef R,
  21794. OpenMPClauseKind) -> bool {
  21795. ConflictExpr = R.front().getAssociatedExpression();
  21796. return true;
  21797. })) {
  21798. Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
  21799. Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
  21800. << ConflictExpr->getSourceRange();
  21801. continue;
  21802. }
  21803. // Store the components in the stack so that they can be used to check
  21804. // against other clauses later on.
  21805. Expr *Component = SimpleRefExpr;
  21806. auto *VD = dyn_cast<VarDecl>(D);
  21807. if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) ||
  21808. isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts())))
  21809. Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get();
  21810. OMPClauseMappableExprCommon::MappableComponent MC(
  21811. Component, D, /*IsNonContiguous=*/false);
  21812. DSAStack->addMappableExpressionComponents(
  21813. D, MC, /*WhereFoundClauseKind=*/OMPC_has_device_addr);
  21814. // Record the expression we've just processed.
  21815. if (!VD && !CurContext->isDependentContext()) {
  21816. DeclRefExpr *Ref =
  21817. buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
  21818. assert(Ref && "has_device_addr capture failed");
  21819. MVLI.ProcessedVarList.push_back(Ref);
  21820. } else
  21821. MVLI.ProcessedVarList.push_back(RefExpr->IgnoreParens());
  21822. // Create a mappable component for the list item. List items in this clause
  21823. // only need a component. We use a null declaration to signal fields in
  21824. // 'this'.
  21825. assert((isa<DeclRefExpr>(SimpleRefExpr) ||
  21826. isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
  21827. "Unexpected device pointer expression!");
  21828. MVLI.VarBaseDeclarations.push_back(
  21829. isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
  21830. MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
  21831. MVLI.VarComponents.back().push_back(MC);
  21832. }
  21833. if (MVLI.ProcessedVarList.empty())
  21834. return nullptr;
  21835. return OMPHasDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList,
  21836. MVLI.VarBaseDeclarations,
  21837. MVLI.VarComponents);
  21838. }
  21839. OMPClause *Sema::ActOnOpenMPAllocateClause(
  21840. Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
  21841. SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
  21842. if (Allocator) {
  21843. // OpenMP [2.11.4 allocate Clause, Description]
  21844. // allocator is an expression of omp_allocator_handle_t type.
  21845. if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
  21846. return nullptr;
  21847. ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
  21848. if (AllocatorRes.isInvalid())
  21849. return nullptr;
  21850. AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
  21851. DSAStack->getOMPAllocatorHandleT(),
  21852. Sema::AA_Initializing,
  21853. /*AllowExplicit=*/true);
  21854. if (AllocatorRes.isInvalid())
  21855. return nullptr;
  21856. Allocator = AllocatorRes.get();
  21857. } else {
  21858. // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
  21859. // allocate clauses that appear on a target construct or on constructs in a
  21860. // target region must specify an allocator expression unless a requires
  21861. // directive with the dynamic_allocators clause is present in the same
  21862. // compilation unit.
  21863. if (LangOpts.OpenMPIsDevice &&
  21864. !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
  21865. targetDiag(StartLoc, diag::err_expected_allocator_expression);
  21866. }
  21867. // Analyze and build list of variables.
  21868. SmallVector<Expr *, 8> Vars;
  21869. for (Expr *RefExpr : VarList) {
  21870. assert(RefExpr && "NULL expr in OpenMP private clause.");
  21871. SourceLocation ELoc;
  21872. SourceRange ERange;
  21873. Expr *SimpleRefExpr = RefExpr;
  21874. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  21875. if (Res.second) {
  21876. // It will be analyzed later.
  21877. Vars.push_back(RefExpr);
  21878. }
  21879. ValueDecl *D = Res.first;
  21880. if (!D)
  21881. continue;
  21882. auto *VD = dyn_cast<VarDecl>(D);
  21883. DeclRefExpr *Ref = nullptr;
  21884. if (!VD && !CurContext->isDependentContext())
  21885. Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
  21886. Vars.push_back((VD || CurContext->isDependentContext())
  21887. ? RefExpr->IgnoreParens()
  21888. : Ref);
  21889. }
  21890. if (Vars.empty())
  21891. return nullptr;
  21892. if (Allocator)
  21893. DSAStack->addInnerAllocatorExpr(Allocator);
  21894. return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
  21895. ColonLoc, EndLoc, Vars);
  21896. }
  21897. OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
  21898. SourceLocation StartLoc,
  21899. SourceLocation LParenLoc,
  21900. SourceLocation EndLoc) {
  21901. SmallVector<Expr *, 8> Vars;
  21902. for (Expr *RefExpr : VarList) {
  21903. assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
  21904. SourceLocation ELoc;
  21905. SourceRange ERange;
  21906. Expr *SimpleRefExpr = RefExpr;
  21907. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
  21908. if (Res.second)
  21909. // It will be analyzed later.
  21910. Vars.push_back(RefExpr);
  21911. ValueDecl *D = Res.first;
  21912. if (!D)
  21913. continue;
  21914. // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
  21915. // A list-item cannot appear in more than one nontemporal clause.
  21916. if (const Expr *PrevRef =
  21917. DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
  21918. Diag(ELoc, diag::err_omp_used_in_clause_twice)
  21919. << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
  21920. Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
  21921. << getOpenMPClauseName(OMPC_nontemporal);
  21922. continue;
  21923. }
  21924. Vars.push_back(RefExpr);
  21925. }
  21926. if (Vars.empty())
  21927. return nullptr;
  21928. return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  21929. Vars);
  21930. }
  21931. OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
  21932. SourceLocation StartLoc,
  21933. SourceLocation LParenLoc,
  21934. SourceLocation EndLoc) {
  21935. SmallVector<Expr *, 8> Vars;
  21936. for (Expr *RefExpr : VarList) {
  21937. assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
  21938. SourceLocation ELoc;
  21939. SourceRange ERange;
  21940. Expr *SimpleRefExpr = RefExpr;
  21941. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  21942. /*AllowArraySection=*/true);
  21943. if (Res.second)
  21944. // It will be analyzed later.
  21945. Vars.push_back(RefExpr);
  21946. ValueDecl *D = Res.first;
  21947. if (!D)
  21948. continue;
  21949. const DSAStackTy::DSAVarData DVar =
  21950. DSAStack->getTopDSA(D, /*FromParent=*/true);
  21951. // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
  21952. // A list item that appears in the inclusive or exclusive clause must appear
  21953. // in a reduction clause with the inscan modifier on the enclosing
  21954. // worksharing-loop, worksharing-loop SIMD, or simd construct.
  21955. if (DVar.CKind != OMPC_reduction || DVar.Modifier != OMPC_REDUCTION_inscan)
  21956. Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
  21957. << RefExpr->getSourceRange();
  21958. if (DSAStack->getParentDirective() != OMPD_unknown)
  21959. DSAStack->markDeclAsUsedInScanDirective(D);
  21960. Vars.push_back(RefExpr);
  21961. }
  21962. if (Vars.empty())
  21963. return nullptr;
  21964. return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  21965. }
  21966. OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
  21967. SourceLocation StartLoc,
  21968. SourceLocation LParenLoc,
  21969. SourceLocation EndLoc) {
  21970. SmallVector<Expr *, 8> Vars;
  21971. for (Expr *RefExpr : VarList) {
  21972. assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
  21973. SourceLocation ELoc;
  21974. SourceRange ERange;
  21975. Expr *SimpleRefExpr = RefExpr;
  21976. auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
  21977. /*AllowArraySection=*/true);
  21978. if (Res.second)
  21979. // It will be analyzed later.
  21980. Vars.push_back(RefExpr);
  21981. ValueDecl *D = Res.first;
  21982. if (!D)
  21983. continue;
  21984. OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective();
  21985. DSAStackTy::DSAVarData DVar;
  21986. if (ParentDirective != OMPD_unknown)
  21987. DVar = DSAStack->getTopDSA(D, /*FromParent=*/true);
  21988. // OpenMP 5.0, 2.9.6, scan Directive, Restrictions.
  21989. // A list item that appears in the inclusive or exclusive clause must appear
  21990. // in a reduction clause with the inscan modifier on the enclosing
  21991. // worksharing-loop, worksharing-loop SIMD, or simd construct.
  21992. if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction ||
  21993. DVar.Modifier != OMPC_REDUCTION_inscan) {
  21994. Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction)
  21995. << RefExpr->getSourceRange();
  21996. } else {
  21997. DSAStack->markDeclAsUsedInScanDirective(D);
  21998. }
  21999. Vars.push_back(RefExpr);
  22000. }
  22001. if (Vars.empty())
  22002. return nullptr;
  22003. return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
  22004. }
  22005. /// Tries to find omp_alloctrait_t type.
  22006. static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) {
  22007. QualType OMPAlloctraitT = Stack->getOMPAlloctraitT();
  22008. if (!OMPAlloctraitT.isNull())
  22009. return true;
  22010. IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t");
  22011. ParsedType PT = S.getTypeName(II, Loc, S.getCurScope());
  22012. if (!PT.getAsOpaquePtr() || PT.get().isNull()) {
  22013. S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t";
  22014. return false;
  22015. }
  22016. Stack->setOMPAlloctraitT(PT.get());
  22017. return true;
  22018. }
  22019. OMPClause *Sema::ActOnOpenMPUsesAllocatorClause(
  22020. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
  22021. ArrayRef<UsesAllocatorsData> Data) {
  22022. // OpenMP [2.12.5, target Construct]
  22023. // allocator is an identifier of omp_allocator_handle_t type.
  22024. if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack))
  22025. return nullptr;
  22026. // OpenMP [2.12.5, target Construct]
  22027. // allocator-traits-array is an identifier of const omp_alloctrait_t * type.
  22028. if (llvm::any_of(
  22029. Data,
  22030. [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) &&
  22031. !findOMPAlloctraitT(*this, StartLoc, DSAStack))
  22032. return nullptr;
  22033. llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators;
  22034. for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
  22035. auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
  22036. StringRef Allocator =
  22037. OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
  22038. DeclarationName AllocatorName = &Context.Idents.get(Allocator);
  22039. PredefinedAllocators.insert(LookupSingleName(
  22040. TUScope, AllocatorName, StartLoc, Sema::LookupAnyName));
  22041. }
  22042. SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData;
  22043. for (const UsesAllocatorsData &D : Data) {
  22044. Expr *AllocatorExpr = nullptr;
  22045. // Check allocator expression.
  22046. if (D.Allocator->isTypeDependent()) {
  22047. AllocatorExpr = D.Allocator;
  22048. } else {
  22049. // Traits were specified - need to assign new allocator to the specified
  22050. // allocator, so it must be an lvalue.
  22051. AllocatorExpr = D.Allocator->IgnoreParenImpCasts();
  22052. auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr);
  22053. bool IsPredefinedAllocator = false;
  22054. if (DRE) {
  22055. OMPAllocateDeclAttr::AllocatorTypeTy AllocatorTy =
  22056. getAllocatorKind(*this, DSAStack, AllocatorExpr);
  22057. IsPredefinedAllocator =
  22058. AllocatorTy !=
  22059. OMPAllocateDeclAttr::AllocatorTypeTy::OMPUserDefinedMemAlloc;
  22060. }
  22061. QualType OMPAllocatorHandleT = DSAStack->getOMPAllocatorHandleT();
  22062. QualType AllocatorExprType = AllocatorExpr->getType();
  22063. bool IsTypeCompatible = IsPredefinedAllocator;
  22064. IsTypeCompatible = IsTypeCompatible ||
  22065. Context.hasSameUnqualifiedType(AllocatorExprType,
  22066. OMPAllocatorHandleT);
  22067. IsTypeCompatible =
  22068. IsTypeCompatible ||
  22069. Context.typesAreCompatible(AllocatorExprType, OMPAllocatorHandleT);
  22070. bool IsNonConstantLValue =
  22071. !AllocatorExprType.isConstant(Context) && AllocatorExpr->isLValue();
  22072. if (!DRE || !IsTypeCompatible ||
  22073. (!IsPredefinedAllocator && !IsNonConstantLValue)) {
  22074. Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected)
  22075. << "omp_allocator_handle_t" << (DRE ? 1 : 0)
  22076. << AllocatorExpr->getType() << D.Allocator->getSourceRange();
  22077. continue;
  22078. }
  22079. // OpenMP [2.12.5, target Construct]
  22080. // Predefined allocators appearing in a uses_allocators clause cannot have
  22081. // traits specified.
  22082. if (IsPredefinedAllocator && D.AllocatorTraits) {
  22083. Diag(D.AllocatorTraits->getExprLoc(),
  22084. diag::err_omp_predefined_allocator_with_traits)
  22085. << D.AllocatorTraits->getSourceRange();
  22086. Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator)
  22087. << cast<NamedDecl>(DRE->getDecl())->getName()
  22088. << D.Allocator->getSourceRange();
  22089. continue;
  22090. }
  22091. // OpenMP [2.12.5, target Construct]
  22092. // Non-predefined allocators appearing in a uses_allocators clause must
  22093. // have traits specified.
  22094. if (!IsPredefinedAllocator && !D.AllocatorTraits) {
  22095. Diag(D.Allocator->getExprLoc(),
  22096. diag::err_omp_nonpredefined_allocator_without_traits);
  22097. continue;
  22098. }
  22099. // No allocator traits - just convert it to rvalue.
  22100. if (!D.AllocatorTraits)
  22101. AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get();
  22102. DSAStack->addUsesAllocatorsDecl(
  22103. DRE->getDecl(),
  22104. IsPredefinedAllocator
  22105. ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator
  22106. : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator);
  22107. }
  22108. Expr *AllocatorTraitsExpr = nullptr;
  22109. if (D.AllocatorTraits) {
  22110. if (D.AllocatorTraits->isTypeDependent()) {
  22111. AllocatorTraitsExpr = D.AllocatorTraits;
  22112. } else {
  22113. // OpenMP [2.12.5, target Construct]
  22114. // Arrays that contain allocator traits that appear in a uses_allocators
  22115. // clause must be constant arrays, have constant values and be defined
  22116. // in the same scope as the construct in which the clause appears.
  22117. AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts();
  22118. // Check that traits expr is a constant array.
  22119. QualType TraitTy;
  22120. if (const ArrayType *Ty =
  22121. AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe())
  22122. if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty))
  22123. TraitTy = ConstArrayTy->getElementType();
  22124. if (TraitTy.isNull() ||
  22125. !(Context.hasSameUnqualifiedType(TraitTy,
  22126. DSAStack->getOMPAlloctraitT()) ||
  22127. Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(),
  22128. /*CompareUnqualified=*/true))) {
  22129. Diag(D.AllocatorTraits->getExprLoc(),
  22130. diag::err_omp_expected_array_alloctraits)
  22131. << AllocatorTraitsExpr->getType();
  22132. continue;
  22133. }
  22134. // Do not map by default allocator traits if it is a standalone
  22135. // variable.
  22136. if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr))
  22137. DSAStack->addUsesAllocatorsDecl(
  22138. DRE->getDecl(),
  22139. DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait);
  22140. }
  22141. }
  22142. OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back();
  22143. NewD.Allocator = AllocatorExpr;
  22144. NewD.AllocatorTraits = AllocatorTraitsExpr;
  22145. NewD.LParenLoc = D.LParenLoc;
  22146. NewD.RParenLoc = D.RParenLoc;
  22147. }
  22148. return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc,
  22149. NewData);
  22150. }
  22151. OMPClause *Sema::ActOnOpenMPAffinityClause(
  22152. SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
  22153. SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) {
  22154. SmallVector<Expr *, 8> Vars;
  22155. for (Expr *RefExpr : Locators) {
  22156. assert(RefExpr && "NULL expr in OpenMP shared clause.");
  22157. if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) {
  22158. // It will be analyzed later.
  22159. Vars.push_back(RefExpr);
  22160. continue;
  22161. }
  22162. SourceLocation ELoc = RefExpr->getExprLoc();
  22163. Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts();
  22164. if (!SimpleExpr->isLValue()) {
  22165. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  22166. << 1 << 0 << RefExpr->getSourceRange();
  22167. continue;
  22168. }
  22169. ExprResult Res;
  22170. {
  22171. Sema::TentativeAnalysisScope Trap(*this);
  22172. Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr);
  22173. }
  22174. if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) &&
  22175. !isa<OMPArrayShapingExpr>(SimpleExpr)) {
  22176. Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
  22177. << 1 << 0 << RefExpr->getSourceRange();
  22178. continue;
  22179. }
  22180. Vars.push_back(SimpleExpr);
  22181. }
  22182. return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
  22183. EndLoc, Modifier, Vars);
  22184. }
  22185. OMPClause *Sema::ActOnOpenMPBindClause(OpenMPBindClauseKind Kind,
  22186. SourceLocation KindLoc,
  22187. SourceLocation StartLoc,
  22188. SourceLocation LParenLoc,
  22189. SourceLocation EndLoc) {
  22190. if (Kind == OMPC_BIND_unknown) {
  22191. Diag(KindLoc, diag::err_omp_unexpected_clause_value)
  22192. << getListOfPossibleValues(OMPC_bind, /*First=*/0,
  22193. /*Last=*/unsigned(OMPC_BIND_unknown))
  22194. << getOpenMPClauseName(OMPC_bind);
  22195. return nullptr;
  22196. }
  22197. return OMPBindClause::Create(Context, Kind, KindLoc, StartLoc, LParenLoc,
  22198. EndLoc);
  22199. }
  22200. OMPClause *Sema::ActOnOpenMPXDynCGroupMemClause(Expr *Size,
  22201. SourceLocation StartLoc,
  22202. SourceLocation LParenLoc,
  22203. SourceLocation EndLoc) {
  22204. Expr *ValExpr = Size;
  22205. Stmt *HelperValStmt = nullptr;
  22206. // OpenMP [2.5, Restrictions]
  22207. // The ompx_dyn_cgroup_mem expression must evaluate to a positive integer
  22208. // value.
  22209. if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_ompx_dyn_cgroup_mem,
  22210. /*StrictlyPositive=*/false))
  22211. return nullptr;
  22212. OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
  22213. OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
  22214. DKind, OMPC_ompx_dyn_cgroup_mem, LangOpts.OpenMP);
  22215. if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
  22216. ValExpr = MakeFullExpr(ValExpr).get();
  22217. llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
  22218. ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
  22219. HelperValStmt = buildPreInits(Context, Captures);
  22220. }
  22221. return new (Context) OMPXDynCGroupMemClause(
  22222. ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
  22223. }